U
    ¾mœdÂ+  ã                   @  s>  d Z ddlmZ ddlmZmZmZ ddlZddlm	Z	 ddl
mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZmZmZmZmZmZmZmZmZ ddlm Z  ddl!m"Z" ddl#m$  m%Z& erâddl!m'Z' ddl(m)Z) dZ*dddœdd„Z+dd„ Z,ddœdd„Z-ddœdd„Z.d'dd d!d dd"œd#d$„Z/d%d&„ Z0dS )(zH
Table Schema builders

https://specs.frictionlessdata.io/table-schema/
é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚcastN)Úloads)Ú	timezones)ÚDtypeObjÚJSONSerializable)Úfind_stack_level)Ú	_registry)
Úis_bool_dtypeÚis_categorical_dtypeÚis_datetime64_dtypeÚis_datetime64tz_dtypeÚis_extension_array_dtypeÚis_integer_dtypeÚis_numeric_dtypeÚis_period_dtypeÚis_string_dtypeÚis_timedelta64_dtype)ÚCategoricalDtype)Ú	DataFrame)ÚSeries)Ú
MultiIndexz1.4.0r   Ústr)ÚxÚreturnc                 C  sx   t | ƒrdS t| ƒrdS t| ƒr$dS t| ƒs<t| ƒs<t| ƒr@dS t| ƒrLdS t| ƒrXdS t| ƒrddS t	| ƒrpdS dS dS )	aœ  
    Convert a NumPy / pandas type to its corresponding json_table.

    Parameters
    ----------
    x : np.dtype or ExtensionDtype

    Returns
    -------
    str
        the Table Schema data types

    Notes
    -----
    This table shows the relationship between NumPy / pandas dtypes,
    and Table Schema dtypes.

    ==============  =================
    Pandas type     Table Schema type
    ==============  =================
    int64           integer
    float64         number
    bool            boolean
    datetime64[ns]  datetime
    timedelta64[ns] duration
    object          str
    categorical     any
    =============== =================
    ÚintegerÚbooleanÚnumberÚdatetimeÚdurationÚanyÚstringN)
r   r   r   r   r   r   r   r   r   r   )r   © r$   úU/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/pandas/io/json/_table_schema.pyÚas_json_table_type1   s"    r&   c                 C  s®   t j| jjŽ rr| jj}t|ƒdkr@| jjdkr@tjdtƒ d� n.t|ƒdkrnt	dd„ |D ƒƒrntjdtƒ d� | S |  
¡ } | jjdkršt  | jj¡| j_n| jjp¤d| j_| S )z?Sets index names to 'index' for regular, or 'level_x' for Multié   Úindexz-Index name of 'index' is not round-trippable.)Ú
stacklevelc                 s  s   | ]}|  d ¡V  qdS ©Zlevel_N©Ú
startswith©Ú.0r   r$   r$   r%   Ú	<genexpr>l   s     z$set_default_names.<locals>.<genexpr>z<Index names beginning with 'level_' are not round-trippable.)ÚcomZall_not_noner(   ÚnamesÚlenÚnameÚwarningsÚwarnr
   r"   ÚcopyÚnlevelsZfill_missing_names)ÚdataZnmsr$   r$   r%   Úset_default_namesc   s$    þþr9   zdict[str, JSONSerializable])r   c                 C  s°   | j }| jd krd}n| j}|t|ƒdœ}t|ƒrX|j}|j}dt|ƒi|d< ||d< nTt|ƒrn|jj	|d< n>t
|ƒršt |j¡rŒd|d< q¬|jj|d< nt|ƒr¬|j|d	< |S )
NÚvalues)r3   ÚtypeÚenumÚconstraintsÚorderedÚfreqÚUTCÚtzÚextDtype)Údtyper3   r&   r   Ú
categoriesr>   Úlistr   r?   Zfreqstrr   r   Zis_utcrA   Úzoner   )ZarrrC   r3   ÚfieldZcatsr>   r$   r$   r%   Ú!convert_pandas_type_to_json_field{   s*    
þ


rH   zstr | CategoricalDtypec                 C  sú   | d }|dkrdS |dkr(|   dd¡S |dkr<|   dd¡S |d	krP|   dd
¡S |dkr\dS |dkrž|   d¡r~d| d › d�S |   d¡r˜d| d › d�S dS nJ|dkrèd| krÎd| krÎt| d d | d d�S d| krät | d ¡S dS td|› �ƒ‚dS )a÷  
    Converts a JSON field descriptor into its corresponding NumPy / pandas type

    Parameters
    ----------
    field
        A JSON field descriptor

    Returns
    -------
    dtype

    Raises
    ------
    ValueError
        If the type of the provided field is unknown or currently unsupported

    Examples
    --------
    >>> convert_json_field_to_pandas_type({"name": "an_int", "type": "integer"})
    'int64'

    >>> convert_json_field_to_pandas_type(
    ...     {
    ...         "name": "a_categorical",
    ...         "type": "any",
    ...         "constraints": {"enum": ["a", "b", "c"]},
    ...         "ordered": True,
    ...     }
    ... )
    CategoricalDtype(categories=['a', 'b', 'c'], ordered=True)

    >>> convert_json_field_to_pandas_type({"name": "a_datetime", "type": "datetime"})
    'datetime64[ns]'

    >>> convert_json_field_to_pandas_type(
    ...     {"name": "a_datetime_with_tz", "type": "datetime", "tz": "US/Central"}
    ... )
    'datetime64[ns, US/Central]'
    r;   r#   Úobjectr   rB   Zint64r   Zfloat64r   Úboolr!   Útimedelta64r    rA   zdatetime64[ns, ú]r?   zperiod[zdatetime64[ns]r"   r=   r>   r<   )rD   r>   z#Unsupported or invalid field type: N)Úgetr   ÚregistryÚfindÚ
ValueError)rG   Útypr$   r$   r%   Ú!convert_json_field_to_pandas_typeš   s6    )


 ÿrR   TzDataFrame | SeriesrJ   zbool | None)r8   r(   Úprimary_keyÚversionr   c                 C  s"  |dkrt | ƒ} i }g }|r~| jjdkrntd| jƒ| _t| jj| jjƒD ]"\}}t|ƒ}||d< | |¡ qHn| t| jƒ¡ | j	dkrª|  
¡ D ]\}	}
| t|
ƒ¡ q�n| t| ƒ¡ ||d< |rþ| jjrþ|dkrþ| jjdkrð| jjg|d< n| jj|d< n|dk	�r||d< |�rt|d< |S )	a‚  
    Create a Table schema from ``data``.

    Parameters
    ----------
    data : Series, DataFrame
    index : bool, default True
        Whether to include ``data.index`` in the schema.
    primary_key : bool or None, default True
        Column names to designate as the primary key.
        The default `None` will set `'primaryKey'` to the index
        level or levels if the index is unique.
    version : bool, default True
        Whether to include a field `pandas_version` with the version
        of pandas that last revised the table schema. This version
        can be different from the installed pandas version.

    Returns
    -------
    dict

    Notes
    -----
    See `Table Schema
    <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for
    conversion types.
    Timedeltas as converted to ISO8601 duration format with
    9 decimal places after the seconds field for nanosecond precision.

    Categoricals are converted to the `any` dtype, and use the `enum` field
    constraint to list the allowed values. The `ordered` attribute is included
    in an `ordered` field.

    Examples
    --------
    >>> from pandas.io.json._table_schema import build_table_schema
    >>> df = pd.DataFrame(
    ...     {'A': [1, 2, 3],
    ...      'B': ['a', 'b', 'c'],
    ...      'C': pd.date_range('2016-01-01', freq='d', periods=3),
    ...     }, index=pd.Index(range(3), name='idx'))
    >>> build_table_schema(df)
    {'fields': [{'name': 'idx', 'type': 'integer'}, {'name': 'A', 'type': 'integer'}, {'name': 'B', 'type': 'string'}, {'name': 'C', 'type': 'datetime'}], 'primaryKey': ['idx'], 'pandas_version': '1.4.0'}
    Tr'   r   r3   ÚfieldsNÚ
primaryKeyZpandas_version)r9   r(   r7   r   ÚzipZlevelsr1   rH   ÚappendÚndimÚitemsZ	is_uniquer3   ÚTABLE_SCHEMA_VERSION)r8   r(   rS   rT   ÚschemarU   Úlevelr3   Z	new_fieldÚcolumnÚsr$   r$   r%   Úbuild_table_schemaã   s4    8

r`   c                 C  sÈ   t | |d�}dd„ |d d D ƒ}t|d |d�| }dd	„ |d d D ƒ}d
| ¡ kr`tdƒ‚| |¡}d|d krÄ| |d d ¡}t|jjƒdkr®|jj	dkrÄd|j_	ndd„ |jjD ƒ|j_|S )a  
    Builds a DataFrame from a given schema

    Parameters
    ----------
    json :
        A JSON table schema
    precise_float : bool
        Flag controlling precision when decoding string to double values, as
        dictated by ``read_json``

    Returns
    -------
    df : DataFrame

    Raises
    ------
    NotImplementedError
        If the JSON table schema contains either timezone or timedelta data

    Notes
    -----
        Because :func:`DataFrame.to_json` uses the string 'index' to denote a
        name-less :class:`Index`, this function sets the name of the returned
        :class:`DataFrame` to ``None`` when said string is encountered with a
        normal :class:`Index`. For a :class:`MultiIndex`, the same limitation
        applies to any strings beginning with 'level_'. Therefore, an
        :class:`Index` name of 'index'  and :class:`MultiIndex` names starting
        with 'level_' are not supported.

    See Also
    --------
    build_table_schema : Inverse function.
    pandas.read_json
    )Úprecise_floatc                 S  s   g | ]}|d  ‘qS ©r3   r$   ©r.   rG   r$   r$   r%   Ú
<listcomp>d  s     z&parse_table_schema.<locals>.<listcomp>r\   rU   r8   )Úcolumnsc                 S  s   i | ]}|d  t |ƒ“qS rb   )rR   rc   r$   r$   r%   Ú
<dictcomp>g  s   ÿ z&parse_table_schema.<locals>.<dictcomp>rK   z<table="orient" can not yet read ISO-formatted Timedelta datarV   r'   r(   Nc                 S  s   g | ]}|  d ¡rdn|‘qS r*   r+   r-   r$   r$   r%   rd   z  s    )
r   r   r:   ÚNotImplementedErrorZastypeZ	set_indexr2   r(   r1   r3   )Újsonra   ÚtableZ	col_orderZdfZdtypesr$   r$   r%   Úparse_table_schema?  s(    $
þÿ

ÿ
rj   )TNT)1Ú__doc__Ú
__future__r   Útypingr   r   r   r4   Zpandas._libs.jsonr   Zpandas._libs.tslibsr   Zpandas._typingr   r	   Zpandas.util._exceptionsr
   Zpandas.core.dtypes.baser   rN   Zpandas.core.dtypes.commonr   r   r   r   r   r   r   r   r   r   Zpandas.core.dtypes.dtypesr   Zpandasr   Zpandas.core.commonÚcoreÚcommonr0   r   Zpandas.core.indexes.multir   r[   r&   r9   rH   rR   r`   rj   r$   r$   r$   r%   Ú<module>   s2   02K   ü\