U
    d5                     @   s  d 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
mZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ eeZdZdd ZdYddZedddddddgZdej_ G dd deddddgZ!de!j_ 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'dZd,d-Z(d[d.d/Z)d0d1 Z*d2d3 Z+d\d5d6Z,d]d8d9Z-G d:d; d;e"Z.d^d<d=Z/d_d?d@Z0dAdB Z1d`dCdDZ2dadEdFZ3dGdH Z4dIdJ Z5dbdKdLZ6ej7ej8j9fej:ej8j;fej<ej8j=fej>ej8j?fej@ej8jAfejBej8jCfejDej8jEfejFej8jGfejHej8jIfejJej8jKfejLej8jMfgZNdMdN ZOdcdOdPZPdddQdRZQdSdT ZRdUdV ZSdWdX ZTdS )ea  
Defines a minimal set of data types that allow to represent datasets with
arbitrary nested structure, including objects of variable length, such as
maps and lists.

This defines a columnar storage format for such datasets on top of caffe2
tensors. In terms of capacity of representation, it can represent most of
the data types supported by Parquet, ORC, DWRF file formats.

See comments in operator_test/dataset_ops_test.py for an example and
walkthrough on how to use schema to store and iterate through a structured
in-memory dataset.
    N)core)	workspace)BlobReference)OrderedDict
namedtuple)
basestring)	viewitemsviewkeys
viewvalues)islice)StringIO)Sequence:c                 C   s.   | r|rd | t|S | r| S |r&|S dS d S )Nz{}{}{} )formatFIELD_SEPARATOR)prefixsuffix r   8/tmp/pip-unpacked-wheel-ua33x9lu/caffe2/python/schema.py_join_field_name&   s    r   Tc                 C   s@   t | tr| j|dS t| ttjfkr2t| dS t| dS dS )z:Clones/normalizes a field before adding it to a container.
keep_blobsdtype)blobN)
isinstanceFieldclonetypenpr   Scalar)Zfield_or_type_or_blobr   r   r   r   _normalize_field1   s
    

r"   FeatureSpecZfeature_typeZfeature_namesZfeature_idsZfeature_is_request_onlyZdesired_hash_sizeZfeature_to_index)NNNNNNc                   @   s"   e Zd ZU dZdZee ed< dS )MetadataaS  Represents additional information associated with a scalar in schema.

    `categorical_limit` - for fields of integral type that are guaranteed to be
    non-negative it specifies the maximum possible value plus one. It's often
    used as a size of an embedding table.

    `expected_value` - anticipated average value of elements in the field.
    Usually makes sense for length fields of lists.

    `feature_specs` - information about the features that contained in this
    field. For example if field have more than 1 feature it can have list of
    feature names contained in this field.r   	__slots__N)__name__
__module____qualname____doc__r%   r   str__annotations__r   r   r   r   r$   K   s   
r$   categorical_limitZexpected_valueZfeature_specs)NNNc                   @   s   e Zd ZU dZdZee ed< dd Zdd Z	dd	 Z
d
d Zdd Zdd Zdd Zdd Zd$ddZdd Zdd Zd%ddZdd Zd d! Zd"d# ZdS )&r   z4Represents an abstract field type in a dataset.
    )_parent_field_offsetsr%   c                 C   sF   d| _ d}g | _|D ] }| j| |t| 7 }q| j| dS )z:Derived classes must call this after their initialization.Nr   r   N)r-   r.   appendlenfield_names)selfchildrenoffsetchildr   r   r   __init__i   s    zField.__init__c                 C   s   | j ddS )NFr   )r   r3   r   r   r   clone_schemas   s    zField.clone_schemac                 C   s   t ddS )z/Return the children field names for this field.Field is an abstract class.NNotImplementedErrorr8   r   r   r   r2   v   s    zField.field_namesc                 C   s   t ddS )z7Return the numpy.dtype for each of the children fields.r:   Nr;   r8   r   r   r   field_typesz   s    zField.field_typesc                 C   s   t ddS )z4Return the Metadata for each of the children fields.r:   Nr;   r8   r   r   r   field_metadata~   s    zField.field_metadatac                 C   s   t ddS )zReturn the list of blobs with contents for this Field.
        Values can either be all numpy.ndarray or BlobReference.
        If any of the fields doesn't have a blob, throws.
        r:   Nr;   r8   r   r   r   field_blobs   s    zField.field_blobsc                 C   s   t ddS )zyReturn the list of all Scalar instances in the Field.
        The order is the same as for field_names() or field_blobs()r:   Nr;   r8   r   r   r   all_scalars   s    zField.all_scalarsc                 C   s   t ddS )z4Return True if every scalar of this field has blobs.r:   Nr;   r8   r   r   r   	has_blobs   s    zField.has_blobsTc                 C   s   t ddS )z)Clone this Field along with its children.r:   Nr;   r3   r   r   r   r   r      s    zField.clonec                 C   s   ||f| _ d S N)r-   )r3   parentZrelative_idr   r   r   _set_parent   s    zField._set_parentc                 C   s   |   }t||t|   S )a  
        Returns a slice representing the range of field ids that belong to
        this field. This slice can be used to index a list of fields.

        E.g.:

        >>> s = Struct(
        >>>     ('a', Scalar()),
        >>>     ('b', Struct(
        >>>         ('b1', Scalar()),
        >>>         ('b2', Scalar()),
        >>>     )),
        >>>     ('c', Scalar()),
        >>> )
        >>> field_data = ['da', 'db1', 'db2', 'dc']
        >>> field_data[s.b.split()]
        ['db1', 'db2']
        )_child_base_idslicer1   r2   )r3   Zbase_idr   r   r   rG      s    zField.sliceNc                 C   s6   | j \}}|dkrdn| j| }|r2|||7 }|S )z"Get the base id of the given childNr   )r-   r.   rF   )r3   Zchild_indexpiposr   r   r   rF      s
    
zField._child_base_idc                 C   s0   |   |  ko.|  | ko.|  | kS )zEquivalance of two schemas)r2   r=   r>   )r3   otherr   r   r   __eq__   s
    zField.__eq__c                 C   s   t dd S )Nr:   r;   r3   indent
str_bufferr   r   r   _pprint_impl   s    zField._pprint_implc                 C   s&   t  }| d| | }|  |S r/   )r   rP   getvalueclose)r3   rO   contentsr   r   r   __repr__   s
    zField.__repr__)T)N)r&   r'   r(   r)   r%   r   r*   r+   r7   r9   r2   r=   r>   r?   r@   rA   r   rE   rG   rF   rL   rP   rT   r   r   r   r   r   c   s"   



r   c                       s   e Zd ZU dZdZee ed< d fdd	Zdd Z	d	d
 Z
dd Zdd Zdd Zdd ZdddZdd Zdd Zdd Z  ZS )Lista(  Represents a variable-length list.

    Values of a list can also be complex fields such as Lists and Structs.
    In addition to the fields exposed by its `values` field, a List exposes an
    additional `lengths` field, which will contain the size of each list under
    the parent domain.
    )lengths_itemsr%   Nc                    st   t |tr$t |tstt|| _nttj|| _t|| _| j	| d | j	| d t
t| | j| jg d S )Nr      )r   r   r!   AssertionErrorr"   rV   r    int32rW   rE   superrU   r7   )r3   valueslengths_blob	__class__r   r   r7      s    

zList.__init__c                 C   s   | j  }dgdd |D  S )NrV   c                 S   s   g | ]}t d |qS r\   r   .0vr   r   r   
<listcomp>   s     z$List.field_names.<locals>.<listcomp>rW   r2   r3   Zvalue_fieldsr   r   r   r2      s    
zList.field_namesc                 C   s   | j  | j  S rC   )rV   r=   rW   r8   r   r   r   r=      s    zList.field_typesc                 C   s   | j  | j  S rC   )rV   r>   rW   r8   r   r   r   r>      s    zList.field_metadatac                 C   s   | j  | j  S rC   )rV   r?   rW   r8   r   r   r   r?      s    zList.field_blobsc                 C   s   | j  | j  S rC   )rV   r@   rW   r8   r   r   r   r@      s    zList.all_scalarsc                 C   s   | j  o| j S rC   )rV   rA   rW   r8   r   r   r   rA      s    zList.has_blobsTc                 C   s"   t | t| j|dt| j|dS Nr   )r   r"   rW   rV   rB   r   r   r   r      s    z
List.clonec                 C   s|   | d| d  | d|d  d  | jj|d |d | d|d  d  | jj|d |d | d| d  d S )	N  zList(
rX   	lengths=
   rN   rO   _items=
)
)writerV   rP   rW   rM   r   r   r   rP      s    zList._pprint_implc                 C   sP   | drt|t| jtr*t| j|S |dks:|dkr@| jS td| dS )\If the value of this list is a struct,
        allow to introspect directly into its fields.__valueitemsField not found in list: %s.N)
startswithAttributeErrorr   rW   Structgetattrr3   itemr   r   r   __getattr__  s    
zList.__getattr__c                 C   s`   | td}t|dkr6|dkr&| jS |dkrP| jS n|d dkrP| j|d  S td| d S )NrX   rV   r\   r   rt   )splitr   r1   rV   rW   KeyErrorr3   rz   namesr   r   r   __getitem__  s    zList.__getitem__)N)Tr&   r'   r(   r)   r%   r   r*   r+   r7   r2   r=   r>   r?   r@   rA   r   rP   r{   r   __classcell__r   r   r^   r   rU      s   

rU   c                       s   e Zd ZU dZdZee ed< d fdd	Zdd Z	d	d
 Z
dd Zdd Zdd Zdd ZdddZdd Zdd Zdd Z  ZS )ListWithEvictedzi
    This class is similar with List, but containing extra field evicted_values for
    LRU Hashing.
    )_evicted_valuesr%   Nc                    sJ   t |tr$t |tstt|| _nttj|| _tt	| j
||d d S )Nr]   )r   r   r!   rY   r"   r   r    int64r[   r   r7   )r3   r\   r]   evicted_valuesr^   r   r   r7   %  s
    
zListWithEvicted.__init__c                 C   s$   | j  }dgdd |D  dg S )NrV   c                 S   s   g | ]}t d |qS r`   ra   rb   r   r   r   re   0  s     z/ListWithEvicted.field_names.<locals>.<listcomp>r   rf   rg   r   r   r   r2   -  s    
zListWithEvicted.field_namesc                 C   s   | j  | j  | j  S rC   )rV   r=   rW   r   r8   r   r   r   r=   3  s    zListWithEvicted.field_typesc                 C   s   | j  | j  | j  S rC   )rV   r>   rW   r   r8   r   r   r   r>   6  s    zListWithEvicted.field_metadatac                 C   s   | j  | j  | j  S rC   )rV   r?   rW   r   r8   r   r   r   r?   9  s    zListWithEvicted.field_blobsc                 C   s   | j  | j  | j  S rC   )rV   r@   rW   r   r8   r   r   r   r@   <  s    zListWithEvicted.all_scalarsc                 C   s   | j  o| j | j  S rC   )rV   rA   rW   r   r8   r   r   r   rA   ?  s    zListWithEvicted.has_blobsTc                 C   s.   t | t| j|dt| j|dt| j|dS rh   )r   r"   rW   rV   r   rB   r   r   r   r   B  s
    zListWithEvicted.clonec                 C   s   | d| d  | d|d  d  | jj|d |d | d|d  d  | jj|d |d | d|d  d  | jj|d |d | d| d	  d S )
Nri   zListWithEvicted(
rX   rj   rk   rl   rm   z_evicted_values=
rn   )ro   rV   rP   rW   r   rM   r   r   r   rP   I  s    zListWithEvicted._pprint_implc                 C   s^   | drt||dkr | jS t| jtr8t| j|S |dksH|dkrN| jS td| dS )rp   rq   r   rr   rs   rt   N)ru   rv   r   r   rW   rw   rx   ry   r   r   r   r{   T  s    
zListWithEvicted.__getattr__c                 C   sn   | td}t|dkrD|dkr&| jS |dkr4| jS |dkr^| jS n|d dkr^| j|d  S td| d S )NrX   rV   r\   r   r   rt   )r|   r   r1   rV   rW   r   r}   r~   r   r   r   r   b  s    zListWithEvicted.__getitem__)NN)Tr   r   r   r^   r   r     s   

r   c                       s   e Zd ZU dZdZee ed<  fddZdd Z	dd	 Z
d
d Zdd Zdd Zdd Zdd Zdd Zd-ddZdd Zdd Zdd Zdd  Zd!d" Zd#d$ Z fd%d&Z fd'd(Zd)d* Zd+d, Z  ZS ).rw   z?Represents a named list of fields sharing the same domain.
    )fields_frozenr%   c                    s  |D ]8}t |dkst|d s(td|d dkstdqdd |D }t | _|D ]p\}}t|krx| ||\}}|| jkr|| j|< qXt|trt| j| tstd| | j| | | j|< qXt	t
| jD ]\}\}}|| | qtt| t| j d	| _d
S )a    fields is a list of tuples in format of (name, field). The name is
        a string of nested name, e.g., `a`, `a:b`, `a:b:c`. For example

        Struct(
          ('a', Scalar()),
          ('b:c', Scalar()),
          ('b:d:e', Scalar()),
          ('b', Struct(
            ('f', Scalar()),
          )),
        )

        is equal to

        Struct(
          ('a', Scalar()),
          ('b', Struct(
            ('c', Scalar()),
            ('d', Struct(('e', Scalar()))),
            ('f', Scalar()),
          )),
        )
        rk   r   zField names cannot be emptyrV   z.Struct cannot contain a field named `lengths`.c                 S   s   g | ]\}}|t |fqS r   r"   )rc   namefieldr   r   r   re     s     z#Struct.__init__.<locals>.<listcomp>zDuplicate field name: %sTN)r1   rY   r   r   r   _struct_from_nested_namer   rw   
ValueError	enumerater   rE   r[   r7   r
   r   )r3   r   r   r   id_r^   r   r   r7   x  s0    

zStruct.__init__c                    s>    fdd | td}t|dks(t|d  |d |fS )Nc                    s<   |  td}t|dkr|}n |d |}t|d |fS NrX   r   )r|   r   r1   rw   )nested_namer   r   Zadded_fieldcreate_internalr   r   r     s
    z8Struct._struct_from_nested_name.<locals>.create_internalrX   rk   r   )r|   r   r1   rY   )r3   r   r   r   r   r   r   r     s    zStruct._struct_from_nested_namec                 C   s   t t| jS rC   )listr   r   r8   r   r   r   get_children  s    zStruct.get_childrenc                    s6   g }t | jD ]"\ }| fdd| D 7 }q|S )Nc                    s   g | ]}t  |qS r   ra   rc   fr   r   r   re     s     z&Struct.field_names.<locals>.<listcomp>)r   r   r2   )r3   r   r   r   r   r   r2     s    zStruct.field_namesc                 C   s(   g }t | jD ]\}}|| 7 }q|S rC   )r   r   r=   )r3   typesr   r   r   r   r   r=     s    zStruct.field_typesc                 C   s(   g }t | jD ]\}}|| 7 }q|S rC   )r   r   r>   )r3   metadatar   r   r   r   r   r>     s    zStruct.field_metadatac                 C   s(   g }t | jD ]\}}|| 7 }q|S rC   )r   r   r?   )r3   blobsr   r   r   r   r   r?     s    zStruct.field_blobsc                 C   s(   g }t | jD ]\}}|| 7 }q|S rC   )r   r   r@   )r3   scalarsr   r   r   r   r   r@     s    zStruct.all_scalarsc                 C   s   t dd t| jD S )Nc                 s   s   | ]}|  V  qd S rC   )rA   )rc   r   r   r   r   	<genexpr>  s     z#Struct.has_blobs.<locals>.<genexpr>)allr
   r   r8   r   r   r   rA     s    zStruct.has_blobsTc                    s$    fddt | jD }t| | S )Nc                    s    g | ]\}}|t | d fqS )r   r   rc   krd   r   r   r   re     s   z Struct.clone.<locals>.<listcomp>)r   r   r   )r3   r   Znormalized_fieldsr   r   r   r     s    
zStruct.clonec              	   C   sh   | td}| j|d d }|d kr*d S t|dkr:|S z||d  W S  ttfk
rb   Y d S X d S r   )r|   r   r   getr1   r}   	TypeError)r3   r   r   r   r   r   r   _get_field_by_nested_name  s    z Struct._get_field_by_nested_namec                 C   sn   | d| d  t| jD ]:\}}| d|d  d| d  |j|d |d q| d| d  d S )	Nri   z	Struct( 
rX   z{}=
rk   rl   z) 
)ro   r   r   r   rP   )r3   rN   rO   r   r   r   r   r   rP     s
     zStruct._pprint_implc                 C   s   |  |}|d k	S rC   )r   r3   rz   r   r   r   r   __contains__  s    
zStruct.__contains__c                 C   s
   t | jS rC   )r1   r   r8   r   r   r   __len__  s    zStruct.__len__c                    s   t |tst |tr:ttj t fdd|D  S t |trZttt	j|dS 
|}|dkrxtd| |S dS )z
        item can be a tuple or list of ints or strings, or a single
        int or string. String item is a nested field name, e.g., "a", "a:b",
        "a:b:c". Int item is the index of a field at the first level of the
        Struct.
        c                    s*   g | ]"}t |tr | n|| fqS r   )r   int)rc   r   keysr3   r   r   re     s   
 z&Struct.__getitem__.<locals>.<listcomp>Nzfield "%s" not found)r   r   tupler	   r   rw   r   nextr   r
   r   r}   r   r   r   r   r     s    

zStruct.__getitem__c                 C   s   t | ||S )z
        similar to python's dictionary get method, return field of item if found
        (i.e. self.item is valid) or otherwise return default_value

        it's a syntax suger of python's builtin getattr method
        )rx   )r3   rz   default_valuer   r   r   r     s    z
Struct.getc                    sJ   | drt|ztt| d| W S  tk
rD   t|Y nX d S )Nrq   r   )ru   rv   r[   rw   __getattribute__r}   ry   r^   r   r   r{      s    
zStruct.__getattr__c                    s4   t | dd r|dstdtt| || d S )Nr   r   z1Struct.__setattr__() is disabled after __init__())rx   ru   r   r[   rw   __setattr__)r3   keyrr   r^   r   r   r   (  s    zStruct.__setattr__c                 C   s   t |tstS t|  }| D ]n\}}||kr<|||< q"|| }t |trXt |tstdtt| d tt| d | || ||< q"tt| S )a  
        Allows to merge fields of two schema.Struct using '+' operator.
        If two Struct have common field names, the merge is conducted
        recursively. Here are examples:

        Example 1
        s1 = Struct(('a', Scalar()))
        s2 = Struct(('b', Scalar()))
        s1 + s2 == Struct(
            ('a', Scalar()),
            ('b', Scalar()),
        )

        Example 2
        s1 = Struct(
            ('a', Scalar()),
            ('b', Struct(('c', Scalar()))),
        )
        s2 = Struct(('b', Struct(('d', Scalar()))))
        s1 + s2 == Struct(
            ('a', Scalar()),
            ('b', Struct(
                ('c', Scalar()),
                ('d', Scalar()),
            )),
        )
        Type of left_field, z, and type of right_field, z6, must both the Struct to allow merging of the field, )	r   rw   NotImplementedr   r   r   r*   r   r   )r3   rK   r4   r   right_field
left_fieldr   r   r   __add__1  s,    

zStruct.__add__c                 C   s   t |tstS t|  }| D ]\}}||kr"|| }t|t|krzt |trn|| }| rn|||< q"|| q"tdtt| d tt| d | q"t|	  S )a  
        Allows to remove common fields of two schema.Struct from self by
        using '-' operator. If two Struct have common field names, the
        removal is conducted recursively. If a child struct has no fields
        inside, it will be removed from its parent. Here are examples:

        Example 1
        s1 = Struct(
            ('a', Scalar()),
            ('b', Scalar()),
        )
        s2 = Struct(('a', Scalar()))
        s1 - s2 == Struct(('b', Scalar()))

        Example 2
        s1 = Struct(
            ('b', Struct(
                ('c', Scalar()),
                ('d', Scalar()),
            ))
        )
        s2 = Struct(
            ('b', Struct(('c', Scalar()))),
        )
        s1 - s2 == Struct(
            ('b', Struct(
                ('d', Scalar()),
            )),
        )

        Example 3
        s1 = Struct(
            ('a', Scalar()),
            ('b', Struct(
                ('d', Scalar()),
            ))
        )
        s2 = Struct(
            ('b', Struct(
                ('c', Scalar())
                ('d', Scalar())
            )),
        )
        s1 - s2 == Struct(
            ('a', Scalar()),
        )
        r   z*, is not the same as that of right_field, z%, yet they have the same field name, )
r   rw   r   r   r   r   popr   r*   rs   )r3   rK   r4   r   r   r   r6   r   r   r   __sub__`  s2    0


zStruct.__sub__)T)r&   r'   r(   r)   r%   r   r*   r+   r7   r   r   r2   r=   r>   r?   r@   rA   r   r   rP   r   r   r   r   r{   r   r   r   r   r   r   r^   r   rw   r  s,   
1
		/rw   c                       s   e Zd ZU dZdZee ed< d- fdd	Zdd Z	d	d
 Z
dd Zdd Zdd Zdd Zdd Zd.ddZdd Zdd Zedd Zdd Zd d! Zd/d#d$Zd0d%d&Zd'd( Zd)d* Zd+d, Z  ZS )1r!   a>  Represents a typed scalar or tensor of fixed shape.

    A Scalar is a leaf in a schema tree, translating to exactly one tensor in
    the dataset's underlying storage.

    Usually, the tensor storing the actual values of this field is a 1D tensor,
    representing a series of values in its domain. It is possible however to
    have higher rank values stored as a Scalar, as long as all entries have
    the same shape.

    E.g.:

        Scalar(np.float64)

            Scalar field of type float64. Caffe2 will expect readers and
            datasets to expose it as a 1D tensor of doubles (vector), where
            the size of the vector is determined by this fields' domain.

        Scalar((np.int32, 5))

            Tensor field of type int32. Caffe2 will expect readers and
            datasets to implement it as a 2D tensor (matrix) of shape (L, 5),
            where L is determined by this fields' domain.

        Scalar((str, (10, 20)))

            Tensor field of type str. Caffe2 will expect readers and
            datasets to implement it as a 3D tensor of shape (L, 10, 20),
            where L is determined by this fields' domain.

    If the field type is unknown at construction time, call Scalar(), that will
    default to np.void as its dtype.

    It is an error to pass a structured dtype to Scalar, since it would contain
    more than one field. Instead, use from_dtype, which will construct
    a nested `Struct` field reflecting the given dtype's structure.

    A Scalar can also contain a blob, which represents the value of this
    Scalar. A blob can be either a numpy.ndarray, in which case it contain the
    actual contents of the Scalar, or a BlobReference, which represents a
    blob living in a caffe2 Workspace. If blob of different types are passed,
    a conversion to numpy.ndarray is attempted.
    )	_metadatar   _original_dtype_blobr%   Nc                    s,   d | _ | j|||dd tt| g  d S )NTunsafe)r   setr[   r!   r7   )r3   r   r   r   r^   r   r   r7     s    zScalar.__init__c                 C   s   dgS )Nr   r   r8   r   r   r   r2     s    zScalar.field_namesc                 C   s   | j S rC   r   r8   r   r   r   
field_type  s    zScalar.field_typec                 C   s   | j gS rC   r   r8   r   r   r   r=     s    zScalar.field_typesc                 C   s   | j gS rC   r   r8   r   r   r   r>     s    zScalar.field_metadatac                 C   s
   | j d k	S rC   )r   r8   r   r   r   rA     s    zScalar.has_blobsc                 C   s   | j d k	std| j gS )N Value is not set for this field.r   rY   r8   r   r   r   r?     s    zScalar.field_blobsc                 C   s   | gS rC   r   r8   r   r   r   r@     s    zScalar.all_scalarsTc                 C   s   t | j|r| jnd | jdS )Nr   r   r   )r!   r   r   r   rB   r   r   r   r     s
    zScalar.clonec                 C   s   | j dk	std| j S )z+Gets the current blob of this Scalar field.Nr   r   r8   r   r   r   r     s    z
Scalar.getc                 C   s   |   S )zShortcut for self.get())r   r8   r   r   r   __call__  s    zScalar.__call__c                 C   s   | j S rC   r   r8   r   r   r   r     s    zScalar.metadatac                 C   s.   t |tstdt||| _|   d S )Nz!metadata must be Metadata, got {})r   r$   rY   r   r   r   _validate_metadata)r3   rr   r   r   r   set_metadata  s
    zScalar.set_metadatac                 C   sL   | j d krd S | j jd k	rH| jd k	rHt| jtjsHtdd| j d S )Nz6`categorical_limit` can be specified only in integral zfields but got {})r   r,   r   r    Z
issubdtypeintegerrY   r   r8   r   r   r   r     s    

zScalar._validate_metadataFc                 C   sj   | j jtjkrT|rTt|tjs,td||j j| j jksTtd| j j|j j| j| j	||d dS )z<Sets only the blob field still validating the existing dtypezGot {!r}zExpected {}, got {})r   r   r   N)
r   baser    voidr   ndarrayrY   r   r   r   )r3   r   throw_on_type_mismatchr   r   r   r   	set_value  s    zScalar.set_valuec                 C   s  |st d |dk	r(t|tr(td|| _|dk	rXt|trX|d dkrX|d df}|dk	rt|tr|d tjkrt	d
||t|}|dk	rzt|tszt|tj}|dk	r|tjkrtj||jd}|jdkr|s|d	|j }n"t|tjstd
tt| t|jdkr8|s8|d}t|jdkrz|dk	rz|jtjkrzt|j|jdd f}|dkrttj}|jrtd|| _|| _|dk	r| | |   dS )a'  Set the type and/or blob of this scalar. See __init__ for details.

        Args:
            dtype: can be any numpy type. If not provided and `blob` is
                   provided, it will be inferred. If no argument is provided,
                   this Scalar will be of type np.void.
            blob:  if provided, can be either a BlobReference or a
                   numpy.ndarray. If a value of different type is passed,
                   a conversion to numpy.ndarray is attempted. Strings aren't
                   accepted, since they can be ambiguous. If you want to pass
                   a string, to either BlobReference(blob) or np.array(blob).
            metadata: optional instance of Metadata, if provided overrides
                      the metadata information of the scalar
        zScalar should be considered immutable. Only call Scalar.set() on newly created Scalar with unsafe=True. This will become an error soon.NzrPassing str blob to Scalar.set() is ambiguous. Do either set(blob=np.array(blob)) or set(blob=BlobReference(blob))rX   r   )rX   zCannot set the Scalar with type {} for blob {}.If this blob is the output of some operation, please verify the input of that operation has proper type.r   )r   zInvalid blob type: %szECannot create Scalar with a structured dtype. Use from_dtype instead.)loggerwarningr   r   r   r   r   r    r   r   r   r   r   r   arrayr   sizeZreshapeshaperY   r*   r   r1   r   r   r   r   )r3   r   r   r   r   Zpreserve_shaper   r   r   r     sZ     






z
Scalar.setc                 C   s6   || _ |d k	rt|| _nttj| _|   d S rC   )r   r    r   r   r   )r3   r   r   r   r   set_typeo  s
    zScalar.set_typec                 C   s*   | d| d| j| j| j d  d S )Nri   zScalar({!r}, {!r}, {!r})r   )ro   r   r   r   r   rM   r   r   r   rP   w  s    
  zScalar._pprint_implc                 C   s   |   S )z
        Return the zero-indexed position of this scalar field in its schema.
        Used in order to index into the field_blob list returned by readers or
        accepted by writers.
        )rF   r8   r   r   r   r   |  s    z	Scalar.id)NNN)T)FF)NNNF)r&   r'   r(   r)   r%   r   r*   r+   r7   r2   r   r=   r>   rA   r?   r@   r   r   r   propertyr   r   r   r   r   r   rP   r   r   r   r   r^   r   r!     s,   
,

	

Sr!   r   r\   c                 C   s   t t|| f||f|dS )zA map is a List of Struct containing keys and values fields.
    Optionally, you can provide custom name for the key and value fields.
    r   )rU   rw   )r   r\   	keys_namevalues_namer]   r   r   r   Map  s    
r   c                 C   s   t t|| f||f||dS )z*A map with extra field evicted_values
    )r]   r   )r   rw   )r   r\   r   r   r]   r   r   r   r   MapWithEvicted  s
    
r   c                    s   t  fddt|D  S )Nc                    s    g | ]\}}d  |f |fqS )z%s_%dr   )rc   rI   r   name_prefixr   r   re     s   zNamedTuple.<locals>.<listcomp>)rw   r   )r   r   r   r   r   
NamedTuple  s    r   c                  G   s   t d|  S )zP
    Creates a Struct with default, sequential, field names of given types.
    r   )r   )r   )r   r   r   r   Tuple  s    r   r   c                 C   s0   t | tst| dkstt|ftjg|   S )z9
    Creates a tuple of `num_field` untyped scalars.
    r   )r   r   rY   r   r    r   )
num_fieldsr   r   r   r   RawTuple  s    r   r   c                 C   s   t | tjs |}t| |f} n$|| j }|| jkrDt| j|f} | jsRt| S g }| jD ]0\}\}}|dksxtd||t||df7 }q\t	| S )aS  Constructs a Caffe2 schema from the given numpy's dtype.

    Numpy supports scalar, array-like and structured datatypes, as long as
    all the shapes are fixed. This function breaks down the given dtype into
    a Caffe2 schema containing `Struct` and `Scalar` types.

    Fields containing byte offsets are not currently supported.
    r   z+Fields with byte offsets are not supported.)_outer_shape)
r   r    r   r   r   r   r!   rY   
from_dtyperw   )r   r   r   struct_fieldsr   Zfdtyper5   r   r   r   r     s    	

r   c                   @   sF   e Zd ZU dZdZee ed< dddZdddZ	d	d
 Z
dd ZdS )_SchemaNodez7This is a private class used to represent a Schema Noder   r4   type_strr   r%   r   c                 C   s   || _ g | _|| _d | _d S rC   r   )r3   r   r   r   r   r   r7     s    z_SchemaNode.__init__c                 C   sB   | j D ] }|j|kr|j|kr|  S qt||}| j | |S rC   )r4   r   r   r   r0   )r3   r   r   r6   r   r   r   	add_child  s    


z_SchemaNode.add_childc           	      C   sX  ddg}dddg}t | jdks*| jd k	r@| jd kr:t S | jS g }| jD ]}||j qJt|t|kr| jD ] }|jdkr| }qr| }qrt||d| _d| _	| jS t|t|kr| jD ]4}|jdkr| }q|jdkr| }q| }qt
|||d| _d| _	| jS g }| jD ]}||j| f q"t| | _d| _	| jS d S )	NrV   r\   r   r   r   rU   r   rw   )r1   r4   r   rw   r0   r   r   	get_fieldrU   r   r   )	r3   Z
list_namesZ	map_namesZchild_namesr6   Zvalues_fieldZlengths_fieldZ	key_fieldr   r   r   r   r     sP    














z_SchemaNode.get_fieldc                 C   s:   | j D ]}|  qtd t| j t| j d S )NzPrinting node: Name and type)r4   print_recursivelyr   infor   r   )r3   r6   r   r   r   r     s
    


z_SchemaNode.print_recursivelyN)r   )r   )r&   r'   r(   r)   r%   r   r*   r+   r7   r   r   r   r   r   r   r   r     s   


4r   c                 C   s*  |dkrdgt |  }|dkr,dgt |  }|dkrBdgt |  }t | t |ksZtdt | t |ksrtdt | t |kstdtdd}t| |||D ]~\}}}}|t}|}	tt |D ]V}
||
 }d}d}|
t |d kr|}t|||d	}|	||}|dk	r||_	|}	qq|
 S )
zR
    Given a list of names, types, and optionally values, construct a Schema.
    Nz2col_names and col_types must have the same length.z5col_names and col_metadata must have the same length.z2col_names and col_blobs must have the same length.rootrw   r   rX   r   )r1   rY   r   zipr|   r   ranger!   r   r   r   )Z	col_namesZ	col_typesZ	col_blobsZcol_metadatar   Zcol_nameZcol_typeZcol_blobcolumnscurrentrI   r   r   r   r   r   r   r   from_column_list&  sP    
   

r   Fc                 C   s   t | tstdt |tr"|g}|  }| }t|t|ksZtdt|t|f t||D ]\}}|j||dd qd|S )zd
    Create a schema that clones the given schema, but containing the given
    list of values.
    z"Argument `schema` must be a Field.z%Values must have %d elements, got %d.Tr   )	r   r   rY   r   r9   r@   r1   r   r   )schemar\   r   recordr   Zscalarrr   r   r   r   from_blob_listU  s    
r   c                 C   s   t | tr| S t | ts"t | tr^tdd | D }|rJtdd | D  S tdd | D  S n(t | tr~tdd t| D  S t	| S d S )Nc                 s   s0   | ](}|t ko&t|d ko&t|d tV  qdS )rk   r   N)r   r1   r   r   r   r   r   r   r   k  s   zas_record.<locals>.<genexpr>c                 S   s   g | ]\}}|t |fqS r   	as_recordr   r   r   r   re   p  s     zas_record.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r   r   r   r   r   re   r  s     c                 S   s   g | ]\}}|t |fqS r   r   r   r   r   r   re   t  s     )
r   r   r   r   r   rw   r   dictr   r"   )rr   Zis_field_listr   r   r   r   g  s    

r   c                    sV   fdd t | tst|  }tdd |D s8t fdd|D }t| ||S )z
    Given a record containing BlobReferences, return a new record with same
    schema, containing numpy arrays, fetched from the current active workspace.
    c                    s,    d krt t| S  jt|   S d S rC   )r   Z	FetchBlobr*   r   fetch)rd   wsr   r   r     s    zFetchRecord.<locals>.fetchc                 s   s   | ]}t |tV  qd S rC   r   r   rb   r   r   r   r     s     zFetchRecord.<locals>.<genexpr>c                    s   g | ]} |qS r   r   )rc   rr   )r   r   r   re     s     zFetchRecord.<locals>.<listcomp>)r   r   rY   r?   r   r   )blob_recordr   r   r?   Zfield_arraysr   )r   r   r   FetchRecordy  s    r   c                    s    fdd}t | tst|  }tdd |D s8tt |trJ| }t|t|ksjtdt| t||D ]\}}||| qtdS )z
    Given a Record containing blob_references and arrays, which is either
    a list of numpy arrays or a Record containing numpy arrays, feeds the
    record to the current workspace.
    c                    s@    d krt t| | n" t|   jt|  | d S rC   )r   ZFeedBlobr*   Zcreate_blobr   feed)brd   r   r   r   r     s    zFeedRecord.<locals>.feedc                 s   s   | ]}t |tV  qd S rC   r   rb   r   r   r   r     s     zFeedRecord.<locals>.<genexpr>z(Values must contain exactly %d ndarrays.N)r   r   rY   r?   r   r1   r   )r   Zarraysr   r   r?   r   r   r   r   r   
FeedRecord  s    

r   c                    s\   t |tr*| }|j ddd |S t |ts<td fdd| D }t||S )aL  
    Given a record of np.arrays, create a BlobReference for each one of them,
    returning a record containing BlobReferences. The name of each returned blob
    is NextScopedBlob(field_name), which guarantees unique name in the current
    net. Use NameScope explicitly to avoid name conflictions between different
    nets.
    Zunnamed_scalarT)r   r   z'Record must be a schema.Field instance.c                    s   g | ]} j |d qS ))r   )NextScopedBlob)rc   r   netr   r   re     s   zNewRecord.<locals>.<listcomp>)	r   r!   r   r   r   r   rY   r2   r   )r   r   resultZ	blob_refsr   r   r   	NewRecord  s    

r  c                 C   s6   t | |}t| | D ]\}}| || q|S )z^
    Given a record of arrays, returns a record of blobs,
    initialized with net.Const.
    )r  r   r?   ZConst)r   Zarray_recordr   r   r   r   r   r   ConstRecord  s    
 r  c              	   C   s   |  st| |}n|}t| | D ]t\}}z.t|}dgt|j }| jg |||d W q* t	k
r   t
d| |r | jg |dgd Y q*X q*|S )Nr   )r   r   zBlob {} has type error)r   )rA   r  r   r=   r?   data_type_for_dtyper   r   ZConstantFillr   r   r   r   )r   Zschema_or_recordZenforce_typesr   Z	blob_typer   Z	data_typer   r   r   r   InitEmptyRecord  s    r  c                 C   s   t |  t | S rC   )r   r2   issubset)r   original_schemar   r   r   is_schema_subset  s    
r  c                 C   sh   t | tstt |tst|r4|  | kr4dS |rL|  | krLdS |rd|  | krddS dS )NFT)r   r   rY   r2   r=   r>   )r   r  Zcheck_field_namesZcheck_field_typesZcheck_field_metasr   r   r   equal_schemas  s    r	  c                 C   s"   t | }|d k	rt| |st|S rC   )r   r	  rY   )r   previousr   r   r   r   schema_check  s    r  c                 C   s6   t D ]\}}| j|kr|  S qtdt| j d S )NzUnknown dtype: )_DATA_TYPE_FOR_DTYPEr   r   r*   )r   np_typedtr   r   r   r    s    

r  c                 C   s2   t D ]\}}|| kr|  S qtdt|  d S )NzUnknown core type: )r  r   r*   )Z	core_typer  r  r   r   r   dtype_for_core_type  s    
r  c                 C   s   |   D ]}|| qd S rC   )r@   r   )r   r   r   r   r   r   attach_metadata_to_scalars%  s    r  )T)r   r\   N)r   r\   NN)r   )r   )NNN)F)NF)N)F)TTF)N)Ur)   loggingZnumpyr    Zcaffe2.pythonr   r   Zcaffe2.python.corer   collectionsr   r   Zpast.builtinsr   Zfuture.utilsr   r	   r
   	itertoolsr   sixr   typingr   	getLoggerr&   r   r   r   r"   r#   __new____defaults__r$   objectr   rU   r   rw   r!   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r*   ZDataTypeSTRINGZfloat16ZFLOAT16Zfloat32FLOATZfloat64ZDOUBLEboolZBOOLZint8ZINT8Zint16ZINT16rZ   ZINT32r   ZINT64Zuint8ZUINT8Zuint16ZUINT16r  r  r	  r  r  r  r  r   r   r   r   <module>   s   



 gSU  7 b   
    

	
P    
/



   

