a
    ¦ˆc$  ã                   @   s&  d Z ddlZddlZddlmZ ddlZddlm	Z	m
Z
mZmZmZmZmZmZmZmZ G dd„ deƒZej e¡Zej ed¡Zej ed¡Zeed	d
d�Zedejƒ edƒ de_edejƒ e e¡D ]RZej e¡d dkrÎeƒ  ed  e¡ƒ ej ee¡e_ed  eej! "¡ ¡ƒ qÎdS )a�  
Property Traits
===============

The ``Image`` class has three traits which are closely related: ``scan_size``,
``scan_width`` and ``scan_height``.  We would ideally like to keep all of these
synchronized.  This can be done with trait observation, as shown in the
previous section, but this sort of pattern is common enough that Traits has
some in-built helpers.

Instead of declaring that ``scan_width = Float()`` we could instead declare it
to be a ``Property`` trait type.  Property traits are similar to ``@property``
decorators in standard Python in that rather than storing a value, they compute
a derived value via a "getter", and optionally store values via a "setter".
Traits uses specially named methods of the form ``_get_<property>`` and
``_set_property`` for these "getters" and "setters."  If there is a "getter"
but no "setter" then the property is read-only.

Additionally, we need to know when the value of the property might change, and
so we need to declare what traits to observe to know when the property might
change.  What all this means is that we can define ``scan_width`` as a
property by::

    class Image(HasTraits):
        ...

        scan_width = Property(Float, depends_on='scan_size')

        def _get_scan_width(self):
            return self.scan_size[0]

        def _set_scan_width(self, value):
            self.scan_size = (value, self.scan_height)

Traits will then take care of hooking up all the required observers to make
everything work as expected; and the `Property` can also be observed if
desired.

Simple `Property` traits like this are computed "lazily": the value is only
calculated when you ask for it.

Cached Properties
-----------------

It would be quite easy to turn the histogram function into a read-only
property.  This might look something like this::

    class Image(HasTraits):
        ...

        histogram = Property(Array, depends_on='image')

        def _get_histogram(self):
            hist, bins = np.histogram(
                self.image,
                bins=256,
                range=(0, 256),
                density=True,
            )
            return hist

This works, but it has a downside that the histogram is re-computed every
time the property is accessed.  For small images, this is probably OK, but
for larger images, or if you are working with many images at once, this may
impact performance.  In these cases, you can specify that the property
should **cache** the returned value and use that value until the trait(s)
the property depend on changes::

    class Image(HasTraits):
        ...

        histogram = Property(Array, depends_on='image')

        @cached_property
        def _get_histogram(self):
            hist, bins = np.histogram(
                self.image,
                bins=256,
                range=(0, 256),
                density=True,
            )
            return hist

This has the trade-off that the result of the computation is being stored
in memory, but in this case the memory is only a few hundred bytes, and so
is unlikely to cause problems; but you probably wouldn't want to do this
with a multi-gigabyte array.

Exercise
--------

Make ``pixel_area`` a read-only property.

é    N)ÚImage)
ÚArrayÚDateÚFileÚFloatÚ	HasTraitsÚPropertyÚStrÚTupleÚcached_propertyÚobservec                   @   sº   e Zd ZdZedd�Zeƒ ZedƒZe	ƒ Z
eeeƒZeedd�Zeedd�Zeddd	�Zeed
d�Zeƒ Zedƒdd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zedd„ ƒZdS )r   z  An SEM image stored in a file. T)ÚexistszN/AÚ	scan_size)Z
depends_on)NNZuint8)ÚshapeZdtypeÚimageÚfilenamec                 C   sL   t  | j¡ d¡}t |¡| _| jjdkrB| j| j	 | jj | _
nd| _
d S )NÚLr   )ÚPILImageÚopenr   ÚconvertÚnpÚarrayr   ÚsizeÚscan_heightÚ
scan_widthÚ
pixel_area)ÚselfÚeventZ	pil_image© r   úl/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/traits/examples/introduction/4_properties.pyÚ
read_image‰   s    ÿzImage.read_imagec                 C   s
   t j ¡ S )N)ÚdatetimeÚdateÚtoday©r   r   r   r   Ú_date_acquired_default˜   s    zImage._date_acquired_defaultc                 C   s   dS )N)çñhãˆµøä>r&   r   r$   r   r   r   Ú_scan_size_default›   s    zImage._scan_size_defaultc                 C   s
   | j d S ©Nr   ©r   r$   r   r   r   Ú_get_scan_width    s    zImage._get_scan_widthc                 C   s   || j d f| _ d S ©Né   r)   ©r   Úvaluer   r   r   Ú_set_scan_width£   s    zImage._set_scan_widthc                 C   s
   | j d S r+   r)   r$   r   r   r   Ú_get_scan_height¦   s    zImage._get_scan_heightc                 C   s   | j d |f| _ d S r(   r)   r-   r   r   r   Ú_set_scan_height©   s    zImage._set_scan_heightc                 C   s   t j| jdddd�\}}|S )Né   )r   r2   T)ÚbinsÚrangeZdensity)r   Ú	histogramr   )r   Úhistr3   r   r   r   Ú_get_histogram¬   s    ü
zImage._get_histogramN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r	   Ú	sample_idÚoperatorr   Zdate_acquiredr
   r   r   r   r   r   r   r   r5   r   r   r    r%   r'   r*   r/   r0   r1   r   r7   r   r   r   r   r   v   s*   


r   Zimageszsample_0001.pngZHannesZ0001)r   r=   r<   z
Scan size:zChange scan width to 1e-4g-Cëâ6?r,   z.pngzChanging filename to {}z'The most frequent intensity of {} is {})#r;   Úosr!   ZPILr   r   Únumpyr   Z
traits.apir   r   r   r   r   r   r	   r
   r   r   ÚpathÚdirnameÚ__file__Zthis_dirÚjoinZ	image_dirr   r   Úprintr   r   ÚlistdirÚsplitextÚformatr5   Zargmaxr   r   r   r   Ú<module>   s:   _0Eýþÿ