U
    HvfJ                     @   s   d Z ddlZddlZddlmZ ddlmZmZm	Z	 dddd	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 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_matrix   )FortranFormatParser	IntFormat	ExpFormatMalformedHeaderhb_readhb_writeHBInfoHBFileHBMatrixTypec                   @   s   e Zd ZdS )r   N__name__
__module____qualname__ r   r   ?/tmp/pip-unpacked-wheel-96ln3f52/scipy/io/_harwell_boeing/hb.pyr      s   c                   @   s   e Zd ZdS )LineOverflowNr   r   r   r   r   r   #   s   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                   @   s8   e Zd ZedddZedd Zdd	d
Zdd ZdS )r
   Default title0Nc                 C   s  |j dd}|j}|j}|j}|j\}	}
|j}|dkrtt	|d }tt	|d }|j
jtjd krtt	t| }q|j
jtjd krtt	t| }qtd|j
j ntd|dkr<t|std	|j
jtjd krd
}n(|j
jtjd kr d}ntd|j
 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 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   ZAllFloatZ
AllIntegerztype %s not implemented yetzfmt argument not supported yet.z Complex values not supported yetintegerrealz"type %s 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shapeZnnzr   Zfrom_numbernpmaxdtypekindZ	typecodesr   absNotImplementedErrorZ	isrealobj
ValueErrorr   r!   fortran_format)clsmtitlekeymxtyper   pointerr%   valuesnrowsncols
nnon_zerosZpointer_fmtZindices_fmtZ
values_fmttpr"   pointer_nlinesindices_nlinesvalues_nlinestotal_nlinesr   r   r   	from_data.   sZ    


       zHBInfo.from_datac                 C   sN  |  d}t|dks&td| |dd }|dd }|  d}t| dkshtd| t|dd }t|dd }t|dd	 }t|d	d }|dd  }	|	d
krd}	nt|	}	|	dkstd|  d}t|dkstd| |dd  }
t|
dks,tdt|
}|j	dkrNtd| |j
dksftd| |jdksztd|dd dkstd| t|dd }t|dd	 }t|d	d }t|dd }|dkst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   z8Expected at least 72 characters for first line, got: 
%sN8   z9Expected at least 56 characters for second line, got: 
%s      *    r   z5Only files without right hand side supported for now.F   z6Expected at least 72 character for third line, got:
%s   z'mxtype expected to be 3 characters long)r   r   z=Only real or integer matrices supported for now (detected %s)r   z9Only unsymmetric matrices supported for now (detected %s)r    z)Only assembled matrices supported for nowz           z!Malformed data for third line: %sz4Unexpected value %d for nltvl (last entry of line 3)zExpected 3 formats, got %sr      )readlinestriplenr.   rstrip_expect_intupperr   from_fortran
value_type	structurestoragesplit)r0   fidliner2   r3   r>   r;   r<   r=   Z
rhs_nlinesZmxtype_sr4   r7   r8   r9   nelementalsctr   r   r   	from_file{   s    

         zHBInfo.from_filer   c                 C   s  || _ || _|dkrd}t|dkr,td|dkr8d}t|dkrTtd| t || _|| _|| _	|| _
t }||}t|tstd| ||}t|tstd	| ||}t|tr|jd
krtd||f tj}n<t|tr|jdkrtd||f t}ntd|f || _|| _|| _tj| _tj| _|| _|| _t||| _|| _	t||| _|| _
t||| _|| _|	| _ |
| _!|| _"|| _#dS )z@Do not use this directly, but the class ctrs (from_* functions).NzNo TitlerA   ztitle cannot be > 72 charactersz|No Key   z!key is > 8 characters (key is %s)z.Expected int format for pointer format, got %sz.Expected int format for indices format, got %s)r   complexz6Inconsistency between matrix type %s and value type %s)r   z Unsupported format for values %r)$r2   r3   rL   r.   warningswarnr   r>   r;   r<   r=   r   parse
isinstancer   r   rQ   r(   Zfloat64intpointer_formatindices_formatvalues_formatZint32Zpointer_dtypeZindices_dtypevalues_dtyper   pointer_nbytes_fullindices_nbytes_fullvalues_nbytes_fullr7   r8   r9   rW   r4   )selfr2   r3   r>   r;   r<   r=   r4   r7   r8   r9   Zpointer_format_strZindices_format_strZvalues_format_strZright_hand_sides_nlinesrW   parserra   rb   rc   rd   r   r   r   __init__   sp    






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.rA   rZ   z%14d%14d%14d%14dz%14s%14d%14d%14d%14drC   r   z%16s%16s%20s      r@   )r2   ljustr3   appendr>   r;   r<   r=   r4   r/   r7   r8   r9   ra   rb   rc   join)rh   headerZpffmtZiffmtZvffmtr   r   r   dump  s*       zHBInfo.dump)r   r   NN)r   r   )r   r   r   classmethodr?   rY   rj   rq   r   r   r   r   r
   -   s   L
X   
Hc              
   C   sL   z
t | W S  tk
rF } z|d kr(d}t||  |W 5 d }~X Y nX d S )NzExpected an int, got %s)r`   r.   )valuemsger   r   r   rN   +  s    
rN   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}z$t
||d |d f|j|jfdW S  tk
r } z|W 5 d }~X Y nX d S )NrF    )r*   sepr   )r'   )ro   readre   rJ   r(   
fromstringr`   rf   rg   rd   r   r7   r8   r.   )	contentrp   Z
ptr_stringptrZ
ind_stringindZ
val_stringvalru   r   r   r   _read_hb_data4  s6       
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r| || t||j| d   d  d S )Nr   r@   r   )Zpython_formatr   Zreshapewritetupler!   )	farr   r   ZpyfmtZ
pyfmt_fullfullrowZnremainr   r   r   write_arrayO  s    
z _write_data.<locals>.write_arrayr@   r   )r#   r   rq   r$   r;   ra   r%   r<   rb   r&   r=   rc   )r1   rU   rp   r   r   r   r   _write_dataL  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edd e D Z	edd e D Z
edd e D Zedd ZdddZedd Zdd ZdS )r   zClass to hold the matrix type.RCPI)r   r[   patternr   SUHZ)Z	symmetricr   Z	hermitianZskewsymmetricZrectangularAE)r    Z	elementalc                 C   s   g | ]\}}||fqS r   r   .0ijr   r   r   
<listcomp>~  s     zHBMatrixType.<listcomp>c                 C   s   g | ]\}}||fqS r   r   r   r   r   r   r     s     c                 C   s   g | ]\}}||fqS r   r   r   r   r   r   r     s     c              
   C   s   t |dkstdz8| j|d  }| j|d  }| j|d  }| |||W S  tk
r| } ztd| |W 5 d }~X Y nX d S )NrH   z:Fortran format for matrix type should be 3 characters longr   r   rI   zUnrecognized format %s)rL   r.   	_f2q_type_f2q_structure_f2q_storageKeyError)r0   r   rQ   rR   rS   ru   r   r   r   rP     s    zHBMatrixType.from_fortranr    c                 C   sX   || _ || _|| _|| jkr(td| || jkr>td| || jkrTtd| d S )NzUnrecognized type %szUnrecognized structure %szUnrecognized storage %s)rQ   rR   rS   	_q2f_typer.   _q2f_structure_q2f_storage)rh   rQ   rR   rS   r   r   r   rj     s    


zHBMatrixType.__init__c                 C   s$   | j | j | j| j  | j| j  S N)r   rQ   r   rR   r   rS   rh   r   r   r   r/     s
    


zHBMatrixType.fortran_formatc                 C   s   d| j | j| jf S )NzHBMatrixType(%s, %s, %s))rQ   rR   rS   r   r   r   r   __repr__  s    zHBMatrixType.__repr__N)r    )r   r   r   __doc__r   r   r   dictitemsr   r   r   rr   rP   rj   propertyr/   r   r   r   r   r   r   i  s0   


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 )r   Nc                 C   s&   || _ |dkrt|| _n|| _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
   rY   _hb_info)rh   filehb_infor   r   r   rj     s    zHBFile.__init__c                 C   s   | j jS r   )r   r2   r   r   r   r   r2     s    zHBFile.titlec                 C   s   | j jS r   )r   r3   r   r   r   r   r3     s    z
HBFile.keyc                 C   s
   | j jjS r   )r   r4   rQ   r   r   r   r   type  s    zHBFile.typec                 C   s
   | j jjS r   )r   r4   rR   r   r   r   r   rR     s    zHBFile.structurec                 C   s
   | j jjS r   )r   r4   rS   r   r   r   r   rS     s    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   )rh   r1   r   r   r   write_matrix  s    zHBFile.write_matrix)N)r   r   r   rj   r   r2   r3   r   rR   rS   r   r   r   r   r   r   r     s   





c              
   C   sB   dd }t | dr|| S t| }||W  5 Q R  S Q R X d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.

    Returns
    -------
    data : scipy.sparse.csc_matrix instance
        The data read from the HB file as a sparse matrix.

    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_matrix, eye
    >>> data = csr_matrix(eye(3))  # create a sparse matrix
    >>> hb_write("data.hb", data)  # write a hb file
    >>> print(hb_read("data.hb"))  # read a hb file
      (0, 0)	1.0
      (1, 1)	1.0
      (2, 2)	1.0

    c                 S   s   t | }| S r   )r   r   rU   Zhbr   r   r   _get_matrix  s    zhb_read.<locals>._get_matrixrx   N)hasattropen)path_or_open_filer   r   r   r   r   r     s
    %

c              
      sh   j dd dkrt  fdd}t| dr>|| S t| d}||W  5 Q R  S Q R X 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-matrix
        the sparse matrix 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_matrix, eye
    >>> data = csr_matrix(eye(3))  # create a sparse matrix
    >>> hb_write("data.hb", data)  # write a hb file
    >>> print(hb_read("data.hb"))  # read a hb file
      (0, 0)	1.0
      (1, 1)	1.0
      (2, 2)	1.0

    Fr   Nc                    s   t |  }|S r   )r   r   r   r   r1   r   r   _set_matrix2  s    
zhb_write.<locals>._set_matrixr   w)r#   r
   r?   r   r   )r   r1   r   r   r   r   r   r   r	     s    (

)N)N)r   r\   Znumpyr(   Zscipy.sparser   Z_fortran_format_parserr   r   r   __all__	Exceptionr   Warningr   r   r
   rN   r~   r   r   r   r   r	   r   r   r   r   <module>   s(   
   
	=/0