File size: 1,033 Bytes
288b0ef
 
 
 
 
ff0d3b3
 
 
288b0ef
 
 
 
 
 
 
 
ff0d3b3
 
 
 
 
 
a561f92
 
 
 
 
ff0d3b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
Compute the inverse of a matrix using NumPy.
"""
import numpy as np
from typing import List, Union
import gradio as gr

from maths.matrices.utils import parse_matrix, format_output

Matrix = Union[List[List[float]], np.ndarray]

def matrix_inverse(matrix: Matrix) -> np.ndarray:
    m = np.array(matrix)
    if m.shape[0] != m.shape[1]:
        raise ValueError("Matrix must be square to compute inverse.")
    return np.linalg.inv(m)

matrix_inverse_interface = gr.Interface(
    fn=lambda m_str: format_output(matrix_inverse(parse_matrix(m_str))),
    inputs=gr.Textbox(label="Matrix (must be square and invertible)", placeholder="e.g., [[1,2],[3,7]]"),
    outputs=gr.Textbox(label="Inverse Matrix"),
    title="Matrix Inverse",
    description="Calculates the inverse of a square, invertible matrix. Input can be JSON (e.g., [[1,2],[3,7]]) or CSV (e.g., 1,2;3,7). Example: Matrix: [[1,2],[3,7]] => Result: [[7,-2],[-3,1]] (actual output will be floats)",
    examples=[
        ["[[1,2],[3,7]]"],
        ["1,2;3,7"]
    ]
)