The Virtual Brain Project

Table Of Contents

Previous topic

logger Package

Next topic

datatypes Package

This Page

traits Package

Traits metadata module

introduction

The problem is that various classes have members whose properties we want to annotate in a way that does not affect the execution of the class algorithms but that exposes an API to pull out this info for a user interface and documentation. It should be readable for the programmers as well. We refer to an annotated/propertied member as a trait.

Consider the following class:

>>> class Point(object):
...     x = 0.0
...     y = 0.0

If you want to present this data to the user, you may want to label each attribute of the Point with more than just ‘x’ or ‘y’, or you want to check that if the user creates a Point, the values have the right type (here, we assume the type of 0.0 means floating point), and if you want to store the instances of Point in a data base, each one needs a unique id. These pieces of information need to be put somewhere, and the best place to put it is in the attribute declaration, for example,

>>> class Point(Type):
...     x = Float(0.0, doc='horizontal position')
...     y = Float(0.0, doc='vertical position')

Here, the type of each attribute is explicit, and a documentation string is provided, all in the same attribute declaration, and this co-location of information makes it easier to maintain, and elsewhere in the program, this information can be accessed programmatically to generate user interfaces, serialize data, validate data, etc. Additionally, all classes’ docstrings will have Traits information automatically added:

>>> print Point.__doc__
Traited class Point
    x: horizontal position, type float
    y: vertical position, type float

The Traits package allows us to write classes like the one above by using a metaclass to customize the class creation. In brief, when Python reads a class definition the Trait metaclass has access to all the attribute declarations, and it will place a dictionary of all the data provided in the declarations on the class. When the classes are instantiated and used, the Trait attributes behave exactly like their values, such that class methods do not need to know they are accessing Trait attributes. For more details, see traits.core.

package modules

core Provides the core of Traits, a metaclass and class that
implement the reflection/annotation that Traits allows.
types_basic Provides basic predefined types as well as the Type that
should be inherited from when making new Types
traited_interface Provides recursive interfaces classes that are data
descriptors, i.e. when placed on classes, they compute the full description of the class and it’s Traited attributes.

util Utility functions and classes.

automatic class documentation

Classes that subclass Type (or subclasses of MetaType) have their docstrings automatically augmented by the repr() of each attribute which is a Type. This allows one to find the trait documentation both in SPhinx and at the console.

References

Suggested reading is Unifying Types and Classes and th Python data model.

core

All problems in computer science can be solved by another layer of indirection, except for the problem of too many layers of indirection.

Traits overview

Traits classes are separated into two modules:

core:
TraitsInfo meta-data container for traits system MetaType base class for traited class creation Type base traited class
mapped:
MappedType basic class for traited class mapped to db
  • (Type) traits mapped to columns
  • (MappedType) traits mapped to column(foreignkey) -> table

Traits metadata

While the traits of a class can be declared nearly arbitrarily, there are intrinsic pieces of information in the meta-data required to make the traits system work:

doc string long description, possibly longer string label string short name appearing in UI default object default value of attribute required boolean determines whether must be set before storage range Range helps validate or specify parameter variation
class tvb.basic.traits.core.MetaType[source]

Bases: abc.ABCMeta

The MetaType class augments the class creation and instantiation of all the types in the Traits system. See the doc-strings of the methods for more details:

__new__ - creates a class __call__ - create a class instance

While the basic Traits mechanisms are described and implemented in this class, see DeclarativeMetaType for implementation and description of database mapping of Traits classes.

class tvb.basic.traits.core.TraitsInfo(trait, name='<no name!>', bound=False, wraps=None, inits=Args(pos=(), kwd={}), value=None, wraps_defaults=())[source]

Bases: dict

TraitsInfo is a container for information related to the owner class and its traited attributes that is used by the traits classes. It is needed because many of the attribute names used by traits, e.g. data & bound, may mean other things to other classes and we can’t step on their toes.

TraitsInfo is a dictionary of the owner’s traited attributes, and its other attributes are:

  • name - name of attribute on owner class

  • bound - whether the trait is bound as data descriptor

  • wraps - class this trait wraps

  • inits - a namedtuple of positional and keyword arguments

    given to intialize the trait instance

  • value - instance value of trait, equal to trait if wraps==None

  • defaults - default args to wraps’ constructor

copy()[source]

Create a copy for current Traits.

file_storage[source]
order_number[source]
range_interval[source]
required[source]
select_multiple[source]
stored_metadata[source]
use_storage[source]
tvb.basic.traits.core.Type[source]

Type class provides a base class for dataTypes and the attributes on dataTypes.

When a Type instance is an attribute of a class and self.bound is True, the instance will act as a data descriptor, setting/getting its corresponding value on the owner class.

In the case of sql’ed values, names are coordinated such that the private value (`obj._name`) of the public attr (`obj.name`) on the owner class used by the Type instance is actually the corresponding sqlAlchemy data descriptor as generated by the value of ‘sql’ keyword to the Type instance __init__.

traits on this class:

tvb.basic.traits.core.TypeBase

Type class provides a base class for dataTypes and the attributes on dataTypes.

When a Type instance is an attribute of a class and self.bound is True, the instance will act as a data descriptor, setting/getting its corresponding value on the owner class.

In the case of sql’ed values, names are coordinated such that the private value (`obj._name`) of the public attr (`obj.name`) on the owner class used by the Type instance is actually the corresponding sqlAlchemy data descriptor as generated by the value of ‘sql’ keyword to the Type instance __init__.

traits on this class:

exceptions

exception tvb.basic.traits.exceptions.MissingEntityException(message, parent_exception=None)[source]

Bases: tvb.basic.traits.exceptions.TVBException

Exception class used for cases when trying to load an entity from database by id or GID and none found.

exception tvb.basic.traits.exceptions.StorageException(message, parent_exception=None)[source]

Bases: tvb.basic.traits.exceptions.TVBException

Exception class used for cases when trying to load an entity from database by id or GID and none found.

exception tvb.basic.traits.exceptions.TVBException(message, parent_exception=None)[source]

Bases: exceptions.Exception

Base class for all TVB exceptions.

exception tvb.basic.traits.exceptions.ValidationException(message, parent_exception=None)[source]

Bases: tvb.basic.traits.exceptions.TVBException

Exception class for problems that occurs during MappedType validation before storing it into DB.

itree_model

A data model for the input trees. .. moduleauthor:: Mihai Andrei <mihai.andrei@codemart.ro>

class tvb.basic.traits.itree_model.ArrayNode(name, type_, default='[]', range_=None, label=None, description=None, required=True)[source]

Bases: tvb.basic.traits.itree_model.NumericNode

class tvb.basic.traits.itree_model.ComplexDtypeNode(name, type_, attributes, label=None, description=None, required=True, conditions=None, filters_ui=None)[source]

Bases: object

Usually a cortex. It is not a LeafNode even though similar to a datatypenode

class tvb.basic.traits.itree_model.DatatypeNode(name, type_, label=None, description=None, required=True, conditions=None, filters_ui=None)[source]

Bases: object

A dataype node. Has filters.

class tvb.basic.traits.itree_model.DictNode(name, type_, attributes, default)[source]

Bases: object

class tvb.basic.traits.itree_model.EnumerateNode(name, select_multiple, default, options, label=None, description=None, required=True)[source]

Bases: object

class tvb.basic.traits.itree_model.LeafNode(name, type_, default=None, label=None, description=None, required=True)[source]

Bases: object

Node has no descendants

class tvb.basic.traits.itree_model.NumericNode(name, type_, default=0, range_=None, label=None, description=None, required=True)[source]

Bases: tvb.basic.traits.itree_model.LeafNode

class tvb.basic.traits.itree_model.Option(name, value)[source]

Bases: object

class tvb.basic.traits.itree_model.Range(min_, max_, step)[source]

Bases: object

class tvb.basic.traits.itree_model.SelectTypeNode(name, select_multiple, options, default=None, label=None, description=None)[source]

Bases: object

This node represents a collection of non mapped Types. Examples Model collection, Integrator collection

class tvb.basic.traits.itree_model.TypeNode(name, value, class_, description, attributes)[source]

Bases: object

A non-mapped type. Has attributes

parameters_factory

tvb.basic.traits.parameters_factory.collapse_params(args, simple_select_list, parent='')[source]

In case of variables with similar names: (name_parameters_[option_xx]_paramKey) collapse then into dictionary of parameters. This is used after parameters POST, on Operation Launch.

tvb.basic.traits.parameters_factory.get_traited_instance_for_name(class_name, parent_class, params_dictionary)[source]
Parameters:
  • class_name – Short Traited Class name.
  • parent_class – Traited basic type expected (e.g. Model)
  • params_dictionary – dictionary of parameters to be passed to the constructor of the class.
Returns:

Class instantiated corresponding to the given name (e.g. FHN() )

tvb.basic.traits.parameters_factory.get_traited_subclasses(parent_class)[source]
Parameters:parent_class – SuperClass, to return valid sub-classes of this (e.g. Model).
Returns:{class_name: sub_class_instance} e.g. {‘WilsonCowan’: WilsonCowan, ....}
tvb.basic.traits.parameters_factory.try_parse(val)[source]

traited_interface

Generate Dictionary required by the Framework to generate UI from it. Returned dictionary will be generated from traited definition of attributes.

class tvb.basic.traits.traited_interface.TraitedInterfaceGenerator[source]

Bases: object

Bases class for interface reading and dumping. As a data descriptor, when it is an attribute of the class it will compute a dictionary and return it.

traited_interface2

Generate Dictionary required by the Framework to generate UI from it. Returned dictionary will be generated from traited definition of attributes.

class tvb.basic.traits.traited_interface2.TraitedInterfaceGeneratorExperimental[source]

Bases: object

types_basic

This module describes the simple of traited attributes one might needs on a class.

If your subclass should be mapped to a database table (true for most entities that will be reused), use MappedType as superclass.

If you subclass is supported natively by SQLAlchemy, subclass Type, otherwise subclass MappedType.

Important: - Type - traited, possible mapped to db col - MappedType - traited, mapped to db table

tvb.basic.traits.types_basic.Bool[source]

Traits type wrapping Python boolean primitive. The only instances of Python bool are True and False.

traits on this class:

tvb.basic.traits.types_basic.Complex[source]

Traits type that wraps Numpy’s complex64.

traits on this class:

tvb.basic.traits.types_basic.DType[source]

Traits type that wraps a Numpy dType specification.

traits on this class:

tvb.basic.traits.types_basic.Dict[source]

Traits type that wraps a python dict.

traits on this class:

tvb.basic.traits.types_basic.Enumerate[source]

Traits type that mimics an enumeration.

traits on this class:

tvb.basic.traits.types_basic.Float[source]

Traits type that wraps Numpy’s float64.

traits on this class:

tvb.basic.traits.types_basic.Integer[source]

Traits type that wraps Numpy’s int32.

traits on this class:

tvb.basic.traits.types_basic.JSONType[source]

Wrapper over a String which holds a serializable object. On set/get JSON load/dump will be called.

traits on this class:

tvb.basic.traits.types_basic.List[source]

Traits type that wraps a Python list.

traits on this class:

tvb.basic.traits.types_basic.MapAsJson[source]

Add functionality of converting from/to JSON

tvb.basic.traits.types_basic.Range[source]

Range is a range that can have multiplicative or additive step sizes. Values generated by Range are by default in the interval [start, stop). Different flags/modes can be set to include/exclude one or both bounds. See the corresponding unittest for more examples.

Instances of Range will not generate their discrete values automatically, but these values can be obtained by converting to a list

Multiplicative ranges are not yet supported by the web ui.

>>> range_values = list(Range(lo=0.0, hi=1.0, step=0.1))
[0.0,
0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

or by direct iteration:

>>> for val in Range(lo=0.0, hi=1.0, step=0.1):
        print val

0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

>>> for val in Range(lo=0.0, hi=2.0, step=1.0):
        print val
0.0
1.0
2.0
>>> for val in Range(lo=0.0, hi=3.0, step=1.0):
        print val
0.0
1.0
2.0
using a fixed multiplier
>>> for val in Range(lo=0.0, hi=5.0, base=2.0):
        print val
0.0
2.0
4.0
>>> for val in Range(lo=1.0, hi=8.O, base=2.0):
        print val
1.0
2.0
4.0

traits on this class:

base ()
fixed multiplier between elements
default: 2.0
hi ()
end of range
default: None
lo ()
start of range
default: 0
mode ()
default behaviour, equivalent to include lo, exclude hi
default: 1
step ()
fixed step size between elements (for additive). It has priority over “base”
default: None
tvb.basic.traits.types_basic.Sequence[source]

Traits type base class that wraps python sequence python types (containers)

traits on this class:

tvb.basic.traits.types_basic.Set[source]

Traits type that wraps a python set.

traits on this class:

tvb.basic.traits.types_basic.Slice[source]

Useful of for specifying views or slices of containers.

traits on this class:

tvb.basic.traits.types_basic.String[source]

Traits type that wraps a Python string.

traits on this class:

tvb.basic.traits.types_basic.Tuple[source]

Traits type that wraps a python tuple.

traits on this class:

tvb.basic.traits.types_basic.ValidationRange[source]

ValidationRange represents a Range used only for validating a number.

traits on this class:

types_mapped

Initialize MappedType base class, based on current environment: - when environment is stand-alone scientific library, use MappedTypeLight - when TVB-Framework is also present: use MappedType with SQL-Alchemy dependency.

types_mapped_light

Mapped super-classes are defined here.

Important:

  • Type - traited, possible mapped to db col
  • MappedType - traited, mapped to db table
tvb.basic.traits.types_mapped_light.Array[source]

Traits type that wraps a NumPy NDArray.

Initialization requires at least shape, and when not given, will be set to (), an empty, 0-dimension array.

traits on this class:

dtype ()

default: None
tvb.basic.traits.types_mapped_light.MappedTypeLight[source]

Light base class for all entities which are about to be mapped in storage. Current light implementation is to be used with the scientific-library stand-alone mode.

traits on this class:

tvb.basic.traits.types_mapped_light.SparseMatrix[source]

Map a big matrix. Will require storage in File Structure.

traits on this class:

dtype ()

default: None

util

All the little functions that make life nicer in the Traits package.

class tvb.basic.traits.util.Args

Bases: tuple

Args(pos, kwd)

kwd

Alias for field number 1

pos

Alias for field number 0

class tvb.basic.traits.util.TypeRegister[source]

Bases: list

TypeRegister is a smart list that can be queried to obtain selections of the classes inheriting from Traits classes.

subclasses(obj, avoid_subclasses=False)[source]

The subclasses method takes a class (or given instance object, will use the class of the instance), and returns a list of all options known to this TypeRegister that are direct subclasses of the class or have the class in their base class list. :param obj: Class or instance :param avoid_subclasses: When specified, subclasses are not retrieved, only current class.

tvb.basic.traits.util.get(obj, key, default=None)[source]

get() is a general function allowing us to ignore whether we are getting from a dictionary or object. If obj is a dictionary, we return the value corresponding to key, otherwise we return the attribute on obj corresponding to key. In both cases, if key does not exist, default is returned.

tvb.basic.traits.util.ispublic(key)
tvb.basic.traits.util.log_debug_array(log, array, array_name, owner='')[source]

Simple access to debugging info on an array.

tvb.basic.traits.util.multiline_math_directives_to_matjax(doc)[source]

Looks for multi-line sphinx math directives in the given rst string It converts them in html text that will be interpreted by mathjax The parsing is simplistic, not a rst parser. Wraps .. math :: body in [egin{split}end{split}]

tvb.basic.traits.util.str_class_name(thing, short_form=False)[source]

A helper function that tries to generate an informative name for its argument: when passed a class, return its name, when passed an object return a string representation of that value.