a :jg:j @sdZddlmZmZmZmZmZmZmZm Z ddlm Z ddl Z ddl Z ddl mZmZmZddlmZmZmZe jjjZe jjZgdZgdZd dd Zd d Z Gd d d eZ!ddZ"e!Z#d!ddZddddddddef ddZddZ$ddZ%d"e j&dddZ'd#ddZ(dS)$a,:mod:`numpy.ma..mrecords` Defines the equivalent of :class:`numpy.recarrays` for masked arrays, where fields can be accessed as attributes. Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes and the masking of individual fields. .. moduleauthor:: Pierre Gerard-Marchant )MAError MaskedArraymaskednomask masked_arraygetdata getmaskarrayfilledN)dtypendarrayarray)recarray fromarrays fromrecords) MaskedRecords mrecarrayrr fromtextfileaddfield)_data_mask _fieldmaskr c Cst|}ddt|D}|dur(|}nXt|ttfr<|}n$t|trR|d}ntd|t|}||kr|||d7}g}t|||j D]P\}}}|t vr|dt vr| ||dfq| |q| ||dfqt |S)z Checks that field names ``descr`` are not reserved keywords. If this is the case, a default 'f%i' is substituted. If the argument `names` is not None, updates the field names to valid names. cSsg|] }d|qS)f%i.0irr;/usr/local/lib/python3.9/site-packages/numpy/ma/mrecords.py 5z_checknames..N,zillegal input names r)lenrange isinstancetupleliststrsplit NameErrorzipdescrreserved_fieldsappendnpr ) r*namesZndescr default_namesZ new_namesZnnamesndtrrr _checknames,s(    r3cCs:dd|jjD}tj|j|d}tdgt||_|S)NcSsg|] }|dfqS)z|b1rrr0rrrrOrz"_get_fieldmask..r F)r r.r-emptyshaper$r!flat)selfmdescrZfdmaskrrr_get_fieldmaskNsr;c@seZdZdZdddddddddeddddfddZdd Zed d Zed d Z ddZ ddZ ddZ ddZ ddZddZddZd,ddZddZd d!Zd"d#Zd-d$d%Zd&d'Zd(d)Zd*d+ZdS).ra Attributes ---------- _data : recarray Underlying data, as a record array. _mask : boolean array Mask of the records. A record is masked when all its fields are masked. _fieldmask : boolean recarray Record array of booleans, setting the mask of each individual field of each record. _fill_value : record Filling values for each field. NrFTc stj|||||||||| | d }t|j| tus>t| sX|sVtdgt |_ ntj | |d} | j |j kr|j| j}}|dkrt | |j } n,||krt| |j } nd}t|||f|s|| d|_n2| jkr| }ntj fdd| Dd }||_ |S) N) r bufoffsetstridesformatsr.titles byteorderalignedF)copyr z?Mask and data not compatible: data size is %i, mask size is %i.Tcsg|]}t|gtqSrr$r!rmmdtyperrrrz)MaskedRecords.__new__..r5)r __new__mamake_mask_descrr rr-sizer$r!rr r7resizeZreshaper __setmask__ _sharedmask)clsr7r r<r=r>r?r.r@rArBmaskZ hard_mask fill_valueZ keep_maskrCoptionsr9ndnmmsgrrrGrrIgs8    zMaskedRecords.__new__cst|dd}|durpt|dt}t|d}|turFtj|j|d}n*t|tfdd|Dd t }|j }|j |d| ||dtkrt |d<dS)Nrr r5csg|]}t|gtqSrrDrEr:rrrrz4MaskedRecords.__array_finalize__..r _baseclass)getattrrr __getattribute__rJZmake_mask_noner7rKnarrayviewr __dict__update _update_from)r9objrZobjmaskZ_dtype_dictrrWr__array_finalize__s$       z MaskedRecords.__array_finalize__cCs t|tS)z2 Returns the data as a recarray. )r r]r r9rrrrszMaskedRecords._datacCs|jS)z! Alias to mask. rXrdrrrrszMaskedRecords._fieldmaskcCs|jrt|jSt|jS)z% Returns the length )ndimr!rr rdrrr__len__s zMaskedRecords.__len__c Cszt||WSty Yn0t|dj}z||dd}Wn8ttfy|}ztd||WYd}~n d}~00t|d}t||d}|j|}|j j durt dd}| dd} | durz | |} Wnt yYn0t| j } | t| r| fnd f}|js(|r|t}t|_d |_| |_| d d} | durz| ||_Wntyd|_Yn0n|}|S) Nr record array has no attribute r^rYz4MaskedRecords is currently limited tosimple records.FrrT _fill_value)objectr[AttributeErrorr fields TypeErrorKeyErrorr]getfieldr r.NotImplementedErrorget IndexErrorr!boolanyr7rrYZ_isfieldrri ValueErroritem) r9attr fielddictrese _localdictrraZ hasmaskedrZtp_lenrirrrr[sP            zMaskedRecords.__getattribute__c Cs|dvr||dSt|d}||v}zt|||}WnFtyt|djpZi}t|dpji}||vs~||vs~YnL0t|djpi}||vr|S|rzt||Wnty|YS0z||dd}Wn:tt fy} zt d|| WYd} ~ n d} ~ 00|t urR|d} | durH|d|} n|} d } nt |} t |} t|d j| g|R} |d || | S) z< Sets the attribute attr to the value val. )rQZ fieldmaskNr^r Z_optinforgrhriTrr)rNrjr[ __setattr__ Exceptionr rl __delattr__rmrnrkrr rsetfield __setitem__)r9rwvalr{ZnewattrretrxZoptinforyrzridvalZmvalrarrrr|sN       zMaskedRecords.__setattr__cCs|j}t|d}t||d}t|trx||t}|||_d|_|d}|durd|||_ |j st|jrtt S|St ||t}t ||t|_|S)z Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`. rrYTriN)r^r r[r]r#r&rrrOrirerr-asarrayrr )r9indxr{rrraZfvalrrr __getitem__%s      zMaskedRecords.__getitem__cCs,t|||t|tr(t||j|<dS)z2 Sets the given record to value. N)rrr#r&rJrr)r9rvaluerrrrEs zMaskedRecords.__setitem__cszjdkr@ddtfddjjDD}dd|dSddtfd djjDD}d d|d Sd S) z8 Calculates the string representation. r cSs(g|] }dddd|DdqS)(rcSsg|] }t|qSrr&rrrrrTr4MaskedRecords.__str__...)joinrsrrrrTsz)MaskedRecords.__str__..csg|]}t|qSrrZrfrdrrrUr[z, ]cSs"g|]}ddd|DqS)rcSsg|] }t|qSrrrrrrrXrrrrrrrrXscsg|]}t|qSrrrrdrrrYrrrN)rLr)r r.r)r9Zmstrrrdr__str__Ns zMaskedRecords.__str__csnjj}dtdd|DdffddjjD}|dd|djfd gtd |S) z6 Calculates the repr representation. z %%%is : %%scSsg|] }t|qSr)r!r4rrrrbrz*MaskedRecords.__repr__..csg|]}|t|fqSrrrfmtr9rrrcrrzmasked_records(z fill_valuez ) )r r.maxinsertextendrRr&r)r9Z_namesZreprstrrrr__repr__\s zMaskedRecords.__repr__cCs|dur*|durt|}qt||}n|durz(t|trLt||}n t||}Wqtyt|}|jdur|jjd}| ||}| |n t||}d|_ Yq0nt|||}t |dt t urt|j}|j|t|_|j|j_|S)z3 Returns a view of the mrecarray. Nrr)r r] issubclassrmr-r rl __class__ __bases__Z __array__r`rirZrrJrKrr7)r9r typeoutputbasetyperHrrrr]is.          zMaskedRecords.viewcCs d|_dS)z+ Forces the mask to hard. TNZ _hardmaskrdrrr harden_maskszMaskedRecords.harden_maskcCs d|_dS)z* Forces the mask to soft FNrrdrrr soften_maskszMaskedRecords.soften_maskcCs$|jt|}|j|_|S)z7 Returns a copy of the masked record. )rrCr]rr)r9copiedrrrrCs zMaskedRecords.copycCsH|dur||St|td}t|j}d||<|S)a Return the data portion of the array as a list. Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If fill_value is None, the corresponding entries in the output list will be ``None``. Nr5)r tolistr\rjr)r9rRresultrQrrrrs zMaskedRecords.tolistcCs,d|j|j|jj|j|j|jf}|S)zWReturn the internal state of the masked array. This is for pickling. r )r7r flagsZfncrtobytesrri)r9staterrr __getstate__szMaskedRecords.__getstate__c Cs^|\}}}}}}}t|||||ftdd|jjD} |jd|| ||f||_dS)at Restore the internal state of the masked array. This is for pickling. ``state`` is typically the output of the ``__getstate__`` output, and is a 5-tuple: - class name - a tuple giving the shape of the data - a typecode for the data - a binary string for the data - a binary string for the mask. cSsg|]\}}|tjfqSrr-rs)rk_rrrrrz.MaskedRecords.__setstate__..rN)r __setstate__r r*r^rR) r9rverZshptypZisfrawZmskZflvrHrrrrs zMaskedRecords.__setstate__cCst|j|jddf|fS)z? Return a 3-tuple for pickling a MaskedArray. )rb)_mrreconstructrrYrrdrrr __reduce__szMaskedRecords.__reduce__)NN)N)__name__ __module__ __qualname____doc__rrIrcpropertyrrrfr[r|rrrrr]rrrCrrrrrrrrrUs6 (   /8   ( rcCs4t||||}tt|d}|j||||dS)zK Build a new MaskedArray from the information stored in a pickle. b1)rQr )r rIr])subtypeZ baseclassZ baseshaperrrrrrrsrFc Cs\dd|D} dd|D} t| |||||||dt} tt| | j_|durX|| _| S)a  Creates a mrecarray from a (flat) list of masked arrays. Parameters ---------- arraylist : sequence A list of (masked) arrays. Each element of the sequence is first converted to a masked array if needed. If a 2D array is passed as argument, it is processed line by line dtype : {None, dtype}, optional Data type descriptor. shape : {None, integer}, optional Number of records. If None, shape is defined from the shape of the first array in the list. formats : {None, sequence}, optional Sequence of formats for each individual field. If None, the formats will be autodetected by inspecting the fields and selecting the highest dtype possible. names : {None, sequence}, optional Sequence of the names of each field. fill_value : {None, sequence}, optional Sequence of data to be used as filling values. Notes ----- Lists of tuples should be preferred over lists of lists for faster processing. cSsg|] }t|qSr)rrxrrrrrzfromarrays..cSsg|]}tt|qSr)r-Z atleast_1drrrrrrrr r7r?r.r@rBrAN) recfromarraysr]rr%r)rr8rR) Z arraylistr r7r?r.r@rBrArRZdatalistZmasklistZ_arrayrrrrsrc Cst|dd} t|trDt|tr.|t}|dur<|j}|}t||||||||dt } |durp|| _ | t urt | } t| j} | r| | j_n(| jdkrdd| D| j_n | | | dur| | jdd<| S)aN Creates a MaskedRecords from a list of records. Parameters ---------- reclist : sequence A list of records. Each element of the sequence is first converted to a masked array if needed. If a 2D array is passed as argument, it is processed line by line dtype : {None, dtype}, optional Data type descriptor. shape : {None,int}, optional Number of records. If None, ``shape`` is defined from the shape of the first array in the list. formats : {None, sequence}, optional Sequence of formats for each individual field. If None, the formats will be autodetected by inspecting the fields and selecting the highest dtype possible. names : {None, sequence}, optional Sequence of the names of each field. fill_value : {None, sequence}, optional Sequence of data to be used as filling values. mask : {nomask, sequence}, optional. External mask to apply on the data. Notes ----- Lists of tuples should be preferred over lists of lists for faster processing. rNrrgcSsg|] }t|qSr)r$rErrrr[rzfromrecords..)rZr#r rr r]r rrecfromrecordsrrRrr-rr!rr8rerN) Zreclistr r7r?r.r@rBrArRrQrZmrecZmaskrecordlengthrrrr"s4"         rcCsg}t|}|jdkr"|d}n|jdkr4td|D]}z t|Wnttfyz t|WnVttfyz t|Wn"ttfy||j Yn0|t tYn0|t tYq80|t tq8|S)a. Tries to guess the dtypes of the str_ ndarray `arr`. Guesses by testing element-wise conversion. Returns a list of dtypes. The array is first converted to ndarray. If the array is 2D, the test is performed on the first line. An exception is raised if the file is 3D or more. rgrzThe array should be 2D at most!) r-rreruintrmfloatcomplexr,r )Zarrvartypesrrrr_guessvartypescs*        rc Cst|dr|Sz t|}Wn6tyP}ztd|d|WYd}~n d}~00|dddkrv|dd|S|tddS) z1 Opens the file handle of file `fname`. readlinezNo such file: ''Nrgz\xrzWow, binary file)hasattropenFileNotFoundErrorrseekcloserp)fnamerrzrrropenfiles  ( r#) delimitorcsZ|tjur.durtdtjdtdd|t|}|}|d| } | } t | dkr6qnq6|durz| }t fdd|D} | j \} } ||durt| d }nNd d|D}t || krd }|d 7}tj|t || fddt| d }d dt||D}dd|D}| j|k}ddt| j|||D}t||dS)a Creates a mrecarray from data stored in the file `filename`. Parameters ---------- fname : {file name/handle} Handle of an opened file. delimiter : {None, string}, optional Alphanumeric character used to separate columns in the file. If None, any (group of) white spacestring(s) will be used. commentchar : {'#', string}, optional Alphanumeric character used to mark the start of a comment. missingchar : {'', string}, optional String indicating missing data, and used to create the masks. varnames : {None, sequence}, optional Sequence of the variable names. If None, a list will be created from the first non empty line of the file. vartypes : {None, sequence}, optional Sequence of the variables dtypes. If None, it will be estimated from the first non-commented line. Ultra simple: the varnames are in the header, one lineNz;fromtextfile() got multiple values for argument 'delimiter'zThe 'delimitor' keyword argument of numpy.ma.mrecords.fromtextfile() is deprecated since NumPy 1.22.0, use 'delimiter' instead.rg) stacklevelr cs2g|]*}|dkrt|dkr|qS)rr )r!stripr')rline commentchar delimiterrrrsz fromtextfile..rcSsg|]}t|qSr)r-r )rvrrrrrz&Attempting to %i dtypes for %i fields!z Reverting to default.cSsg|]\}}||fqSrr)rr0rrrrrrcSsg|]}t|qSr)rJZdefault_fill_valuerrrrrrcSs$g|]\}}}}t||||dqS))rQr rR)r)rarFr2rrrrrs r5)r-_NoValuermwarningswarnDeprecationWarningrrfindrr'r!rr7rrr)Tr)rrrZ missingcharvarnamesrrZftextr firstlineZ _varnamesZ _variablesrZnfieldsrVr:ZmfillvrZ _datalistrrrrsB      rcs|j|j|dus|tvr*dtj}t|}tjj||jfg}t j |fddjj Dj |jgjj |Rttdd|jD}t j |fddjj Dj t|gjj |R_S)zAdds a new field to the masked record array Uses `newfield` as data and `newfieldname` as name. If `newfieldname` is None, the new field name is set to 'fi', where `i` is the number of existing fields. Nrcs$g|]}jj|g|RqSrrror)rnewdatarrrszaddfield..cSsg|]}|tjfqSrrr4rrrrrcs$g|]}jj|g|RqSrrr)rnewmaskrrrs)rrr+r!r rJr r-r*r r7rlvaluesrr]rr.r)ZmrecordZnewfieldZ newfieldnameZnewdtypeZ newmdtyper)rrrrrrs,          r)N)NNNNNFNN)NrrNN)N))rZnumpy.marrrrrrrr rJrnumpyr-r r r r\Znumpy._core.recordsr rrrrZ_corerecordsZ_byteorderconvcoreZ_check_fill_value__all__r+r3r;rrrrrrrrrrrrsD(   "  + A% P