3
®?d]–¨  ã               @   s  d Z yddlZW n ek
r,   edƒ‚Y nX ddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlZejdk r�ejZneZd	d
„ ZG dd„ dƒZG dd„ deƒZd<dd„Zd=dd„Zdd„ Zdd„ ZG dd„ deƒZeeƒG dd„ dejƒƒZG dd„ deƒZeeƒG dd„ deƒƒZ e ƒ Z!G d d!„ d!eƒZ"ee"ƒG d"d#„ d#eƒƒZ#G d$d%„ d%eƒZ$G d&d'„ d'ƒZ%G d(d)„ d)eƒZ&G d*d+„ d+e&ƒZ'G d,d-„ d-eƒZ(G d.d/„ d/e(ƒZ)G d0d1„ d1e(ƒZ*G d2d3„ d3e(ƒZ+G d4d5„ d5e+ƒZ,G d6d7„ d7e,ƒZ-G d8d9„ d9e,ƒZ.d:d;„ Z/dS )>aé  This module provides classes that allow Numpy-type access
to VTK datasets and arrays. This is best described with some examples.

To normalize a VTK array:

import vtk
import vtk.numpy_interface.dataset_adapter as dsa
import vtk.numpy_interface.algorithms as algs

rt = vtk.vtkRTAnalyticSource()
rt.Update()
image = dsa.WrapDataObject(rt.GetOutput())
rtdata = image.PointData['RTData']
rtmin = algs.min(rtdata)
rtmax = algs.max(rtdata)
rtnorm = (rtdata - rtmin) / (rtmax - rtmin)
image.PointData.append(rtnorm, 'RTData - normalized')
print image.GetPointData().GetArray('RTData - normalized').GetRange()

To calculate gradient:

grad= algs.gradient(rtnorm)

To access subsets:

>>> grad[0:10]
VTKArray([[ 0.10729134,  0.03763443,  0.03136338],
       [ 0.02754352,  0.03886006,  0.032589  ],
       [ 0.02248248,  0.04127144,  0.03500038],
       [ 0.02678365,  0.04357527,  0.03730421],
       [ 0.01765099,  0.04571581,  0.03944477],
       [ 0.02344007,  0.04763837,  0.04136734],
       [ 0.01089381,  0.04929155,  0.04302051],
       [ 0.01769151,  0.05062952,  0.04435848],
       [ 0.002764  ,  0.05161414,  0.04534309],
       [ 0.01010841,  0.05221677,  0.04594573]])

>>> grad[:, 0]
VTKArray([ 0.10729134,  0.02754352,  0.02248248, ..., -0.02748174,
       -0.02410045,  0.05509736])

All of this functionality is also supported for composite datasets
even though their data arrays may be spread across multiple datasets.
We have implemented a VTKCompositeDataArray class that handles many
Numpy style operators and is supported by all algorithms in the
algorithms module.

This module also provides an API to access composite datasets.
For example:

mb = vtk.vtkMultiBlockDataSet()
mb.SetBlock(0, image.VTKObject)
mb.SetBlock(1e, image.VTKObject)
cds = dsa.WrapDataObject(mb)
for block in cds:
    print block

Note that this module implements only the wrappers for datasets
and arrays. The classes implement many useful operators. However,
to make best use of these classes, take a look at the algorithms
module.
é    NzWThis module depends on the numpy module. Please makesure that it is installed properly.)Úbuffer_shared)Únumpy_support)ÚvtkDataObject)ÚvtkWeakReferencei   c             C   s´   | |g}t | tjƒr°t |tjƒr°t| jƒ}t|jƒ}||ks`|dks`|dks`| jd |jd krd|S ||k rz|}|}d}n|}|}d}x(||k r®tj|| |ƒ||< |d }qˆW |S )ae  Returns a list with the two arguments, any of them may be
    processed.  If the arguments are numpy.ndarrays, append 1s to the
    shape of the array with the smallest number of dimensions until
    the arrays have the same number of dimensions. Does nothing if the
    arguments are not ndarrays or the arrays have the same number of
    dimensions.

    r   é   )Ú
isinstanceÚnumpyÚndarrayÚlenÚshapeZexpand_dims)Úa1Úa2ÚlZlen1Zlen2ÚdZ	maxLengthÚi© r   úB/tmp/pip-build-op5p2y5_/vtk/vtk/numpy_interface/dataset_adapter.pyÚreshape_append_onesS   s$    	


r   c               @   s(   e Zd ZdZejZejZejZejZdS )ÚArrayAssociationz+Easy access to vtkDataObject.AttributeTypesN)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚPOINTÚCELLÚFIELDÚROWr   r   r   r   r   p   s
   r   c               @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚVTKObjectWrapperzÞSuperclass for classes that wrap VTK objects with Python objects.
    This class holds a reference to the wrapped VTK object. It also
    forwards unresolved methods to the underlying object by overloading
    __get__attr.c             C   s
   || _ d S )N)Ú	VTKObject)ÚselfÚ	vtkobjectr   r   r   Ú__init__|   s    zVTKObjectWrapper.__init__c             C   s   t | j|ƒS )z2Forwards unknown attribute requests to VTK object.)Úgetattrr   )r   Únamer   r   r   Ú__getattr__   s    zVTKObjectWrapper.__getattr__N)r   r   r   r   r!   r$   r   r   r   r   r   w   s   r   c             C   sT   t j| ƒ}|j}t|ƒdkrF|d dkrF|j|d ddfƒjdddƒ}t|| |d�S )zAGiven a vtkDataArray and a dataset owning it, returns a VTKArray.é   r   é	   r   é   )ÚarrayÚdataset)r   Zvtk_to_numpyr   r
   ÚreshapeÚ	transposeÚVTKArray)r(   r)   Únarrayr   r   r   r   ÚvtkDataArrayToVTKArrayƒ   s
    
r.   Únumpy_arrayc             C   s   t j| |d�}|j|ƒ |S )zØGiven a numpy array or a VTKArray and a name, returns a vtkDataArray.
    The resulting vtkDataArray will store a reference to the numpy array:
    the numpy array is released only when the vtkDataArray is destroyed.)Ú
array_type)r   Znumpy_to_vtkZSetName)r(   r#   r0   Úvtkarrayr   r   r   ÚnumpyTovtkDataArray�   s    
r2   c             C   sn   | d krd S | j jr| S tj| ƒ} | jj}| j}t|ƒdkrj|d | dkrj|d | dkrj| jdddƒS | S )Nr'   r   r%   r   )	ÚflagsÚ
contiguousr   ÚasarrayÚdtypeÚitemsizeÚstridesr
   r+   )r(   Úsizer8   r   r   r   Ú_make_tensor_array_contiguous—   s    
,r:   c                s   ‡ fdd„}|S )z0For compatibility between python 2 and python 3.c                s4   t | ƒjƒ }|jdd ƒ |jdd ƒ ˆ | j| j|ƒS )NÚ__dict__Ú__weakref__)ÚvarsÚcopyÚpopr   Ú	__bases__)ÚclsÚbody)Úmcsr   r   Ú	decorator¥   s    z_metaclass.<locals>.decoratorr   )rC   rD   r   )rC   r   Ú
_metaclass£   s    rE   c               @   s   e Zd Zdd„ ZdS )ÚVTKArrayMetaClassc                sð   ‡fdd„‰‡fdd„‰ ‡fdd„‰‡fdd„‰‡ ‡fd	d
„}|dƒ |dƒ |dƒ t jdk rh|dƒ |dƒ |dƒ |dƒ |dƒ |dƒ |dƒ ˆdƒ |dƒ ˆdƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ tj| ||ˆƒS )a²  We overwrite numerical/comparison operators because we might need
        to reshape one of the arrays to perform the operation without
        broadcast errors. For instace:

        An array G of shape (n,3) resulted from computing the
        gradient on a scalar array S of shape (n,) cannot be added together without
        reshaping.
        G + expand_dims(S,1) works,
        G + S gives an error:
        ValueError: operands could not be broadcast together with shapes (n,3) (n,)

        This metaclass overwrites operators such that it computes this
        reshape operation automatically by appending 1s to the
        dimensions of the array with fewer dimensions.

        c                s   ‡ fdd„}ˆ |_ |ˆˆ < dS )zXCreate an attribute named attr_name that calls
            _numeric_op(self, other, op).c                s   t j| |ˆ ƒS )N)r,   Ú_numeric_op)r   Úother)Ú	attr_namer   r   ÚclosureÁ   s    zBVTKArrayMetaClass.__new__.<locals>.add_numeric_op.<locals>.closureN)r   )rI   rJ   )Úattr)rI   r   Úadd_numeric_op¾   s    z1VTKArrayMetaClass.__new__.<locals>.add_numeric_opc                s   ˆ d|  ƒ dS )z;Adds '__[op_name]__' attribute that uses operator.[op_name]z__%s__Nr   )Úop_name)rL   r   r   Úadd_default_numeric_opÆ   s    z9VTKArrayMetaClass.__new__.<locals>.add_default_numeric_opc                s   ‡ fdd„}ˆ |_ |ˆˆ < dS )z`Create an attribute named attr_name that calls
            _reverse_numeric_op(self, other, op).c                s   t j| |ˆ ƒS )N)r,   Ú_reverse_numeric_op)r   rH   )rI   r   r   rJ   Í   s    zJVTKArrayMetaClass.__new__.<locals>.add_reverse_numeric_op.<locals>.closureN)r   )rI   rJ   )rK   )rI   r   Úadd_reverse_numeric_opÊ   s    z9VTKArrayMetaClass.__new__.<locals>.add_reverse_numeric_opc                s   ˆ d|  ƒ dS )z<Adds '__r[op_name]__' attribute that uses operator.[op_name]z__r%s__Nr   )rM   )rP   r   r   Úadd_default_reverse_numeric_opÒ   s    zAVTKArrayMetaClass.__new__.<locals>.add_default_reverse_numeric_opc                s   ˆ | ƒ ˆ| ƒ dS )zDCall both add_default_numeric_op and add_default_reverse_numeric_op.Nr   )rM   )rN   rQ   r   r   Úadd_default_numeric_opsÖ   s    z:VTKArrayMetaClass.__new__.<locals>.add_default_numeric_opsÚaddÚsubÚmuli   ÚdivÚtruedivÚfloordivÚmodÚpowÚlshiftÚrshiftÚandÚxorÚorÚltÚleÚeqÚneÚgeÚgt)ÚsysÚ
hexversionÚtypeÚ__new__)rC   r#   ÚparentrK   rR   r   )rN   rQ   rL   rP   rK   r   ri   ­   s4    
zVTKArrayMetaClass.__new__N)r   r   r   ri   r   r   r   r   rF   ¬   s   rF   c               @   s^   e Zd ZdZdd„ Zdd„ Zddd„Zd	d
„ Zdd„ Zddd„Z	e
dd„ ƒZejdd„ ƒZdS )r,   z¾This is a sub-class of numpy ndarray that stores a
    reference to a vtk array as well as the owning dataset.
    The numpy array and vtk array should point to the same
    memory location.c             C   s$   t | |ƒ}ttj|ƒ|d |d ƒS )zYUsed to implement numpy-style numerical operations such as __add__,
        __mul__, etc.r   r   )r   r"   r   r	   )r   rH   rI   r   r   r   r   rG   ù   s    
zVTKArray._numeric_opc             C   s$   t | |ƒ}ttj|ƒ|d |d ƒS )zYUsed to implement numpy-style numerical operations such as __add__,
        __mul__, etc.r   r   )r   r"   r   r	   )r   rH   rI   r   r   r   r   rO   ÿ   s    
zVTKArray._reverse_numeric_opNc             C   s<   t j|ƒj| ƒ}tj|_||_|r8tƒ |_|jj	|jƒ |S )N)
r   r5   Úviewr   r   ÚAssociationr   r   Ú_datasetÚSet)rA   Zinput_arrayr(   r)   Úobjr   r   r   ri     s    zVTKArray.__new__c             C   sh   t | ƒ}t |ƒ}d | _yt||ƒr0t|dd ƒ| _W n tk
rF   Y nX t|dd ƒ| _t|dd ƒ| _d S )Nr   rl   ÚDataSet)r:   r   r   r"   Ú	TypeErrorrl   rp   )r   ro   ZslfÚobj2r   r   r   Ú__array_finalize__  s    
zVTKArray.__array_finalize__c             C   sN   y| j d }W n tk
r&   d}Y nX |dkrDtd| jj|f ƒ‚t||ƒS )z1Forwards unknown attribute requests to VTK array.r   Nz!'%s' object has no attribute '%s')r;   ÚKeyErrorÚAttributeErrorÚ	__class__r   r"   )r   r#   Úor   r   r   r$   #  s    
zVTKArray.__getattr__c             C   s&   |j f kr|f  S tjj| ||ƒS d S )N)r   r   r	   Ú__array_wrap__)r   Zout_arrÚcontextr   r   r   rx   .  s    
zVTKArray.__array_wrap__c             C   s,   t | dƒr(| jr(| jjƒ r(t| jjƒ ƒS dS )zÜ
        Get the dataset this array is associated with. The reference to the
        dataset is held through a vtkWeakReference to ensure it doesn't prevent
        the dataset from being collected if necessary.
        rm   N)Úhasattrrm   ZGetÚWrapDataObject)r   r   r   r   rp   5  s    zVTKArray.DataSetc             C   sB   |r8|j r8t| dƒ s | jdkr(tƒ | _| jj|j ƒ nd| _dS )zz
        Set the dataset this array is associated with. The reference is held
        through a vtkWeakReference.
        rm   N)r   rz   rm   r   rn   )r   r)   r   r   r   rp   A  s
    
)NN)N)r   r   r   r   rG   rO   ri   rs   r$   rx   Úpropertyrp   Úsetterr   r   r   r   r,   ò   s   

r,   c               @   s   e Zd Zdd„ ZdS )ÚVTKNoneArrayMetaClassc                s  ‡fdd„‰‡fdd„‰‡fdd„‰ ‡ ‡fdd„}|d	ƒ |d
ƒ |dƒ t jdk r\|dƒ |dƒ |dƒ |dƒ |dƒ |dƒ |dƒ ˆdtjƒ ˆdtjƒ |dƒ ˆdtjƒ ˆdtjƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ tj| ||ˆƒS )z@Simplify the implementation of the numeric/logical sequence API.c                s   ‡ fdd„}| |_ |ˆ| < dS )zXCreate an attribute named attr_name that calls
            _numeric_op(self, other, op).c                s   t j| |ˆ ƒS )N)ÚVTKNoneArrayÚ_op)r   rH   )Úopr   r   rJ   W  s    z?VTKNoneArrayMetaClass.__new__.<locals>._add_op.<locals>.closureN)r   )rI   r�   rJ   )rK   )r�   r   Ú_add_opT  s    z.VTKNoneArrayMetaClass.__new__.<locals>._add_opc                s   ˆ d|  t t| ƒƒ dS )z<Adds '__r[op_name]__' attribute that uses operator.[op_name]z__r%s__N)r"   Úoperator)rM   )r‚   r   r   Ú_add_default_reverse_op\  s    z>VTKNoneArrayMetaClass.__new__.<locals>._add_default_reverse_opc                s   ˆ d|  t t| ƒƒ dS )z;Adds '__[op_name]__' attribute that uses operator.[op_name]z__%s__N)r"   rƒ   )rM   )r‚   r   r   Ú_add_default_op`  s    z6VTKNoneArrayMetaClass.__new__.<locals>._add_default_opc                s   ˆ | ƒ ˆ| ƒ dS )zDCall both add_default_numeric_op and add_default_reverse_numeric_op.Nr   )rM   )r…   r„   r   r   Ú_add_default_opsd  s    z7VTKNoneArrayMetaClass.__new__.<locals>._add_default_opsrS   rT   rU   i   rV   rW   rX   rY   rZ   r[   r\   Ú__and__Ú__rand__r^   Ú__or__Ú__ror__r`   ra   rb   rc   rd   re   )rf   rg   rƒ   Úand_Úor_rh   ri   )rC   r#   rj   rK   r†   r   )r…   r„   r‚   rK   r   ri   R  s6    
zVTKNoneArrayMetaClass.__new__N)r   r   r   ri   r   r   r   r   r~   Q  s   r~   c               @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	r   aÂ  VTKNoneArray is used to represent a "void" array. An instance
    of this class (NoneArray) is returned instead of None when an
    array that doesn't exist in a DataSetAttributes is requested.
    All operations on the NoneArray return NoneArray. The main reason
    for this is to support operations in parallel where one of the
    processes may be working on an empty dataset. In such cases,
    the process is still expected to evaluate a whole expression because
    some of the functions may perform bulk MPI communication. None
    cannot be used in these instances because it cannot properly override
    operators such as __add__, __sub__ etc. This is the main raison
    d'etre for VTKNoneArray.c             C   s   t S )N)Ú	NoneArray)r   Úindexr   r   r   Ú__getitem__�  s    zVTKNoneArray.__getitem__c             C   s   t S )zYUsed to implement numpy-style numerical operations such as __add__,
        __mul__, etc.)r�   )r   rH   r�   r   r   r   r€   “  s    zVTKNoneArray._opc             C   s   t S )z'Implements numpy array's astype method.)r�   )r   r6   r   r   r   Úastype˜  s    zVTKNoneArray.astypeN)r   r   r   r   r�   r€   r�   r   r   r   r   r   ‚  s   r   c               @   s   e Zd Zdd„ ZdS )ÚVTKCompositeDataArrayMetaClassc                s  ‡fdd„‰‡fdd„‰‡fdd„‰‡fdd„‰ ‡ ‡fd	d
„}|dƒ |dƒ |dƒ t jdk rh|dƒ |dƒ |dƒ |dƒ |dƒ |dƒ |dƒ ˆdtjƒ ˆdtjƒ |dƒ ˆdtjƒ ˆdtjƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ dƒ ˆ d ƒ tj| ||ˆƒS )!z@Simplify the implementation of the numeric/logical sequence API.c                s   ‡ fdd„}| |_ |ˆ| < dS )zXCreate an attribute named attr_name that calls
            _numeric_op(self, other, op).c                s   t j| |ˆ ƒS )N)ÚVTKCompositeDataArrayrG   )r   rH   )r�   r   r   rJ   ¤  s    zOVTKCompositeDataArrayMetaClass.__new__.<locals>.add_numeric_op.<locals>.closureN)r   )rI   r�   rJ   )rK   )r�   r   rL   ¡  s    z>VTKCompositeDataArrayMetaClass.__new__.<locals>.add_numeric_opc                s   ‡ fdd„}| |_ |ˆ| < dS )z`Create an attribute named attr_name that calls
            _reverse_numeric_op(self, other, op).c                s   t j| |ˆ ƒS )N)r’   rO   )r   rH   )r�   r   r   rJ   ¬  s    zWVTKCompositeDataArrayMetaClass.__new__.<locals>.add_reverse_numeric_op.<locals>.closureN)r   )rI   r�   rJ   )rK   )r�   r   rP   ©  s    zFVTKCompositeDataArrayMetaClass.__new__.<locals>.add_reverse_numeric_opc                s   ˆ d|  t t| ƒƒ dS )z<Adds '__r[op_name]__' attribute that uses operator.[op_name]z__r%s__N)r"   rƒ   )rM   )rP   r   r   rQ   ±  s    zNVTKCompositeDataArrayMetaClass.__new__.<locals>.add_default_reverse_numeric_opc                s   ˆ d|  t t| ƒƒ dS )z;Adds '__[op_name]__' attribute that uses operator.[op_name]z__%s__N)r"   rƒ   )rM   )rL   r   r   rN   µ  s    zFVTKCompositeDataArrayMetaClass.__new__.<locals>.add_default_numeric_opc                s   ˆ | ƒ ˆ| ƒ dS )zDCall both add_default_numeric_op and add_default_reverse_numeric_op.Nr   )rM   )rN   rQ   r   r   rR   ¹  s    zGVTKCompositeDataArrayMetaClass.__new__.<locals>.add_default_numeric_opsrS   rT   rU   i   rV   rW   rX   rY   rZ   r[   r\   r‡   rˆ   r^   r‰   rŠ   r`   ra   rb   rc   rd   re   )rf   rg   rƒ   r‹   rŒ   rh   ri   )rC   r#   rj   rK   rR   r   )rN   rQ   rL   rP   rK   r   ri   Ÿ  s8    
z&VTKCompositeDataArrayMetaClass.__new__N)r   r   r   ri   r   r   r   r   r‘   ž  s   r‘   c               @   sr   e Zd ZdZg dddfdd„Zdd„ Zdd„ ZeeƒZd	d
„ Z	ee	ƒZ
dd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )r’   ad  This class manages a set of arrays of the same name contained
    within a composite dataset. Its main purpose is to provide a
    Numpy-type interface to composite data arrays which are naturally
    nothing but a collection of vtkDataArrays. A VTKCompositeDataArray
    makes such a collection appear as a single Numpy array and support
    all array operations that this module and the associated algorithm
    module support. Note that this is not a subclass of a Numpy array
    and as such cannot be passed to native Numpy functions. Instead
    VTK modules should be used to process composite arrays.
    Nc             C   s|   || _ || _|| _d}|dkr^x>| j D ]4}t|dƒr&|dkrD|j}q&|jr&||jkr&d}P q&W |rj|| _ntj| _d| _dS )añ  Construct a composite array given a container of
        arrays, a dataset, name and association. It is sufficient
        to define a container of arrays to define a composite array.
        It is also possible to initialize an array by defining
        the dataset, name and array association. In that case,
        the underlying arrays will be created lazily when they
        are needed. It is recommended to use the latter method
        when initializing from an existing composite dataset.TNrl   F)Ú_Arraysrp   ÚNamerz   rl   r   r   ÚInitialized)r   Zarraysr)   r#   ÚassociationZvalidAssociationr(   r   r   r   r!   ä  s     

zVTKCompositeDataArray.__init__c             C   s\   | j r
d S d| _ | jd ks$| jd kr(d S g | _x(| jD ]}| jj|j| jƒ| j ƒ q6W d S )NT)r•   rp   r”   r“   ÚappendÚGetAttributesrl   )r   Údsr   r   r   Z__init_from_composite   s    z+VTKCompositeDataArray.__init_from_compositec             C   sJ   | j ƒ  tjdƒ}x2| jD ](}y||j7 }W q tk
r@   Y qX qW |S )z,Returns the number of elements in the array.r   )Ú+_VTKCompositeDataArray__init_from_compositer   Zint64r“   r9   ru   )r   r9   Úar   r   r   ÚGetSize  s    

zVTKCompositeDataArray.GetSizec             C   s   | j ƒ  | jS )z~Returns the internal container of VTKArrays. If necessary,
        this will populate the array list from a composite dataset.)rš   r“   )r   r   r   r   Ú	GetArrays  s    zVTKCompositeDataArray.GetArraysc             C   sœ   | j ƒ  g }t|ƒtkrZxtt| j|jƒD ],\}}|tk	rJ|j|j|ƒƒ q(|jtƒ q(W n4x2| jD ](}|tk	r€|j|j|ƒƒ qb|jtƒ qbW t|| j	d�S )aC  Overwritten to refer indexing to underlying VTKArrays.
        For the most part, this will behave like Numpy. Note
        that indexing is done per array - arrays are never treated
        as forming a bigger array. If the index is another composite
        array, a one-to-one mapping between arrays is assumed.
        )r)   )
rš   rh   r’   Úizipr“   ÚArraysr�   r—   r�   rp   )r   rŽ   Úresr›   Úidxr   r   r   r�   "  s    z!VTKCompositeDataArray.__getitem__c             C   sÌ   | j ƒ  g }t|ƒtkrtx t| j|jƒD ]F\}}|tk	rd|tk	rdt||ƒ}|j||d |d ƒƒ q(|jtƒ q(W nFxD| jD ]:}|tk	r¬t||ƒ}|j||d |d ƒƒ q||jtƒ q|W t|| j	| j
d�S )zYUsed to implement numpy-style numerical operations such as __add__,
        __mul__, etc.r   r   )r)   r–   )rš   rh   r’   rž   r“   rŸ   r�   r   r—   rp   rl   )r   rH   r�   r    r   r   r   r›   r   r   r   rG   9  s    

z!VTKCompositeDataArray._numeric_opc             C   sÌ   | j ƒ  g }t|ƒtkrtx t| j|jƒD ]F\}}|tk	rd|tkrdt||ƒ}|j	||d |d ƒƒ q(|j	tƒ q(W nFxD| jD ]:}|tk	r¬t||ƒ}|j	||d |d ƒƒ q||j	tƒ q|W t|| j
| jd�S )zYUsed to implement numpy-style numerical operations such as __add__,
        __mul__, etc.r   r   )r)   r–   )rš   rh   r’   rž   r“   rŸ   r�   ZnotNoneArrayr   r—   rp   rl   )r   rH   r�   r    r   r   r   r›   r   r   r   rO   O  s    

z)VTKCompositeDataArray._reverse_numeric_opc             C   s
   | j jƒ S )N)rŸ   Ú__str__)r   r   r   r   r¢   e  s    zVTKCompositeDataArray.__str__c             C   sR   g }| t k	r@x2| jD ](}|t kr,|jt ƒ q|j|j|ƒƒ qW t|| j| jd�S )z)Implements numpy array's as array method.)r)   r–   )r�   rŸ   r—   r�   r’   rp   rl   )r   r6   r    r›   r   r   r   r�   h  s    zVTKCompositeDataArray.astype)r   r   r   r   r!   rš   rœ   r|   r9   r�   rŸ   r�   rG   rO   r¢   r�   r   r   r   r   r’   ×  s   r’   c                   sP   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
‡  ZS )ÚDataSetAttributeszThis is a python friendly wrapper of vtkDataSetAttributes. It
    returns VTKArrays. It also provides the dictionary interface.c                s    t t| ƒj|ƒ || _|| _d S )N)Úsuperr£   r!   rp   rl   )r   r    r)   r–   )rv   r   r   r!   y  s    zDataSetAttributes.__init__c             C   s
   | j |ƒS )z;Implements the [] operator. Accepts an array name or index.)ÚGetArray)r   r¡   r   r   r   r�   €  s    zDataSetAttributes.__getitem__c             C   s`   t |tƒr || jjƒ kr tdƒ‚| jj|ƒ}|sH| jj|ƒ}|rD|S tS t|| j	ƒ}| j
|_
|S )z+Given an index or name, returns a VTKArray.zarray index out of range)r   Úintr   ÚGetNumberOfArraysÚ
IndexErrorr¥   ÚGetAbstractArrayr�   r.   rp   rl   )r   r¡   r1   r(   r   r   r   r¥   „  s    zDataSetAttributes.GetArrayc             C   sB   g }| j jƒ }x.t|ƒD ]"}| j j|ƒjƒ }|r|j|ƒ qW |S )z*Returns the names of the arrays as a list.)r   r§   Úranger©   ÚGetNamer—   )r   ZkysÚnarraysr   r#   r   r   r   Úkeys’  s    
zDataSetAttributes.keysc             C   sB   g }| j jƒ }x.t|ƒD ]"}| j j|ƒ}|jƒ r|j|ƒ qW |S )zReturns the arrays as a list.)r   r§   rª   r©   r«   r—   )r   Úvalsr¬   r   r›   r   r   r   Úvaluesœ  s    
zDataSetAttributes.valuesc             C   s8   y| j j|ƒ W n" tk
r2   | j j|j ƒ Y nX dS )z"A wrapper for vtkDataSet.PassData.N)r   ÚPassDatarq   )r   rH   r   r   r   r°   ¦  s    zDataSetAttributes.PassDatac             C   sä  |t krdS | jtjkr$| jjƒ }n4| jtjkr<| jjƒ }nt|t	j
ƒsNd}n
|jd }t|t	j
ƒ stt	j|ƒdkrŽt	j|ƒ}|j|ƒ |}nL|jd |krÚd}x|jD ]}||9 }q¨W t	j||fƒ}|jƒ |dd…< |}|j}t|ƒdk�r`|jj}|jd | dk�r|jd | dk�sR|jd | dk�r`|jd | dk�r`|jj �r`|jdddƒ}|jj�stt	j|ƒ}t|ƒdk�rž|j|d |d |d  ƒ}t|ƒ}	y|j|	_W n tk
�rÈ   Y nX t|	|ƒ}
| jj|
ƒ dS )z.Appends a new array to the dataset attributes.Nr   r   r'   r%   )r�   rl   r   r   rp   ÚGetNumberOfPointsr   ÚGetNumberOfCellsr   r   r	   r   ÚndimÚemptyÚfillÚflattenr
   r6   r7   r8   r3   r4   r+   Zascontiguousarrayr*   r,   r   ru   r2   ZAddArray)r   r-   r#   Z	arrLengthZtmparrayÚ
componentsr   r   r9   r>   Zarrr   r   r   r—   ­  sL    


((

 
zDataSetAttributes.append)r   r   r   r   r!   r�   r¥   r­   r¯   r°   r—   Ú__classcell__r   r   )rv   r   r£   u  s   

r£   c               @   sH   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dS )ÚCompositeDataSetAttributesam  This is a python friendly wrapper for vtkDataSetAttributes for composite
    datsets. Since composite datasets themselves don't have attribute data, but
    the attribute data is associated with the leaf nodes in the composite
    dataset, this class simulates a DataSetAttributes interface by taking a
    union of DataSetAttributes associated with all leaf nodes.c             C   s$   || _ || _g | _i | _| jƒ  d S )N)rp   rl   Ú
ArrayNamesrŸ   Ú1_CompositeDataSetAttributes__determine_arraynames)r   r)   r–   r   r   r   r!   ò  s
    z#CompositeDataSetAttributes.__init__c             C   s^   t ƒ }g }xH| jD ]>}|j| jƒ}x,|jƒ D ] }||kr,|j|ƒ |j|ƒ q,W qW || _d S )N)Úsetrp   r˜   rl   r­   rS   r—   rº   )r   Z	array_setZ
array_listr)   ZdsaZ
array_namer   r   r   Z__determine_arraynamesÿ  s    
z1CompositeDataSetAttributes.__determine_arraynamesc             C   s   | j S )z*Returns the names of the arrays as a list.)rº   )r   r   r   r   r­   
  s    zCompositeDataSetAttributes.keysc             C   s
   | j |ƒS )z2Implements the [] operator. Accepts an array name.)r¥   )r   r¡   r   r   r   r�     s    z&CompositeDataSetAttributes.__getitem__c             C   s´   |t krdS d}t|tƒsTx&| jD ]}|j| jƒj||ƒ d}q"W |r°| jj|ƒ n\x:t| j|j	ƒD ](\}}|dk	rd|j| jƒj||ƒ d}qdW |r°| jj|ƒ t
j|ƒ| j	|< dS )z8Appends a new array to the composite dataset attributes.NFT)r�   r   r’   rp   r˜   rl   r—   rº   rž   rŸ   ÚweakrefÚref)r   r-   r#   Úaddedr™   r(   r   r   r   r—     s     
z!CompositeDataSetAttributes.appendc             C   s`   |}|| j krtS || jks,| j| ƒ dkrPt| j|| jd�}tj|ƒ| j|< n| j| ƒ }|S )z*Given a name, returns a VTKCompositeArray.N)r)   r#   r–   )rº   r�   rŸ   r’   rp   rl   r½   r¾   )r   r¡   Z	arraynamer(   r   r   r   r¥   *  s    
z#CompositeDataSetAttributes.GetArrayc             C   sL   xFt | j|jƒD ]4\}}x*tjtjgD ]}|j|ƒj|j|ƒƒ q&W qW dS )z(Emulate PassData for composite datasets.N)Úziprp   r   r   r   r˜   r°   )r   rH   ÚthisÚthatÚassocr   r   r   r°   7  s    z#CompositeDataSetAttributes.PassDataN)r   r   r   r   r!   r»   r­   r�   r—   r¥   r°   r   r   r   r   r¹   ë  s   r¹   c               @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )ÚCompositeDataIteratorzøWrapper for a vtkCompositeDataIterator class to satisfy
       the python iterator protocol. This iterator iterates
       over non-empty leaf nodes. To iterate over empty or
       non-leaf nodes, use the vtkCompositeDataIterator directly.
       c             C   s*   |j ƒ | _| jr&| jjd ƒ | jjƒ  d S )N)ZNewIteratorÚIteratorZ
UnRegisterZGoToFirstItem)r   Úcdsr   r   r   r!   D  s    
zCompositeDataIterator.__init__c             C   s   | S )Nr   )r   r   r   r   Ú__iter__J  s    zCompositeDataIterator.__iter__c             C   s4   | j s
t‚| j jƒ rt‚| j jƒ }| j jƒ  t|ƒS )N)rÅ   ÚStopIterationÚIsDoneWithTraversalÚGetCurrentDataObjectÚGoToNextItemr{   )r   ÚretValr   r   r   Ú__next__M  s    


zCompositeDataIterator.__next__c             C   s   | j ƒ S )N)rÍ   )r   r   r   r   ÚnextW  s    zCompositeDataIterator.nextc             C   s   t | j|ƒS )z5Returns attributes from the vtkCompositeDataIterator.)r"   rÅ   )r   r#   r   r   r   r$   Z  s    z!CompositeDataIterator.__getattr__N)	r   r   r   r   r!   rÇ   rÍ   rÎ   r$   r   r   r   r   rÄ   =  s   
rÄ   c               @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚMultiCompositeDataIteratorad  Iterator that can be used to iterate over multiple
    composite datasets together. This iterator works only
    with arrays that were copied from an original using
    CopyStructured. The most common use case is to use
    CopyStructure, then iterate over input and output together
    while creating output datasets from corresponding input
    datasets.c             C   s   t j| |d ƒ || _d S )Nr   )rÄ   r!   ÚDatasets)r   rÆ   r   r   r   r!   f  s    z#MultiCompositeDataIterator.__init__c             C   sz   | j s
t‚| j jƒ rt‚g }|jt| j jƒ ƒƒ t| jƒdkrlx,| jdd … D ]}|jt|j| j ƒƒƒ qNW | j j	ƒ  |S )Nr   )
rÅ   rÈ   rÉ   r—   r{   rÊ   r
   rÐ   Z
GetDataSetrË   )r   rÌ   Zcdr   r   r   rÍ   j  s    

z#MultiCompositeDataIterator.__next__c             C   s   | j ƒ S )N)rÍ   )r   r   r   r   rÎ   x  s    zMultiCompositeDataIterator.nextN)r   r   r   r   r!   rÍ   rÎ   r   r   r   r   rÏ   ^  s   rÏ   c               @   s.   e Zd ZdZdd„ Zdd„ ZeedddƒZdS )Ú
DataObjectz`A wrapper for vtkDataObject that makes it easier to access FielData
    arrays as VTKArrays
    c             C   s0   |t jkrt| jjƒ | |ƒS t| jj|ƒ| |ƒS )zVReturns the attributes specified by the type as a DataSetAttributes
         instance.)r   r   r£   r   ÚGetFieldDatar˜   )r   rh   r   r   r   r˜   €  s    
zDataObject.GetAttributesc             C   s   t | jjƒ | tjƒS )z7Returns the field data as a DataSetAttributes instance.)r£   r   rÒ   r   r   )r   r   r   r   rÒ   ‡  s    zDataObject.GetFieldDataNz6This property returns the field data of a data object.)r   r   r   r   r˜   rÒ   r|   Ú	FieldDatar   r   r   r   rÑ   {  s   rÑ   c               @   s&   e Zd ZdZdd„ ZeedddƒZdS )ÚTablez\A wrapper for vtkFielData that makes it easier to access RowData array as
    VTKArrays
    c             C   s   | j tjƒS )z5Returns the row data as a DataSetAttributes instance.)r˜   r   r   )r   r   r   r   Ú
GetRowData‘  s    zTable.GetRowDataNz0This property returns the row data of the table.)r   r   r   r   rÕ   r|   ZRowDatar   r   r   r   rÔ   �  s   rÔ   c               @   s˜   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zee
dddƒZeedddƒZeedddƒZeedddƒZdS )ÚCompositeDataSetz®A wrapper for vtkCompositeData and subclasses that makes it easier
    to access Point/Cell/Field data as VTKCompositeDataArrays. It also
    provides a Python type iterator.c             C   s(   t j| |ƒ d | _d | _d | _d | _d S )N)rÑ   r!   Ú
_PointDataÚ	_CellDataÚ
_FieldDataÚ_Points)r   r    r   r   r   r!   œ  s
    zCompositeDataSet.__init__c             C   s   t | ƒS )z/Creates an iterator for the contained datasets.)rÄ   )r   r   r   r   rÇ   £  s    zCompositeDataSet.__iter__c             C   s(   d}x| D ]}||j |ƒ7 }q
W t|ƒS )z™Returns the total number of cells or points depending
        on the value of assoc which can be ArrayAssociation.POINT or
        ArrayAssociation.CELL.r   )ÚGetNumberOfElementsr¦   )r   rÃ   Úresultr)   r   r   r   rÛ   §  s    
z$CompositeDataSet.GetNumberOfElementsc             C   s   | j tjƒS )zæReturns the total number of points of all datasets
        in the composite dataset. Note that this traverses the
        whole composite dataset every time and should not be
        called repeatedly for large composite datasets.)rÛ   r   r   )r   r   r   r   r±   °  s    z"CompositeDataSet.GetNumberOfPointsc             C   s   | j tjƒS )zåReturns the total number of cells of all datasets
        in the composite dataset. Note that this traverses the
        whole composite dataset every time and should not be
        called repeatedly for large composite datasets.)rÛ   r   r   )r   r   r   r   r²   ·  s    z!CompositeDataSet.GetNumberOfCellsc             C   s
   t | |ƒS )z^Returns the attributes specified by the type as a
        CompositeDataSetAttributes instance.)r¹   )r   rh   r   r   r   r˜   ¾  s    zCompositeDataSet.GetAttributesc             C   s6   | j dks| j ƒ dkr.| jtjƒ}tj|ƒ| _ | j ƒ S )z7Returns the point data as a DataSetAttributes instance.N)r×   r˜   r   r   r½   r¾   )r   Zpdatar   r   r   ÚGetPointDataÃ  s    zCompositeDataSet.GetPointDatac             C   s6   | j dks| j ƒ dkr.| jtjƒ}tj|ƒ| _ | j ƒ S )z6Returns the cell data as a DataSetAttributes instance.N)rØ   r˜   r   r   r½   r¾   )r   Úcdatar   r   r   ÚGetCellDataÊ  s    zCompositeDataSet.GetCellDatac             C   s6   | j dks| j ƒ dkr.| jtjƒ}tj|ƒ| _ | j ƒ S )z7Returns the field data as a DataSetAttributes instance.N)rÙ   r˜   r   r   r½   r¾   )r   Úfdatar   r   r   rÒ   Ñ  s    zCompositeDataSet.GetFieldDatac             C   s®   | j dks| j ƒ dkr¦g }xN| D ]F}y
|j}W n tk
rF   d}Y nX |dkr\|jtƒ q |j|ƒ q W t|ƒdksˆtdd„ |D ƒƒrŽt}nt|| d�}tj	|ƒ| _ | j ƒ S )z7Returns the points as a VTKCompositeDataArray instance.Nr   c             S   s   g | ]}|t k‘qS r   )r�   )Ú.0r›   r   r   r   ú
<listcomp>æ  s    z.CompositeDataSet.GetPoints.<locals>.<listcomp>)r)   )
rÚ   ÚPointsru   r—   r�   r
   Úallr’   r½   r¾   )r   Úptsr™   Z_ptsZcptsr   r   r   Ú	GetPointsØ  s    


zCompositeDataSet.GetPointsNz4This property returns the point data of the dataset.z1This property returns the cell data of a dataset.z2This property returns the field data of a dataset.z0This property returns the points of the dataset.)r   r   r   r   r!   rÇ   rÛ   r±   r²   r˜   rÝ   rß   rÒ   ræ   r|   Ú	PointDataÚCellDatarÓ   rã   r   r   r   r   rÖ   —  s   	rÖ   c               @   s<   e Zd ZdZdd„ Zdd„ ZeedddƒZeedddƒZdS )	rp   z[This is a python friendly wrapper of a vtkDataSet that defines
    a few useful properties.c             C   s   | j tjƒS )z7Returns the point data as a DataSetAttributes instance.)r˜   r   r   )r   r   r   r   rÝ   ö  s    zDataSet.GetPointDatac             C   s   | j tjƒS )z6Returns the cell data as a DataSetAttributes instance.)r˜   r   r   )r   r   r   r   rß   ú  s    zDataSet.GetCellDataNz4This property returns the point data of the dataset.z1This property returns the cell data of a dataset.)	r   r   r   r   rÝ   rß   r|   rç   rè   r   r   r   r   rp   ò  s
   rp   c               @   s.   e Zd ZdZdd„ Zdd„ ZeeeddƒZdS )ÚPointSetz\This is a python friendly wrapper of a vtkPointSet that defines
    a few useful properties.c             C   s.   | j jƒ sdS t| j jƒ jƒ | ƒ}tj|_|S )zcReturns the points as a VTKArray instance. Returns None if the
        dataset has implicit points.N)r   ræ   r.   ÚGetDatar   r   rl   )r   r(   r   r   r   ræ     s    
zPointSet.GetPointsc             C   sD   ddl m} t||ƒr|}nt|ƒ}|ƒ }|j|ƒ | jj|ƒ dS )z:Given a VTKArray instance, sets the points of the dataset.r   )Ú	vtkPointsN)Úvtk.vtkCommonCorerë   r   r2   ZSetDatar   Ú	SetPoints)r   rå   rë   Úpr   r   r   rí     s    

zPointSet.SetPointsNz7This property returns the point coordinates of dataset.)r   r   r   r   ræ   rí   r|   rã   r   r   r   r   ré     s   
ré   c               @   s&   e Zd ZdZdd„ ZeedddƒZdS )ÚPolyDataz\This is a python friendly wrapper of a vtkPolyData that defines
    a few useful properties.c             C   s"   | j jƒ sdS t| j jƒ jƒ | ƒS )z)Returns the polys as a VTKArray instance.N)r   ZGetPolysr.   rê   )r   r   r   r   ÚGetPolygons  s    
zPolyData.GetPolygonsNz3This property returns the connectivity of polygons.)r   r   r   r   rð   r|   ZPolygonsr   r   r   r   rï     s   rï   c               @   sZ   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zeed
d
dƒZ	eed
d
dƒZ
eed
d
dƒZd
S )ÚUnstructuredGridzdThis is a python friendly wrapper of a vtkUnstructuredGrid that defines
    a few useful properties.c             C   s   | j jƒ sdS t| j jƒ | ƒS )z.Returns the cell types as a VTKArray instance.N)r   ZGetCellTypesArrayr.   )r   r   r   r   ÚGetCellTypes,  s    
zUnstructuredGrid.GetCellTypesc             C   s   | j jƒ sdS t| j jƒ | ƒS )z2Returns the cell locations as a VTKArray instance.N)r   ZGetCellLocationsArrayr.   )r   r   r   r   ÚGetCellLocations3  s    
z!UnstructuredGrid.GetCellLocationsc             C   s"   | j jƒ sdS t| j jƒ jƒ | ƒS )z)Returns the cells as a VTKArray instance.N)r   ÚGetCellsr.   rê   )r   r   r   r   rô   :  s    
zUnstructuredGrid.GetCellsc             C   sb   ddl m} ddlm} t|ƒ}t||d�}t||d�}|ƒ }|j|jƒ |ƒ | jj|||ƒ dS )zlGiven cellTypes, cellLocations, cells as VTKArrays,
        populates the unstructured grid data structures.r   )ÚVTK_ID_TYPE)ÚvtkCellArray)r0   N)Úvtkrõ   Úvtk.vtkCommonDataModelrö   r2   ÚSetCellsZGetNumberOfTuplesr   )r   Z	cellTypesZcellLocationsÚcellsrõ   rö   Úcar   r   r   rù   A  s    zUnstructuredGrid.SetCellsNz)This property returns the types of cells.z-This property returns the locations of cells.z0This property returns the connectivity of cells.)r   r   r   r   rò   ró   rô   rù   r|   Z	CellTypesZCellLocationsZCellsr   r   r   r   rñ   (  s   rñ   c             C   sp   | j dƒrt| ƒS | j dƒr$t| ƒS | j dƒr6t| ƒS | j dƒrHt| ƒS | j dƒrZt| ƒS | j dƒrlt| ƒS dS )z4Returns a Numpy friendly wrapper of a vtkDataObject.ZvtkPolyDataZvtkUnstructuredGridZvtkPointSetZ
vtkDataSetZvtkCompositeDataSetZvtkTableN)ZIsArï   rñ   ré   rp   rÖ   rÔ   )r™   r   r   r   r{   Q  s    





r{   )N)r/   N)0r   r   ÚImportErrorÚRuntimeErrorÚ	itertoolsrƒ   rf   r÷   r   Zvtk.utilr   rø   r   rì   r   r½   rg   rž   rÀ   r   r   Úobjectr   r.   r2   r:   rE   rh   rF   r	   r,   r~   r   r�   r‘   r’   r£   r¹   rÄ   rÏ   rÑ   rÔ   rÖ   rp   ré   rï   rñ   r{   r   r   r   r   Ú<module>>   s\   


	F
^19 vR!
[)