U C^h @sHdZddlmZmZmZddlZddlZddlZddl m Z ddlm Z m Z m Z mZmZddlmZmZejjjZddlmZddlmZmZmZmZmZm Z m!Z!m"Z"ejj#Z#dd d d d d gZ$ddddgZ%d$ddZ&ddZ'Gdddee(Z)ddZ*e)Z+d%dd Zddddddddef dd ZddZ,ddZ-d&d"d Z.d'd#d Z/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 )divisionabsolute_importprint_functionN) basestring)bool_dtypendarrayrecarrayarray) fromarrays fromrecords)MAError MaskedArraymaskednomask masked_arraygetdata getmaskarrayfilled MaskedRecords mrecarrayr r fromtextfileaddfield_data_mask _fieldmaskrc Cst|}ddt|D}|dkr(|}nZt|ttfr<|}n&t|trR|d}ntdt|t|}||kr|||d7}g}t |||j D]P\}}}|t kr|dt kr| ||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.0irr4/tmp/pip-install-6_kvzl1k/numpy/numpy/ma/mrecords.py :sz_checknames..N,zillegal input names %sr)lenrange isinstancetupleliststrsplit NameErrorreprzipdescrreserved_fieldsappendnpr) r/namesZndescrZ default_namesZ new_namesZnnamesndtrrr! _checknames1s(    r7cCs:dd|jjD}tj|j|d}tdgt||_|S)NcSsg|] }|dfqS)z|b1rrr4rrr!r"Tsz"_get_fieldmask..rF)rr3r2emptyshaper(r%flat)selfmdescrZfdmaskrrr!_get_fieldmaskSsr?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| tks>t| sX|sVtdgt |_ ntj | |d} | j |j kr|j| j}}|dkrt | |j } n,||krt| |j } nd}t|||fd}|s|| d|_n2| jkr| }ntj fdd| Dd }||_ |S) N) rbufoffsetstridesformatsr3titles byteorderalignedFcopyr$z?Mask and data not compatible: data size is %i, mask size is %i.Tcsg|]}t|gtqSrr(r%rmmdtyperr!r"sz)MaskedRecords.__new__..r9)r __new__mamake_mask_descrrrr2sizer(r%rr r;resizeZreshaper __setmask__ _sharedmask)clsr;rr@rArBrCr3rDrErFmaskZ hard_mask fill_valueZ keep_maskrHoptionsr=ZndnmmsgrrrLr!rNls@    zMaskedRecords.__new__cst|dd}|dkrpt|dt}t|d}|tkrFtj|j|d}n*t|tfdd|Dd t }|j }|j |d| ||dtkrt |d<dS)Nrrr9csg|]}t|gtqSrrIrJr>rr!r"sz4MaskedRecords.__array_finalize__..r _baseclass)getattrrr__getattribute__rOZmake_mask_noner;rPnarrayviewr __dict__update _update_from)r=objrZobjmaskZ_dtype_dictrr[r!__array_finalize__s$       z MaskedRecords.__array_finalize__cCs t|tS)z2 Returns the data as a recarray. )rrar r=rrr!rszMaskedRecords._datacCs|jS)z! Alias to mask. r\rhrrr!rszMaskedRecords._fieldmaskcCs|jrt|jSt|jS)z% Returns the length )ndimr%rrrhrrr!__len__s zMaskedRecords.__len__c Cszt||WStk r"YnXt|dj}z||dd}Wn$ttfk rjtd|YnXt|d}t||d}|j|}|j j dk rt dd}| dd}|dk r z ||}Wnt k rYnXt|j } |t| r| fnd f}|js|rx|t}t|_d |_||_| d d} | dk rz| ||_Wntk rtd|_YnXn|}|S) Nr record array has no attribute %srbr]z4MaskedRecords is currently limited tosimple records.FrrT _fill_value)objectr_AttributeErrorrfields TypeErrorKeyErrorragetfieldrr3NotImplementedErrorget IndexErrorr%boolanyr;rr]Z_isfieldrrm ValueErroritem) r=attr fielddictres _localdictrreZ hasmaskedrZtp_lenrmrrr!r_sH          zMaskedRecords.__getattribute__c Cs~|dkr||dSt|d}||k}zt|||}WnHtk rt|djp\i}t|dpli}||ks||ksYnNXt|djpi}||kr|S|rzt||Wntk r|YSXz||dd}Wn&tt fk r t d|YnX|t krB|d} | dk r8|d|} n|} d } nt |} t |} t|d j| f|} |d || | S) z< Sets the attribute attr to the value val. )rVZ fieldmaskNrbrZ_optinforkrlrmTrr)rSrnr_ __setattr__ Exceptionrrp __delattr__rqrrrorrrsetfield __setitem__) r=r{valr~Znewattrretr|Zoptinfor}rmdvalZmvalrerrr!rsF     zMaskedRecords.__setattr__cCs|j}t|d}t||d}t|trx||t}|||_d|_|d}|dk rd|||_ |j st|jrtt 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`. rr]TrmNFrG)rbrr_rar'rrrrTrmrirr2r rr )r=indxr~rrreZfvalrrr! __getitem__)s      zMaskedRecords.__getitem__cCs,t|||t|tr(t||j|<dS)z2 Sets the given record to value. N)rrr'rrOrr)r=rvaluerrr!rIs zMaskedRecords.__setitem__csrjdkr..joinrsrrr!r"Xsz)MaskedRecords.__str__..csg|]}t|qSrr^rfrhrr!r"Ysz[%s]z, cSs$g|]}dddd|DqS)z%sr#cSsg|] }t|qSrrrrrr!r"\srrrrrr!r"\scsg|]}t|qSrrrrhrr!r"]srN)rQr.rr3r)r=Zmstrrrhr!__str__Rs zMaskedRecords.__str__csnjj}dtdd|DdffddjjD}|dd|djfd gtd |S) z6 Calculates the repr representation. z %%%is : %%scSsg|] }t|qSr)r%r8rrr!r"fsz*MaskedRecords.__repr__..csg|]}|t|fqSrrrfmtr=rr!r"gsrzmasked_records(z fill_valuez ) )rr3maxinsertextendrWr*r)r=_namesZreprstrrrr!__repr__`s zMaskedRecords.__repr__cCs|dkr*|dkrt|}qt||}n|dkrz,t|trPt||}d}n t||}Wqtk rt|}|jdkr|jjd}| ||}| |n t||}d|_ YqXnt|||}t |dt t k r t|j}|j|t|_|j|j_|S)z3 Returns a view of the mrecarray. Nrr)rra issubclassrqr2rrp __class__ __bases__Z __array__rdrmr^rrOrPrr;)r=rtypeoutputbasetyperMrrr!rams0          zMaskedRecords.viewcCs d|_dS)z+ Forces the mask to hard. TNZ _hardmaskrhrrr! harden_maskszMaskedRecords.harden_maskcCs d|_dS)z* Forces the mask to soft FNrrhrrr! soften_maskszMaskedRecords.soften_maskcCs$|jt|}|j|_|S)z7 Returns a copy of the masked record. )rrHrarr)r=copiedrrr!rHs zMaskedRecords.copycCsH|dk r||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)rtolistr`rnr)r=rWresultrVrrr!rs zMaskedRecords.tolistcCs,d|j|j|jj|j|j|jf}|S)zWReturn the internal state of the masked array. This is for pickling. r$)r;rflagsZfncrtobytesrrm)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_rrr!r"sz.MaskedRecords.__setstate__..rN)r __setstate__rr/rbrW) r=rverZshptypZisfrawZmskZflvrMrrr!rs zMaskedRecords.__setstate__cCst|j|jddf|fS)z? Return a 3-tuple for pickling a MaskedArray. )rb)_mrreconstructrr]rrhrrr! __reduce__szMaskedRecords.__reduce__)NN)N)__name__ __module__ __qualname____doc__rrNrgpropertyrrrjr_rrrrrrarrrHrrrrrrrr!rZsB )   .7   ) cCs4t||||}tt|d}|j||||dS)zK Build a new MaskedArray from the information stored in a pickle. Zb1)rVr)rrNra)subtypeZ baseclassZ baseshaperrrrrr!rsrFc Cs\dd|D} dd|D} t| |||||||dt} tt| | j_|dk rX|| _| 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)rrxrrr!r"szfromarrays..cSsg|]}tt|qSr)r2Z atleast_1drrrrr!r"srr;rCr3rDrFrEN) recfromarraysrarr)r.rr<rW) Z arraylistrr;rCr3rDrFrErWZdatalistZmasklistZ_arrayrrr!r s"c Cst|dd} t|trDt|tr.|t}|dkr<|j}|}t||||||||dt } |dk rp|| _ | t k rt j | dd} t| j} | r| | j_n(| jdkrdd| D| j_n | | | dk r| | 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. rNrFrGrkcSsg|] }t|qSr)r(rJrrr!r"_szfromrecords..)r^r'rrrrarrrecfromrecordsrrWrr2r r%rr<rirS) Zreclistrr;rCr3rDrFrErWrVrZmrecZmaskrecordlengthrrr!r &s8"        cCsg}t|}|jdkr"|d}n|jdkr4td|D]}z t|Wnttfk rz t|WnZttfk rz t|Wn$ttfk r||j YnX|t tYnX|t tYq8X|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. rkrzThe array should be 2D at most!) r2Zasarrayriryintrqfloatcomplexr1r)Zarrvartypesrrrr!_guessvartypesgs*        rcCstt|dr|Sz t|}Wn tk r:td|YnX|dddkr`|dd|S|tddS)z1 Opens the file handle of file `fname`. readlinezNo such file: '%s'Nrkz\xrzWow, binary file)hasattropenIOErrorrseekclosert)fnamerrrr!openfiles   r#cs*t|}|}|d|}|} t| dkrq@q|dkrL| }tfdd|D} | j\} } ||dkrt | d}nLdd|D}t|| krd} | d7} t j | t|| fd d t | d}d dt ||D}d d|D}| j |k}d dt | 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 lineNr$cs2g|]*}|dkrt|dkr|qS)rr$)r%stripr+)rline commentchar delimitorrr!r"s z fromtextfile..rcSsg|]}t|qSr)r2r)rvrrr!r"sz&Attempting to %i dtypes for %i fields!z Reverting to default.rk) stacklevelcSsg|]\}}||fqSrr)rr4rrrr!r"scSsg|]}t|qSr)rOZdefault_fill_valuerrrr!r"scSs$g|]\}}}}t||||dqS))rVrrW)r)rarKr6rrrr!r"s r9)rrfindrr+r%rr;rrwarningswarnr.Tr )rrrZ missingcharvarnamesrZftextr firstlineZ _varnamesZ _variablesrZnfieldsrZr>ZmfillvrZ _datalistrrr!rs4      cs|j|j|dks|tkr*dtj}t|}tjj||jfg}t j |fddjj Dj |jfjj |ttdd|jD}t j |fddjj Dj t|fjj |_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|f|qSrrrsr)rnewdatarr!r"szaddfield..cSsg|] }|tfqSrrr8rrr!r"scs"g|]}jj|f|qSrrr)rnewmaskrr!r"s)rrr0r%rrOr r2r/r r;rpvaluesrrarr3r)ZmrecordZnewfieldZ newfieldnameZnewdtypeZ newmdtyper)rrrrr!rs,          )N)NNNNNFNN)NrrNN)N)0r __future__rrrsysrZnumpyr2Z numpy.compatrrrrr r r`Znumpy.core.recordsr rr rcorerecordsZ_byteorderconvZnumpy.marOr rrrrrrrZ_check_fill_value__all__r0r7r?rnrrrrrrrrrrr!s`    (  "  + A% D