11"""Main package API."""
2+
23import re
34from typing import Any
45from typing import Optional
@@ -12,40 +13,51 @@ def to_matrix(
1213 arr : NDArray [Any ],
1314 style : str = "b" ,
1415 num_format : Optional [str ] = None ,
16+ scientific_notation : bool = False ,
1517) -> str :
1618 """Convert a numpy.NDArray to LaTeX matrix.
1719
1820 Args:
1921 arr: the array to be converted
2022 style: a style formatter string, either "b" for "bmatrix" or "p" for "pmatrix"
2123 num_format: a number formatter string, e.g. ".2f"
24+ scientific_notation: a flag to determine whether 1 x 10^3 should be used,
25+ otherwise e-notation is used (1e3)
2226
2327 Returns:
2428 the string representation of the array
2529 """
26-
27- def num_formatter (x : Union [np .int64 , np .float64 , np .float32 ]) -> str :
28- return f"%{ num_format } " % x
29-
3030 environment = f"{ style } matrix"
3131
3232 formatter = {}
3333 if num_format :
34+
35+ def num_formatter (x : Union [np .int64 , np .float64 , np .float32 ]) -> str :
36+ return f"%{ num_format } " % x
37+
3438 formatter .update ({"float_kind" : num_formatter , "int_kind" : num_formatter })
3539
3640 lines = (
37- np .array2string (arr , max_line_width = np .inf , formatter = formatter ) # type: ignore # noqa
41+ np .array2string (
42+ arr ,
43+ max_line_width = np .inf , # type: ignore # noqa
44+ formatter = formatter , # type: ignore # noqa
45+ separator = " & " ,
46+ )
3847 .replace ("[" , "" )
3948 .replace ("]" , "" )
49+ .replace (" &\n " , "\n " )
4050 )
4151
4252 if num_format and "e" in num_format :
4353 pattern = r"e(-?\d+)"
4454 replace = r"\\mathrm{e}{\g<1>}"
55+ if scientific_notation :
56+ replace = r" \\times 10^{\g<1>}"
4557 lines = re .sub (pattern , replace , lines )
4658
4759 rv = [f"\\ begin{{{ environment } }}" ]
48- rv += [" " + " & " . join ( line .split () ) + r" \\" for line in lines .splitlines ()]
60+ rv += [line .strip ( ) + r" \\" for line in lines .splitlines ()]
4961 rv += [f"\\ end{{{ environment } }}" ]
5062
5163 return "\n " .join (rv )
0 commit comments