
    >qjP                         d Z ddlZddlZddlZddlmZ ddlmZm	Z	 ddl
mZmZmZ ddgZ G d	 d
e      Z G d de      Zd Z G d d      ZddZd Zd Z G d d      Z G d d      ZeddZddZy)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)_NoValue)	csc_array
csc_matrix   )FortranFormatParser	IntFormat	ExpFormathb_readhb_writec                       e Zd Zy)MalformedHeaderN__name__
__module____qualname__     Z/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/scipy/io/_harwell_boeing/hb.pyr   r           r   r   c                       e Zd Zy)LineOverflowNr   r   r   r   r   r   $   r   r   r   c                 F    | j                   | j                  z  dz   |dz
  z  S )zcReturn the number of bytes to read to get every full lines for the
    given parsed fortran format.r   )repeatwidth)fmtnliness     r   _nbytes_fullr   (   s%     JJ"Q&6A:66r   c                   >    e Zd Zedd       Zed        Z	 ddZd Zy)HBInfoNc                    |j                  d      }|j                  }|j                  }|j                  }|j                  \  }	}
|j
                  }|bt        j                  t        j                  |dz   d            }t        j                  t        j                  |dz   d            }|j                  j                  t        j                  d   v rRt        j                  t        j                  t        j                  |      t        j                  d                   }n|j                  j                  t        j                  d   v r?t        j                  t        j                  t        j                  |      d             }n0d|j                  j                   d}t!        |      t!        d	      |t        j"                  |      st%        d
      |j                  j                  t        j                  d   v rd}nE|j                  j                  t        j                  d   v rd}nt!        d|j                   d      t'        |dd      }nt%        d      d } |||j(                        } |||j(                        } |||j(                        }||z   |z   } | ||||||||	|
||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copyr   )initial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                 R    || j                   z  }|| j                   z  |k7  r|dz  }|S )Nr   )r   )r   sizer   s      r   _nlinesz!HBInfo.from_data.<locals>._nlinesn   s/    SZZ'F

"d*!Mr   )tocscindptrindicesdatashapennzr   from_numbernpmaxdtypekind	typecodesr	   absfloat64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_nliness                         r   	from_datazHBInfo.from_data/   sh   * GGG(())wwuUU
; $//w{A0NOK#//w{A0NOK||  BLL$<<&22VVBFF6NBJJqMBBD
""bll<&@@&22VVBFF6NA668
 "&,,"3"3!44HI)'22%&GHH><<' !CDD||  BLL$>>""bll:&>>)FLL>)DEG G!"m[AF?@@	 !gll; gll;
FKK8%6F5#..-E5*&&(B(B%%	' 	'r   c                 4   |j                         j                  d      }t        |      dkD  st        d|       |dd }|dd }|j                         j                  d      }t        |j	                               dk\  st        d|       t        |dd       }t        |dd       }t        |dd	       }t        |d	d       }|dd j                         }	|	d
k(  rd}	nt        |	      }	|	dk(  st        d      |j                         j                  d      }t        |      dk\  st        d|       |dd j                         }
t        |
      dk(  st        d      t        j                  |
      }|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      |j                         j                  d      }|j                         }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: 
N8   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: zUnexpected value z! for nltvl (last entry of line 3)zExpected 3 formats, got r      )readlinestriplenr=   rstrip_expect_intupperr>   from_fortran
value_type	structurestoragesplit)r@   fidlinerB   rC   rR   rO   rP   rQ   
rhs_nlinesmxtype_srD   rG   rH   rI   nelementalscts                    r   	from_filezHBInfo.from_file   s    ||~##D)4y2~ ''+f. / /Sb	23i ||~##D)4;;=!R' ''+f. / /"49-$T"R[1$T"R[1#DBK0"R[&&(
J$Z0JQ $ % % ||~##D)4yB  &&*V- . . 8>>#8}!FGG**84$77 ..4XQ8 9 9=0 ..4XQ8 9 9~~,HIIAbzX%>tfEFFDBK(DBK( b-
!$r"+.a#K=0QR 
 ||~##D)ZZ\2w!|7t<==5#5%a5"Q%A{	, 	,r   c                 R   |d}t        |      dkD  rt        d      |d}t        |      dkD  r t        j                  d| dt        d	
       || _        || _        || _        || _        || _	        || _
        t               }|j                  |      }t        |t              st        d|       |j                  |      }t        |t              st        d|       |j                  |      }t        |t              r0|j                   dvrt        d| d|       t"        j$                  }nDt        |t              r&|j                   dvrt        d| d|       t&        }nt        d|      || _        || _        || _        t"        j.                  | _        t"        j.                  | _        || _        || _        t7        ||      | _        || _	        t7        ||      | _        || _
        t7        ||      | _        || _        |	| _         |
| _!        || _"        || _#        y)z@Do not use this directly, but the class ctrs (from_* functions).NzNo TitlerV   ztitle cannot be > 72 charactersz|No Key   zkey is > 8 characters (key is r^   r]   )
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 )$rb   r=   warningswarnr   rB   rC   rR   rO   rP   rQ   r   parse
isinstancer   r	   rg   r4   r:   intpointer_formatindices_formatvalues_formatint32pointer_dtypeindices_dtypevalues_dtyper   pointer_nbytes_fullindices_nbytes_fullvalues_nbytes_fullrG   rH   rI   ro   rD   )selfrB   rC   rR   rO   rP   rQ   rD   rG   rH   rI   pointer_format_strindices_format_strvalues_format_strright_hand_sides_nlinesro   parserr{   r|   r}   r   s                        r   __init__zHBInfo.__init__   sJ    =Eu:?>??;Cs8a<MM:3%qA&16
(,,*$&&89.)4K ./1 2 2  &89.)4K ./1 2 2 %67mY/  (;; #EfX N//<o"? @ @::Ly1  3 #EfX N//<o"? @ @ L=m=NOPP,,*XXXX(,#/#O ,#/#O *".}m"L

$&r   c                    | j                   j                  d      | j                  j                  d      z   g}|j                  | j                  d| j
                  d| j                  d| j                  d       |j                  | j                  j                  j                  d      d| j                  d| j                  d| j                  ddd       | j                  j                  }| j                  j                  }| j                  j                  }|j                  |j                  d      d|j                  d      d|j                  d	      d
       dj!                  |      S )z<Gives the header corresponding to this instance as a string.rV   rs   14drX   14sr      16s   20srU   )rB   ljustrC   appendrR   rO   rP   rQ   rD   r?   rG   rH   rI   r{   r|   r}   join)r   headerpffmtiffmtvffmts        r   dumpzHBInfo.dump  sJ   **""2&)::;**3/0C0CC/HI\I\]`Habfbtbtuxayz{3399"=cB4::cBRSWS]S]^aRbcgcrcrsvbwxyz}w~  	A##22##22""11R-ekk"oc-B5;;r?SVBWXYyy  r   )zDefault title0NN)r   r   )r   r   r   classmethodrS   rq   r   r   r   r   r   r   r   .   s?    N' N'` S, S,r 45	GR!r   r   c                 b    	 t        |       S # t        $ r}|d}t        || z        |d }~ww xY w)NzExpected an int, got %s)rz   r=   )valuemsges      r   rd   rd   -  s<    -5z -;+Cu%1,-s   
 	.).c                 j   dj                  | j                  |j                        | j                         g      }t	        j
                  |t        d      }dj                  | j                  |j                        | j                         g      }t	        j
                  |t        d      }dj                  | j                  |j                        | j                         g      }t	        j
                  ||j                  d      }t        ||dz
  |dz
  f|j                  |j                  f      S )Nr[    )r6   sepr   )r1   )r   readr   r`   r4   
fromstringrz   r   r   r   r   rG   rH   )contentr   
ptr_stringptr
ind_stringind
val_stringvals           r   _read_hb_datar   6  s   ',,v'A'AB"++-/ 0J
--
3 C ',,v'A'AB'')+ ,J
--
3 C ',,v'@'@A!**,. /J
--
%%30C c3q5#a%(v||0LMMr   c                    | j                  d      } d }|j                  |j                                |j                  d        ||| j                  dz   |j                  |j
                          ||| j                  dz   |j                  |j                          ||| j                  |j                  |j                         y )NFr!   c                    |j                   }||j                  z  }|d |dz
  |j                  z   }|j                  |dz
  |j                  f      D ]"  }| j                  |t	        |      z  dz          $ |j
                  |j
                  z
  }|dkD  r4| j                  ||z  t	        ||j
                  |z
  d        z  dz          y y )Nr   rU   r   )python_formatr   reshapewritetupler+   )	farr   r   pyfmt
pyfmt_fullfullrownremains	            r   write_arrayz _write_data.<locals>.write_arrayM  s     !!SZZ'
 ,FQJ#**,-<<3:: 67 	4CGGJs+d23	4''DII%Q;GGUW_b71B1C.D(EELM r   rU   r   )r-   r   r   r.   rO   r{   r/   rP   r|   r0   rQ   r}   )rA   rk   r   r   s       r   _write_datar   J  s    	UAN IIfkkmIIdOQXXaZ!6!6%%'QYYq[&"7"7%%'QVVV11$$&r   c                   t   e Zd ZdZdddddZddd	d
ddZdddZej                         D  ci c]  \  }}||
 c}}} Zej                         D  ci c]  \  }}||
 c}}} Z	ej                         D  ci c]  \  }}||
 c}}} Z
ed        ZddZed        Zd Zyc c}}} w c c}}} w c c}}} w )r>   zClass to hold the matrix type.RCPI)r'   ru   patternr&   SUHZ)	symmetricr(   	hermitianskewsymmetricrectangularAE)r)   	elementalc                     t        |      dk(  st        d      	 | j                  |d      }| j                  |d      }| j                  |d      } | |||      S # t
        $ r}t        d|       |d }~ww xY w)Nr]   z:Fortran format for matrix type should be 3 characters longr   r   r_   zUnrecognized format )rb   r=   	_f2q_type_f2q_structure_f2q_storageKeyError)r@   r   rg   rh   ri   r   s         r   rf   zHBMatrixType.from_fortran  s    3x1} / 0 0	Bs1v.J**3q62I&&s1v.Gz9g66 	B3C59:A	Bs   ?A 	A8$A33A8c                     || _         || _        || _        || j                  vrt	        d|       || j
                  vrt	        d|       || j                  vrt	        d|       y )NzUnrecognized type zUnrecognized structure zUnrecognized storage )rg   rh   ri   	_q2f_typer=   _q2f_structure_q2f_storage)r   rg   rh   ri   s       r   r   zHBMatrixType.__init__  s}    $"T^^+1*>??D///6ykBCC$+++4WI>?? ,r   c                     | j                   | j                     | j                  | j                     z   | j                  | j
                     z   S N)r   rg   r   rh   r   ri   r   s    r   r?   zHBMatrixType.fortran_format  sE    ~~doo.""4>>23  ./ 	/r   c                 V    d| j                    d| j                   d| j                   dS )NzHBMatrixType(z, r^   )rg   rh   ri   r   s    r   __repr__zHBMatrixType.__repr__  s,    t/r$..1ADLL>QRSSr   N)r)   )r   r   r   __doc__r   r   r   itemsr   r   r   r   rf   r   propertyr?   r   ).0ijs   000r   r>   r>   g  s    ( 	I  N L
 #,//"344$!QA4I'5';';'=>>tq!ad>N%1%7%7%9::TQAqD:L
B 
B
@ / /
TG 5>:s   B%B,;B3r>   c                   p    e Zd Zd
dZed        Zed        Zed        Zed        Zed        Z	d Z
d	 Zy)HBFileNc                 Z    || _         |t        j                  |      | _        y|| _        y)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   rq   _hb_info)r   filehb_infos      r   r   zHBFile.__init__  s+     	?",,T2DM $DMr   c                 .    | j                   j                  S r   )r   rB   r   s    r   rB   zHBFile.title  s    }}"""r   c                 .    | j                   j                  S r   )r   rC   r   s    r   rC   z
HBFile.key  s    }}   r   c                 B    | j                   j                  j                  S r   )r   rD   rg   r   s    r   typezHBFile.type  s    }}##...r   c                 B    | j                   j                  j                  S r   )r   rD   rh   r   s    r   rh   zHBFile.structure  s    }}##---r   c                 B    | j                   j                  j                  S r   )r   rD   ri   r   s    r   ri   zHBFile.storage  s    }}##+++r   c                 B    t        | j                  | j                        S r   )r   r   r   r   s    r   read_matrixzHBFile.read_matrix  s    TYY66r   c                 D    t        || j                  | j                        S r   )r   r   r   )r   rA   s     r   write_matrixzHBFile.write_matrix  s    1dii77r   r   )r   r   r   r   r   rB   rC   r   rh   ri   r   r   r   r   r   r   r     su    $& # # ! ! / / . . , ,78r   r   )spmatrixc                8   d }t        | d      r	 ||       }nt        |       5 } ||      }ddd       |t        u rDd}t        j                  j                  t              f}t        j                  |t        |       d}|rt              S S # 1 sw Y   dxY w)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 matrix. Otherwise return sparse array.

        .. deprecated:: 1.18.0
            The default value for `spmatrix` is changing to False in v1.20.
            That means the default return value will be a sparse array.
            Unless you use * instead of @, ** for matrix power, or you depend
            on 2D shapes from e.g. ``A.sum(axis=0)``, it may not matter to you.
            See :ref:`Migration from spmatrix to sparray <migration_to_sparray>`.

    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                 8    t        |       }|j                         S r   )r   r   )rk   hbs     r   _get_matrixzhb_read.<locals>._get_matrix  s    C[~~r   r   Na  The default value for `spmatrix` is changing to `False` in v1.20.
            That means the default return type will be a sparse array.
            Unless you use * instead of @, ** for matrix power, or you depend
            on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
            See the spmatrix to sparray migration guide for details.
            https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
            )skip_file_prefixesT)hasattropenr   ospathdirname__file__rv   rw   DeprecationWarningr   )path_or_open_filer   r   r0   r   r   prefixess          r   r
   r
     s    `   &),-#$ 	"q>D	" 8 GGOOH-/c-(K$K#	" 	"s   	BBc                     j                  d      t        j                        fd}t        | d      r	 ||        yt	        | d      5 } ||       ddd       y# 1 sw Y   yxY w)ak  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

    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                 @    t        |       }|j                         y r   )r   r   )rk   r   r   rA   s     r   _set_matrixzhb_write.<locals>._set_matrixH  s    C!
r   r   w)r-   r   rS   r   r   )r   rA   r   r  r   s    ``  r   r   r     so    L 	
UA""1%  '*%&#S) 	QN	 	 	s   	A%%A.r   )r   r   rv   numpyr4   scipy._lib.deprecationr   scipy.sparser   r   _fortran_format_parserr   r   r	   __all__	Exceptionr   Warningr   r   r   rd   r   r   r>   r   r
   r   r   r   r   <module>r     s   
( 
   + . M Mj
!	i 		7 	7|! |!~-N(&:9T 9Tx,8 ,8^ ,4 HV3r   