o
    Ö­j;L  ã                   @   sÈ   d Z ddlZddlZddlmZmZ ddlmZm	Z	m
Z
 ddgZG dd	„ d	eƒZG d
d„ deƒZdd„ ZG dd„ dƒZddd„Zdd„ Zdd„ ZG dd„ dƒZG dd„ dƒZddœdd„Zddd„ZdS )a  
Implementation of Harwell-Boeing read/write.

At the moment not the full Harwell-Boeing format is supported. Supported
features are:

    - assembled, non-symmetric, real matrices
    - integer for pointer/indices
    - exponential format for float values, and int format

é    N)Ú	csc_arrayÚ
csc_matrixé   )ÚFortranFormatParserÚ	IntFormatÚ	ExpFormatÚhb_readÚhb_writec                   @   ó   e Zd ZdS )ÚMalformedHeaderN©Ú__name__Ú
__module__Ú__qualname__© r   r   úX/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.pyr      ó    r   c                   @   r
   )ÚLineOverflowNr   r   r   r   r   r   "   r   r   c                 C   s   | j | j d |d  S )zcReturn the number of bytes to read to get every full lines for the
    given parsed fortran format.r   )ÚrepeatÚwidth)ÚfmtÚnlinesr   r   r   Ú_nbytes_full&   s   r   c                   @   s:   e Zd Zeddd„ƒZedd„ ƒZ	dd	d
„Zdd„ ZdS )ÚHBInfoúDefault titleÚ0Nc                 C   s¦  |j dd�}|j}|j}|j}|j\}	}
|j}|du rgt t 	|d ¡¡}t t 	|d ¡¡}|j
jtjd v rEt t 	t |¡¡ ¡}n&|j
jtjd v r[t t 	t |¡¡ ¡}nd|j
j› d�}t|ƒ‚td	ƒ‚|du r t |¡sxtd
ƒ‚|j
jtjd v r„d}n|j
jtjd v r�d}n	td|j
› d�ƒ‚t|ddƒ}ntdƒ‚dd„ }|||jƒ}|||jƒ}|||jƒ}|| | }| ||||||||	|
||j|j|jƒS )aâ  Create a HBInfo instance from an existing sparse matrix.

        Parameters
        ----------
        m : sparse array or matrix
            the HBInfo instance will derive its parameters from m
        title : str
            Title to put in the HB header
        key : str
            Key
        mxtype : HBMatrixType
            type of the input matrix
        fmt : dict
            not implemented

        Returns
        -------
        hb_info : HBInfo instance
        F©ÚcopyNr   ÚAllFloatÚ
AllIntegerztype z not implemented yetzfmt argument not supported yet.z Complex values not supported yetÚintegerÚrealz for values not implementedÚunsymmetricÚ	assembledz mxtype argument not handled yet.c                 S   s$   || j  }|| j  |kr|d7 }|S )Nr   )r   )r   Úsizer   r   r   r   Ú_nlinesi   s   
z!HBInfo.from_data.<locals>._nlines)ÚtocscÚindptrÚindicesÚdataÚshapeÚnnzr   Úfrom_numberÚnpÚmaxÚdtypeÚkindÚ	typecodesr   ÚabsÚNotImplementedErrorÚ	isrealobjÚ
ValueErrorÚHBMatrixTyper$   Úfortran_format)ÚclsÚmÚtitleÚkeyÚmxtyper   Úpointerr(   ÚvaluesÚnrowsÚncolsÚ
nnon_zerosÚpointer_fmtÚindices_fmtÚ
values_fmtÚmessageÚtpr%   Úpointer_nlinesÚindices_nlinesÚvalues_nlinesÚtotal_nlinesr   r   r   Ú	from_data-   sN   

ÿüzHBInfo.from_datac                 C   sR  |  ¡  d¡}t|ƒdkstd|› �ƒ‚|dd… }|dd… }|  ¡  d¡}t| ¡ ƒdks6td|› �ƒ‚t|dd… ƒ}t|dd… ƒ}t|dd	… ƒ}t|d	d… ƒ}|dd…  ¡ }	|	d
kred}	nt|	ƒ}	|	dksqtdƒ‚|  ¡  d¡}t|ƒdks…td|› �ƒ‚|dd…  ¡ }
t|
ƒdks—tdƒ‚t |
¡}|j	dvr©td|› d�ƒ‚|j
dks¶td|› d�ƒ‚|jdks¿tdƒ‚|dd… dksÎtd|› �ƒ‚t|dd… ƒ}t|dd	… ƒ}t|d	d… ƒ}t|dd… ƒ}|dksøtd| ƒ‚|  ¡  d¡}| ¡ }t|ƒdk�std|› �ƒ‚| |||||||||||d |d |d |	|ƒS )a6  Create a HBInfo instance from a file object containing a matrix in the
        HB format.

        Parameters
        ----------
        fid : file-like matrix
            File or file-like object containing a matrix in the HB format.

        Returns
        -------
        hb_info : HBInfo instance
        Ú
éH   z6Expected at least 72 characters for first line, got: 
Né8   z7Expected at least 56 characters for second line, got: 
é   é   é*   Ú r   z5Only files without right hand side supported for now.éF   z4Expected at least 72 character for third line, got:
é   z'mxtype expected to be 3 characters long)r!   r    z:Only real or integer matrices supported for now (detected ú)r"   z6Only unsymmetric matrices supported for now (detected r#   z)Only assembled matrices supported for nowz           zMalformed data for third line: z4Unexpected value %d for nltvl (last entry of line 3)zExpected 3 formats, got r   é   )ÚreadlineÚstripÚlenr5   ÚrstripÚ_expect_intÚupperr6   Úfrom_fortranÚ
value_typeÚ	structureÚstorageÚsplit)r8   ÚfidÚliner:   r;   rJ   rG   rH   rI   Ú
rhs_nlinesÚmxtype_sr<   r?   r@   rA   ÚnelementalsÚctr   r   r   Ú	from_file{   sz   ÿÿÿ


ÿ

ÿ
ÿüzHBInfo.from_filer   c                 C   s´  |du rd}t |ƒdkrtdƒ‚|du rd}t |ƒdkr(tjd|› d�td	d
� || _|| _|| _|| _|| _	|| _
tƒ }| |¡}t|tƒsNtd|› �ƒ‚| |¡}t|tƒs_td|› �ƒ‚| |¡}t|tƒr||jdvrxtd|› d|› �ƒ‚tj}nt|tƒr“|jdvr�td|› d|› �ƒ‚t}ntd|›�ƒ‚|| _|| _|| _tj| _tj| _|| _|| _t||ƒ| _|| _	t||ƒ| _|| _
t||ƒ| _|| _|	| _ |
| _!|| _"|| _#dS )z@Do not use this directly, but the class ctrs (from_* functions).NzNo TitlerM   ztitle cannot be > 72 charactersz|No Keyé   zkey is > 8 characters (key is rU   rT   )Ú
stacklevelz,Expected int format for pointer format, got z,Expected int format for indices format, got )r!   Úcomplexz"Inconsistency between matrix type z and value type )r    zUnsupported format for values )$rY   r5   ÚwarningsÚwarnr   r:   r;   rJ   rG   rH   rI   r   ÚparseÚ
isinstancer   r   r^   r-   Úfloat64ÚintÚpointer_formatÚindices_formatÚvalues_formatÚint32Úpointer_dtypeÚindices_dtypeÚvalues_dtyper   Úpointer_nbytes_fullÚindices_nbytes_fullÚvalues_nbytes_fullr?   r@   rA   rf   r<   )Úselfr:   r;   rJ   rG   rH   rI   r<   r?   r@   rA   Úpointer_format_strÚindices_format_strÚvalues_format_strÚright_hand_sides_nlinesrf   Úparserrr   rs   rt   rx   r   r   r   Ú__init__Ð   st   ÿ

ÿ

ÿ



ÿ


ÿ
zHBInfo.__init__c                 C   s¨   | j  d¡| j d¡ g}| d| j| j| j| jf ¡ | d| jj	 d¡| j
| j| jdf ¡ | jj	}| jj	}| jj	}| d| d¡| d¡| d	¡f ¡ d
 |¡S )z<Gives the header corresponding to this instance as a string.rM   ri   z%14d%14d%14d%14dz%14s%14d%14d%14d%14drO   r   z%16s%16s%20sé   é   rL   )r:   Úljustr;   ÚappendrJ   rG   rH   rI   r<   r7   r?   r@   rA   rr   rs   rt   Újoin)r|   ÚheaderÚpffmtÚiffmtÚvffmtr   r   r   Údump  s$   ÿÿ
ÿÿÿ
zHBInfo.dump)r   r   NN)r   r   )r   r   r   ÚclassmethodrK   rh   r‚   rŒ   r   r   r   r   r   ,   s    M
X
üIr   c              
   C   s>   zt | ƒW S  ty } z|d u rd}t||  ƒ|‚d }~ww )NzExpected an int, got %s)rq   r5   )ÚvalueÚmsgÚer   r   r   r[   ,  s   
€ýr[   c                 C   s¢   d  |  |j¡|  ¡ g¡}tj|tdd�}d  |  |j¡|  ¡ g¡}tj|tdd�}d  |  |j¡|  ¡ g¡}tj||j	dd�}t
||d |d f|j|jfd�S )NrR   ú )r/   Úsepr   )r*   )r‡   Úreadry   rW   r-   Ú
fromstringrq   rz   r{   rx   r   r?   r@   )Úcontentrˆ   Ú
ptr_stringÚptrÚ
ind_stringÚindÚ
val_stringÚvalr   r   r   Ú_read_hb_data5  s&   ÿÿÿÿÿÿ"rœ   c                 C   st   | j dd�} dd„ }| | ¡ ¡ | d¡ ||| jd |j|jƒ ||| jd |j|jƒ ||| j	|j
|jƒ d S )NFr   c           	      S   sš   |j }||j }|d |d |j … }| |d |jf¡D ]}|  |t|ƒ d ¡ q|j|j }|dkrK|  || t||j| d … ƒ d ¡ d S d S )Nr   rL   r   )Úpython_formatr   ÚreshapeÚwriteÚtupler$   )	ÚfÚarr   r   ÚpyfmtÚ
pyfmt_fullÚfullÚrowÚnremainr   r   r   Úwrite_arrayL  s   
,ÿz _write_data.<locals>.write_arrayrL   r   )r&   rŸ   rŒ   r'   rG   rr   r(   rH   rs   r)   rI   rt   )r9   rb   rˆ   r¨   r   r   r   Ú_write_dataI  s   
ÿÿÿr©   c                   @   s˜   e Zd ZdZdddddœZddd	d
ddœZdddœZdd„ e ¡ D ƒZdd„ e ¡ D ƒZ	dd„ e ¡ D ƒZ
edd„ ƒZddd„Zedd„ ƒZdd„ ZdS )r6   zClass to hold the matrix type.ÚRÚCÚPÚI)r!   rk   Úpatternr    ÚSÚUÚHÚZ)Ú	symmetricr"   Ú	hermitianÚskewsymmetricÚrectangularÚAÚE)r#   Ú	elementalc                 C   ó   i | ]\}}||“qS r   r   ©Ú.0ÚiÚjr   r   r   Ú
<dictcomp>{  ó    zHBMatrixType.<dictcomp>c                 C   rº   r   r   r»   r   r   r   r¿   |  rÀ   c                 C   rº   r   r   r»   r   r   r   r¿   }  rÀ   c              
   C   sv   t |ƒdks
tdƒ‚z| j|d  }| j|d  }| j|d  }| |||ƒW S  ty: } ztd|› �ƒ|‚d }~ww )NrT   z:Fortran format for matrix type should be 3 characters longr   r   rV   zUnrecognized format )rY   r5   Ú	_f2q_typeÚ_f2q_structureÚ_f2q_storageÚKeyError)r8   r   r^   r_   r`   r�   r   r   r   r]     s   €ÿzHBMatrixType.from_fortranr#   c                 C   s^   || _ || _|| _|| jvrtd|› �ƒ‚|| jvr!td|› �ƒ‚|| jvr-td|› �ƒ‚d S )NzUnrecognized type zUnrecognized structure zUnrecognized storage )r^   r_   r`   Ú	_q2f_typer5   Ú_q2f_structureÚ_q2f_storage)r|   r^   r_   r`   r   r   r   r‚   Œ  s   


ÿzHBMatrixType.__init__c                 C   s$   | j | j | j| j  | j| j  S ©N)rÅ   r^   rÆ   r_   rÇ   r`   ©r|   r   r   r   r7   ˜  s
   

ÿ
þzHBMatrixType.fortran_formatc                 C   s   d| j › d| j› d| j› d�S )NzHBMatrixType(z, rU   )r^   r_   r`   rÉ   r   r   r   Ú__repr__ž  s   zHBMatrixType.__repr__N)r#   )r   r   r   Ú__doc__rÅ   rÆ   rÇ   ÚitemsrÁ   rÂ   rÃ   r�   r]   r‚   Úpropertyr7   rÊ   r   r   r   r   r6   f  s2    üûþ


r6   c                   @   sb   e Zd Zddd„Zedd„ ƒZedd„ ƒZedd	„ ƒZed
d„ ƒZedd„ ƒZ	dd„ Z
dd„ ZdS )ÚHBFileNc                 C   s(   || _ |du rt |¡| _dS || _dS )a  Create a HBFile instance.

        Parameters
        ----------
        file : file-object
            StringIO work as well
        hb_info : HBInfo, optional
            Should be given as an argument for writing, in which case the file
            should be writable.
        N)Ú_fidr   rh   Ú_hb_info)r|   ÚfileÚhb_infor   r   r   r‚   £  s   
zHBFile.__init__c                 C   ó   | j jS rÈ   )rÐ   r:   rÉ   r   r   r   r:   ¶  ó   zHBFile.titlec                 C   rÓ   rÈ   )rÐ   r;   rÉ   r   r   r   r;   º  rÔ   z
HBFile.keyc                 C   ó
   | j jjS rÈ   )rÐ   r<   r^   rÉ   r   r   r   Útype¾  ó   
zHBFile.typec                 C   rÕ   rÈ   )rÐ   r<   r_   rÉ   r   r   r   r_   Â  r×   zHBFile.structurec                 C   rÕ   rÈ   )rÐ   r<   r`   rÉ   r   r   r   r`   Æ  r×   zHBFile.storagec                 C   s   t | j| jƒS rÈ   )rœ   rÏ   rÐ   rÉ   r   r   r   Úread_matrixÊ  s   zHBFile.read_matrixc                 C   s   t || j| jƒS rÈ   )r©   rÏ   rÐ   )r|   r9   r   r   r   Úwrite_matrixÍ  s   zHBFile.write_matrixrÈ   )r   r   r   r‚   rÍ   r:   r;   rÖ   r_   r`   rØ   rÙ   r   r   r   r   rÎ   ¢  s    





rÎ   T)Úspmatrixc                C   s\   dd„ }t | dƒr|| ƒ}nt| ƒ�}||ƒ}W d  ƒ n1 s!w   Y  |r,t|ƒS |S )aî  Read HB-format file.

    Parameters
    ----------
    path_or_open_file : path-like or file-like
        If a file-like object, it is used as-is. Otherwise, it is opened
        before reading.
    spmatrix : bool, optional (default: True)
        If ``True``, return sparse ``coo_matrix``. Otherwise return ``coo_array``.

    Returns
    -------
    data : csc_array or csc_matrix
        The data read from the HB file as a sparse array.

    Notes
    -----
    At the moment not the full Harwell-Boeing format is supported. Supported
    features are:

        - assembled, non-symmetric, real matrices
        - integer for pointer/indices
        - exponential format for float values, and int format

    Examples
    --------
    We can read and write a harwell-boeing format file:

    >>> from scipy.io import hb_read, hb_write
    >>> from scipy.sparse import csr_array, eye
    >>> data = csr_array(eye(3))  # create a sparse array
    >>> hb_write("data.hb", data)  # write a hb file
    >>> print(hb_read("data.hb", spmatrix=False))  # read a hb file
    <Compressed Sparse Column sparse array of dtype 'float64'
        with 3 stored elements and shape (3, 3)>
        Coords	Values
        (0, 0)	1.0
        (1, 1)	1.0
        (2, 2)	1.0
    c                 S   s   t | ƒ}| ¡ S rÈ   )rÎ   rØ   ©rb   Úhbr   r   r   Ú_get_matrixú  s   zhb_read.<locals>._get_matrixr“   N)ÚhasattrÚopenr   )Úpath_or_open_filerÚ   rÝ   r)   r¡   r   r   r   r   Ñ  s   )



ÿc                    st   ˆj dd�‰ˆ du rt ˆ¡‰ ‡ ‡fdd„}t| dƒr|| ƒS t| dƒ�}||ƒW  d  ƒ S 1 s3w   Y  dS )a™  Write HB-format file.

    Parameters
    ----------
    path_or_open_file : path-like or file-like
        If a file-like object, it is used as-is. Otherwise, it is opened
        before writing.
    m : sparse array or matrix
        the sparse array to write
    hb_info : HBInfo
        contains the meta-data for write

    Returns
    -------
    None

    Notes
    -----
    At the moment not the full Harwell-Boeing format is supported. Supported
    features are:

        - assembled, non-symmetric, real matrices
        - integer for pointer/indices
        - exponential format for float values, and int format

    Examples
    --------
    We can read and write a harwell-boeing format file:

    >>> from scipy.io import hb_read, hb_write
    >>> from scipy.sparse import csr_array, eye
    >>> data = csr_array(eye(3))  # create a sparse array
    >>> hb_write("data.hb", data)  # write a hb file
    >>> print(hb_read("data.hb", spmatrix=False))  # read a hb file
    <Compressed Sparse Column sparse array of dtype 'float64'
        with 3 stored elements and shape (3, 3)>
        Coords	Values
        (0, 0)	1.0
        (1, 1)	1.0
        (2, 2)	1.0
    Fr   Nc                    s   t | ˆ ƒ}| ˆ¡S rÈ   )rÎ   rÙ   rÛ   ©rÒ   r9   r   r   Ú_set_matrix7  s   

zhb_write.<locals>._set_matrixrŸ   Úw)r&   r   rK   rÞ   rß   )rà   r9   rÒ   râ   r¡   r   rá   r   r	     s   *

$ÿrÈ   )rË   rl   Únumpyr-   Úscipy.sparser   r   Ú_fortran_format_parserr   r   r   Ú__all__Ú	Exceptionr   ÚWarningr   r   r   r[   rœ   r©   r6   rÎ   r   r	   r   r   r   r   Ú<module>   s&      
	</7