
    Be)                       d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZmZmZ ddlm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mZmZ ddl m!Z! ddl"m#Z# ddl$m%Z% erddl&m'Z' ddl(m)Z) ddlm*Z* d Z+ G d de!          Z, G d d          Z- G d d          Z. G d de,          Z/ G d de/          Z0 G d  d!e/e-          Z1 G d" d#e,          Z2 G d$ d%e,          Z3dS )&zG
Defines a VTKPane which renders a vtk plot using VTKPlot bokeh model.
    )annotationsN)abstractmethod)IOTYPE_CHECKINGAnyClassVarDictMappingOptional)urlopen)LinearColorMapper)make_globally_unique_id)JupyterComm   )ParamMethod)isfile	lazy_load   )PaneBase)Bokeh   )PRESET_CMAPS)Document)Model)Commc                P    t          j        |                               d          S )Nzutf-8)base64	b64encodedecode)xs    2lib/python3.11/site-packages/panel/pane/vtk/vtk.py<lambda>r"   #   s    )!,,33G<<     c                       e Zd Z ej        i dd          Z ej        dd          Z ej        dd          Z ej	        dd	          Z
 ej	        dd
          ZdZ fdZd fdZ xZS )AbstractVTKTa  
        Parameters of the axes to construct in the 3d view.

        Must contain at least ``xticker``, ``yticker`` and ``zticker``.

        A ``ticker`` is a dictionary which contains:
          - ``ticks`` (array of numbers) - required.
              Positions in the scene coordinates of the corresponding
              axis' ticks.
          - ``labels`` (array of strings) - optional.
              Label displayed respectively to the `ticks` positions.
              If `labels` are not defined they are inferred from the
              `ticks` array.
          - ``digits``: number of decimal digits when `ticks` are converted to `labels`.
          - ``fontsize``: size in pts of the ticks labels.
          - ``show_grid``: boolean.
                If true (default) the axes grid is visible.
          - ``grid_opacity``: float between 0-1.
                Defines the grid opacity.
          - ``axes_opacity``: float between 0-1.
                Defines the axes lines opacity.
    )defaultnested_refsdocz(
      State of the rendered VTK camera.)r'   r(   z-
      Color mapper of the actor in the sceneFz:
      Activate/Deactivate the orientation widget display.r&   r(   )r&   constantc                    t                                          |          }d|v r;|d         3t          t          j        d         d          }|d         } |di ||d<   |S Naxespanel.models.vtkVTKAxes )super_process_param_changegetattrsysmodules)selfmsgr/   r-   	__class__s       r!   r2   z!AbstractVTK._process_param_changeL   sf    gg++C00S==S[4ck*<=yIIGv;D!'//D//CK
r#   events$Dict[str, param.parameterized.Event]r7   Dict[str, Any]rootr   modelr(   r   commOptional[Comm]returnNonec                X   d|v r~|d         vt          t          j        d         d          }|d         }t          |t                    r |di ||d<   n-t          ||          r |di |                                |d<   t                                          ||||||           d S r,   )r3   r4   r5   
isinstancedictproperties_with_valuesr1   _update_model)
r6   r9   r7   r<   r=   r(   r>   r/   r-   r8   s
            r!   rF   zAbstractVTK._update_modelT   s     S==S[4ck*<=yIIGv;D$%% G%gooooFD'** G%gFF(C(C(E(EFFFfc4TBBBBBr#   )r9   r:   r7   r;   r<   r   r=   r   r(   r   r>   r?   r@   rA   )__name__
__module____qualname__paramr	   r-   cameraListcolor_mappersBooleanorientation_widgetinteractive_orientation_widget_AbstractVTK__abstractr2   rF   __classcell__r8   s   @r!   r%   r%   &   s       5:bd 9 	 	 	D. UZD /+ , , ,F EJ4 60 1 1 1M 'u ;= > > > &3U]4$%O%O%O"J    C C C C C C C C C Cr#   r%   c                      e Zd ZdZd Zd Zd Zd Zd Ze	d             Z
e
j        d             Z
e	d	             Zed
             Zed             ZdS )SyncHelperszI
    Class containing helpers functions to update vtkRenderingWindow
    c                    dd l }|                                }|                                }|                    |           |S )Nr   )vtkvtkRenderervtkRenderWindowAddRenderer)r6   rW   renren_wins       r!   make_ren_winzSyncHelpers.make_ren_wing   sD    


oo%%''C   r#   c                    |                                                      |||           |                                  d S N)get_rendererSetBackgroundsynchronize)r6   rgbs       r!   set_backgroundzSyncHelpers.set_backgroundn   s>    ))!Q222r#   c                ^    |D ])}|                                                      |           *dS z
        Add a list of `actors` to the VTK renderer
        if `reset_camera` is True, the current camera and it's clipping
        will be reset.
        N)r`   AddActorr6   actorsactors      r!   
add_actorszSyncHelpers.add_actorsr   s@      	0 	0E((////	0 	0r#   c                ^    |D ])}|                                                      |           *dS rh   )r`   RemoveActorrj   s      r!   remove_actorszSyncHelpers.remove_actors{   s@      	3 	3E++E2222	3 	3r#   c                :    |                      | j                   d S r_   )rp   rk   r6   s    r!   remove_all_actorszSyncHelpers.remove_all_actors   s    4;'''''r#   c                N    |                                                                  S r_   )r`   GetActiveCamerarr   s    r!   
vtk_camerazSyncHelpers.vtk_camera   s       ""22444r#   c                T    |                                                      |           d S r_   )r`   SetActiveCamera)r6   rK   s     r!   rv   zSyncHelpers.vtk_camera   s(    ++F33333r#   c                h    t          |                                                                           S r_   )listr`   	GetActorsrr   s    r!   rk   zSyncHelpers.actors   s(    D%%''1133444r#   c                    dS )zD
        function to synchronize the renderer with the view
        Nr0   rr   s    r!   rb   zSyncHelpers.synchronize         r#   c                    dS )z"
        Reset the camera
        Nr0   rr   s    r!   reset_camerazSyncHelpers.reset_camera   r}   r#   N)rG   rH   rI   __doc__r]   rf   rm   rp   rs   propertyrv   setterrk   r   rb   r   r0   r#   r!   rU   rU   b   s             0 0 03 3 3( ( ( 5 5 X5 4 4 4 5 5 X5   ^
   ^  r#   rU   c                  0    e Zd ZdZd Zedd            ZdS )VTKa  
    The VTK pane renders a VTK scene inside a panel, making it possible to
    interact with complex geometries in 3D.

    Reference: https://panel.holoviz.org/reference/panes/VTK.html

    :Example:

    >>> pn.extension('vtk')
    >>> VTK(some_vtk_object, width=500, height=500)

    This is a Class factory and allows to switch between VTKJS,
    VTKRenderWindow, and VTKRenderWindowSynchronized pane as a function of the
    object type and when the serialisation of the vtkRenderWindow occurs.

    Once a pane is returned by this class (inst = VTK(object)), one can
    use pn.help(inst) to see parameters available for the current pane
    c                T   t                               |          rft          j        |fi |rt          |fi |S |                    dd          r$t          j        j                            d           t          |fi |S t                              |          rt          |fi |S d S )NrP   Fz_Setting interactive_orientation_widget=True will break synchronization capabilities of the pane)	BaseVTKRenderWindowappliesVTKRenderWindowgetrJ   mainwarningVTKRenderWindowSynchronizedVTKJS)r6   objparamss      r!   __new__zVTK.__new__   s    &&s++ 	(&s55f55 B&s55f555::>FF TJ$,,  .S  T  T  T23AA&AAA]]3 	('''''	( 	(r#   Tc                ~    ddl m} |rt           ||           d          S t           ||           d          S )Nr   )import_synch_file)filenameF)serialize_on_instantiationT)synchronizable_deserializerr   r   r   )r   synchronizabler   s      r!   import_scenezVTK.import_scene   st    BBBBBB 		.!!8444+0   
 #!!8444+/   r#   NT)rG   rH   rI   r   r   staticmethodr   r0   r#   r!   r   r      sM         &	( 	( 	(    \  r#   r   c                  >    e Zd ZU  ej        dd          Z ej        ddd          Z ej        ddd          ZdZddd	Z	d
e
d<   dZ fdZed             Zd Zd ZddZ ej        d          dd            ZddZddZd ZddZed             Z xZS )r   Fz
        Activate/Deactivate keys binding.

        Warning: These keys bind may not work as expected in a notebook
        context if they interact with already binded keys
    r)   Ta  
         defines when the serialization of the vtkRenderWindow scene occurs.
         If set to True the scene object is serialized when the pane is created
         else (default) when the panel is displayed to the screen.

         This parameter is constant, once set it can't be modified.

         Warning: when the serialization occurs at instantiation, the vtkRenderWindow and
         the view are not fully synchronized. The view displays the state of the scene
         captured when the panel was created, if elements where added or removed between the
         instantiation and the display these changes will not be reflected.
         Moreover when the pane object is updated (replaced or call to param.trigger('object')),
         all the scene is rebuilt from scratch.
    r&   r*   r(   a  
        If true, enable the serialization of all data arrays of vtkDataSets (point data, cell data and field data).
        By default the value is False and only active scalars of each dataset are serialized and transfer to the
        javascript side.

        Enabling this option will increase memory and network transfer volume but results in more reactive visualizations
        by using some custom javascript functions.
    N)r   serialize_all_data_arrays"ClassVar[Mapping[str, str | None]]_renamec                    |                     dd          | _         t                      j        |fi | dd lmc mc m} |                                 d S )Ndebug_serializerFr   )	pop_debug_serializerr1   __init__(panel.pane.vtk.synchronizable_serializerpanerW   synchronizable_serializerinitializeSerializers)r6   objectr   rwsr8   s       r!   r   zBaseVTKRenderWindow.__init__   su    !',>!F!F**6***>>>>>>>>>>>>!!#####r#   c                p    dt           j        vrdt           j        vrdS dd l}t          ||j                  S )NrW   
vtkmodulesFr   )r4   r5   rW   rC   rY   )clsr   kwargsrW   s       r!   r   zBaseVTKRenderWindow.applies   s<    ##CK(G(G5JJJc3#6777r#   c                Z    t          | j                                                  d         S )z>
        Get the vtk Renderer associated to this pane
        r   )rz   r   GetRenderersrr   s    r!   r`   z BaseVTKRenderWindow.get_renderer  s%     DK,,..//22r#   c                4    |                                 }|                                \  }}t          j        t	          |          t          j                                      d          } fd|d d d df         D             }t          ||||          S )N)dtype)   c                $    g | ]} j         | S r0   )_rgb2hex).0rgbr6   s     r!   
<listcomp>z6BaseVTKRenderWindow._vtklut2bkcmap.<locals>.<listcomp>  s"    AAA3=4=#&AAAr#   r   )lowhighnamepalette)GetTableGetTableRangenp
frombuffer
memoryviewuint8reshaper   )r6   lutr   tabler   r   rgba_arrr   s   `       r!   _vtklut2bkcmapz"BaseVTKRenderWindow._vtklut2bkcmap
  s    %%''	TM*U"3"3BHEEEMMgVVAAAA(111RaR4.AAA St$PPPPr#   c                b   |sg }|                                                                  D ]h}|                    d          rQ|                                }|                                }|                    |                     ||                     ini }|                                                                  D ]]}|                                }|	                                }	|	r1|	|vr-|                                }|                     ||	          ||	<   ^|
                                }|S )NvtkScalarBarActor)r`   GetViewPropsIsAGetTitleGetLookupTableappendr   r{   	GetMapperGetArrayNamevalues)
r6   infercmaps	view_propr   r   infered_cmapsrl   mapper	cmap_names
             r!   get_color_mappersz%BaseVTKRenderWindow.get_color_mappers  s>    	+E!..00==?? A A	==!455 A$--//D#2244CLL!4!4S$!?!?@@@	A M**,,6688 S S**"//11	 S-!?!? //11C/3/B/B3	/R/RM),!((**Er#   rM   c                   |s| j         }ddlm}m}m} g }|D ]V}t          j        |j        |j        d          }|	                     |||j
         ||          dddd                     W |d ddd	          fd
|D              S )Nr   )ColorBarFixedTickerPlot   )ticks
horizontal)r   r   )color_mappertitletickerlabel_standoffbackground_fill_alphaorientationlocationstretch_width)toolbar_locationframe_heightsizing_modeoutline_line_widthc                <    g | ]}                     |d           S )below)
add_layout)r   cbplots     r!   r   z<BaseVTKRenderWindow._construct_colorbars.<locals>.<listcomp>4  s'    444"W	%	%444r#   )rM   bokeh.modelsr   r   r   r   linspacer   r   r   r   )	r6   rM   r   r   r   cbsr   r   r   s	           @r!   _construct_colorbarsz(BaseVTKRenderWindow._construct_colorbars$  s     	/ .M<<<<<<<<<<) 	 	LK 0,2CQGGEJJxx)"'"{/// |^d	       tT'(* * *44444444r#   c                    |r:|                      d          }|                     |          }t          |          S t          | j                  S )NT)r   )r   r   r   r   )r6   r   rM   r=   s       r!   construct_colorbarsz'BaseVTKRenderWindow.construct_colorbars7  sP     	: 222>>M--m<<E<<t8999r#   	vtk_scenec                $   d|vr|dz  }dd l mc mc m} |                    || j                  }|                     | j        |dd          \  }}}t          j	        |d	          5 }|
                    d
t          j        |                     |                                D ])\  }	}
|
                    d|	z  |
t          j                   *|
                    dt          j        |                     d d d            n# 1 swxY w Y   |S )N.z.synchr   )r   debugTFbinarycompressionw)modez
index.jsonzdata/%szannotations.json)r   r   rW   r   SynchronizationContextr   _serialize_ren_winr   zipfileZipFilewritestrjsondumpsitemsZIP_DEFLATED)r6   r   all_data_arraysr   contextscenearraysr   zfr   datas              r!   export_scenez BaseVTKRenderWindow.export_scene?  sw   h H>>>>>>>>>>>>,,^b^t,uu%)%<%<T['Z^lq%<%r%r"v{_XC000 	EBKKdj&7&7888$llnn J J
dI,dG4HIIIIKK*DJ{,C,CDDD		E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E
 s   *BDD	D	c                V    |                                  }| j        |k    r	|| _        d S d S r_   )r   rM   )r6   rM   s     r!   _update_color_mappersz)BaseVTKRenderWindow._update_color_mappersM  s7    ..00..!.D /.r#   c                   dd l mc mc m} g |                                 |                                 |                                 |                    d |                    |          d          }d|d         d<   fdj	        
                                D             }                                }	|||	fS )Nr   r   
propertiesnumberOfLayersc                J    i | ]}|v|                     |d d           S )TFr   )getCachedDataArray)r   r   r
  exclude_arrayss     r!   
<dictcomp>z:BaseVTKRenderWindow._serialize_ren_win.<locals>.<dictcomp>[  sD     
 
 
^9S9S ',,T$E,RR9S9S9Sr#   )r   r   rW   r   OffScreenRenderingOnModifiedRenderserializeInstancegetReferenceIddataArrayCachekeysgetAnnotations)
r6   r\   r
  r   r   r  r   r  r  r   s
     `  `    r!   r  z&BaseVTKRenderWindow._serialize_ren_winR  s    >>>>>>>>>>>>!N$$&&&%%dGW5K5KG5T5TV]_`aa01l,-
 
 
 
 
.3355
 
 
 ,,..fk))r#   c                D   t           t          j        f}t          | |          r7t          ||          t          ||          u rd                    | ||          S d                    t          d| z            t          d|z            t          d|z                      S )Nz#{0:02x}{1:02x}{2:02x}   )intr   integerrC   format)rc   rd   re   int_types       r!   r   zBaseVTKRenderWindow._rgb2hexb  s    $a"" 	z!X'>'>*QPXBYBY'Y'Y+221a;;;+22C!Gc#'llCaLL  r#   )Fr_   r   )r   F)FTN)rG   rH   rI   rJ   rN   enable_keybindingsr   r   _applies_kwr   __annotations___BaseVTKRenderWindow__abstractr   classmethodr   r`   r   r   dependsr   r   r  r  r  r   r   rR   rS   s   @r!   r   r      s         'u ; 	 	 	 "/ut R "	 "	 "	 !.ed Q !	 !	 !	 KQUtx2y2yGyyyyJ$ $ $ $ $ 8 8 [83 3 3Q Q Q   & U]?##   $#$: : : :   / / /
* * * *    \    r#   r   c                  X     e Zd ZdZdZe fd            Zd fd	Z	 	 dddZddZ	 xZ
S )r   z
    VTK panes allow rendering vtkRenderWindow objects.
    Capture the scene of the vtkRenderWindow passed at instantiation
    To update the display a new vtkRenderWindow must be passed as object
    Tc                h    |                     dd          } t                      j        |fi |o|S Nr   Fr   r1   r   r   r   r   r   r8   s       r!   r   zVTKRenderWindow.appliesv  s@    %+ZZ0Le%T%T"..v.. +*	,r#   Nc                     t          t          |           j        |fi | |1|                                 | _        |                     d d            d S d S r_   )r1   r   r   r   rM   _updater6   r   r   r8   s      r!   r   zVTKRenderWindow.__init__|  sd    -ot$$-f?????!%!7!7!9!9DLLt$$$$$ r#   r(   r   r<   Optional[Model]parentr>   r?   r@   r   c                R   t          ddt          |t                    |          }|                     |          }| j        '|                    | j        | j        | j                    |di |}|p|}| 	                    |ddg|||           ||f| j
        |j        d         <   |S )Nr.   VTKSynchronizedPlot)r  r  rM   r'  rO   idr0   )r   rC   r   _get_propertiesr   update_scene_arraysrM   _link_props_modelsref)r6   r(   r<   r6  r>   r8  propsr=   s           r!   
_get_modelzVTKRenderWindow._get_model  s     ( 5z$7T7TVZ
 
 $$S));"LLt{4<tOaLbbb##,,e,,}u(*>?dD	
 	
 	
 ).vTXd^$r#   r@  strr=   rA   c                .   dd l mc mc m} |                    t                      | j        | j                  }|                     | j	        |          \  | _
        | _        | _        |*|                    d| j        | j
        | j                   d S d S )Nr   id_rootr   r   T)rebuildr  r  r   )r   r   rW   r   r   r   r   r   r  r   r<  r=  _annotationsr;  )r6   r@  r=   r   r
  s        r!   r3  zVTKRenderWindow._update  s    >>>>>>>>>>>>,,+--&*&D( - 
 

 8<7N7NK8
 8
4T\4#4 LLdl$+[_[lLmmmmm r#   r_   NNN
r(   r   r<   r5  r6  r5  r>   r?   r@   r   r@  rC  r=   r   r@   rA   )rG   rH   rI   r   _updatesr+  r   r   rB  r3  rR   rS   s   @r!   r   r   m  s          H, , , , [,
% % % % % % 6:?C    $n n n n n n n nr#   r   c                       e Zd ZU dZ ej        ddd          Z ej        d          Z ed#ddie	j
        Z
d	ed
<   dZe fd            Zd$ fd	Z	 	 d%d&dZd$d' fdZd(dZd Zd  Zd! Zd" Z xZS ))r   z
    VTK panes allow rendering VTK objects.
    Synchronize a vtkRenderWindow constructs on python side
    with a custom bokeh model on javascript side
    FTz
    r   )r&   _one_time_resetone_time_resetr   r   c                j    |                     dd          } t                      j        |fi |o| S r/  r0  r1  s       r!   r   z#VTKRenderWindowSynchronized.applies  s?    %+ZZ0Le%T%T"uwws--f--P6P2PPr#   Nc                v    ||                                  } t                      j        |fi | i | _        d S r_   )r]   r1   r   	_contextsr4  s      r!   r   z$VTKRenderWindowSynchronized.__init__  sC    >&&((F**6***r#   r(   r   r<   r5  r6  r>   r?   r@   r   c                .   t          ddt          |t                    |          }dd lmc mc m} |                    t                      | j	        | j
                  }|                     | j        |          \  }}	}
|                                  |                     |          }|                    ||	|
| j                    |di |}|p|}g d}|                     |||||           || j        |j        <   ||f| j        |j        d         <   |S )	Nr.   r8  r   rE  )r  r  r   rM   )rK   rM   r'  rO  rO   r9  r0   )r   rC   r   r   r   rW   r   r   r   r   r   r  r   r  r:  r;  rM   r>  rR  r9  r?  r@  )r6   r(   r<   r6  r>   r8  r   r
  r  r  r   rA  r=   linkeds                 r!   rB  z&VTKRenderWindowSynchronized._get_model  sP    ( 5z$7T7TVZ
 
 	?>>>>>>>>>>>,,+--&*&D( - 
 

 &*%<%<T['%R%R"v{""$$$$$S))5[X\Xjkkk##,,e,,}ujjjT4888$+ux (-vTXd^$r#   Model | NonerA   c                    |j         d         }| j                            |d            t                                          |           d S )Nr9  )r@  rR  r   r1   _cleanup)r6   r<   r@  r8   s      r!   rW  z$VTKRenderWindowSynchronized._cleanup  sD    htn3%%%r#   r@  rC  r=   c                    | j         |j                 }|                     | j        ||j                  \  }}}|                                 |                    |||           d S )N)r  )r  r  r   )rR  r9  r  r   arrays_processedcheckForArraysToReleaser;  )r6   r@  r=   r
  r  r  r   s          r!   r3  z#VTKRenderWindowSynchronized._update  sq    .*%)%<%<K 1 &= &
 &
"v{
 	'')))F%[IIIIIr#   c                :    | j                             d           d S )Nr   )rJ   triggerrr   s    r!   rb   z'VTKRenderWindowSynchronized.synchronize  s    
8$$$$$r#   c                f    t          |t                    st          d          |j        | _        dS )zX
        Associate the camera of an other VTKSynchronized pane to this renderer
        z4Only instance of VTKRenderWindow class can be linkedN)rC   r   	TypeErrorrv   )r6   others     r!   link_cameraz'VTKRenderWindowSynchronized.link_camera  s4     %!<== 	/RSSS#.DOOOr#   c                l    |                                                                   | j         | _        d S r_   )r`   ResetCamerarN  rr   s    r!   r   z(VTKRenderWindowSynchronized.reset_camera  s4    '')))#'#77r#   c           	        ddl }| j        }|                                }|| _        g d}| j        | j                                        D ]\  }}||vrt          |t                    r: t          |d|d                                         z   |dd         z             |  X t          |d|d                                         z   |dd         z             |           dS |	                    |           dS )zN
        Create a fresh vtkCamera instance and set it to the renderer
        r   N)mtimeprojectionMatrix
viewMatrixphysicalTranslationphysicalScalephysicalViewUpphysicalViewNorthremoteIdSetr   )
rW   rv   	vtkCamerarK   r  rC   rz   r3   
capitalizeDeepCopy)r6   rW   
old_camera
new_cameraexclude_propertieskvs          r!   unlink_cameraz)VTKRenderWindowSynchronized.unlink_camera  s$    	


_
]]__
$	
 	
 	
 ;"))++ R R1...!!T** RN
EAaDOO4E4E,E!"",MNNPQRRRN
EAaDOO4E4E,E!"",MNNqQQQR R 
+++++r#   r0   r_   rI  rJ  )r<   rU  r@   rA   rK  )rG   rH   rI   r   rJ   rN   rP   rN  rD   r   r   r)  rL  r+  r   r   rB  rW  r3  rb   r`  r   ru  rR   rS   s   @r!   r   r     s          &3U]54 V &	 &	 &	" $emE222O26$ 32 32GW 32(032 32G 2 2 2 2 HQ Q Q Q [Q      6:?C    2      
J J J J% % %/ / /8 8 8, , , , , , ,r#   r   c                      e Zd ZU dZ ej        ddd          Z ej        dd          Z ej	        d	e
d
          Z ej        ddd          Z ej        dd          Z ej        dd          Z ej        dddd          Z ej	        dg dd          Z ej        d          Z ej        dd          Z ej        ddd          Z ej        d d!d"          Z ej        d#d$          Z ej        dd%          Z ej        dd&          Z ej        dddd'          Z ej        d(d!d)*          Z ej        d+dd,          Z ej        d-d.          Z ej        dd/0          Z  ej        dd10          Z! ej        dd20          Z"i Z#d d d d3Z$d4e%d5<   dZ&dR fd6	Z'e(dSd;            Z)	 	 dTdUdDZ* fdEZ+dF Z, fdGZ- fdHZ.dVdMZ/e(dN             Z0dO Z1dP Z2dQ Z3 xZ4S )W	VTKVolumeaM  
    The `VTKVolume` pane renders 3d volumetric data defined on regular grids.
    It may be constructed from a 3D NumPy array or a vtkVolume.

    The pane provides a number of interactive control which can be set either
    through callbacks from Python or Javascript callbacks.

    Reference: https://panel.holoviz.org/reference/panes/VTKVolume.html

    :Example:

    >>> pn.extension('vtk')
    >>> VTKVolume(
    ...    data_matrix, spacing=(3,2,1), interpolation='nearest',
    ...    edge_gradient=0, sampling=0,
    ...    sizing_mode='stretch_width', height=400,
    ... )
    g?g{Gz?z
        Value to control the ambient lighting. It is the light an
        object gives even in the absence of strong light. It is
        constant in all directions.)r&   stepr(   TzL
        If True the volume controller panel options is expanded in the viewr)   erdc_rainbow_brightzE
        Name of the colormap used to transform pixel value in color.)r&   objectsr(   gffffff?z|
        Value to control the diffuse Lighting. It relies on both the
        light direction and the object surface normal.zd
        If set to True, the 3D representation of the volume is
        displayed using ray casting.Fz
        If set to true, the orthgonal slices in the three (X, Y, Z)
        directions are displayed. Position of each slice can be
        controlled using slice_(i,j,k) parameters.g?)r   r   zd
        Parameter to adjust the opacity of the volume based on the
        gradient between voxels.)r&   boundsrx  r(   fast_linear)r|  linearnearesta  
        interpolation type for sampling a volume. `nearest`
        interpolation will snap to the closest voxel, `linear` will
        perform trilinear interpolation to compute a scalar value from
        surrounding voxels.  `fast_linear` under WebGL 1 will perform
        bilinear interpolation on X and Y but use nearest for Z. This
        is slightly faster than full linear at the cost of no Z axis
        linear interpolation.z+Lookup Table in format {low, high, palette})r(   g@@z?
        Maximum data size transfer allowed without subsampling      ?)g        r  z0
        Opacity applied to nan values in slices)r&   r{  r(   Nr   )r&   length
allow_Nonez#52576ez
        Allows to specify the background color of the 3D rendering.
        The value must be specified as an hexadecimal color string.z
        If set to True the colormap is rescaled between min and max
        value of the non-transparent pixel, otherwise  the full range
        of the pixel values are used.z
        If set to False, then the mapper for the volume will not
        perform shading computations, it is the same as setting
        ambient=1, diffuse=0, specular=0.z
        Parameter to adjust the distance between samples used for
        rendering. The lower the value is the more precise is the
        representation but it is more computationally intensive.)r   r   r   z1
        Distance between voxel in each direction)r&   r  r(   g333333?z}
        Value to control specular lighting. It is the light reflects
        back toward the camera when hitting the object.g       @z
        Specular power refers to how much light is reflected in a
        mirror like fashion, rather than scattered randomly in a
        diffuse manner.zb
        Integer parameter to control the position of the slice normal
        to the X direction.)per_instancer(   zb
        Integer parameter to control the position of the slice normal
        to the Y direction.zb
        Integer parameter to control the position of the slice normal
        to the Z direction.)max_data_sizespacingoriginr   r   c                     t                      j        |fi | | j        | _        |                     d d            d S r_   )r1   r   r  _sub_spacingr3  r4  s      r!   r   zVTKVolume.__init__  sF    **6*** LT4     r#   r   r   r@   float | bool | Nonec                $   t          t          j                  rj        dk    s2t	          fd| j                                        D                       rdS dt          j        vrdt          j        vrdS dd l	}t          |j
                  S )Nr   c                0    g | ]}t          |          S r0   )rC   )r   rs  r   s     r!   r   z%VTKVolume.applies.<locals>.<listcomp>  s#    EEEC##EEEr#   TrW   r   Fr   )rC   r   ndarrayndimany_serializersr  r4   r5   rW   vtkImageData)r   r   rW   s    ` r!   r   zVTKVolume.applies  s    RZ(( 	5SX]]EEEES-=-B-B-D-DEEEFF .;4#+%%,ck*I*I5JJJc3#3444r#   r(   r   r<   r5  r6  r>   r?   r   c                <   t          ddt          |t                    |          }|                     |                                           }| j        
| j        |d<    |di |}||}|                     |g d|||           ||f| j        |j        d         <   |S )Nr.   VTKVolumePlotr  )colormaprO   rK   r   controller_expandednan_opacityr9  r0   )	r   rC   r   r2   _init_params_volume_datar>  r?  r@  )r6   r(   r<   r6  r>   r  rA  r=   s           r!   rB  zVTKVolume._get_model  s     "D+1N1NPT
 
 **4+<+<+>+>??( -E&M&&&&<D | | |  B  DH  JN  	O  	O  	O(-vTXd^$r#   c                `    d | _         t                                          |||||           d S r_   )_legendr1   _update_object)r6   r@  r(   r<   r6  r>   r8   s         r!   r  zVTKVolume._update_object  s0    sCvt<<<<<r#   c                    t          | j        t          j                  r| j        j        S | j                                        S r_   )rC   r   r   r  shapeGetDimensionsrr   s    r!   _get_object_dimensionsz VTKVolume._get_object_dimensions  s7    dk2:.. 	/;$$;,,...r#   c                8   t                                          |          }| j        pdddd}|                                D ]U\  }}| j        }| j        }||v r>||         }t          t          j        |||         z  ||         z                      ||<   V|S Nr   r   r   )slice_islice_jslice_k)	r1   r2   r   r  _subsample_dimensions_orginal_dimensionsr#  r   round	r6   r7   slice_paramsrs  rt  sub_dimori_dimindexr8   s	           r!   r2   zVTKVolume._process_param_change  s    gg++C00;"&'1BBL		 P P142$$(OE !gen*<wu~*M!N!NOOCF
r#   c                8   t                                          |          }| j        pdddd}|                                D ]U\  }}| j        }| j        }||v r>||         }t          t          j        |||         z  ||         z                      ||<   V|S r  )	r1   _process_property_changer   r  r  r  r#  r   r  r  s	           r!   r  z"VTKVolume._process_property_change  s    gg..s33;"&'1BBL		 P P142$$(OE !gen*<wu~*M!N!NOOCF
r#   r@  rC  r=   rA   c                   |                                  | _        | j        |                                 | _        | j        d         | _        d| j        d         dz
  f| j        j        _        | j        d         dz
  dz  | _        d| j        d         dz
  f| j        j        _        | j        d         dz
  dz  | _        d| j        d         dz
  f| j        j	        _        | j        d         dz
  dz  | _	        || j        |_
        d S d S )Ndimsr   r   r   )_get_volume_datar  r  r  r  rJ   r  r{  r  r  r  )r6   r@  r=   s      r!   r3  zVTKVolume._update  s    1133('+'B'B'D'DD$)-):6)BD&)*D,DQ,G,I(JDJ% 4Q79A=DL)*D,DQ,G,I(JDJ% 4Q79A=DL)*D,DQ,G,I(JDJ% 4Q79A=DL*EJJJ r#   c                >    | j                             ||i           dS )z
        Register a serializer for a given type of class.
        A serializer is a function which take an instance of `class_type`
        (like a vtk.vtkImageData) as input and return a numpy array of the data
        N)r  r;  )r   
class_type
serializers      r!   register_serializerzVTKVolume.register_serializer  s&     	J 788888r#   c           
         t          t          |                    d                    |j        | j        | j        t          j        |          t          j        |          f|j	        j
                  S )NForder)bufferr  r  r  
data_ranger   )rD   base64encoderavelr  r  r  r   nanminnanmaxr   r   )r6   	sub_arrays     r!   _volume_from_arrayzVTKVolume._volume_from_array  sf    	c : :;;%;	),,bi	.B.BC/&
 
 
 	
r#   c                     j         d S t           j         t          j                  r-                                           j                             S  fdt          j                                        D             }|s2dd l	}ddl
m fd}t                              |j        |           |}n|d         } |           S )Nc                D    g | ]\  }}t          j        |          |S r0   )rC   r   )r   rs  rt  r6   s      r!   r   z.VTKVolume._get_volume_data.<locals>.<listcomp>  s2    #o#o#o$!QT^_c_jlmTnTn#oA#o#o#or#   r   )numpy_supportc                   | j         }                    |                                                                          }|                                }|                                | _        |                                | _        | 	                    | 
                    |                    |d                              S )Nr  r  )r   vtk_to_numpyGetPointData
GetScalarsr  
GetSpacingr  	GetOriginr  r  _subsample_arrayr   )inst	imageDataarrayr  r  s       r!   volume_serializerz5VTKVolume._get_volume_data.<locals>.volume_serializer  s     $I)66y7M7M7O7O7Z7Z7\7\]]E$2244D#,#7#7#9#9DL"+"5"5"7"7DK2243H3HW[cfIgIg3h3hiiir#   )r   rC   r   r  r  r  rw  r  r  rW   vtk.utilr  r  r  )r6   available_serializerrW   r  r  r  s   `    @r!   r  zVTKVolume._get_volume_data  s    ;4RZ00 	$**4+@+@+M+MNNN#o#o#o#o)2H2N2N2P2P#o#o#o ' 5


222222j j j j j --c.>@QRRR.

1!4
:d###r#   c                \  	 |j         }| j        }t          d t          ||          D                       }t	          j        |j        dz  | j        z            	t          	fd|D                       }d t          ||          D             }t          d |D                       r	 dd l	m
} |j                            |d |D             dd	          }n# t          $ r |d d t          t	          j        |d                             d d t          t	          j        |d
                             d d t          t	          j        |d                             f         }Y nw xY wt          d t          ||j                   D                       | _        n|}| j        | _        |S )Nc              3  ,   K   | ]\  }}|d z
  |z  V  dS r   Nr0   )r   o_sss      r!   	<genexpr>z-VTKVolume._subsample_array.<locals>.<genexpr>  s.      PPaa1}PPPPPPr#   g    .Ac              3  <   K   | ]}t          |z            V  d S r_   )r#  )r   r  	dim_ratios     r!   r  z-VTKVolume._subsample_array.<locals>.<genexpr>  s/      II3#cIo..IIIIIIr#   c                :    g | ]\  }}t          ||          |z  S r0   )max)r   m_sr  s      r!   r   z.VTKVolume._subsample_array.<locals>.<listcomp>  s)    ```XS#Sc]]S0```r#   c                    g | ]}|d k    	S r   r0   r   d_fs     r!   r   z.VTKVolume._subsample_array.<locals>.<listcomp>  s    555Ca555r#   r   c                    g | ]}d |z  S r  r0   r  s     r!   r   z.VTKVolume._subsample_array.<locals>.<listcomp>  s    >d>d>d3q3w>d>d>dr#   r~  )zoomr  r   r   r   c              3  ,   K   | ]\  }}||d z
  z  V  dS r  r0   )r   er  s      r!   r  z-VTKVolume._subsample_array.<locals>.<genexpr>  s.      %[%[daa1q5k%[%[%[%[%[%[r#   )r  r  tuplezipr   cbrtnbytesr  r  scipy.ndimagendimageinterpolationr  ImportErrorr#  ceilr  )
r6   r  original_shaper  extent	max_shapedowsnscale_factorndr  r  s
            @r!   r  zVTKVolume._subsample_array  s   ,PP3~w3O3OPPPPPGU\C/43EEFF	IIII.IIIII	``YP^A_A_```55#455566 	-H******,11%>d>dRc>d>d>dlmt}1~~		 H H H!"F"FC0A!0D(E(E$F$F"F"F"FC0A!0D(E(E$F$F"F"F"FC0A!0D(E(E$F$F"F#G H			H !&%[%[c&)/>Z>Z%[%[%[ [ [DI $Ds   *.C BE)(E)r_   r   r   r@   r  rI  rJ  rK  )5rG   rH   rI   r   rJ   NumberambientrN   r  Selectorr   r  diffusedisplay_volumedisplay_slicesedge_gradientr  r	   r   r  r  Tupler  Colorrender_backgroundrescaleshadowsamplingr  specularspecular_powerIntegerr  r  r  r  r   r)  rL  r   r+  r   rB  r  r  r2   r  r3  r  r  r  r  rR   rS   s   @r!   rw  rw    se         & el3T 8' ( ( (G
 (%- ;O P P P u~&;\ XH I I IH el3T 8: ; ; ;G #U]4 6( ) ) )N #U]5 76 7 7 7N
 !ELV$ M$ % % %M #EN=BdBdBd k! " " "M UZIJJJF EL)= DB C C CM %,r( A3 4 4 4K U[aDAAAF#I <G H H H emE 0) * * *G
 U]4 .- . . .F
 u|CT HD E E EH
 ek)A <4 5 5 5G u|Cd 9; < < <H "U\" 3   N
 em 4      G em 4      G em 4      G LDHUYei2j2jGjjjjH! ! ! ! ! !
 5 5 5 [5 6:?C    $= = = = =/ / /
 
 
 
 

 
 
 
 
+ + + + 9 9 [9
 
 
$ $ $4      r#   rw  c                       e Zd ZdZ ej        dd          Zi ZdZd  fd	Z	e
d!d            Z	 	 d"d#dZd Zd$dZd%d&dZ xZS )'r   a  
    The VTKJS pane allow rendering a vtk scene stored in a vtkjs.

    Reference: https://panel.holoviz.org/reference/panes/VTKJS.html

    :Example:

    >>> pn.extension('vtk')
    >>> VTK(
    ...    'https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs',
    ...     sizing_mode='stretch_width', height=400, enable_keybindings=True,
    ...     orientation_widget=True
    ... )
    Fz
        Activate/Deactivate keys binding.

        Warning: These keybindings may not work as expected in a
                 notebook context if they interact with already
                 bound keys.r)   TNc                J     t                      j        |fi | d | _        d S r_   )r1   r   _vtkjsr4  s      r!   r   zVTKJS.__init__:  s-    **6***r#   r   r   r@   r  c                b    t          |t                    r|                    d          rdS d S d S )N.vtkjsT)rC   rC  endswith)r   r   s     r!   r   zVTKJS.applies>  s@    c3 	CLL$:$: 	4	 	 	 	r#   r(   r   r<   r5  r6  r>   r?   r   c                F   t          ddt          |t                    |          }|                     |          }|                                 }|t          |          |d<    |di |}|p|}|                     |g d|||           ||f| j        |j        d         <   |S )z?
        Should return the bokeh model to be rendered.
        r.   	VTKJSPlotNr  )rK   r'  rO   r9  r0   )	r   rC   r   r:  
_get_vtkjsr  r>  r?  r@  )	r6   r(   r<   r6  r>   r	  rA  vtkjsr=   s	            r!   rB  zVTKJS._get_modelC  s     0+z$P[?\?\^bcc	$$S))!!(//E&M	""E""}u V V VX[]acghhh(-vTXd^$r#   c                   | j         | j        t          | j        t                    r| j                            d          rt          | j                  rBt          | j        d          5 }|                                }d d d            n# 1 swxY w Y   nWt          | j                  }|                                }n.t          | j        d          r| j                                        }|| _         | j         S )Nr  rbread)
r  r   rC   rC  r  r   openr  r   hasattr)r6   fr  data_urls       r!   r
  zVTKJS._get_vtkjsU  s   ;4;#:$+s++ +0D0DX0N0N +$+&& ,dk400 )A !) ) ) ) ) ) ) ) ) ) ) ) ) ) )  't{33H$MMOOEEf-- +((**DK{s   ,BBBr@  rC  r=   rA   c                l    d | _         |                                 }|t          |          n||_        d S r_   )r  r
  r  r  )r6   r@  r=   r  s       r!   r3  zVTKJS._updatec  s5    !!,1,=\%(((5


r#   vtk_panel.vtkjsr   str | IOc                   t          |d          r)|                    |                                            dS t          |d          5 }|                    |                                            ddd           dS # 1 swxY w Y   dS )zz
        Exports current VTK data to .vtkjs file.

        Arguments
        ---------
        filename: str | IO
        writewbN)r  r  r
  r  )r6   r   r  s      r!   export_vtkjszVTKJS.export_vtkjsh  s     8W%% 	+NN4??,,-----h%% +))***+ + + + + + + + + + + + + + + + + +s   
(A??BBr_   r  rI  rJ  rK  )r  )r   r  )rG   rH   rI   r   rJ   rN   r'  r  rL  r   r+  r   rB  r
  r3  r  rR   rS   s   @r!   r   r     s          'u ;  ! ! ! LH         [
 6:?C    $  I I I I
+ + + + + + + + +r#   r   )4r   
__future__r   r   r  r4   r  abcr   typingr   r   r   r   r	   r
   r   urllib.requestr   numpyr   rJ   r   r   bokeh.util.serializationr   pyviz_commsr   r   utilr   r   baser   r   r   enumsr   bokeh.documentr   bokeh.modelr   r   r  r%   rU   r   r   r   r   rw  r   r0   r#   r!   <module>r&     sK    # " " " " "   



                         # " " " " "      * * * * * * < < < < < < # # # # # #             % % % % % % % %                   !''''''!!!!!!      <<9C 9C 9C 9C 9C( 9C 9C 9Cx; ; ; ; ; ; ; ;|+ + + + + + + +\\ \ \ \ \+ \ \ \~3n 3n 3n 3n 3n) 3n 3n 3nln, n, n, n, n,"5{ n, n, n,dG G G G G G G GTU+ U+ U+ U+ U+K U+ U+ U+ U+ U+r#   