a
    yn„f´+  ã                   @  sÜ   d dl mZ d dlZd dlmZ d dlmZmZ d dlm	Z	 d dl
Z
d dlmZ d dlZd dlmZ d dlmZ d d	lmZ d d
lmZ dZe ¡ Ze ¡ Zeƒ dddd dddddddœ	dd„ƒZdd„ ZG dd„ dƒZdS )é    )ÚannotationsN)ÚNumber)ÚPathLikeÚfsdecode)Úurlparse)Ú_ext)Úbehavior_of)Úhigh_level_function)ÚNumpy)ÚNumpyMetadata)Úto_jsonF)	Úline_delimitedÚnum_indent_spacesÚnum_readability_spacesÚ
nan_stringÚposinf_stringÚneginf_stringÚcomplex_record_fieldsÚconvert_bytesÚconvert_otherc       	         c  s$   | fV  t | |||||||||	|
ƒS )a,  
    Args:
        array: Array-like data (anything #ak.to_layout recognizes).
        file (None, path-like, or file-like object): If None, this function returns
            JSON-encoded bytes. Otherwise, this function has no return value.
            If a string/pathlib.Path, this function opens a file with that name, writes JSON
            data, and closes the file. If that path has a URI protocol (like
            "https://" or "s3://"), this function attempts to open the file with
            the fsspec library. If a file-like object with a `write` method,
            this function writes to the object, but does not close it.
        line_delimited (bool or str): If False, a single JSON document is written,
            representing the entire array or record. If True, each element of the
            array (or just the one record) is written on a separate line of text,
            separated by `"\n"`. If a string, such as `"\r\n"`, it is taken as a
            custom line delimiter. (Use `os.linesep` for a platform-dependent
            line delimiter.)
        num_indent_spaces (None or nonnegative int): Number of spaces to indent nested
            elements, for pretty-printed JSON. If None, the JSON output is written
            on one line of text. Ignored if `line_delimited` is True or a string.
        num_readability_spaces (nonnegative int): Number of spaces to include after
            commas (`,`) and colons (`:`), for pretty-printed JSON.
        nan_string (None or str): If not None, floating-point NaN values will be
            replaced with this string instead of a JSON number.
        posinf_string (None or str): If not None, floating-point positive infinity
            values will be replaced with this string instead of a JSON number.
        neginf_string (None or str): If not None, floating-point negative infinity
            values will be replaced with this string instead of a JSON number.
        complex_record_fields (None or (str, str)): If not None, defines a pair of
            field names to interpret records as complex numbers, such as
            `("real", "imag")`.
        convert_bytes (None or function): If not None, this function is applied to
            all Python 3 bytes objects to produce something JSON serializable,
            such as a string using UTF-8 or Base64 encoding, lists of integers, etc.
        convert_other (None or function): Passed to `json.dump` or `json.dumps`
            as `default` to convert any other objects that #ak.to_list would return
            but are not JSON serializable.

    Converts `array` (many types supported, including all Awkward Arrays and
    Records) into JSON text. Returns bytes (encoded JSON) if `file` is None;
    otherwise, this function returns nothing and writes to a file.

    This function converts the array into Python objects with #ak.to_list, performs
    some conversions to make the data JSON serializable (`nan_string`,
    `posinf_string`, `neginf_string`, `complex_record_fields`, `convert_bytes`,
    `convert_other`), then uses `json.dumps` to return a string or `json.dump`
    to write to a file (depending on the value of `file`).

    If `line_delimited` is True or a line-delimiter string like `"\r\n"`/`os.linesep`,
    the output is line-delimited JSON, variously referred to as "ldjson", "ndjson", and
    "jsonl". (Use an appropriate file extension!)

    To pretty-print the JSON, set `num_indent_spaces=4, num_readability_spaces=1` (for
    example).

    Awkward Array types have the following JSON translations.

    * #ak.types.OptionType: missing values are converted into None.
    * #ak.types.ListType: converted into JSON lists.
    * #ak.types.RegularType: also converted into JSON lists. JSON (and
      Python) forms lose information about the regularity of list lengths.
    * #ak.types.ListType or #ak.types.RegularType with parameter `"__array__"`
      equal to `"string"`: converted into JSON strings.
    * #ak.types.RecordType without field names: converted into JSON
      objects with numbers as strings for keys.
    * #ak.types.RecordType with field names: converted into JSON objects.
    * #ak.types.UnionType: JSON data are naturally heterogeneous.

    If the array contains any NaN (not a number), infinite values, or
    imaginary/complex types, `nan_string`, `posinf_string`, and/or `neginf_string`
    _must_ be supplied.

    If the array contains any raw bytestrings (`"__array__"` equal to `"bytestring"`),
    `convert_bytes` _must_ be supplied. To interpret as strings, use `bytes.decode`.
    To Base64-encode, use `lambda x: base64.b64encode(x).decode()`.

    Other non-serializable types are only possible through custom behaviors that
    override `__getitem__` (which might return arbitrary Python objects). Use
    `convert_other` to detect these types and convert them.

    See also #ak.from_json.
    )Ú_impl)ÚarrayÚfiler   r   r   r   r   r   r   r   r   © r   ú`/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/awkward/operations/ak_to_json.pyr      s    aõr   c                   sl  | d u st | ttttfƒr0tjj| gdd�}�nt | tjj	ƒrF| j
}nøt | tjjƒrr| j
j| j
j| j
jd … }nÌt | tjjƒrŒ|  ¡ j
}n²t | tjjƒr²| j| j| jd … }nŒt | tjƒrô|  ¡ \}}}tj |¡}tjj|||tjjdd�}nJt | tjjƒ�r
| }n4t| dƒ�r0t| dƒ�r0tj | ¡}ntd| ›�ƒ‚|j|||||	t| ƒd�}|�rnt |tƒ�snd	}d
d|  dd|  f}ˆ d u�rît ˆ tttfƒ�rât t!ˆ ƒƒ}|j"dk�sÆ|j#dk�rÔ‡ fdd„}n‡ fdd„}n‡ fdd„}�zJ|�r¨ˆ d u �rJg }|D ]2}| $t%j&|ddddd ||
dd�	¡ | $|¡ �q
d '|¡W S |ƒ �D}|D ].}t%j(||ddddd ||
dd�
 | )|¡ �qVW d   ƒ n1 �sœ0    Y  n�t | tjjtjjfƒ�rÈ|d }ˆ d u �rðt%j&|dddd|||
dd�	W S |ƒ �0}t%j(||dddd|||
dd�
W  d   ƒ W S 1 �s.0    Y  W n, t*�yf } z||‚W Y d }~n
d }~0 0 d S )NF)Ú	highlevelé   )Ú	byteorderr   ÚshapeZdtypezunrecognized array type: )r   r   r   r   r   ZbehaviorÚ
ú,ú ú:Ú c                     s   t ˆ ddd�S ©NÚwÚutf8)Úencoding)Úopenr   ©r   r   r   ÚopenerÏ   s    z_impl.<locals>.openerc                     s   t jˆ ddd� ¡ S r$   )Úfsspecr(   r   r)   r   r   r*   Ô   s    c                     s   t ˆ ƒS ©N)Ú_NoContextManagerr   r)   r   r   r*   Ù   s    T)ÚskipkeysÚensure_asciiÚcheck_circularÚ	allow_nanÚindentÚ
separatorsÚdefaultÚ	sort_keysr   )+Ú
isinstanceÚboolÚstrÚbytesr   ÚakÚ
operationsZ	from_iterr   ZArrayZlayoutZRecordr   ÚatZArrayBuilderZsnapshotÚrecordr   Z
to_buffersZformsÚ	from_jsonZfrom_buffersZ_utilZnative_byteorderÚcontentsZContentÚhasattrZ
NumpyArrayÚ	TypeErrorr   r   r   r   r   ÚschemeÚnetlocÚappendÚjsonÚdumpsÚjoinÚdumpÚwriteÚ	Exception)r   r   r   r   r   r   r   r   r   r   r   ÚoutZformstrÚlengthÚbuffersÚformZjsondatar3   Ú
parsed_urlr*   ZdatumZopenfileÚerrr   r)   r   r   Œ   sÒ    ÿú	

þ

÷ÿö0
÷ö,r   c                   @  s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )r-   c                 C  s
   || _ d S r,   r)   )Úselfr   r   r   r   Ú__init__&  s    z_NoContextManager.__init__c                 C  s   | j S r,   r)   )rQ   r   r   r   Ú	__enter__)  s    z_NoContextManager.__enter__c                 C  s   d S r,   r   )rQ   Zexception_typeZexception_valueZexception_tracebackr   r   r   Ú__exit__,  s    z_NoContextManager.__exit__N)Ú__name__Ú
__module__Ú__qualname__rR   rS   rT   r   r   r   r   r-   %  s   r-   )N)Ú
__future__r   rE   Únumbersr   Úosr   r   Úurllib.parser   r+   Zawkward_cpp.libr   Zawkwardr:   Zawkward._behaviorr   Zawkward._dispatchr	   Zawkward._nplikes.numpyr
   Zawkward._nplikes.numpy_liker   Ú__all__ÚinstanceÚnpÚnumpyr   r   r-   r   r   r   r   Ú<module>   s<    þôr 