├── traittypes ├── tests │ ├── __init__.py │ ├── test_import_errors.py │ ├── notes jeroen │ ├── test_validators.py │ └── test_traittypes.py ├── _version.py ├── __init__.py ├── utils.py └── traittypes.py ├── docs ├── requirements.txt ├── source │ ├── index.rst │ ├── api_documentation.rst │ ├── introduction.rst │ ├── usage.rst │ └── conf.py ├── Makefile └── make.bat ├── setup.cfg ├── MANIFEST.in ├── MANIFEST ├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md └── setup.py /traittypes/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [metadata] 5 | license_file = LICENSE 6 | -------------------------------------------------------------------------------- /traittypes/_version.py: -------------------------------------------------------------------------------- 1 | version_info = (0, 2, 3) 2 | __version__ = '.'.join(map(str, version_info)) 3 | -------------------------------------------------------------------------------- /traittypes/__init__.py: -------------------------------------------------------------------------------- 1 | from .traittypes import * 2 | from ._version import version_info, __version__ 3 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | ============================================= 2 | traittypes: Trait Types for Scientific Python 3 | ============================================= 4 | 5 | .. toctree:: 6 | 7 | introduction 8 | usage 9 | api_documentation 10 | -------------------------------------------------------------------------------- /traittypes/tests/test_import_errors.py: -------------------------------------------------------------------------------- 1 | 2 | import pytest 3 | 4 | from ..traittypes import _DelayedImportError 5 | 6 | def test_delayed_access_raises(): 7 | dummy = _DelayedImportError('mypackage') 8 | with pytest.raises(RuntimeError): 9 | dummy.asarray([1, 2, 3]) 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CONTRIBUTING.md 2 | include README.md 3 | include LICENSE 4 | 5 | # Documentation 6 | graft docs 7 | exclude docs/\#* 8 | 9 | # Examples 10 | graft examples 11 | 12 | # docs subdirs we want to skip 13 | prune docs/build 14 | prune docs/gh-pages 15 | prune docs/dist 16 | 17 | # Patterns to exclude from any directory 18 | global-exclude *~ 19 | global-exclude *.pyc 20 | global-exclude *.pyo 21 | global-exclude .git 22 | global-exclude .ipynb_checkpoints 23 | -------------------------------------------------------------------------------- /MANIFEST: -------------------------------------------------------------------------------- 1 | # file GENERATED by distutils, do NOT edit 2 | LICENSE 3 | README.md 4 | setup.cfg 5 | setup.py 6 | docs/Makefile 7 | docs/make.bat 8 | docs/requirements.txt 9 | docs/source/api_documentation.rst 10 | docs/source/conf.py 11 | docs/source/index.rst 12 | docs/source/introduction.rst 13 | docs/source/usage.rst 14 | traittypes/__init__.py 15 | traittypes/_version.py 16 | traittypes/traittypes.py 17 | traittypes/tests/__init__.py 18 | traittypes/tests/test_import_errors.py 19 | traittypes/tests/test_traittypes.py 20 | traittypes/tests/test_validators.py 21 | -------------------------------------------------------------------------------- /traittypes/utils.py: -------------------------------------------------------------------------------- 1 | """Sentinel class for constants with useful reprs""" 2 | 3 | # Copyright (c) Jupyter Development Team. 4 | # Distributed under the terms of the Modified BSD License. 5 | 6 | 7 | class Sentinel(object): 8 | 9 | def __init__(self, name, module, docstring=None): 10 | self.name = name 11 | self.module = module 12 | if docstring: 13 | self.__doc__ = docstring 14 | 15 | def __repr__(self): 16 | return str(self.module) + '.' + self.name 17 | 18 | def __copy__(self): 19 | return self 20 | 21 | def __deepcopy__(self, memo): 22 | return self 23 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | defaults: 12 | run: 13 | shell: bash -l {0} 14 | 15 | jobs: 16 | tests: 17 | runs-on: ubuntu-latest 18 | steps: 19 | 20 | - name: Checkout 21 | uses: actions/checkout@v4 22 | 23 | - uses: mamba-org/setup-micromamba@v2 24 | with: 25 | environment-name: test-env 26 | create-args: >- 27 | python=3.11 28 | pip 29 | pandas=1 30 | numpy=1 31 | xarray 32 | pytest 33 | 34 | - name: Install 35 | run: pip install eager . coveralls pytest-cov 36 | 37 | - name: Test coverage 38 | run: pytest --cov=traittypes traittypes 39 | -------------------------------------------------------------------------------- /traittypes/tests/notes jeroen: -------------------------------------------------------------------------------- 1 | Procedural. 2 | 3 | s = IntSlider() 4 | t = Text() 5 | dlink((s, value), (d, value), foo) 6 | HBox([s, t]) 7 | 8 | 9 | Magics!! 10 | 11 | * decorator -> example with explicit code. 12 | * use of abbreviations as default values : the default values don't make sense for the function. 13 | * introspection -> explicitly give the arguments? 14 | * widget abbreviation -> explicit widget. 15 | 16 | 17 | * future meaningful use of abbreviations 18 | 19 | def f(x : float, y : int): 20 | pass 21 | 22 | interact(f) 23 | 24 | * encode constraints in type annotations. 25 | 26 | 27 | 28 | 29 | 30 | float -> Float -> FloatWidget 31 | def f(x = Float(min=0, max=4), y = Int()): 32 | float -> Float -> FloatWidget 33 | 34 | 35 | def f(): 36 | 37 | 38 | 39 | 40 | thierry monteil -------------------------------------------------------------------------------- /docs/source/api_documentation.rst: -------------------------------------------------------------------------------- 1 | API Reference Documentation 2 | --------------------------- 3 | 4 | The ``SciType`` trait type is the base trait type for all Scipy trait types. 5 | 6 | It complements the ``traitlets.TraitType`` with a special API to register custom 7 | validators. 8 | 9 | .. autoclass:: traittypes.traittypes.SciType 10 | :members: 11 | 12 | The ``Array`` trait type holds a numpy Array. 13 | 14 | .. autoclass:: traittypes.traittypes.Array 15 | 16 | The ``DataFrame`` trait type holds a pandas DataFrame. 17 | 18 | .. autoclass:: traittypes.traittypes.DataFrame 19 | 20 | The ``Series`` trait type holds a pandas Series. 21 | 22 | .. autoclass:: traittypes.traittypes.Series 23 | 24 | The ``Dataset`` trait type holds an xarray Dataset. 25 | 26 | .. autoclass:: traittypes.traittypes.Dataset 27 | 28 | The ``DataArray`` trait type holds an xarray DataArray. 29 | 30 | .. autoclass:: traittypes.traittypes.DataArray 31 | -------------------------------------------------------------------------------- /docs/source/introduction.rst: -------------------------------------------------------------------------------- 1 | .. _introduction: 2 | 3 | Introduction 4 | ============ 5 | 6 | The `traittypes` module provides a robust reference implementation of trait 7 | types for common data structures used in the scipy stack such as 8 | 9 | - `numpy `_ arrays 10 | - `pandas `_ and `xarray `_ data structures 11 | 12 | which are out of the scope of the main `traitlets `_ 13 | project but are a common requirement to build applications with traitlets in 14 | combination with the scipy stack. 15 | 16 | Another goal is to create adequate serialization and deserialization routines 17 | for these trait types to be used with the `ipywidgets `_ 18 | project (``to_json`` and ``from_json``). These could also return a list of binary 19 | buffers as allowed by the current messaging protocol. 20 | -------------------------------------------------------------------------------- /docs/source/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | Example: Validating the Shape of a Numpy Array 5 | ---------------------------------------------- 6 | 7 | We pass a validation function to the ``valid`` method of the ``Array`` trait type. 8 | 9 | In this example, the validation function is returned by the ``shape`` closure which stores 10 | the tuple in its closure. 11 | 12 | .. code:: 13 | 14 | from traitlets import HasTraits, TraitError 15 | from traittypes import Array 16 | 17 | def shape(*dimensions): 18 | def validator(trait, value): 19 | if value.shape != dimensions: 20 | raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) 21 | else: 22 | return value 23 | return validator 24 | 25 | class Foo(HasTraits): 26 | bar = Array(np.identity(2)).valid(shape(2, 2)) 27 | foo = Foo() 28 | 29 | foo.bar = [1, 2] # Should raise a TraitError 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | coverage.xml 43 | *,cover 44 | 45 | # Translations 46 | *.mo 47 | *.pot 48 | 49 | # Django stuff: 50 | *.log 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | docs/source/_generate/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | # OS X 60 | .DS_Store 61 | 62 | .pytest_cache/ 63 | -------------------------------------------------------------------------------- /traittypes/tests/test_validators.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # Copyright (c) Jupyter Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | import pytest 8 | 9 | from traitlets import HasTraits, TraitError 10 | 11 | from ..traittypes import SciType 12 | 13 | 14 | def test_coercion_validator(): 15 | # Test with a squeeze coercion 16 | def truncate(trait, value): 17 | return value[:10] 18 | 19 | class Foo(HasTraits): 20 | bar = SciType().valid(truncate) 21 | 22 | foo = Foo(bar=list(range(20))) 23 | assert foo.bar == list(range(10)) 24 | foo.bar = list(range(10, 40)) 25 | assert foo.bar == list(range(10, 20)) 26 | 27 | 28 | def test_validaton_error(): 29 | # Test with a squeeze coercion 30 | def maxlen(trait, value): 31 | if len(value) > 10: 32 | raise ValueError('Too long sequence!') 33 | return value 34 | 35 | class Foo(HasTraits): 36 | bar = SciType().valid(maxlen) 37 | 38 | # Check that it works as expected: 39 | foo = Foo(bar=list(range(5))) 40 | assert foo.bar == list(range(5)) 41 | # Check that it fails as expected: 42 | with pytest.raises(TraitError): # Should convert ValueError to TraitError 43 | foo.bar = list(range(10, 40)) 44 | assert foo.bar == list(range(5)) 45 | # Check that it can again be set correctly 46 | foo = Foo(bar=list(range(5, 10))) 47 | assert foo.bar == list(range(5, 10)) 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) IPython Development Team. 2 | 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | * Neither the name of traittypes nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scipy Trait Types 2 | 3 | [![Build Status](https://travis-ci.org/jupyter-widgets/traittypes.svg?branch=master)](https://travis-ci.org/jupyter-widgets/traittypes) 4 | [![Documentation Status](https://readthedocs.org/projects/traittypes/badge/?version=latest)](http://traittypes.readthedocs.org/en/latest/?badge=latest) 5 | 6 | Trait types for NumPy, SciPy and friends 7 | 8 | ## Goals 9 | 10 | Provide a reference implementation of trait types for common data structures 11 | used in the scipy stack such as 12 | - [numpy](https://github.com/numpy/numpy) arrays 13 | - [pandas](https://github.com/pydata/pandas) and [xarray](https://github.com/pydata/xarray) data structures 14 | 15 | which are out of the scope of the main [traitlets](https://github.com/ipython/traitlets) 16 | project but are a common requirement to build applications with traitlets in 17 | combination with the scipy stack. 18 | 19 | Another goal is to create adequate serialization and deserialization routines 20 | for these trait types to be used with the [ipywidgets](https://github.com/ipython/ipywidgets) 21 | project (`to_json` and `from_json`). These could also return a list of binary 22 | buffers as allowed by the current messaging protocol. 23 | 24 | ## Installation 25 | 26 | 27 | Using `pip`: 28 | 29 | Make sure you have [pip installed](https://pip.readthedocs.org/en/stable/installing/) and run: 30 | 31 | ``` 32 | pip install traittypes 33 | ``` 34 | 35 | Using `conda`: 36 | 37 | ``` 38 | conda install -c conda-forge traittypes 39 | ``` 40 | 41 | ## Usage 42 | 43 | `traittypes` extends the `traitlets` library with an implementation of trait types for numpy arrays, pandas dataframes, pandas series, xarray datasets and xarray dataarrays. 44 | - `traittypes` works around some limitations with numpy array comparison to only trigger change events when necessary. 45 | - `traittypes` also extends the traitlets API for adding custom validators to constrain proposed values for the attribute. 46 | 47 | For a general introduction to `traitlets`, check out the [traitlets documentation](https://traitlets.readthedocs.io/en/stable/). 48 | 49 | ### Example usage with a custom validator 50 | 51 | ```python 52 | from traitlets import HasTraits, TraitError 53 | from traittypes import Array 54 | 55 | def shape(*dimensions): 56 | def validator(trait, value): 57 | if value.shape != dimensions: 58 | raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) 59 | else: 60 | return value 61 | return validator 62 | 63 | class Foo(HasTraits): 64 | bar = Array(np.identity(2)).valid(shape(2, 2)) 65 | foo = Foo() 66 | 67 | foo.bar = [1, 2] # Should raise a TraitError 68 | ``` 69 | 70 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | from __future__ import print_function 8 | 9 | # the name of the project 10 | name = 'traittypes' 11 | 12 | #----------------------------------------------------------------------------- 13 | # Minimal Python version sanity check 14 | #----------------------------------------------------------------------------- 15 | 16 | import sys 17 | 18 | v = sys.version_info 19 | if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3, 5)): 20 | error = "ERROR: %s requires Python version 2.7 or 3.5 or above." % name 21 | print(error, file=sys.stderr) 22 | sys.exit(1) 23 | 24 | PY3 = (sys.version_info[0] >= 3) 25 | 26 | #----------------------------------------------------------------------------- 27 | # get on with it 28 | #----------------------------------------------------------------------------- 29 | 30 | import os 31 | from glob import glob 32 | 33 | from distutils.core import setup 34 | 35 | pjoin = os.path.join 36 | here = os.path.abspath(os.path.dirname(__file__)) 37 | pkg_root = pjoin(here, name) 38 | 39 | packages = [] 40 | for d, _, _ in os.walk(pjoin(here, name)): 41 | if os.path.exists(pjoin(d, '__init__.py')): 42 | packages.append(d[len(here)+1:].replace(os.path.sep, '.')) 43 | 44 | version_ns = {} 45 | with open(pjoin(here, name, '_version.py')) as f: 46 | exec(f.read(), {}, version_ns) 47 | 48 | 49 | setup_args = dict( 50 | name = name, 51 | version = version_ns['__version__'], 52 | scripts = glob(pjoin('scripts', '*')), 53 | packages = packages, 54 | description = "Scipy trait types", 55 | long_description= "Custom trait types for scientific computing.", 56 | author = 'IPython Development Team', 57 | author_email = 'ipython-dev@scipy.org', 58 | url = 'http://ipython.org', 59 | license = 'BSD', 60 | platforms = "Linux, Mac OS X, Windows", 61 | keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'], 62 | classifiers = [ 63 | 'Intended Audience :: Developers', 64 | 'Intended Audience :: System Administrators', 65 | 'Intended Audience :: Science/Research', 66 | 'License :: OSI Approved :: BSD License', 67 | 'Programming Language :: Python', 68 | 'Programming Language :: Python :: 2.7', 69 | 'Programming Language :: Python :: 3', 70 | 'Programming Language :: Python :: 3.5', 71 | 'Programming Language :: Python :: 3.6', 72 | ], 73 | ) 74 | 75 | if 'develop' in sys.argv or any(a.startswith('bdist') for a in sys.argv): 76 | import setuptools 77 | 78 | setuptools_args = {} 79 | 80 | install_requires = setuptools_args['install_requires'] = [ 81 | 'traitlets>=4.2.2', 82 | ] 83 | 84 | extras_require = setuptools_args['extras_require'] = { 85 | 'test': [ 86 | 'numpy', 87 | 'pandas', 88 | 'xarray', 89 | 'pytest', # traitlets[test] require this 90 | ] 91 | } 92 | 93 | if 'setuptools' in sys.modules: 94 | setup_args.update(setuptools_args) 95 | 96 | if __name__ == '__main__': 97 | setup(**setup_args) 98 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext api 23 | 24 | default: html 25 | 26 | help: 27 | @echo "Please use \`make ' where is one of" 28 | @echo " html to make standalone HTML files" 29 | @echo " dirhtml to make HTML files named index.html in directories" 30 | @echo " singlehtml to make a single large HTML file" 31 | @echo " pickle to make pickle files" 32 | @echo " json to make JSON files" 33 | @echo " htmlhelp to make HTML files and a HTML help project" 34 | @echo " qthelp to make HTML files and a qthelp project" 35 | @echo " applehelp to make an Apple Help Book" 36 | @echo " devhelp to make HTML files and a Devhelp project" 37 | @echo " epub to make an epub" 38 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 39 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 40 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 41 | @echo " text to make text files" 42 | @echo " man to make manual pages" 43 | @echo " texinfo to make Texinfo files" 44 | @echo " info to make Texinfo files and run them through makeinfo" 45 | @echo " gettext to make PO message catalogs" 46 | @echo " changes to make an overview of all changed/added/deprecated items" 47 | @echo " xml to make Docutils-native XML files" 48 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 49 | @echo " linkcheck to check all external links for integrity" 50 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 51 | @echo " coverage to run coverage check of the documentation (if enabled)" 52 | 53 | clean: 54 | rm -rf $(BUILDDIR)/* 55 | 56 | html: 57 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 58 | @echo 59 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 60 | 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | singlehtml: 67 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 68 | @echo 69 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 70 | 71 | pickle: 72 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 73 | @echo 74 | @echo "Build finished; now you can process the pickle files." 75 | 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | htmlhelp: 82 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 83 | @echo 84 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 85 | ".hhp project file in $(BUILDDIR)/htmlhelp." 86 | 87 | qthelp: 88 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 89 | @echo 90 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 91 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 92 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/traittypes.qhcp" 93 | @echo "To view the help file:" 94 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/traittypes.qhc" 95 | 96 | applehelp: 97 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 98 | @echo 99 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 100 | @echo "N.B. You won't be able to view it unless you put it in" \ 101 | "~/Library/Documentation/Help or install it in your application" \ 102 | "bundle." 103 | 104 | devhelp: 105 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 106 | @echo 107 | @echo "Build finished." 108 | @echo "To view the help file:" 109 | @echo "# mkdir -p $$HOME/.local/share/devhelp/traittypes" 110 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/traittypes" 111 | @echo "# devhelp" 112 | 113 | epub: 114 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 115 | @echo 116 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 117 | 118 | latex: 119 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 120 | @echo 121 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 122 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 123 | "(use \`make latexpdf' here to do that automatically)." 124 | 125 | latexpdf: 126 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 127 | @echo "Running LaTeX files through pdflatex..." 128 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 129 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 130 | 131 | latexpdfja: 132 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 133 | @echo "Running LaTeX files through platex and dvipdfmx..." 134 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 135 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 136 | 137 | text: 138 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 139 | @echo 140 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 141 | 142 | man: 143 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 144 | @echo 145 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 146 | 147 | texinfo: 148 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 149 | @echo 150 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 151 | @echo "Run \`make' in that directory to run these through makeinfo" \ 152 | "(use \`make info' here to do that automatically)." 153 | 154 | info: 155 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 156 | @echo "Running Texinfo files through makeinfo..." 157 | make -C $(BUILDDIR)/texinfo info 158 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 159 | 160 | gettext: 161 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 162 | @echo 163 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 164 | 165 | changes: 166 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 167 | @echo 168 | @echo "The overview file is in $(BUILDDIR)/changes." 169 | 170 | linkcheck: 171 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 172 | @echo 173 | @echo "Link check complete; look for any errors in the above output " \ 174 | "or in $(BUILDDIR)/linkcheck/output.txt." 175 | 176 | doctest: 177 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 178 | @echo "Testing of doctests in the sources finished, look at the " \ 179 | "results in $(BUILDDIR)/doctest/output.txt." 180 | 181 | coverage: 182 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 183 | @echo "Testing of coverage in the sources finished, look at the " \ 184 | "results in $(BUILDDIR)/coverage/python.txt." 185 | 186 | xml: 187 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 188 | @echo 189 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 190 | 191 | pseudoxml: 192 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 193 | @echo 194 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 195 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 2> nul 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\traittypes.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\traittypes.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /traittypes/tests/test_traittypes.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | """Tests for traittypes.traittypes.""" 3 | 4 | # Copyright (c) IPython Development Team. 5 | # Distributed under the terms of the Modified BSD License. 6 | 7 | from unittest import TestCase 8 | from traitlets import HasTraits, TraitError, observe, Undefined 9 | from traitlets.tests.test_traitlets import TraitTestBase 10 | from traittypes import Array, DataFrame, Series, Dataset, DataArray 11 | import numpy as np 12 | import pandas as pd 13 | import xarray as xr 14 | 15 | 16 | # Good / Bad value trait test cases 17 | 18 | 19 | class IntArrayTrait(HasTraits): 20 | value = Array().tag(dtype=np.int32) 21 | 22 | 23 | class TestIntArray(TraitTestBase): 24 | """ 25 | Test dtype validation with a ``dtype=np.int32`` 26 | """ 27 | obj = IntArrayTrait() 28 | 29 | _good_values = [1, [1, 2, 3], [[1, 2, 3], [4, 5, 6]], np.array([1])] 30 | 31 | def assertEqual(self, v1, v2): 32 | return np.testing.assert_array_equal(v1, v2) 33 | 34 | 35 | # Other test cases 36 | 37 | 38 | class TestArray(TestCase): 39 | 40 | def test_array_equal(self): 41 | notifications = [] 42 | class Foo(HasTraits): 43 | bar = Array([1, 2]) 44 | @observe('bar') 45 | def _(self, change): 46 | notifications.append(change) 47 | foo = Foo() 48 | foo.bar = [1, 2] 49 | self.assertFalse(len(notifications)) 50 | foo.bar = [1, 1] 51 | self.assertTrue(len(notifications)) 52 | 53 | def test_initial_values(self): 54 | class Foo(HasTraits): 55 | a = Array() 56 | b = Array(dtype='int') 57 | c = Array(None, allow_none=True) 58 | d = Array([]) 59 | e = Array(Undefined) 60 | foo = Foo() 61 | self.assertTrue(np.array_equal(foo.a, np.array(0))) 62 | self.assertTrue(np.array_equal(foo.b, np.array(0))) 63 | self.assertTrue(foo.c is None) 64 | self.assertTrue(np.array_equal(foo.d, [])) 65 | self.assertTrue(foo.e is Undefined) 66 | 67 | def test_allow_none(self): 68 | class Foo(HasTraits): 69 | bar = Array() 70 | baz = Array(allow_none=True) 71 | foo = Foo() 72 | with self.assertRaises(TraitError): 73 | foo.bar = None 74 | foo.baz = None 75 | 76 | def test_custom_validators(self): 77 | # Test with a squeeze coercion 78 | def squeeze(trait, value): 79 | if 1 in value.shape: 80 | value = np.squeeze(value) 81 | return value 82 | 83 | class Foo(HasTraits): 84 | bar = Array().valid(squeeze) 85 | 86 | foo = Foo(bar=[[1], [2]]) 87 | self.assertTrue(np.array_equal(foo.bar, [1, 2])) 88 | foo.bar = [[1], [2], [3]] 89 | self.assertTrue(np.array_equal(foo.bar, [1, 2, 3])) 90 | 91 | # Test with a shape constraint 92 | def shape(*dimensions): 93 | def validator(trait, value): 94 | if value.shape != dimensions: 95 | raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) 96 | else: 97 | return value 98 | return validator 99 | 100 | class Foo(HasTraits): 101 | bar = Array(np.identity(2)).valid(shape(2, 2)) 102 | foo = Foo() 103 | with self.assertRaises(TraitError): 104 | foo.bar = [1] 105 | new_value = [[0, 1], [1, 0]] 106 | foo.bar = new_value 107 | self.assertTrue(np.array_equal(foo.bar, new_value)) 108 | 109 | 110 | class TestDataFrame(TestCase): 111 | 112 | def test_df_equal(self): 113 | notifications = [] 114 | class Foo(HasTraits): 115 | bar = DataFrame([1, 2]) 116 | @observe('bar') 117 | def _(self, change): 118 | notifications.append(change) 119 | foo = Foo() 120 | foo.bar = [1, 2] 121 | self.assertEqual(notifications, []) 122 | foo.bar = [1, 1] 123 | self.assertEqual(len(notifications), 1) 124 | 125 | def test_initial_values(self): 126 | class Foo(HasTraits): 127 | a = DataFrame() 128 | b = DataFrame(None, allow_none=True) 129 | c = DataFrame([]) 130 | d = DataFrame(Undefined) 131 | foo = Foo() 132 | self.assertTrue(foo.a.equals(pd.DataFrame())) 133 | self.assertTrue(foo.b is None) 134 | self.assertTrue(foo.c.equals(pd.DataFrame([]))) 135 | self.assertTrue(foo.d is Undefined) 136 | 137 | def test_allow_none(self): 138 | class Foo(HasTraits): 139 | bar = DataFrame() 140 | baz = DataFrame(allow_none=True) 141 | foo = Foo() 142 | with self.assertRaises(TraitError): 143 | foo.bar = None 144 | foo.baz = None 145 | 146 | 147 | class TestSeries(TestCase): 148 | 149 | def test_series_equal(self): 150 | notifications = [] 151 | class Foo(HasTraits): 152 | bar = Series([1, 2], dtype=np.int64) 153 | @observe('bar') 154 | def _(self, change): 155 | notifications.append(change) 156 | foo = Foo() 157 | foo.bar = [1, 2] 158 | self.assertEqual(notifications, []) 159 | foo.bar = [1, 1] 160 | self.assertEqual(len(notifications), 1) 161 | 162 | def test_initial_values(self): 163 | class Foo(HasTraits): 164 | a = Series() 165 | b = Series(None, allow_none=True) 166 | c = Series([]) 167 | d = Series(Undefined) 168 | foo = Foo() 169 | self.assertTrue(foo.a.equals(pd.Series())) 170 | self.assertTrue(foo.b is None) 171 | self.assertTrue(foo.c.equals(pd.Series([]))) 172 | self.assertTrue(foo.d is Undefined) 173 | 174 | def test_allow_none(self): 175 | class Foo(HasTraits): 176 | bar = Series() 177 | baz = Series(allow_none=True) 178 | foo = Foo() 179 | with self.assertRaises(TraitError): 180 | foo.bar = None 181 | foo.baz = None 182 | 183 | 184 | class TestDataset(TestCase): 185 | 186 | def test_ds_equal(self): 187 | notifications = [] 188 | class Foo(HasTraits): 189 | bar = Dataset({'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14}) 190 | @observe('bar') 191 | def _(self, change): 192 | notifications.append(change) 193 | foo = Foo() 194 | foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.14} 195 | self.assertEqual(notifications, []) 196 | foo.bar = {'foo': xr.DataArray([[0, 1, 2], [3, 4, 5]], coords={'x': ['a', 'b']}, dims=('x', 'y')), 'bar': ('x', [1, 2]), 'baz': 3.15} 197 | self.assertEqual(len(notifications), 1) 198 | 199 | def test_initial_values(self): 200 | class Foo(HasTraits): 201 | a = Dataset() 202 | b = Dataset(None, allow_none=True) 203 | d = Dataset(Undefined) 204 | foo = Foo() 205 | self.assertTrue(foo.a.equals(xr.Dataset())) 206 | self.assertTrue(foo.b is None) 207 | self.assertTrue(foo.d is Undefined) 208 | 209 | def test_allow_none(self): 210 | class Foo(HasTraits): 211 | bar = Dataset() 212 | baz = Dataset(allow_none=True) 213 | foo = Foo() 214 | with self.assertRaises(TraitError): 215 | foo.bar = None 216 | foo.baz = None 217 | 218 | 219 | class TestDataArray(TestCase): 220 | 221 | def test_ds_equal(self): 222 | notifications = [] 223 | class Foo(HasTraits): 224 | bar = DataArray([[0, 1], [2, 3]]) 225 | @observe('bar') 226 | def _(self, change): 227 | notifications.append(change) 228 | foo = Foo() 229 | foo.bar = [[0, 1], [2, 3]] 230 | self.assertEqual(notifications, []) 231 | foo.bar = [[0, 1], [2, 4]] 232 | self.assertEqual(len(notifications), 1) 233 | 234 | def test_initial_values(self): 235 | class Foo(HasTraits): 236 | b = DataArray(None, allow_none=True) 237 | c = DataArray([]) 238 | d = DataArray(Undefined) 239 | foo = Foo() 240 | self.assertTrue(foo.b is None) 241 | self.assertTrue(foo.c.equals(xr.DataArray([]))) 242 | self.assertTrue(foo.d is Undefined) 243 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # traittypes documentation build configuration file. 4 | # 5 | # NOTE: This file has been edited manually from the auto-generated one from 6 | # sphinx. Do NOT delete and re-generate. If any changes from sphinx are 7 | # needed, generate a scratch one and merge by hand any new fields needed. 8 | # 9 | 10 | import sys 11 | import os 12 | 13 | 14 | # We load the traittypes release info into a dict by explicit execution 15 | import traittypes 16 | release = traittypes.__version__ 17 | 18 | # -- General configuration ------------------------------------------------ 19 | 20 | # If your documentation needs a minimal Sphinx version, state it here. 21 | #needs_sphinx = '1.0' 22 | 23 | # Add any Sphinx extension module names here, as strings. They can be 24 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 25 | # ones. 26 | extensions = [ 27 | 'sphinx.ext.autodoc', 28 | 'sphinx.ext.intersphinx', 29 | 'sphinx.ext.autosummary', 30 | 'sphinx.ext.viewcode', 31 | 'sphinx.ext.napoleon', 32 | 'sphinx.ext.mathjax', 33 | ] 34 | 35 | autosummary_generate = True 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix(es) of source filenames. 41 | source_suffix = '.rst' 42 | 43 | # Add dev disclaimer. 44 | if 'dev' in release: 45 | rst_prolog = """ 46 | .. note:: 47 | 48 | This documentation is for a development version of traittypes. There may be 49 | significant differences from the latest stable release. 50 | 51 | """ 52 | 53 | # The encoding of source files. 54 | #source_encoding = 'utf-8-sig' 55 | 56 | # The master toctree document. 57 | master_doc = 'index' 58 | 59 | # General information about the project. 60 | project = u'traittypes' 61 | author = u'The IPython Contributors' 62 | 63 | # The version info for the project you're documenting, acts as replacement for 64 | # |version| and |release|, also used in various other places throughout the 65 | # built documents. 66 | # 67 | 68 | # The language for content autogenerated by Sphinx. Refer to documentation 69 | # for a list of supported languages. 70 | language = None 71 | 72 | # There are two options for replacing |today|: either, you set today to some 73 | # non-false value, then it is used: 74 | #today = '' 75 | # Else, today_fmt is used as the format for a strftime call. 76 | #today_fmt = '%B %d, %Y' 77 | 78 | # List of patterns, relative to source directory, that match files and 79 | # directories to ignore when looking for source files. 80 | exclude_patterns = [] 81 | 82 | # The reST default role (used for this markup: `text`) to use for all 83 | # documents. 84 | #default_role = None 85 | 86 | # If true, '()' will be appended to :func: etc. cross-reference text. 87 | #add_function_parentheses = True 88 | 89 | # If true, the current module name will be prepended to all description 90 | # unit titles (such as .. function::). 91 | #add_module_names = True 92 | 93 | # If true, sectionauthor and moduleauthor directives will be shown in the 94 | # output. They are ignored by default. 95 | #show_authors = False 96 | 97 | # The name of the Pygments (syntax highlighting) style to use. 98 | pygments_style = 'sphinx' 99 | 100 | # A list of ignored prefixes for module index sorting. 101 | #modindex_common_prefix = [] 102 | 103 | # If true, keep warnings as "system message" paragraphs in the built documents. 104 | #keep_warnings = False 105 | 106 | 107 | # -- Options for HTML output ---------------------------------------------- 108 | 109 | # The theme to use for HTML and HTML Help pages. See the documentation for 110 | # a list of builtin themes. 111 | #html_theme = 'alabaster' 112 | 113 | # Theme options are theme-specific and customize the look and feel of a theme 114 | # further. For a list of options available for each theme, see the 115 | # documentation. 116 | #html_theme_options = {} 117 | 118 | # Add any paths that contain custom themes here, relative to this directory. 119 | #html_theme_path = [] 120 | 121 | # The name for this set of Sphinx documents. If None, it defaults to 122 | # " v documentation". 123 | #html_title = None 124 | 125 | # A shorter title for the navigation bar. Default is the same as html_title. 126 | #html_short_title = None 127 | 128 | # The name of an image file (relative to this directory) to place at the top 129 | # of the sidebar. 130 | #html_logo = None 131 | 132 | # The name of an image file (within the static path) to use as favicon of the 133 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 134 | # pixels large. 135 | #html_favicon = None 136 | 137 | # Add any paths that contain custom static files (such as style sheets) here, 138 | # relative to this directory. They are copied after the builtin static files, 139 | # so a file named "default.css" will overwrite the builtin "default.css". 140 | # html_static_path = ['_static'] 141 | 142 | # Add any extra paths that contain custom files (such as robots.txt or 143 | # .htaccess) here, relative to this directory. These files are copied 144 | # directly to the root of the documentation. 145 | #html_extra_path = [] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 148 | # using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names to 159 | # template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 175 | #html_show_sphinx = True 176 | 177 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 178 | #html_show_copyright = True 179 | 180 | # If true, an OpenSearch description file will be output, and all pages will 181 | # contain a tag referring to it. The value of this option must be the 182 | # base URL from which the finished HTML is served. 183 | #html_use_opensearch = '' 184 | 185 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 186 | #html_file_suffix = None 187 | 188 | # Output file base name for HTML help builder. 189 | htmlhelp_basename = 'traittypesdoc' 190 | 191 | 192 | # -- Options for LaTeX output --------------------------------------------- 193 | 194 | latex_elements = { 195 | # The paper size ('letterpaper' or 'a4paper'). 196 | #'papersize': 'letterpaper', 197 | 198 | # The font size ('10pt', '11pt' or '12pt'). 199 | #'pointsize': '10pt', 200 | 201 | # Additional stuff for the LaTeX preamble. 202 | #'preamble': '', 203 | } 204 | 205 | # Grouping the document tree into LaTeX files. List of tuples 206 | # (source start file, target name, title, 207 | # author, documentclass [howto, manual, or own class]). 208 | latex_documents = [ 209 | ('index', 'traittypes.tex', u'traittypes Documentation', 210 | u'IPython contributors', 'manual'), 211 | ] 212 | 213 | # The name of an image file (relative to this directory) to place at the top of 214 | # the title page. 215 | #latex_logo = None 216 | 217 | # For "manual" documents, if this is true, then toplevel headings are parts, 218 | # not chapters. 219 | #latex_use_parts = False 220 | 221 | # If true, show page references after internal links. 222 | #latex_show_pagerefs = False 223 | 224 | # If true, show URL addresses after external links. 225 | #latex_show_urls = False 226 | 227 | # Documents to append as an appendix to all manuals. 228 | #latex_appendices = [] 229 | 230 | # If false, no module index is generated. 231 | #latex_domain_indices = True 232 | 233 | 234 | # -- Options for manual page output --------------------------------------- 235 | 236 | # One entry per manual page. List of tuples 237 | # (source start file, name, description, authors, manual section). 238 | man_pages = [ 239 | ('index', 'traittypes', u'traittypes Documentation', 240 | [u'IPython contributors'], 1) 241 | ] 242 | 243 | # If true, show URL addresses after external links. 244 | #man_show_urls = False 245 | 246 | 247 | # -- Options for Texinfo output ------------------------------------------- 248 | 249 | # Grouping the document tree into Texinfo files. List of tuples 250 | # (source start file, target name, title, author, 251 | # dir menu entry, description, category) 252 | texinfo_documents = [ 253 | ('index', 'traittypes', u'traittypes Documentation', 254 | u'IPython contributors', 'traittypes', 'One line description of project.', 255 | 'Miscellaneous'), 256 | ] 257 | 258 | # Documents to append as an appendix to all manuals. 259 | #texinfo_appendices = [] 260 | 261 | # If false, no module index is generated. 262 | #texinfo_domain_indices = True 263 | 264 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 265 | #texinfo_show_urls = 'footnote' 266 | 267 | # If true, do not generate a @detailmenu in the "Top" node's menu. 268 | #texinfo_no_detailmenu = False 269 | -------------------------------------------------------------------------------- /traittypes/traittypes.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import warnings 3 | 4 | from traitlets import TraitType, TraitError, Undefined 5 | from .utils import Sentinel 6 | 7 | class _DelayedImportError(object): 8 | def __init__(self, package_name): 9 | self.package_name = package_name 10 | 11 | def __getattribute__(self, name): 12 | package_name = super(_DelayedImportError, self).__getattribute__('package_name') 13 | raise RuntimeError('Missing dependency: %s' % package_name) 14 | 15 | try: 16 | import numpy as np 17 | except ImportError: 18 | np = _DelayedImportError('numpy') 19 | 20 | 21 | Empty = Sentinel('Empty', 'traittypes', 22 | """ 23 | Used in traittypes to specify that the default value should 24 | be an empty dataset 25 | """) 26 | 27 | 28 | class SciType(TraitType): 29 | 30 | """A base trait type for numpy arrays, pandas dataframes, pandas series, xarray datasets and xarray dataarrays.""" 31 | 32 | def __init__(self, **kwargs): 33 | super(SciType, self).__init__(**kwargs) 34 | self.validators = [] 35 | 36 | def valid(self, *validators): 37 | """ 38 | Register new trait validators 39 | 40 | Validators are functions that take two arguments. 41 | - The trait instance 42 | - The proposed value 43 | 44 | Validators return the (potentially modified) value, which is either 45 | assigned to the HasTraits attribute or input into the next validator. 46 | 47 | They are evaluated in the order in which they are provided to the `valid` 48 | function. 49 | 50 | Example 51 | ------- 52 | 53 | .. code:: python 54 | 55 | # Test with a shape constraint 56 | def shape(*dimensions): 57 | def validator(trait, value): 58 | if value.shape != dimensions: 59 | raise TraitError('Expected an of shape %s and got and array with shape %s' % (dimensions, value.shape)) 60 | else: 61 | return value 62 | return validator 63 | 64 | class Foo(HasTraits): 65 | bar = Array(np.identity(2)).valid(shape(2, 2)) 66 | foo = Foo() 67 | 68 | foo.bar = [1, 2] # Should raise a TraitError 69 | """ 70 | self.validators.extend(validators) 71 | return self 72 | 73 | def validate(self, obj, value): 74 | """Validate the value against registered validators.""" 75 | try: 76 | for validator in self.validators: 77 | value = validator(self, value) 78 | return value 79 | except (ValueError, TypeError) as e: 80 | raise TraitError(e) 81 | 82 | 83 | class Array(SciType): 84 | 85 | """A numpy array trait type.""" 86 | 87 | info_text = 'a numpy array' 88 | dtype = None 89 | 90 | def validate(self, obj, value): 91 | if value is None and not self.allow_none: 92 | self.error(obj, value) 93 | if value is None or value is Undefined: 94 | return super(Array, self).validate(obj, value) 95 | try: 96 | r = np.asarray(value, dtype=self.dtype) 97 | if isinstance(value, np.ndarray) and r is not value: 98 | warnings.warn( 99 | 'Given trait value dtype "%s" does not match required type "%s". ' 100 | 'A coerced copy has been created.' % ( 101 | np.dtype(value.dtype).name, 102 | np.dtype(self.dtype).name)) 103 | value = r 104 | except (ValueError, TypeError) as e: 105 | raise TraitError(e) 106 | return super(Array, self).validate(obj, value) 107 | 108 | def set(self, obj, value): 109 | new_value = self._validate(obj, value) 110 | old_value = obj._trait_values.get(self.name, self.default_value) 111 | obj._trait_values[self.name] = new_value 112 | if not np.array_equal(old_value, new_value): 113 | obj._notify_trait(self.name, old_value, new_value) 114 | 115 | def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): 116 | self.dtype = dtype 117 | if default_value is Empty: 118 | default_value = np.array(0, dtype=self.dtype) 119 | elif default_value is not None and default_value is not Undefined: 120 | default_value = np.asarray(default_value, dtype=self.dtype) 121 | super(Array, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) 122 | 123 | def make_dynamic_default(self): 124 | if self.default_value is None or self.default_value is Undefined: 125 | return self.default_value 126 | else: 127 | return np.copy(self.default_value) 128 | 129 | 130 | class PandasType(SciType): 131 | 132 | """A pandas dataframe or series trait type.""" 133 | 134 | info_text = 'a pandas dataframe or series' 135 | 136 | klass = None 137 | 138 | def validate(self, obj, value): 139 | if value is None and not self.allow_none: 140 | self.error(obj, value) 141 | if value is None or value is Undefined: 142 | return super(PandasType, self).validate(obj, value) 143 | try: 144 | value = self.klass(value) 145 | except (ValueError, TypeError) as e: 146 | raise TraitError(e) 147 | return super(PandasType, self).validate(obj, value) 148 | 149 | def set(self, obj, value): 150 | new_value = self._validate(obj, value) 151 | old_value = obj._trait_values.get(self.name, self.default_value) 152 | obj._trait_values[self.name] = new_value 153 | if ((old_value is None and new_value is not None) or 154 | (old_value is Undefined and new_value is not Undefined) or 155 | not old_value.equals(new_value)): 156 | obj._notify_trait(self.name, old_value, new_value) 157 | 158 | def __init__(self, default_value=Empty, allow_none=False, klass=None, klass_kwargs=None, **kwargs): 159 | if klass is None: 160 | klass = self.klass 161 | if klass_kwargs is None: 162 | klass_kwargs = {} 163 | if (klass is not None) and inspect.isclass(klass): 164 | self.klass = klass 165 | else: 166 | raise TraitError('The klass attribute must be a class' 167 | ' not: %r' % klass) 168 | if default_value is Empty: 169 | default_value = klass(**klass_kwargs) 170 | elif default_value is not None and default_value is not Undefined: 171 | default_value = klass(default_value, **klass_kwargs) 172 | super(PandasType, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) 173 | 174 | def make_dynamic_default(self): 175 | if self.default_value is None or self.default_value is Undefined: 176 | return self.default_value 177 | else: 178 | return self.default_value.copy() 179 | 180 | 181 | class DataFrame(PandasType): 182 | 183 | """A pandas dataframe trait type.""" 184 | 185 | info_text = 'a pandas dataframe' 186 | 187 | def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): 188 | if 'klass' not in kwargs and self.klass is None: 189 | import pandas as pd 190 | kwargs['klass'] = pd.DataFrame 191 | super(DataFrame, self).__init__( 192 | default_value=default_value, allow_none=allow_none, **kwargs) 193 | self.tag(dtype=dtype) 194 | 195 | 196 | class Series(PandasType): 197 | 198 | """A pandas series trait type.""" 199 | 200 | info_text = 'a pandas series' 201 | dtype = None 202 | 203 | def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): 204 | if 'klass' not in kwargs and self.klass is None: 205 | import pandas as pd 206 | kwargs['klass'] = pd.Series 207 | if dtype is None: 208 | dtype = np.float64 209 | super(Series, self).__init__( 210 | default_value=default_value, allow_none=allow_none, klass_kwargs={"dtype": dtype}, **kwargs) 211 | self.tag(dtype=dtype) 212 | self.dtype = dtype 213 | 214 | 215 | class XarrayType(SciType): 216 | 217 | """An xarray dataset or dataarray trait type.""" 218 | 219 | info_text = 'an xarray dataset or dataarray' 220 | 221 | klass = None 222 | 223 | def validate(self, obj, value): 224 | if value is None and not self.allow_none: 225 | self.error(obj, value) 226 | if value is None or value is Undefined: 227 | return super(XarrayType, self).validate(obj, value) 228 | try: 229 | value = self.klass(value) 230 | except (ValueError, TypeError) as e: 231 | raise TraitError(e) 232 | return super(XarrayType, self).validate(obj, value) 233 | 234 | def set(self, obj, value): 235 | new_value = self._validate(obj, value) 236 | old_value = obj._trait_values.get(self.name, self.default_value) 237 | obj._trait_values[self.name] = new_value 238 | if ((old_value is None and new_value is not None) or 239 | (old_value is Undefined and new_value is not Undefined) or 240 | not old_value.equals(new_value)): 241 | obj._notify_trait(self.name, old_value, new_value) 242 | 243 | def __init__(self, default_value=Empty, allow_none=False, klass=None, **kwargs): 244 | if klass is None: 245 | klass = self.klass 246 | if (klass is not None) and inspect.isclass(klass): 247 | self.klass = klass 248 | else: 249 | raise TraitError('The klass attribute must be a class' 250 | ' not: %r' % klass) 251 | if default_value is Empty: 252 | default_value = klass() 253 | elif default_value is not None and default_value is not Undefined: 254 | default_value = klass(default_value) 255 | super(XarrayType, self).__init__(default_value=default_value, allow_none=allow_none, **kwargs) 256 | 257 | def make_dynamic_default(self): 258 | if self.default_value is None or self.default_value is Undefined: 259 | return self.default_value 260 | else: 261 | return self.default_value.copy() 262 | 263 | 264 | class Dataset(XarrayType): 265 | 266 | """An xarray dataset trait type.""" 267 | 268 | info_text = 'an xarray dataset' 269 | 270 | def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): 271 | if 'klass' not in kwargs and self.klass is None: 272 | import xarray as xr 273 | kwargs['klass'] = xr.Dataset 274 | super(Dataset, self).__init__( 275 | default_value=default_value, allow_none=allow_none, **kwargs) 276 | self.tag(dtype=dtype) 277 | 278 | 279 | class DataArray(XarrayType): 280 | 281 | """An xarray dataarray trait type.""" 282 | 283 | info_text = 'an xarray dataarray' 284 | dtype = None 285 | 286 | def __init__(self, default_value=Empty, allow_none=False, dtype=None, **kwargs): 287 | if 'klass' not in kwargs and self.klass is None: 288 | import xarray as xr 289 | kwargs['klass'] = xr.DataArray 290 | super(DataArray, self).__init__( 291 | default_value=default_value, allow_none=allow_none, **kwargs) 292 | self.tag(dtype=dtype) 293 | self.dtype = dtype 294 | --------------------------------------------------------------------------------