o 6a>h @sdZddlmZmZmZmZmZmZmZm Z ddlm Z ddl Z ddl Z ddl mZmZmZmZmZddlmZmZe jjjZe jjZgdZgdZddd Zd d Z Gd d d eZ!ddZ"e!Z#   d ddZddddddddef ddZddZ$ddZ%  d!ddZ&dddZ'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)bool_dtypendarrayrecarrayarray) fromarrays fromrecords) MaskedRecords mrecarrayrr fromtextfileaddfield)_data_mask _fieldmaskr c Cst|}ddt|D}|dur|}n,t|ttfr|}nt|tr)|d}ntd|t|}||kr@|||d7}g}t|||j D](\}}}|t vrh|dt vrb| ||dfqI| |qI| ||dfqIt |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.0irr3/usr/lib/python3/dist-packages/numpy/ma/mrecords.py 6z_checknames..N,zillegal input names r)lenrange isinstancetupleliststrsplit NameErrorzipdescrreserved_fieldsappendnpr ) r+namesndescr default_names new_namesnnamesndtrrr _checknames-s(     r7cCs:dd|jjD}tj|j|d}tdgt||_|S)NcSsg|]}|dfqS)z|b1rrr4rrrrPrz"_get_fieldmask..r F)r r/r.emptyshaper%r"flat)selfmdescrfdmaskrrr_get_fieldmaskOsr@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| tust| s-|s+tdgt |_ |Stj | |d} | j |j kre|j| j}}|dkrMt | |j } n||krYt| |j } n d}t|||fd}|sq|| d|_|S| jkry| }ntj fdd| Dd }||_ |S) N) r bufoffsetstridesformatsr/titles byteorderalignedFcopyr!z?Mask and data not compatible: data size is %i, mask size is %i.Tcg|] }t|gtqSrr%r"rmmdtyperrrz)MaskedRecords.__new__..r9)r __new__mamake_mask_descrr rr.sizer%r"rrr;resizereshaper __setmask__ _sharedmask)clsr;r rArBrCrDr/rErFrGmask hard_mask fill_value keep_maskrIoptionsr=ndnmmsgrrrNrrQhs>    zMaskedRecords.__new__cst|dd}|dur8t|dt}t|d}|tur#tj|j|d}nt|tfdd|Dd t }|j }|j |d| ||dtkrPt |d<dS)Nrr r9crJrrKrLr>rrrrPz4MaskedRecords.__array_finalize__..r _baseclass)getattrrr __getattribute__rRmake_mask_noner;rSnarrayviewr __dict__update _update_from)r=objrobjmask_dtype_dictrrbr__array_finalize__s$       z MaskedRecords.__array_finalize__cCs t|tS)z2 Returns the data as a recarray. )r rir r=rrrrs zMaskedRecords._datacCs|jS)z! Alias to mask. rcrrrrrrszMaskedRecords._fieldmaskcCs|jrt|jSt|jS)z% Returns the length )ndimr"rr rrrrr__len__s  zMaskedRecords.__len__c Cszt||WStyYnwt|dj}z ||dd}Wnttfy8}ztd||d}~wwt|d}t||d}|j|}|j j durVt dd}| dd} | durz| |} Wn t yqYnwt| j } | t| r| fnd f}|js|r|t}t|_d |_| |_| d d} | durz| ||_W|Styd|_Y|Sw|S|}|S) Nr record array has no attribute rjrdz4MaskedRecords is currently limited tosimple records.FrrT _fill_value)objectrfAttributeErrorr fields TypeErrorKeyErrorrigetfieldr r/NotImplementedErrorget IndexErrorr"boolanyr;rrd_isfieldrrw ValueErroritem) r=attr fielddictrese _localdictrrm hasmaskedrtp_lenrwrrrrfs`             zMaskedRecords.__getattribute__c Cs~|dvr ||dSt|d}||v}z t|||}Wn#tyAt|djp-i}t|dp5i}||vs?||vs?Yn&wt|djpJi}||vrQ|S|rgzt||Wn tyf|YSwz ||dd}Wntt fy} zt d|| d} ~ ww|t ur|d} | dur|d|} n|} d } nt |} t |} t|d j| g|R} |d || | S) z< Sets the attribute attr to the value val. )rZ fieldmaskNrjr _optinforurvrwTrr)rWrxrf __setattr__ Exceptionr rz __delattr__r{r|ryrr rsetfield __setitem__)r=rvalrnewattrretroptinforrrwdvalmvalrmrrrrsX    zMaskedRecords.__setattr__cCs|j}t|d}t||d}t|tr<||t}|||_d|_|d}|dur2|||_ |j s:|jr:t S|St j ||ddt}t j ||ddt|_|S)z Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`. rrdTrwNFrH)rjr rfrir$r'rrrXrwrsrr.rrr )r=indxrrrrmfvalrrr __getitem__'s      zMaskedRecords.__getitem__cCs0t|||t|trt||j|<dSdS)z2 Sets the given record to value. N)rrr$r'rRrr)r=rvaluerrrrGs zMaskedRecords.__setitem__csvjdkr ddtfddjjDD}dd|dSddtfd djjDD}d d|d S) z8 Calculates the string representation. r!cSs(g|]}dddd|DdqS)(r cSg|]}t|qSrr'rrrrrVr4MaskedRecords.__str__...)joinrsrrrrVs z)MaskedRecords.__str__..cg|]}t|qSrrerfrrrrrW[z, ]cSs"g|] }ddd|DqS)r cSrrrrrrrrZrrrrrrrrZscrrrrrrrrr[rrr)rTr*r r/r)r=mstrrrrr__str__Ps zMaskedRecords.__str__csnjj}dtdd|DdffddjjD}|dd|djfd gtd |S) z6 Calculates the repr representation. z %%%is : %%scSrr)r"r8rrrrdrz*MaskedRecords.__repr__..csg|] }|t|fqSrrrfmtr=rrrerPrzmasked_records(z fill_valuez ) )r r/maxinsertextendr\r'r)r=_namesreprstrrrr__repr__^s zMaskedRecords.__repr__cCs|dur|durt|}nYt||}nR|dur`zt|tr(t||}d}nt||}Wn7ty_t|}|jdurT|jjd}| ||}| |nt||}d|_ Ynwt|||}t |dt t urt|j}|j|t|_|j|j_|S)z3 Returns a view of the mrecarray. Nrr)r ri issubclassr{r.r rz __class__ __bases__ __array__rlrwrerrRrSrr;)r=r typeoutputbasetyperOrrrriks4              zMaskedRecords.viewcC d|_dS)z+ Forces the mask to hard. TN _hardmaskrrrrr harden_mask zMaskedRecords.harden_maskcCr)z* Forces the mask to soft FNrrrrrr soften_maskrzMaskedRecords.soften_maskcCs$|jt|}|j|_|S)z7 Returns a copy of the masked record. )rrIrirr)r=copiedrrrrIs 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``. Nr9)r tolistrhrxr)r=r\resultrZrrrrs  zMaskedRecords.tolistcCs,d|j|j|jj|j|j|jf}|S)zWReturn the internal state of the masked array. This is for pickling. r!)r;r flagsfncrtobytesrrw)r=staterrr __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|]\}}|tfqSrr )rk_rrrrz.MaskedRecords.__setstate__..rN)r __setstate__r r+rjr\) r=rvershptypisfrawmskflvrOrrrrs  zMaskedRecords.__setstate__cCst|j|jddf|fS)z? Return a 3-tuple for pickling a MaskedArray. )rb)_mrreconstructrrdrrrrrr __reduce__szMaskedRecords.__reduce__)NNN)__name__ __module__ __qualname____doc__rrQrqpropertyrrrtrfrrrrrrirrrIrrrrrrrrrVs8 )   /8   )  rcCs4t||||}tt|d}|j||||dS)zK Build a new MaskedArray from the information stored in a pickle. b1)rZr )r rQri)subtype baseclass baseshaperrrrrrrsrFc Cs\dd|D} dd|D} t| |||||||dt} tt| | j_|dur,|| _| 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. cSrr)rrxrrrrrzfromarrays..cSsg|] }tt|qSr)r. atleast_1drrrrrrsr r;rDr/rErGrFN) recfromarraysrirr&r*rr<r\) arraylistr r;rDr/rErGrFr\datalistmasklist_arrayrrrrsrc Cst|dd} t|tr"t|tr|t}|dur|j}|}t||||||||dt } |dur8|| _ | t urct j | dd} t| j} | rO| | j_n| jdkr^dd| D| j_n| | | durn| | 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. rNrFrHrucSrr)r%rLrrrr_rzfromrecords..)rer$r rr rir rrecfromrecordsrr\rr.rr"rr<rsrW) reclistr r;rDr/rErGrFr\rZrmrecmaskrecordlengthrrrr&s4 "       rcCsg}t|}|jdkr|d}n |jdkrtd|D]V}zt|WnEttfyizt|Wn+ttfy^zt|WnttfyS||j Yn w|t tYn w|t tYqw|t tq|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. rurzThe array should be 2D at most!) r.asarrayrsrintr{floatcomplexr-r )arrvartypesrrrr_guessvartypesgs4        rc Cszt|dr|Szt|}Wnty"}z td|d|d}~ww|dddkr5|dd|S|td) z1 Opens the file handle of file `fname`. readlinezNo such file: ''Nruz\xrzWow, binary file)hasattropenIOErrorrseekcloser~)fnamerrrrropenfiles   r#cs,t|} |}|d|}|} t| dkr nq|dur'| }tfdd|D} | j\} } ||durGt | d}n&dd|D}t|| krmd} | d 7} t j | t|| fd d t | d}d dt ||D}d d|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. delimitor : {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 lineTNr!cs2g|]}|dkrt|dkr|qS)rr!)r"stripr()rline commentchar delimitorrrrs z fromtextfile..rcSg|]}t|qSr)r.r )rvrrrrrz&Attempting to %i dtypes for %i fields!z Reverting to default.ru) stacklevelcSsg|]\}}||fqSrr)rr4rrrrrrcSr r)rRdefault_fill_valuerrrrrrcSs$g|]\}}}}t||||dqS))rZr r\)r)rarMr6rrrrrs r9)rrfindrr(r"rr;rrwarningswarnr*Tr)rr r  missingcharvarnamesrftextr firstline _varnames _variablesrnfieldsrar>mfillvr _datalistrr rrs8       rcs|j|j|dus|tvrdtj}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. Nrc$g|]}jj|g|RqSrrr}r)rnewdatarrrzaddfield..cSsg|]}|tfqSrrr8rrrrrcrrrr)rnewmaskrrrr!)rrr,r"r rRrr.r+r r;rzvaluesrrirr/r)mrecordnewfield newfieldnamenewdtype newmdtyper)rrr r"rrs,          rr)NNNNNFNN)NrrNN)(rnumpy.marrrrrrrr rRrnumpyr.r r r r rrhnumpy.core.recordsrrrrcorerecords_byteorderconv_check_fill_value__all__r,r7r@rrrrrrrrrrrsB(   "  + A% D