U
    Pe                     @   s  d Z dZ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mZmZmZmZmZmZmZ ddl
mZm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  ddl!m"Z" e se#Z$dZ%dZ&dZ'e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 dd de-Z/G dd de-Z0dd Z1dd  Z2d!d" Z3d#d$ Z4d%d& Z5d'd( Z6d)d* Z7d+d, Z8d-d. Z9d/d0 Z:d1d2 Z;dS )3a\  
Multistroke gesture recognizer
==============================

.. versionadded::
    1.9.0

.. warning::

    This is experimental and subject to change as long as this warning notice
    is present.

See :file:`kivy/examples/demo/multistroke/main.py` for a complete application
example.

Conceptual Overview
-------------------

This module implements the Protractor gesture recognition algorithm.

:class:`Recognizer` is the search/database API similar to
:class:`~kivy.gesture.GestureDatabase`. It maintains a list of
:class:`MultistrokeGesture` objects and allows you to search for a
user-input gestures among them.

:class:`ProgressTracker` tracks the progress of a :meth:`Recognizer.recognize`
call. It can be used to interact with the running recognizer task, for example
forcing it to stop half-way, or analyzing results as they arrive.

:class:`MultistrokeGesture` represents a gesture in the gesture database
(:attr:`Recognizer.db`). It is a container for :class:`UnistrokeTemplate`
objects, and implements the heap permute algorithm to automatically generate
all possible stroke orders (if desired).

:class:`UnistrokeTemplate` represents a single stroke path. It's typically
instantiated automatically by :class:`MultistrokeGesture`, but sometimes you
may need to create them manually.

:class:`Candidate` represents a user-input gesture that is used to search
the gesture database for matches. It is normally instantiated automatically
by calling :meth:`Recognizer.recognize`.

Usage examples
--------------

See :file:`kivy/examples/demo/multistroke/main.py` for a complete application
example.

You can bind to events on :class:`Recognizer` to track the state of all
calls to :meth:`Recognizer.recognize`. The callback function will receive an
instance of :class:`ProgressTracker` that can be used to analyze and control
various aspects of the recognition process ::

    from kivy.vector import Vector
    from kivy.multistroke import Recognizer

    gdb = Recognizer()

    def search_start(gdb, pt):
        print("A search is starting with %d tasks" % (pt.tasks))

    def search_stop(gdb, pt):
        # This will call max() on the result dictionary, so it's best to store
        # it instead of calling it 3 times consecutively
        best = pt.best
        print("Search ended (%s). Best is %s (score %f, distance %f)" % (
            pt.status, best['name'], best['score'], best['dist'] ))

    # Bind your callbacks to track all matching operations
    gdb.bind(on_search_start=search_start)
    gdb.bind(on_search_complete=search_stop)

    # The format below is referred to as `strokes`, a list of stroke paths.
    # Note that each path shown here consists of two points, ie a straight
    # line; if you plot them it looks like a T, hence the name.
    gdb.add_gesture('T', [
        [Vector(30, 7), Vector(103, 7)],
        [Vector(66, 7), Vector(66, 87)]])

    # Now you can search for the 'T' gesture using similar data (user input).
    # This will trigger both of the callbacks bound above.
    gdb.recognize([
        [Vector(45, 8), Vector(110, 12)],
        [Vector(88, 9), Vector(85, 95)]])

On the next :class:`~kivy.clock.Clock` tick, the matching process starts
(and, in this case, completes).

To track individual calls to :meth:`Recognizer.recognize`, use the return
value (also a :class:`ProgressTracker` instance) ::

    # Same as above, but keep track of progress using returned value
    progress = gdb.recognize([
        [Vector(45, 8), Vector(110, 12)],
        [Vector(88, 9), Vector(85, 95)]])

    progress.bind(on_progress=my_other_callback)
    print(progress.progress) # = 0

    # [ assuming a kivy.clock.Clock.tick() here ]

    print(result.progress) # = 1

Algorithm details
-----------------

For more information about the matching algorithm, see:

"Protractor: A fast and accurate gesture recognizer" by Yang Li
  http://yangl.org/pdf/protractor-chi2010.pdf

"$N-Protractor" by Lisa Anthony and Jacob O. Wobbrock
  http://depts.washington.edu/aimgroup/proj/dollar/ndollar-protractor.pdf

Some of the code is derived from the JavaScript implementation here:
  http://depts.washington.edu/aimgroup/proj/dollar/ndollar.html
)
RecognizerProgressTrackerMultistrokeGestureUnistrokeTemplate	Candidate    N)match)deque)sqrtpiradiansacosatanatan2powfloor)sincosVector)Clock)EventDispatcher)ListProperty)PY2)BytesIO
   g     @o@g      ?c                   @   s   e Zd ZdS )MultistrokeErrorN)__name__
__module____qualname__ r   r   4/tmp/pip-unpacked-wheel-xzebddm3/kivy/multistroke.pyr      s   r   c                       s   e Zd ZdZeg Z fddZdd Zdd Zdd	 Z	dddZ
dddZdd Zdd ZdddZdd Zdd Zdd Z  ZS )r   aQ  :class:`Recognizer` provides a gesture database with matching
    facilities.

    :Events:
        `on_search_start`
            Fired when a new search is started using this Recognizer.

        `on_search_complete`
            Fired when a running search ends, for whatever reason.
            (use :data:`ProgressTracker.status` to find out)

    :Properties:
        `db`
            A :class:`ListProperty` that contains the available
            :class:`MultistrokeGesture` objects.

            :attr:`db` is a
            :class:`~kivy.properties.ListProperty` and defaults to []
    c                    s*   t t| jf | | d | d d S )Non_search_starton_search_complete)superr   __init__register_event_type)selfkwargs	__class__r   r    r$      s    
zRecognizer.__init__c                 K   s  d}|j }|dd}|dk	r0d}t|ts0|g}|dd}d\}}|dk	rvd}t|trb|\}}nt|trvd| }}|dd}|dk	rd}t|ts|g}|dd}	|	dk	rd}t|	ts|	g}	|d	d}
|
dk	rd}| d
d}|od}|dkod}| ddp
| j}|s|r0|s0t|dd d}n|}t }|sN|| |S |j}|D ]}|
dk	rv|
|j	krvqX|	r|j
|	krqX|rt|j|krqX|dk	r|j|k rqX|dk	r|j|kr|  S |r|D ]"}t||jr||  qqn|| qX|S )a)  :meth:`filter` returns a subset of objects in :attr:`self.db`,
        according to given criteria. This is used by many other methods of
        the :class:`Recognizer`; the arguments below can for example be
        used when calling :meth:`Recognizer.recognize` or
        :meth:`Recognizer.export_gesture`. You normally don't need to call
        this directly.

        :Arguments:

            `name`
                Limits the returned list to gestures where
                :attr:`MultistrokeGesture.name` matches given regular
                expression(s). If re.match(name, MultistrokeGesture.name)
                tests true, the gesture is included in the returned list.
                Can be a string or an array of strings ::

                    gdb = Recognizer()

                    # Will match all names that start with a capital N
                    # (ie Next, New, N, Nebraska etc, but not "n" or "next")
                    gdb.filter(name='N')

                    # exactly 'N'
                    gdb.filter(name='N$')

                    # Nebraska, teletubbies, France, fraggle, N, n, etc
                    gdb.filter(name=['[Nn]', '(?i)T', '(?i)F'])

            `priority`
                Limits the returned list to gestures with certain
                :attr:`MultistrokeGesture.priority` values. If specified as an
                integer, only gestures with a lower priority are returned. If
                specified as a list (min/max) ::

                    # Max priority 50
                    gdb.filter(priority=50)

                    # Max priority 50 (same result as above)
                    gdb.filter(priority=[0, 50])

                    # Min priority 50, max 100
                    gdb.filter(priority=[50, 100])

                When this option is used, :attr:`Recognizer.db` is
                automatically sorted according to priority, incurring extra
                cost. You can use `force_priority_sort` to override this
                behavior if your gestures are already sorted according to
                priority.

            `orientation_sensitive`
                Limits the returned list to gestures that are
                orientation sensitive (True), gestures that are not orientation
                sensitive (False) or None (ignore template sensitivity, this is
                the default).

            `numstrokes`
                Limits the returned list to gestures that have the specified
                number of strokes (in :attr:`MultistrokeGesture.strokes`).
                Can be a single integer or a list of integers.

            `numpoints`
                Limits the returned list to gestures that have specific
                :attr:`MultistrokeGesture.numpoints` values. This is provided
                for flexibility, do not use it unless you understand what it
                does. Can be a single integer or a list of integers.

            `force_priority_sort`
                Can be used to override the default sort behavior. Normally
                :class:`MultistrokeGesture` objects are returned in priority
                order if the `priority` option is used. Setting this to True
                will return gestures sorted in priority order, False will
                return in the order gestures were added. None means decide
                automatically (the default).

                .. Note ::
                    For improved performance, you can load your gesture
                    database in priority order and set this to False when
                    calling :meth:`Recognizer.recognize`

            `db`
                Can be set if you want to filter a different list of objects
                than :attr:`Recognizer.db`. You probably don't want to do this;
                it is used internally by :meth:`import_gesture`.
        FnameNTpriority)NN
numstrokes	numpointsorientation_sensitiveforce_priority_sortdbc                 S   s   | j S N)r+   )nr   r   r    <lambda>8      z#Recognizer.filter.<locals>.<lambda>key)get
isinstancelistintr0   sortedr   extendappendorientation_sensr-   lenstrokesr+   re_matchr*   )r&   r'   Zhave_filtersZ
kwargs_getr*   r+   Zmin_pZmax_pr,   r-   r>   r/   Zforce_sort_onZforce_sort_offr0   tasklistoutZ
out_appendgesturefr   r   r    filter   sx    U













zRecognizer.filterc                 K   s(   |sdS | j tf ||d| dS )aS  Add a new gesture to the database. This will instantiate a new
        :class:`MultistrokeGesture` with `strokes` and append it to self.db.

        .. Note ::
            If you already have instantiated a :class:`MultistrokeGesture`
            object and wish to add it, append it to :attr:`Recognizer.db`
            manually.
        F)r*   r@   T)r0   r=   r   r&   r*   r@   r'   r   r   r    add_gesture_  s    	zRecognizer.add_gesturec                 C   sb   t tt|}t|}g }|j}| D ],}|d }dd |D |d< |t	f | q0|S )zParse data formatted by export_gesture(). Returns a list of
        :class:`MultistrokeGesture` objects. This is used internally by
        :meth:`import_gesture`, you normally don't need to call this
        directly.r@   c                 S   s   g | ]}d d |D qS )c                 S   s   g | ]\}}t ||qS r   r   ).0xyr   r   r    
<listcomp>{  s
    z7Recognizer.parse_gesture.<locals>.<listcomp>.<listcomp>r   rI   liner   r   r    rL   {  s   z,Recognizer.parse_gesture.<locals>.<listcomp>)
r   zlib
decompressbase64	b64decodepickle	Unpicklerr=   loadr   )r&   dataiopmultistrokesZ	ms_appendmultistroker@   r   r   r    parse_gestureo  s    

zRecognizer.parse_gestureNc                 K   s   t  }tj|dd}g }dddddd}| }| jf |D ]P}t|}	d	|ji}	|D ]}
t||
|	|
< qVtd
d |j	D |	d< |
|	 q<|| |rt|d}|tt| d |  ntt| dS dS )a  Export a list of :class:`MultistrokeGesture` objects. Outputs a
        base64-encoded string that can be decoded to a Python list with
        the :meth:`parse_gesture` function or imported directly to
        :attr:`self.db` using :meth:`Recognizer.import_gesture`. If
        `filename` is specified, the output is written to disk, otherwise
        returned.

        This method accepts optional :meth:`Recognizer.filter` arguments.
        r   )protocold      TF      >@)r+   r-   stroke_sensr>   angle_similarityr*   c                 s   s   | ]}d d |D V  qdS )c                 S   s   g | ]}|j |jfqS r   )rJ   rK   )rI   rX   r   r   r    rL     s     z7Recognizer.export_gesture.<locals>.<genexpr>.<listcomp>Nr   rM   r   r   r    	<genexpr>  s   z,Recognizer.export_gesture.<locals>.<genexpr>r@   wb	   N)r   rS   PicklerkeysrF   dictr*   getattrtupler@   r=   dumpopenwriterQ   	b64encoderO   compressgetvalueclose)r&   filenamer'   rW   rX   rY   defaultsZdkeysrZ   mattrrE   r   r   r    export_gesture  s.    
 



zRecognizer.export_gesturec              	   K   sf   |dk	r(t |d}| }W 5 Q R X n|dkr8td| jf d| |i|}|rb| j| dS )a  Import a list of gestures as formatted by :meth:`export_gesture`.
        One of `data` or `filename` must be specified.

        This method accepts optional :meth:`Recognizer.filter` arguments,
        if none are specified then all gestures in specified data are
        imported.Nrbz'import_gesture needs data= or filename=r0   )rk   readr   rF   r[   r0   r<   )r&   rV   rq   r'   infilenewr   r   r    import_gesture  s    zRecognizer.import_gesturec                 K   sH   t |drDt|jtrD| jf |}|rD|jd ||jdd< dS dS )zTransfers :class:`MultistrokeGesture` objects from
        :attr:`Recognizer.db` to another :class:`Recognizer` instance `tgt`.

        This method accepts optional :meth:`Recognizer.filter` arguments.
        r0   NT)hasattrr8   r0   r9   rF   r=   )r&   Ztgtr'   sendr   r   r    transfer_gesture  s    zRecognizer.transfer_gesturec                 K   s8   | j f |D ]&}|D ]}|d|j}|| qqdS )a  This method is used to prepare :class:`UnistrokeTemplate` objects
        within the gestures in self.db. This is useful if you want to minimize
        punishment of lazy resampling by preparing all vectors in advance. If
        you do this before a call to :meth:`Recognizer.export_gesture`, you
        will have the vectors computed when you load the data later.

        This method accepts optional :meth:`Recognizer.filter` arguments.

        `force_numpoints`, if specified, will prepare all templates to the
        given number of points (instead of each template's preferred n; ie
        :data:`UnistrokeTemplate.numpoints`). You normally don't want to
        do this.force_numpointsN)rF   r7   r-   prepare)r&   r'   rD   tplr2   r   r   r    prepare_templates  s    zRecognizer.prepare_templatesr   c              
      s    dt jf |tts`d_d fdd}t	| S  	f
ddd  sd	 nt	d	 S )
a%  Search for gestures matching `strokes`. Returns a
        :class:`ProgressTracker` instance.

        This method accepts optional :meth:`Recognizer.filter` arguments.

        :Arguments:

            `strokes`
                A list of stroke paths (list of lists of
                :class:`~kivy.vector.Vector` objects) that will be matched
                against gestures in the database. Can also be a
                :class:`Candidate` instance.

                .. Warning ::

                    If you manually supply a :class:`Candidate` that has a
                    skip-flag, make sure that the correct filter arguments
                    are set. Otherwise the system will attempt to load vectors
                    that have not been computed. For example, if you set
                    `skip_bounded` and do not set `orientation_sensitive` to
                    False, it will raise an exception if an
                    orientation_sensitive :class:`UnistrokeTemplate`
                    is encountered.

            `goodscore`
                If this is set (between 0.0 - 1.0) and a gesture score is
                equal to or higher than the specified value, the search is
                immediately halted and the on_search_complete event is
                fired (+ the on_complete event of the associated
                :class:`ProgressTracker` instance). Default is None (disabled).

            `timeout`
                Specifies a timeout (in seconds) for when the search is
                aborted and the results returned. This option applies only
                when `max_gpf` is not 0. Default value is 0, meaning all
                gestures in the database will be tested, no matter how long
                it takes.

            `max_gpf`
                Specifies the maximum number of :class:`MultistrokeGesture`
                objects that can be processed per frame. When exceeded, will
                cause the search to halt and resume work in the next frame.
                Setting to 0 will complete the search immediately (and block
                the UI).

                .. Warning ::

                    This does not limit the number of
                    :class:`UnistrokeTemplate` objects matched! If a single
                    gesture has a million templates, they will all be
                    processed in a single frame with max_gpf=1!

            `delay`
                Sets an optional delay between each run of the recognizer
                loop. Normally, a run is scheduled for the next frame until
                the tasklist is exhausted. If you set this, there will be an
                additional delay between each run (specified in seconds).
                Default is 0, resume in the next frame.

            `force_numpoints`
                forces all templates (and candidate) to be prepared to a
                certain number of points. This can be useful for example if
                you are evaluating templates for optimal n (do not use this
                unless you understand what it does).
        Zmax_gpfcompleter"   c                    s     d d S )Non_completedispatch)dt)resultr   r    result_hack(  s    z)Recognizer.recognize.<locals>.result_hackc           
         s  j }d}|sĈrĈjsĈ r*j |  k rĈ	rLt j 	krLd_d}qĈ }|jf\}}}}|d k	r||||}d k	r|krd_d} j	|7  _	 j d7  _ 
d q
fdd}	sd	_|	 S jrd
_|	 S |r |	 S t dS d S )NFtimeoutT	goodscore   on_progressc                      s     d  d  dS )Nr   r"   Fr   r   )r   r&   r   r    	_dispatchK  s    
z@Recognizer.recognize.<locals>._recognize_tick.<locals>._dispatchr   stop)
_completed_break_flagr   get_time_start_timestatuspopleftmatch_candidate_add_result
_match_opsr   schedule_once)
r   Zstart_gcZstop_nowrD   r   dresmosscorer   
ZGPF_recognize_tickcanddelayr   r'   r   r&   rB   r   r   r    r   .  sL    z-Recognizer.recognize.<locals>._recognize_tickr!   r   )
r7   DEFAULT_GPFrF   
_candidater   r?   r   r   r   r   )r&   r@   r   r   r   r'   r   r   r   r    	recognize  s     B

0
zRecognizer.recognizec                 K   sl   t |tr|S t |tr.t|r.t |d ts6tdt|}|dd }|dkrZd|_n|dkrhd|_|S )Nr   z,recognize() needs strokes= list or Candidater.   FT)r8   r   r9   r?   r   r7   skip_boundedskip_invariant)r&   r@   r'   r   Zo_filterr   r   r    r   f  s    
zRecognizer._candidatec                 C   s   d S r1   r   r&   r   r   r   r    r!   }  s    zRecognizer.on_search_startc                 C   s   d S r1   r   r   r   r   r    r"     s    zRecognizer.on_search_complete)N)NN)Nr   r   )r   r   r   __doc__r   r0   r$   rF   rH   r[   ru   rz   r~   r   r   r   r!   r"   __classcell__r   r   r(   r    r      s     '
&

 r   c                       s`   e Zd ZdZ fddZedd Zedd Zdd	 Zd
d Z	dd Z
dd Zdd Z  ZS )r   a	  Represents an ongoing (or completed) search operation. Instantiated and
    returned by the :meth:`Recognizer.recognize` method when it is called. The
    `results` attribute is a dictionary that is  updated as the recognition
    operation progresses.

    .. Note ::
        You do not need to instantiate this class.

    :Arguments:
        `candidate`
            :class:`Candidate` object to be evaluated
        `tasks`
            Total number of gestures in tasklist (to test against)

    :Events:
        `on_progress`
            Fired for every gesture that is processed
        `on_result`
            Fired when a new result is added, and it is the first match
            for the `name` so far, or a consecutive match with better score.
        `on_complete`
            Fired when the search is completed, for whatever reason.
            (use `ProgressTracker.status` to find out)

    :Attributes:
        `results`
            A dictionary of all results (so far). The key is the name of the
            gesture (ie :attr:`UnistrokeTemplate.name` usually inherited from
            :class:`MultistrokeGesture`). Each item in the dictionary is a
            dict with the following entries:

                `name`
                    Name of the matched template (redundant)
                `score`
                    Computed score from 1.0 (perfect match) to 0.0
                `dist`
                    Cosine distance from candidate to template (low=closer)
                `gesture`
                    The :class:`MultistrokeGesture` object that was matched
                `best_template`
                    Index of the best matching template (in
                    :attr:`MultistrokeGesture.templates`)
                `template_results`
                    List of distances for all templates. The list index
                    corresponds to a :class:`UnistrokeTemplate` index in
                    gesture.templates.

        `status`
            `search`
                Currently working
            `stop`
                Was stopped by the user (:meth:`stop` called)
            `timeout`
                A timeout occurred (specified as `timeout=` to recognize())
            `goodscore`
                The search was stopped early because a gesture with a high
                enough score was found (specified as `goodscore=` to
                recognize())
            `complete`
                The search is complete (all gestures matching filters were
                tested)
    c                    sh   d| _ || _i | _|| _t | _d| _d| _d| _	| 
d | 
d | 
d tt| jf | d S )Nsearchr   Fr   r   	on_result)r   	candidateresultstasksr   r   r   r   r   r   r%   r#   r   r$   )r&   r   r   r'   r(   r   r    r$     s    



zProgressTracker.__init__c                 C   s   | j s
dS | jt| j  S )z\Returns the progress as a float, 0 is 0% done, 1 is 100%. This
        is a Python property.r   )r   r   floatr&   r   r   r    progress  s    zProgressTracker.progressc                    sN   | j   sddddS t  fddd} | d  | d  | d	 dS )
a  Return the best match found by recognize() so far. It returns a
        dictionary with three keys, 'name', 'dist' and 'score' representing
        the template's name, distance (from candidate path) and the
        computed score value. This is a Python property.Nr   )r*   distr   c                    s    |  d S )Nr   r   )rr   r   r    r3     r4   z&ProgressTracker.best.<locals>.<lambda>r5   r*   r   r   )r   max)r&   br   r   r    best  s    


zProgressTracker.bestc                 C   s
   d| _ dS )zRaises a stop flag that is checked by the search process. It will
        be stopped on the next clock tick (if it is still running).TN)r   r   r   r   r    r     s    zProgressTracker.stopc                 C   s   |t |kr|j| j}ndS || jks:|| j| d k r|||||d| j|< |sdd| j| d< nd|t  | j| d< | d| j|  | j| d S dS d S )N        r   )r*   r   rD   Zbest_templateZtemplate_results      ?r   r   )r?   	templatesr*   r   r
   r   )r&   rD   r   r   r   r2   r   r   r    r     s     zProgressTracker._add_resultc                 C   s   d S r1   r   r   r   r   r    r     s    zProgressTracker.on_completec                 C   s   d S r1   r   r   r   r   r    r     s    zProgressTracker.on_progressc                 C   s   d S r1   r   r   r   r   r    r     s    zProgressTracker.on_result)r   r   r   r   r$   propertyr   r   r   r   r   r   r   r   r   r   r(   r    r     s   >

r   c                   @   sV   e Zd ZdZdddZdd Zddd	Zdd
dZdd Zdd Z	dd Z
dd ZdS )r   a9  :class:`MultistrokeGesture` represents a gesture. It maintains a set of
    `strokes` and generates unistroke (ie :class:`UnistrokeTemplate`)
    permutations that are used for evaluating candidates against this gesture
    later.

    :Arguments:
        `name`
            Identifies the name of the gesture - it is returned to you in the
            results of a :meth:`Recognizer.recognize` search. You can have any
            number of MultistrokeGesture objects with the same name; many
            definitions of one gesture. The same name is given to all the
            generated unistroke permutations. Required, no default.
        `strokes`
            A list of paths that represents the gesture. A path is a list of
            Vector objects::

                gesture = MultistrokeGesture('my_gesture', strokes=[
                  [Vector(x1, y1), Vector(x2, y2), ...... ], # stroke 1
                  [Vector(), Vector(), Vector(), Vector() ]  # stroke 2
                  #, [stroke 3], [stroke 4], ...
                ])

            For template matching purposes, all the strokes are combined to a
            single list (unistroke). You should still specify the strokes
            individually, and set `stroke_sensitive` True (whenever possible).

            Once you do this, unistroke permutations are immediately generated
            and stored in `self.templates` for later, unless you set the
            `permute` flag to False.
        `priority`
            Determines when :func:`Recognizer.recognize` will attempt to match
            this template, lower priorities are evaluated first (only if
            a priority `filter` is used). You should use lower priority on
            gestures that are more likely to match. For example, set user
            templates at lower number than generic templates. Default is 100.
        `numpoints`
            Determines the number of points this gesture should be resampled to
            (for matching purposes). The default is 16.
        `stroke_sensitive`
            Determines if the number of strokes (paths) in this gesture is
            required to be the same in the candidate (user input) gesture
            during matching. If this is False, candidates will always be
            evaluated, disregarding the number of strokes. Default is True.
        `orientation_sensitive`
            Determines if this gesture is orientation sensitive. If True,
            aligns the indicative orientation with the one of eight base
            orientations that requires least rotation. Default is True.
        `angle_similarity`
            This is used by the :func:`Recognizer.recognize` function when a
            candidate is evaluated against this gesture. If the angles between
            them are too far off, the template is considered a non-match.
            Default is 30.0 (degrees)
        `permute`
            If False, do not use Heap Permute algorithm to generate different
            stroke orders when instantiated. If you set this to False, a
            single UnistrokeTemplate built from `strokes` is used.
    Nc                 K   s   || _ |dd| _|dd| _|dd| _|dd| _|dd	| _g | _|d k	r|| _|d
drv|   n"t	|dd |D | j| jdg| _
d S )Nr+   r]   r-   r^   Zstroke_sensitiveTr.   ra   r_   permutec                 S   s   g | ]}|D ]}|qqS r   r   rI   subir   r   r    rL   g  s       z/MultistrokeGesture.__init__.<locals>.<listcomp>pointsr-   r.   )r*   r7   r+   r-   r`   r>   ra   r@   r   r   r   rG   r   r   r    r$   X  s     
zMultistrokeGesture.__init__c                 C   s
   t | jS r1   )r   ra   r   r   r   r    angle_similarity_thresholdk  s    z-MultistrokeGesture.angle_similarity_thresholdFc                 C   s   | j | |r|   dS )zAdd a stroke to the self.strokes list. If `permute` is True, the
        :meth:`permute` method is called to generate new unistroke templatesN)r@   r=   r   )r&   stroker   r   r   r    
add_stroken  s    zMultistrokeGesture.add_strokec                 C   s   |}|dks|dk r| j }||}|||j}d}d}tdt|dD ]\}	|||	 ||	  ||	d  ||	d    7 }|||	 ||	d   ||	d  ||	   7 }qJt|| }
|t|
 |t|
  }|dkrd}n|dkrd}t	|S )a!  Compute the distance from this Candidate to a UnistrokeTemplate.
        Returns the Cosine distance between the stroke paths.

        `numpoints` will prepare both the UnistrokeTemplate and Candidate path
        to n points (when necessary), you probably don't want to do this.
        N   r   r   r   r{   )
r-   
get_vectorget_protractor_vectorr>   xranger?   r   math_cosmath_sinr   )r&   r   r   r-   r2   Zv1Zv2ar   r   Zangler   r   r   r    get_distanceu  s"    
,.zMultistrokeGesture.get_distancec                 K   s   t d}d}d}g }| jr:t| jt|jkr:||||fS |j}|j}| j}	|  }
t| j	D ]r\}}|j
rt|rzq^n|rzq^|d7 }|d|j}|j||d}||
krq^|	|||d}|| ||k r^|}|}q^||||fS )a  Match a given candidate against this MultistrokeGesture object. Will
        test against all templates and report results as a list of four
        items:

            `index 0`
                Best matching template's index (in self.templates)
            `index 1`
                Computed distance from the template to the candidate path
            `index 2`
                List of distances for all templates. The list index
                corresponds to a :class:`UnistrokeTemplate` index in
                self.templates.
            `index 3`
                Counter for the number of performed matching operations, ie
                templates matched against the candidate
        infinityNr   r   r   )r-   )r   r`   r?   r@   r   r   r   r   	enumerater   r>   r7   r-   get_angle_similarityr=   )r&   r   r'   Zbest_dZbest_tplr   rC   r   r   r   Zang_sim_thresholdidxr   r2   Zang_simr   r   r   r    r     s6    
z"MultistrokeGesture.match_candidatec                    sV   dd t dt jD  _g  _ t j  ` fdd  D  _ `dS )a  Generate all possible unistroke permutations from self.strokes and
        save the resulting list of UnistrokeTemplate objects in self.templates.

        Quote from http://faculty.washington.edu/wobbrock/pubs/gi-10.2.pdf ::

            We use Heap Permute [16] (p. 179) to generate all stroke orders
            in a multistroke gesture. Then, to generate stroke directions for
            each order, we treat each component stroke as a dichotomous
            [0,1] variable. There are 2^N combinations for N strokes, so we
            convert the decimal values 0 to 2^N-1, inclusive, to binary
            representations and regard each bit as indicating forward (0) or
            reverse (1). This algorithm is often used to generate truth tables
            in propositional logic.

        See section 4.1: "$N Algorithm" of the linked paper for details.

        .. Warning ::

            Using heap permute for gestures with more than 3 strokes
            can result in very large number of templates (a 9-stroke
            gesture = 38 million templates). If you are dealing with
            these types of gestures, you should manually compose
            all the desired stroke orders.
        c                 S   s   g | ]}|qS r   r   )rI   r   r   r   r    rL     s     z.MultistrokeGesture.permute.<locals>.<listcomp>r   c                    s"   g | ]}t  j| j jd qS )r   )r   r*   r-   r>   )rI   Zpermutationr   r   r    rL     s   N)r   r?   r@   _order_orders_heap_permute_make_unistrokesr   r   r   r   r    r     s    
zMultistrokeGesture.permutec                 C   s   | j }|dkr$| j|d d   nxd}td|D ]h}| |d  |d dkrv|d }||d  |d< |||d < q2|| }||d  ||< |||d < q2d S )Nr   r   r   )r   r   r=   r   r   )r&   r2   Z
self_orderr   tmpr   r   r    r   	  s    z MultistrokeGesture._heap_permutec           
      C   s   g }|j }| j}| jD ]}d}|tdt|k rg }|j }tdt|D ]D}|||  d d  }	||? d@ dkrx|	  |d  |	|dd < qH|| |d7 }qq|S )Nr   r   r   r{   )r=   r@   r   r   r?   r   reverse)
r&   Z
unistrokesZunistrokes_appendZself_strokesr   r   Z	unistrokeZunistroke_appendr   Zptsr   r   r    r     s"    
z#MultistrokeGesture._make_unistrokes)N)F)N)r   r   r   r   r$   r   r   r   r   r   r   r   r   r   r   r    r     s   9


'C*r   c                   @   sT   e Zd ZdZdddZdd ZdddZdd	d
ZdddZdddZ	dddZ
dS )r   a  Represents a (uni)stroke path as a list of Vectors. Normally, this class
    is instantiated by MultistrokeGesture and not by the programmer directly.
    However, it is possible to manually compose UnistrokeTemplate objects.

    :Arguments:
        `name`
            Identifies the name of the gesture. This is normally inherited from
            the parent MultistrokeGesture object when a template is generated.
        `points`
            A list of points that represents a unistroke path. This is normally
            one of the possible stroke order permutations from a
            MultistrokeGesture.
        `numpoints`
            The number of points this template should (ideally) be resampled to
            before the matching process. The default is 16, but you can use a
            template-specific settings if that improves results.
        `orientation_sensitive`
            Determines if this template is orientation sensitive (True) or
            fully rotation invariant (False). The default is True.

    .. Note::
        You will get an exception if you set a skip-flag and then attempt to
        retrieve those vectors.
    Nc                 K   s@   || _ |dd| _|dd| _i | _g | _|d k	r<|| _d S )Nr-   r^   r.   T)r*   r7   r-   r>   r0   r   )r&   r*   r   r'   r   r   r    r$   N  s    zUnistrokeTemplate.__init__c                 C   s   | j | i | _dS )z\Add a point to the unistroke/path. This invalidates all previously
        computed vectors.Nr   r=   r0   )r&   rX   r   r   r    	add_pointY  s    zUnistrokeTemplate.add_pointc                 C   s0   |r|p| j }|| jkr"| | | j| | S r1   r-   r0   r   )r&   r6   r-   r2   r   r   r    _get_db_keya  s    

zUnistrokeTemplate._get_db_keyc                 C   s   |  d|S )Nstartvectorr   r&   r-   r   r   r    get_start_unit_vectorg  s    z'UnistrokeTemplate.get_start_unit_vectorc                 C   s   |  d|S )Nvectorr   r   r   r   r    r   j  s    zUnistrokeTemplate.get_vectorc                 C   s   |  d|S )Nr   r   r   r   r   r    
get_pointsm  s    zUnistrokeTemplate.get_pointsc                 C   s   | j std|p| j}|r$|dk r,tdt| j |}t|}t|| }t|tt}| j	rjt||
 }t
|t}t||d t|| j	d| j|< dS )zThis function prepares the UnistrokeTemplate for matching given a
        target number of points (for resample). 16 is optimal.z$prepare() called without self.pointsr   z'prepare() called with invalid numpoints   )r   r   N)r   r   r-   resampleindicative_angle	rotate_by	scale_dim
SQUARESIZEONEDTHRESHOLDr>   translate_toORIGINstart_unit_vector	vectorizer0   )r&   r-   r2   rX   r   r   r   r    r   p  s    


zUnistrokeTemplate.prepare)N)N)N)N)N)N)r   r   r   r   r$   r   r   r   r   r   r   r   r   r   r    r   5  s   




r   c                   @   sL   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dddZ
dS )r   aD  Represents a set of unistroke paths of user input, ie data to be matched
    against a :class:`UnistrokeTemplate` object using the Protractor algorithm.
    By default, data is precomputed to match both rotation bounded and fully
    invariant :class:`UnistrokeTemplate` objects.

    :Arguments:
        `strokes`
            See :data:`MultistrokeGesture.strokes` for format example. The
            Candidate strokes are simply combined to a unistroke in the order
            given. The idea is that this will match one of the unistroke
            permutations in `MultistrokeGesture.templates`.
        `numpoints`
            The Candidate's default N; this is only for a fallback, it is not
            normally used since n is driven by the UnistrokeTemplate we are
            being compared to.
        `skip_bounded`
            If True, do not generate/store rotation bounded vectors
        `skip_invariant`
            If True, do not generate/store rotation invariant vectors

    Note that you WILL get errors if you set a skip-flag and then attempt to
    retrieve the data.Nr^   c                 K   s@   | dd| _| dd| _|| _i | _g | _|d k	r<|| _d S )Nr   Fr   )r7   r   r   r-   r0   r@   )r&   r@   r-   r'   r   r   r    r$     s    zCandidate.__init__c                 C   s   | j | i | _dS )z[Add a stroke to the candidate; this will invalidate all
        previously computed vectorsNr   )r&   r   r   r   r    r     s    zCandidate.add_strokec                 C   s@   |r|p| j }|| jkr"| | |r*dp,d}| j| ||  S )NZbound_Zinv_r   )r&   r6   r-   r>   r2   prefixr   r   r    r     s
    

zCandidate._get_db_keyc                 C   s   |  d||S )a  (Internal use only) Get the start vector for this Candidate,
        with the path resampled to `numpoints` points. This is the first
        step in the matching process. It is compared to a
        UnistrokeTemplate object's start vector to determine angle
        similarity.r   r   r&   r-   r>   r   r   r    r     s    zCandidate.get_start_unit_vectorc                 C   s   |  d||S )z^(Internal use only) Return vector for comparing to a
        UnistrokeTemplate with Protractorr   r   r   r   r   r    r     s    zCandidate.get_protractor_vectorc                 K   s^   | d| j}| ||j\}}||\}}|| ||  }|dkrJdS |dkrVtS t|S )z(Internal use only) Compute the angle similarity between this
        Candidate and a UnistrokeTemplate object. Returns a number that
        represents the angle similarity (lower is more similar).r-   r   r   r{   )r7   r-   r   r>   r
   r   )r&   r   r'   r2   Zv1xZv1yZv2xZv2yr   r   r    r     s    zCandidate.get_angle_similarityc           	      C   s   |r|p| j }dd | jD }t||}t|}t|| }t|tt}|d }i }| jst	|t
}t|||d< t|d|d< | jst||
 }t	|t
}t|||d< t|d|d	< || j|< d
S )a  Prepare the Candidate vectors. self.strokes is combined to a single
        unistroke (connected end-to-end), resampled to :attr:`numpoints`
        points, and then the vectors are calculated and stored in self.db (for
        use by `get_distance` and `get_angle_similarity`)c                 S   s   g | ]}|D ]}|qqS r   r   r   r   r   r    rL     s       z%Candidate.prepare.<locals>.<listcomp>r   Zinv_startvectorFZ
inv_vectorZbound_startvectorTZbound_vectorN)r-   r@   r   r   r   r   r   r   r   r   r   r   r   r   r0   )	r&   r-   r2   r   r   Zangidxr   Z
inv_pointsZbound_pointsr   r   r    r     s$    


zCandidate.prepare)Nr^   )N)r   r   r   r   r$   r   r   r   r   r   r   r   r   r   r    r     s   
r   c                 C   sB  t | r|r|dk rtdt| |d  }d}d}| d g}| d d  }d}t | }|j}	|j}
|t |k r(||d  }|| }t||}|| |kr|d || | |d |d    }|d || | |d |d    }t||}|	| |
|| |d7 }|d7 }d}n||7 }|d7 }qb||k r>|	| d  |S )Nr   z(resample() called with invalid argumentsr   r   r   r{   )r?   r   path_lengthr=   insertdistancer   )r   r2   intervalDr   	newpointsZ
workpointsZnewpoints_lenZworkpoints_lenZ
new_appendZwork_insertp1p2r   qxqyqr   r   r    r     s:    

$$



r   c                 C   s.   t | \}}t|| d d  || d d  S Nr   r   )centroidr   )r   cxcyr   r   r    r   5  s    r   c                 C   s   t | \}}t|}t|}g }|j}tdt| D ]j}| | d | | | | d | |  | }	| | d | | | | d | |  | }
|t|	|
 q4|S r   )r   r   r   r=   r   r?   r   )r   r   r   r   r   r   r   newpoints_appendr   r   r   r   r   r    r   :  s    ,,r   c                 C   s   t | \}}}}|dks |dkr0td||t|| || |k}|rh|t|| }|t|| }	n|| }|| }	g }
|
j}| D ]*}|d | }|d |	 }|t|| q|
S )Nr   z2scale_dim() called with invalid points: h:{}, w:{}r   )bounding_boxr   formatminr   r=   r   )r   sizeZ	oneDratioZbbox_xZbbox_yZbbox_wZbbox_hZ	uniformlyZqx_sizeZqy_sizer   r   rX   r   r   r   r   r    r   J  s*     r   c           
      C   sV   t | \}}|\}}g }| D ]4}|d | | }|d | | }	|t||	 q|S r   )r   r=   r   )
r   ptr   r   ZptxZptyr   rX   r   r   r   r   r    r   g  s    r   c                 C   s   d}d}|r^t | d d | d d }td t|td  td   }t|| }t|| }d}g }d}|j}	| D ]T\}
}|
| ||  }|| |
|  }|	| |	| |d7 }||d |d  7 }qtt|}td|D ]}||  |  < q|S )Nr   r   r   r   g      @g       @r   )r   r
   r   r   r   r=   r	   r   )r   Zuse_bounded_rotation_invariancer   r   angZbosumr   Z
vector_lenZvector_appendpxpyZnewxZnewyZ	magnituder   r   r   r    r   s  s,     r   c                 C   sZ   d}d}t | }td|D ]$}|| | d 7 }|| | d 7 }q|| }|| }t||S )Nr   r   r   )r?   r   r   )r   rJ   rK   Z
points_lenr   r   r   r    r     s    r   c                 C   sz   t d}t d}t d}t d}| D ]8\}}||k r8|}||krD|}||k rP|}||kr$|}q$|||| d || d fS )Nr   z	-infinityr   )r   )r   ZminxZminyZmaxxZmaxyr  r  r   r   r    r     s    r   c                 C   s6   d}t dt| D ]}|t| |d  | | 7 }q|S )Nr   r   )r   r?   r   )r   r   r   r   r   r    r     s    r   c                 C   s4   |d | d  }|d | d  }t |d |d  S Nr   r   r   )r	   )r   r   ZdxZdyr   r   r    r     s    r   c                 C   s`   t |}| | d | d d  | | d | d d   }}t|d |d  }t|| || S r  )r:   r	   r   )r   indexr   ZvxZvylengthr   r   r    r     s    2r   )<r   __all__rS   rQ   rO   rer   rA   collectionsr   mathr	   r
   r   r   r   r   r   r   r   r   r   r   Zkivy.vectorr   Z
kivy.clockr   Z
kivy.eventr   Zkivy.propertiesr   Zkivy.compatr   rW   r   ranger   r   r   r   r   	Exceptionr   r   r   objectr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    <module>   sV   v(
   n   `w)