-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdatrix2.py
More file actions
5987 lines (5352 loc) · 372 KB
/
Copy pathpdatrix2.py
File metadata and controls
5987 lines (5352 loc) · 372 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Datrix 2
import os
def clc():
os.system('cls' if os.name == 'nt' else 'clear')
clc()
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from skimage.color import rgb2gray
from skimage.transform import radon, iradon, iradon_sart, resize
from skimage import img_as_float
from PIL import Image
import Funciones as fn
from math import ceil, sqrt, hypot
import io
import tempfile
import matplotlib.animation as animation
from matplotlib.animation import writers
from matplotlib.animation import PillowWriter
from skimage.data import shepp_logan_phantom
import pydicom
from numba import njit
from numba.typed import List
from numba import njit, int32, float64
from pydicom.pixel_data_handlers.util import apply_voi_lut
import cv2
import scipy.ndimage
from scipy.fft import fft2, ifft2, fftshift, ifftshift
#import tkinter as tk
#from tkinter import filedialog
from skimage.draw import line, polygon
import streamlit_image_coordinates as sc
from streamlit_drawable_canvas import st_canvas
from PIL import ImageDraw
import pandas as pd
from matplotlib.patches import Rectangle, Ellipse, Polygon
import base64
from io import BytesIO
from scipy.interpolate import UnivariateSpline
import plotly.graph_objects as go
icono = Image.open("logodatrix.jpg")
##---------
st.set_page_config(
page_title="Datrix",
page_icon=icono,
#layout="wide",
#initial_sidebar_state = "collapsed"
)
##---------
#st.title("🧮 DaTrix")
#titulo_personalizado("🧮 DaTrix", nivel=2, tamaño=56, color="black")
# Función para convertir imagen local a base64
def get_image_base64(path):
with open(path, "rb") as img_file:
return base64.b64encode(img_file.read()).decode()
#Ruta a tu imagen (ajustá el nombre del archivo)
img_base64 = get_image_base64("logodatrix.jpg")
# Título con logo centrado
st.markdown(
f"""
<div style='text-align: center;'>
<h1 style='display: inline-flex; align-items: center; gap: 10px; font-size: 56px;'>
<img src='data:image/jpeg;base64,{img_base64}' width='56'/>
DaTrix
</h1>
<p style='font-size: 20px;'>App hecha con amor</p>
</div>
""",
unsafe_allow_html=True
)
#Una app para operaciones con matrices, procesamiento de imágenes y simulaciones de reconstrucción tomográfica.
#st.write("Una app para operaciones con matrices, procesamiento de imágenes y simulaciones de reconstrucción tomográfica.")
# Menú principal
modulo = st.sidebar.radio("Seleccionar módulo", [
"Inicio",
"Álgebra y análisis numérico",
"Procesamiento de imágenes",
"Reconstrucción tomográfica",
"Sobre mí"
])
st.sidebar.markdown("---")
st.sidebar.markdown("[📂 Repositorio en GitHub](https://github.com/David-Basti/datrix)")
match modulo:
case "Inicio":
st.subheader("Bienvenido a DaTrix")
st.write("**DaTrix** es una app con tres módulos principales, que podés explorar desde el menú lateral:")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("#### 🔢 Álgebra y Análisis Numérico")
st.markdown(" --- ")
st.markdown("""
- Operaciones con matrices
- Resolución de sistemas
- Ajustes e interpolación
- Integración y ecuaciones
- Análisis de Fourier
""")
with col2:
st.markdown("#### 🖼️ Procesamiento de Imágenes")
st.markdown(" --- ")
st.markdown("""
- Visualización con ventaneo
- Edición y filtrado
- Calibración y escalas
- Histogramas y perfiles
- Regiones de interés (ROI)
""")
with col3:
st.markdown("#### 💻 Reconstrucción Tomográfica")
st.markdown(" --- ")
st.markdown("""
- Simulación de CT y SPECT
- Métodos: FBP, MLEM, OSEM, SART
- Parámetros personalizables
- Comparación ROI real/reconstruida
- Gráficos iterativos
""")
st.write("👈 Usá el menú lateral para comenzar.")
case "Álgebra y análisis numérico":
#with st.expander("Módulo 1",expanded=True):
st.title("🔢 Módulo 1: Álgebra y análisis numérico")
tabs = st.tabs(["Operaciones con matrices", "Sistemas y curvas"])
#titulo_personalizado("🔢 Módulo 1: Operaciones con matriz única", nivel=2, tamaño=56, color="black")
with tabs[0]:
cool, _ =st.columns([1,5])
#titulo_personalizado("📥 Matriz A", nivel=2, tamaño=42, color="black",centrado=False)
with cool:
if st.button("🔄 Reiniciar"):
st.session_state['expresion'] = None
st.session_state['exp2'] = None
st.session_state["B"] = None
st.session_state["resulvect"] = None
st.session_state["resultadoa"] = None
st.session_state["resultado"] = None
vale3 = 1
resultado = None
resultadoa = None
resulvect = None
resultado2 = None
ra = None
rv = None
operacion = None
oper = None
st.session_state["operacion"] = None
st.session_state["resultado2"] = None
st.session_state["mantenerpegado"] = None
st.session_state["mantenerpegado2"] = None
st.session_state["mantenerpegado3"] = None
st.session_state["copiado"] = None
texto_A = "1, 2, 3\n4, 5, 6\n7, 8, 9"
texto_A1 = "1, 2, 3\n4, 5, 6\n7, 8, 9"
texto_B = "1, 4, 7\n2, 5, 8\n3, 6, 9"
if "copiado" not in st.session_state:
st.session_state["copiado"] = None
if "mantenerpegado" not in st.session_state:
st.session_state["mantenerpegado"] = None
if "mantenerpegado2" not in st.session_state:
st.session_state["mantenerpegado2"] = None
if "mantenerpegado3" not in st.session_state:
st.session_state["mantenerpegado3"] = None
col1, col2 =st.columns(2)
with col2:
if st.button("Pegar", key="pegado") and st.session_state["copiado"] is not None:
st.session_state["mantenerpegado"] = st.session_state["copiado"]
if st.session_state["mantenerpegado"] is not None:
texto_A = st.session_state["mantenerpegado"]
else:
texto_A = "1, 2, 3\n4, 5, 6\n7, 8, 9"
st.header("📥 Matriz M")
A = None
texto_A = st.text_area("Ingresá la matriz M (por filas, separados por coma)", texto_A)#"1 2 3\n4 5 6\n7 8 9")
try:
filas = texto_A.strip().split("\n")
A = []
for fila in filas:
elementos = fila.strip().split(",")
fila_simb = [sp.sympify(elem.strip()) for elem in elementos]
A.append(fila_simb)
A = sp.simplify(sp.Matrix(A))
st.latex(sp.latex(A))
except:
st.error(f"❌ Error al interpretar la matriz M")
st.stop()
if "B" not in st.session_state:
st.session_state["B"] = texto_A
if st.session_state["B"] != texto_A:
st.session_state["expresion"] = A
st.session_state["ex2"] = "M"
st.session_state["B"] = texto_A
if "ex2" not in st.session_state:
st.session_state["ex2"] = "M"
if 'expresion' not in st.session_state:
st.session_state['expresion'] = A # Empieza con la matriz A
with col1:
c1,c2,c3 = st.columns(3)
with c1:
st.write("🔢 Elevar por un escalar")
expr3 = st.text_input("Escalar (a)", value="1")
try:
escalar_3 = sp.sympify(expr3)
except (sp.SympifyError, TypeError):
st.error("⚠️ No se pudo interpretar el escalar simbólicamente.")
escalar_3 = 1
escalar_3 = sp.sympify(escalar_3)
try:
escalar_3f = float(escalar_3)
except (ValueError, TypeError):
st.error("❌ El escalar (a) debe ser un número.")
escalar_3f = 1
if not escalar_3.is_number:
st.error("❌ El escalar (a) debe ser un número real.")
escalar_3 = 1
if st.button("Elevar"):
if escalar_3f == 1:
st.session_state['expresion'] = f"({st.session_state['expresion']})"
#st.session_state['ex2'] = f"({st.session_state['ex2']})"
elif A.shape[0] != A.shape[1]:
st.error("❌ La matriz debe ser cuadrada para poder elevarse a una potencia.")
escalar_3 = 1
elif escalar_3f < 0 and (sp.sympify(sp.simplify(str(st.session_state['expresion'])))).det() == 0:
#d = A.det()
#if d != 0:
st.error("❌ Para exponentes negativos el det(A) debe ser distinto de cero")
escalar_3 = 1
else:
st.session_state['expresion'] = f"({st.session_state['expresion']})**{(escalar_3)}"
#st.session_state["ex2"] = f"({st.session_state["ex2"]})^({escalar_3})"
#else:
#st.session_state['expresion'] = f"({st.session_state['expresion']})**{escalar_3}"
#st.session_state['ex2'] = f"({st.session_state['ex2']})**{escalar_3}"
with c2:
st.write("🔢 Producto por un escalar")
expr1 = st.text_input("Escalar (b)", value="1")
try:
escalar_1 = sp.sympify(expr1)
#st.write("Escalar (b) interpretado como:", escalar_1)
except (sp.SympifyError, TypeError):
st.error("⚠️ No se pudo interpretar el escalar simbólicamente.")
escalar_1 = 1
if st.button("Multiplicar"):
if escalar_1 != 1:
st.session_state['expresion'] = f"({st.session_state['expresion']}) * {escalar_1}"
#st.session_state['ex2'] = f"({st.session_state['ex2']}) * {escalar_1}"
with c3:
st.write("🔢 Sumar un escalar")
expr2=st.text_input("Escalar (c)", value="0")
try:
escalar_2 = sp.sympify(expr2)
#st.write("Escalar (c) interpretado como:", escalar_2)
except (sp.SympifyError, TypeError):
st.error("⚠️ No se pudo interpretar el escalar simbólicamente.")
escalar_2 = 0
if st.button("Sumar"):
if escalar_2 != 0:
st.session_state['expresion'] = f"({st.session_state['expresion']}) + {sp.srepr(escalar_2 * sp.ones(*A.shape))}"
#st.session_state['ex2'] = f"({st.session_state['ex2']}) + {escalar_2}"
#with st.expander("Mostrar escalares"):
# with c1:
# st.write("(a) se interpretó como:", escalar_3)
# with c2:
# st.write("(b) se interpretó como:", escalar_1)
# with c3:
# st.write("(c) se interpretó como:",escalar_2)
R = None
try:
# Evaluar la expresión acumulada
R = sp.simplify(sp.sympify(st.session_state['expresion'])).subs(A, A) # Asumiendo que A es tu matriz original
#st.write("Resultado de la operación acumulada:")
with st.container():
cl1, cl2 = st.columns(2)
with cl2:
#with st.expander("Matriz luego de operaciones escalares:"):
st.latex("Matriz\,post\,operaciones\,escalares")
st.latex(sp.latex(R))
#with cl1:
#st.latex(sp.latex("Expresión acumulada"))
#st.write("Expresión acumulada:")
#st.latex(sp.latex(sp.sympify(st.session_state['ex2'])))
#with st.expander(""):
# st.write("La matriz M puede aparecer como denominador si el exponente es negativo." \
# " Eso es incorrecto. Lo correcto es M^(-n).")
except Exception as e:
st.error(f"Hubo un error al calcular: {str(e)}")
if R is not None:
A = R
columna1, columna2 = st.columns(2)
with columna1:
st.header("⚙️ Operación")
operacion = st.radio("Elegí una operación", ["Ninguna", "Rango", "Transpuesta", "Determinante", "Inversa",
"Autovalores y autovectores"])
resultado = None
resulvect = None
resultadoa = None
ra = None
rv = None
if st.button("Calcular",key="Calcular"):
if A is not None:
match operacion:
case "Ninguna":
st.session_state["resulvect"] = None
resultado = A
st.session_state["resultado"] = resultado
case "Transpuesta":
st.session_state["resulvect"] = None
resultado = A.T
st.session_state["resultado"] = resultado # lo guardamos
case "Rango":
st.session_state["resulvect"] = None
resultado = A.rank()
st.session_state["resultado"] = sp.sympify(resultado)
case "Determinante":
st.session_state["resulvect"] = None
if A.shape[0] == A.shape[1]:
resultado = A.det()
st.session_state["resultado"] = resultado
else:
resultado = ("⚠️ La matriz debe ser cuadrada")
st.session_state["resultado"] = resultado
case "Inversa":
st.session_state["resulvect"] = None
if A.shape[0] == A.shape[1]:
determinante = A.det()
#dets = As.det()
if determinante == 0:
resultado = ("La matriz no es inversible")
st.session_state["resultado"] = resultado
else:
resultado = A.inv()
st.session_state["resultado"] = resultado
#rs = As.inv()
else:
resultado = ("⚠️ La matriz debe ser cuadrada")
st.session_state["resultado"] = resultado
case "Autovalores y autovectores":
if A.shape[0] == A.shape[1]:
resultado = None
st.session_state["resultado"] = resultado
ra = A.eigenvals()
rv = A.eigenvects()
resultadoa = {val.evalf(): mult for val, mult in ra.items()}
st.session_state["resultadoa"] = resultadoa
st.session_state["resulvect"] = rv
else:
resultado = ("⚠️ La matriz debe ser cuadrada")
st.session_state["resultado"] = resultado
else:
st.error("⚠️ Debe cargar una matriz")
with columna2:
if st.session_state.get("resultado") is not None and st.session_state.get("resulvect") is None:
if isinstance(st.session_state["resultado"], str):
st.error(st.session_state["resultado"])
else:
resultado = sp.simplify(st.session_state["resultado"])
with st.expander("Resultado", expanded=True):
usar_d = st.checkbox("Mostrar resultado con decimales",key="mostrar1")
if usar_d:
st.latex(sp.latex(resultado.evalf()))
else:
st.latex(sp.latex(resultado))
if st.button("Copiar",key="Copiar1"):
if isinstance(resultado, sp.Matrix):
st.session_state["copiado"] = "\n".join(",".join(str(val) for val in fila) for fila in resultado.tolist())
elif isinstance(resultado,int):
st.session_state["copiado"] = str(resultado)
else:
st.session_state["copiado"] = "\n".join(",".join(str(val) for val in fila) for fila in resultado.tolist())
if st.session_state.get("resulvect") is not None and st.session_state.get("resultadoa") is not None:
if isinstance(st.session_state["resultado"], str):
st.error(st.session_state["resultado"])
else:
resultadoa = sp.simplify(st.session_state["resultadoa"])
rv = st.session_state["resulvect"]
with st.expander("Autovalores y autovectores", expanded=True):
usar1 = st.checkbox("Mostrar decimales, autovalores", key="Autovalores_dec")
usar2 = st.checkbox("Mostrar decimales, autovectores", key="Autovectores_dec")
k = 1
for val, mult, vectores in rv:
val_str = sp.latex(val.evalf()) if usar1 else sp.latex(sp.nsimplify(val))
st.latex(f"\\lambda_{k} = {val_str},\\ \\text{{multiplicidad}} = {mult}")
vectores_proc = [v.evalf() if usar2 else v for v in vectores]
for i, v in enumerate(vectores_proc, start=1):
st.latex(f"\\vec{{v}}_{{{k}}} = {sp.latex(v)}")
k += 1
#for val, mult in resultadoa.items():
# val_str = sp.latex(val) if usar1 else sp.latex(sp.nsimplify(val))
# st.latex(f"\\lambda_{k} = {val_str},\\ \\text{{multiplicidad}} = {mult}")
# k += 1
#with st.expander("Autovectores", expanded=True):
#usar2 = st.checkbox("Mostrar decimales", key="Autovectores_dec")
#k = 1
#for val, mult, vectores in rv:
# vectores_proc = [v.evalf() if usar2 else v for v in vectores]
# for v in vectores_proc:
# st.latex(f"\\vec{{v}}_{k} = {sp.latex(v)}")
# k += 1
col1, col2 = st.columns(2)
with col1:
st.header("📥 Matriz A")
A1 = None
if st.button("Pegar", key="pegado2") and st.session_state["copiado"] is not None:
st.session_state["mantenerpegado2"] = st.session_state["copiado"]
if st.session_state["mantenerpegado2"] is not None:
texto_A1 = st.session_state["mantenerpegado2"]
else:
texto_A1 = "1, 2, 3\n4, 5, 6\n7, 8, 9"
texto_A1 = st.text_area("Ingresá la matriz A (por filas, separados por coma)", texto_A1)
try:
filas = texto_A1.strip().split("\n")
A1 = []
for fila in filas:
elementos = fila.strip().split(",")
fila_simb = [sp.sympify(elem.strip()) for elem in elementos]
A1.append(fila_simb)
A1 = sp.simplify(sp.Matrix(A1))
st.latex(sp.latex(A1))
except:
st.error(f"❌ Error al interpretar la matriz A")
st.stop()
# ------------------------------
# Entrada para la matriz B
# ------------------------------
with col2:
st.header("📥 Matriz B")
B = None
if st.button("Pegar", key="pegado3") and st.session_state["copiado"] is not None:
st.session_state["mantenerpegado3"] = st.session_state["copiado"]
if st.session_state["mantenerpegado3"] is not None:
texto_B = st.session_state["mantenerpegado3"]
else:
texto_B = "1, 4, 7\n2, 5, 8\n3, 6, 9"
texto_B = st.text_area("Ingresá la matriz B (por filas, separados por coma)", texto_B)
try:
filas = texto_B.strip().split("\n")
B = []
for fila in filas:
elementos = fila.strip().split(",")
fila_simb = [sp.sympify(elem.strip()) for elem in elementos]
B.append(fila_simb)
B = sp.simplify(sp.Matrix(B))
st.latex(sp.latex(B))
except:
st.error(f"❌ Error al interpretar la matriz B")
st.stop()
# ------------------------------
# Selección de operación
# ------------------------------
resultado2 = None
if "resultado2" not in st.session_state:
st.session_state["resultado2"]=None
if "operacion" not in st.session_state:
st.session_state["operacion"] = None
st.header("⚙️ Operación")
kolum1, kolum2, kolum3 = st.columns(3)
with kolum1:
#SS=st.radio("",["Suma", "Sustracción"],["Q"],["W"])
if st.button("A+B",key="A+B"):
#if st.session_state["A+B"]:
st.session_state["operacion"] = "Suma"
if st.button("A-B",key="A-B"):
#if st.session_state["A-B"]:
st.session_state["operacion"] = "Sustracción"
with kolum2:
#BB=st.radio("",["Producto bin a bin", "Cociente bin a bin"])
if st.button("A.*B",key="A.*B"):
#if st.session_state["A.*B"]:
st.session_state["operacion"] = "Producto bin a bin"
if st.button("A./B",key="A./B"):
#if st.session_state["A./B"]:
st.session_state["operacion"] = "Cociente bin a bin"
with kolum3:
#CC=st.radio("",["Producto matricial", "Conmutador"])
if st.button("AB",key="AB"):
#if st.session_state["AB"]:
st.session_state["operacion"] = "Producto matricial"
if st.button("AB-BA",key="AB-BA"):
#if st.session_state["AB-BA"]:
st.session_state["operacion"] = "Conmutador"
#operacion = st.sidebar.radio("Elegí una operación", ["Suma", "Sustracción", "Producto matricial",
#"Producto bin a bin", "Cociente bin a bin"])
if st.session_state["operacion"] is not None:
st.write(f"🔧 Operación seleccionada: **{st.session_state['operacion']}**")
if st.button("Calcular"):
oper = st.session_state["operacion"]
if oper is None:
st.warning("⚠️ Primero seleccioná una operación.")
else:
match oper:
case "Suma":
if A1.shape != B.shape:
st.error("❌ la dim(A) y dim(B) deben ser iguales")
resultado2 = None
else:
resultado2 = A1 + B
case "Sustracción":
if A1.shape != B.shape:
st.error("❌ la dim(A) y dim(B) deben ser iguales")
resultado2 = None
else:
resultado2 = A1 - B
case "Producto bin a bin":
if A1.shape != B.shape:
st.error("❌ la dim(A) y dim(B) deben ser iguales")
resultado2 = None
else:
resultado2 = fn.mult_elementwise(A1, B)
case "Cociente bin a bin":
if A1.shape != B.shape:
st.error("❌ la dim(A) y dim(B) deben ser iguales")
resultado2 = None
else:
hay_cero = any([b == 0 for b in B])
if hay_cero:
st.error("❌ No se puede dividir bin a bin porque hay al menos un cero en la matriz B.")
resultado2 = None
else:
resultado2 = fn.divide_elementwise(A1, B)
case "Producto matricial":
if A1.shape[1] != B.shape[0]:
st.error("El número de columnas de A debe ser igual al número de filas de B")
resultado2 = None
else:
resultado2 = fn.prox(A1, B)
case "Conmutador":
if A1.shape[1] == B.shape[0] and B.shape[1] == A1.shape[0]:
resultado2 = fn.prox(A1, B) - fn.prox(B, A1)
else:
st.error("Dimensiones incompatibles")
resultado2 = None
case _:
resultado2 = None
st.session_state["resultado2"] = resultado2
#st.session_state["calcular_flag"] = False # Reseteamos el flag
#st.button("Calcular",key="Calc2")
#st.session_state["resultado2"]=resultado2
if st.session_state.get("resultado2") is not None:
st.write("Resultado")
usar_dab = st.checkbox("Mostrar resultado con decimales",key="mostrar2")
if usar_dab:
st.latex(sp.latex(st.session_state["resultado2"].evalf()))
else:
st.latex(sp.latex(sp.simplify(st.session_state["resultado2"])))
if st.button("Copiar",key="Copiar2"):
if isinstance(st.session_state["resultado2"],sp.Integer):
st.session_state["copiado"] = str(st.session_state["resultado2"])
elif isinstance(st.session_state["resultado2"], sp.Matrix):
st.session_state["copiado"] = "\n".join(",".join(str(val) for val in fila) for fila in st.session_state["resultado2"].tolist())
#elif isinstance(resultado2,sp.Integer):
# st.session_state["copiado"] = str(st.session_state["resultado2"])
#else:
# st.session_state["copiado"] = "\n".join(" ".join(str(val) for val in fila) for fila in st.session_state["resultado2"].tolist())
st.title("🧮 Resolución de sistemas de ecuaciones lineales")
st.markdown("Resolvé sistemas lineales de la forma **C·x = b** con coeficientes numéricos o simbólicos.")
archivo = st.file_uploader("Subí un archivo con la matriz C y el vector b", type=["csv", "xlsx"])
C = None
b = None
if archivo is not None:
try:
if archivo.name.endswith(".csv"):
df = pd.read_csv(archivo, header=None)
else:
df = pd.read_excel(archivo, header=None)
if df.shape[1] < 2:
st.error("El archivo debe tener al menos dos columnas (C y b).")
else:
try:
df_sym = df.applymap(lambda x: sp.sympify(str(x)))
C = sp.Matrix(df_sym.iloc[:, :-1].values.tolist())
b = sp.Matrix(df_sym.iloc[:, -1].values.tolist())
except Exception as e:
st.error(f"Error al interpretar simbólicamente los datos: {e}")
except Exception as e:
st.error(f"Error al leer el archivo: {e}")
else:
st.subheader("Carga manual")
gol1,gol2=st.columns([0.7,0.3])
with gol1:
C_txt = st.text_area("Matriz C (fila por fila, separado por coma)", "2, 1\n1, 3")
with gol2:
b_txt = st.text_area("Vector b (una entrada por fila)", "8\n13")
try:
C_list = [list(map(sp.sympify, fila.split(','))) for fila in C_txt.strip().split('\n')]
b_list = list(map(sp.sympify, b_txt.strip().split('\n')))
C = sp.Matrix(C_list)
b = sp.Matrix(b_list)
except Exception as e:
st.error(f"Error al procesar los datos simbólicamente: {e}")
if C is not None and b is not None and C.rows == b.rows:
try:
if C.rows == C.cols:
x = C.LUsolve(b)
x = sp.Matrix([sp.simplify(xi) for xi in x])
st.success("✅ Sistema cuadrado: solución exacta encontrada.")
else:
st.warning("⚠️ Sistema no cuadrado. Se usará método de mínimos cuadrados.")
Ct = C.T
normal_matrix = Ct * C
normal_rhs = Ct * b
try:
x = normal_matrix.inv() * normal_rhs
#x = (C.T * C).inv() * (C.T * b)
x = sp.Matrix([sp.simplify(xi) for xi in x])
st.success("✅ Solución por mínimos cuadrados:")
except:
x = None
st.error("❌ No se pudo invertir la matriz normal. El sistema no tiene solución por mínimos cuadrados.")
if x is not None:
usar_decimales_sistemas = st.checkbox("Mostrar decimales", key="mostrardecsistemas")
# Mostrar la solución en LaTeX
if usar_decimales_sistemas:
solucion_latex = r"x = \begin{bmatrix}" + r"\\".join([sp.latex(xi.evalf()) for xi in x]) + r"\end{bmatrix}"
else:
solucion_latex = r"x = \begin{bmatrix}" + r"\\".join([sp.latex(xi) for xi in x]) + r"\end{bmatrix}"
st.latex(solucion_latex)
# Botón para copiar la matriz solución x
if st.button("Copiar solución x", key="copiar_x"):
if isinstance(x, sp.Matrix):
# Convertir a texto: filas separadas por \n, elementos separados por coma
st.session_state["copiado"] = "\n".join(
",".join(str(val) for val in fila) for fila in x.tolist()
)
#st.success("Solución x copiada al portapapeles (session_state)")
elif isinstance(x, (int, float)):
st.session_state["copiado"] = str(x)
#st.success("Solución x copiada al portapapeles (session_state)")
else:
# Por si x es algún otro tipo de objeto iterable
st.session_state["copiado"] = "\n".join(
",".join(str(val) for val in fila) for fila in x.tolist()
)
#st.success("Solución x copiada al portapapeles (session_state)")
mostrar_decimales_residuo = st.checkbox("Mostrar decimales", key="mostrardecresi")
# Mostrar el residuo simbólico y su norma
residuo = C * x - b
residuo = sp.Matrix([sp.simplify(ri) for ri in residuo])
error = sp.sqrt(sum([ri**2 for ri in residuo]))
if mostrar_decimales_residuo:
# Residuo como vector columna con decimales
residuo_latex = r"\begin{bmatrix}" + r"\\".join([sp.latex(ri.evalf()) for ri in residuo]) + r"\end{bmatrix}"
# Error como número con decimales
error_latex = sp.latex(error.evalf())
else:
residuo_latex = r"\begin{bmatrix}" + r"\\".join([sp.latex(ri) for ri in residuo]) + r"\end{bmatrix}"
error_latex = sp.latex(error)
# Mostrar en pantalla
st.latex(rf"\text{{Residuo: }} \; {residuo_latex}")
st.latex(rf"\text{{Error del residuo: }} \; \|C \cdot x - b\| = {error_latex}")
#st.latex(rf"\text{{Error del residuo: }} \|C \cdot x - b\| = {sp.latex(error)}")
except Exception as e:
st.error(f"No se pudo resolver el sistema simbólicamente: {e}")
else:
st.warning("Verificá que C y b estén bien definidos y tengan la misma cantidad de filas.")
with tabs[1]:
U = None
f = None
opcion = st.radio("Elegí una operación", ["Ajuste polinómico", "Interpolación Spline", "Ajuste exponencial"],horizontal=True,key="opcionsec1")
# --- Lógica para cada opción ---
if opcion == "Ajuste polinómico":
st.title("📐 Ajuste y resolución de sistemas lineales")
U, V, W = fn.cargar_datos_uv_w()
if U is not None and V is not None:
U = np.array(U)
V = np.array(V)
#st.write(U,V)
if len(U) == 0 or len(V) == 0:
st.error("Error: las listas de datos U y V no pueden estar vacías.")
st.stop()
st.subheader("Cortar la función")
xinicial = st.number_input(
"Extremo inferior",
value=float(0), # valor por defecto
min_value=float(0), # valor mínimo que se puede elegir
max_value=float(len(U)), # valor máximo que se puede elegir
step=len(U) / 100,
format="%.4f")
xfinal = st.number_input("Extremo superior",
value=float(len(U)), # valor por defecto
min_value=float(0), # valor mínimo que se puede elegir
max_value=float(len(U)), # valor máximo que se puede elegir
step=(len(U)) / 100,
format="%.4f")
if xinicial<=xfinal:
U = U[int(xinicial):int(xfinal)]
V = V[int(xinicial):int(xfinal)]
if W is not None:
W = W[int(xinicial):int(xfinal)]
if len(U) == len(V):
usar_W = W is not None and len(W) == len(U)
st.subheader("Personalización del gráfico")
col1, col2 = st.columns([0.3,0.7])
with col1:
if 1<=len(U)-1:
grado = st.number_input("Grado del polinomio", min_value=1, max_value=len(U)-1, value=1,step=1)
else:
st.error("El grado 1 es mayor al grado máximo 0")
st.stop()
st.write(f"Grado sugerido {len(U)-1}")
titulo = st.text_input("Título del gráfico", value="V vs U")
xlabel = st.text_input("Etiqueta del eje X", value="U, []")
ylabel = st.text_input("Etiqueta del eje Y", value="V, []")
resultados = fn.RLE_polyfit(U=U, V=V, grado=grado, W=W if usar_W else None,
plot=True, titulo=titulo, xlabel=xlabel, ylabel=ylabel, use_weights=True, show_errorbars=True)
with col2:
st.pyplot(resultados['fig'])
st.markdown("### 📊 Resultados")
if grado == 1:
a = resultados['a']
b = resultados['b']
sign_b = '+' if b >= 0 else '-'
b_abs = abs(b)
with st.expander("Ver resultados"):
st.latex(rf"""
\begin{{aligned}}
y &= {a:.5f}x {sign_b} {b_abs:.5f} \\
a &= {a:.5f} \quad & b &= {b:.5f} \\
R^2 &= {resultados['R']:.5f} \quad & D &= {resultados['D']:.5f} \\
\Delta a &= {resultados['𝛥a']:.5f} \quad & \Delta b &= {resultados['𝛥b']:.5f}
\end{{aligned}}
""")
else:
ecuacion = fn.formatear_ecuacion(resultados['coef'])
with st.expander("Ver resultados"):
st.latex(ecuacion)
coef_str = r" \\ ".join([
fn.formato_coeficiente(resultados['coef'][i], resultados['delta_coef'][i], i, grado)
for i in range(len(resultados['coef']))
])
st.latex(r"\begin{aligned}" + coef_str + r"\end{aligned}")
st.latex(rf"R^2 = {resultados['R2']:.5f}")
st.latex(rf"D = {resultados['D']:.5f}")
else:
st.warning("Los vectores U y V deben tener la misma longitud.")
else: st.warning("El extremo superior debe ser mayor al inferior")
else:
st.warning("No hay datos válidos para procesar.")
elif opcion == "Interpolación Spline":
st.title("🔗 Interpolación Spline")
U, V, W = fn.cargar_datos_uv_w()
if U is not None and V is not None and len(U) == len(V):
st.subheader("Cortar la función")
xinicial = st.number_input(
"Extremo inferior en (x)",
value=float(0), # valor por defecto
min_value=float(0), # valor mínimo que se puede elegir
max_value=float(len(U)), # valor máximo que se puede elegir
step=len(U) / 100,
format="%.4f")
xfinal = st.number_input("Extremo en (x) superior",
value=float(len(U)), # valor por defecto
min_value=float(0), # valor mínimo que se puede elegir
max_value=float(len(U)), # valor máximo que se puede elegir
step=(len(U)) / 100,
format="%.4f")
if xinicial<=xfinal:
U = U[int(xinicial):int(xfinal)]
V = V[int(xinicial):int(xfinal)]
if W is not None:
W = W[int(xinicial):int(xfinal)]
if xinicial == xfinal:
st.stop()
st.subheader("Configuración del gráfico")
col1, col2 = st.columns([0.3, 0.7])
with col1:
titulo = st.text_input("Título del gráfico", value="Spline de V vs U")
xlabel = st.text_input("Etiqueta del eje X", value="U, []")
ylabel = st.text_input("Etiqueta del eje Y", value="V, []")
suavizado = st.slider("Nivel de suavizado (s)", min_value=0.0, max_value=10.0, value=0.0, step=0.1)
orden = np.argsort(U)
U_ord = U[orden]
V_ord = V[orden]
if W is not None and len(W)==len(U):
W_ord = W[orden]
else:
W_ord = None
if len(np.unique(U_ord)) != len(U_ord):
st.warning("Hay valores repetidos en U.")
else:
spline = UnivariateSpline(U_ord, V_ord, w=(1/W_ord if W_ord is not None and len(W)==len(U) else None), s=suavizado)
U_interp = np.linspace(U_ord.min(), U_ord.max(), 1000)
V_interp = spline(U_interp)
ylimit2 = st.number_input(
"Extremo inferior en (y) visible",
value=float(min(V_interp)), # valor por defecto
min_value=float(min(V_interp)-(np.max(W)+10.0 if W is not None else 10.0)), # valor mínimo que se puede elegir
max_value=float(max(V_interp)+(np.max(W)+10.0 if W is not None else 10.0)), # valor máximo que se puede elegir
step=0.01,
format="%.4f",key="yspline1")
ylimit1 = st.number_input(
"Extremo superior en (y) visible",
value=float(max(V_interp)), # valor por defecto
min_value=float(min(V_interp)-(np.max(W)+10.0 if W is not None else 10.0)), # valor mínimo que se puede elegir
max_value=float(max(V_interp)+(np.max(W)+10.0 if W is not None else 10.0)), # valor máximo que se puede elegir
step=0.01,
format="%.4f",key="yspline2")
with col2:
fig, ax = plt.subplots()
ax.plot(U, V, 'ro', label='Datos')
ax.plot(U_interp, V_interp, label='Spline', color='blue')
if W is not None and len(W)==len(U):
ax.errorbar(U, V, yerr=W, fmt='none', ecolor='black', capsize=3, label="Errores")
ax.set_title(titulo)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.ylim([ylimit2,ylimit1])
#ax.legend()
st.pyplot(fig)
else: st.warning("El extremo superior debe ser mayor al inferior")
else:
st.warning("No hay datos válidos para realizar la interpolación.")
st.stop()
elif opcion == "Ajuste exponencial":
st.title("📈 Ajuste Exponencial")
U, V, W = fn.cargar_datos_uv_w()
if U is not None and V is not None:
U = np.array(U)
V = np.array(V)
if len(U) == 0 or len(V) == 0:
st.error("Error: las listas de datos U y V no pueden estar vacías.")
st.stop()
st.subheader("Cortar la función")
xinicial = st.number_input(
"Extremo inferior",
value=float(0),
min_value=float(0),
max_value=float(len(U)),
step=len(U) / 100,
format="%.4f",
key="xexp1")
xfinal = st.number_input(
"Extremo superior",
value=float(len(U)),
min_value=float(0),
max_value=float(len(U)),
step=len(U) / 100,
format="%.4f",
key="xexp2")
if xinicial <= xfinal:
U = U[int(xinicial):int(xfinal)]
V = V[int(xinicial):int(xfinal)]
if W is not None:
W = W[int(xinicial):int(xfinal)]
if len(U) == len(V):
usar_W = W is not None and len(W) == len(U)
st.subheader("Personalización del gráfico")
col1, col2 = st.columns([0.3, 0.7])
with col1:
titulo = st.text_input("Título del gráfico", value="Ajuste Exponencial de V vs U")
xlabel = st.text_input("Etiqueta del eje X", value="U, []")
ylabel = st.text_input("Etiqueta del eje Y", value="V, []")
resultados = fn.RLE_exponential_fit(
U=U, V=V, W=W if usar_W else None,
plot=True, titulo=titulo, xlabel=xlabel, ylabel=ylabel,
use_weights=True, show_errorbars=True
)
with col2:
if resultados and 'fig' in resultados and resultados['fig'] is not None:
st.pyplot(resultados['fig'])
else:
st.warning("No se pudo generar el gráfico. Verifica que los datos no estén vacíos.")
st.stop()
st.markdown("### 📊 Resultados del ajuste exponencial")
a = resultados['a']
b = resultados['b']
delta_a = resultados['𝛥a']
delta_b = resultados['𝛥b']
R2 = resultados['R2']
D = resultados['D']
c = resultados['c']
delta_c = resultados['𝛥c']
sign_b = '+' if b >= 0 else '-'
b_abs = abs(b)
with st.expander("Ver resultados"):
st.latex(rf"""
\begin{{aligned}}
y &= {a:.5f} \cdot e^{{{b:.5f}x}} + {c:.5f} \\
a &= {a:.5f} \quad & \Delta a &= {delta_a:.5f} \\
b &= {b:.5f} \quad & \Delta b &= {delta_b:.5f} \\
c &= {c:.5f} \quad & \Delta c &= {delta_c:.5f} \\
R^2 &= {R2:.5f} \quad & D &= {D:.5f}
\end{{aligned}}
""")
else:
st.warning("Los vectores U y V deben tener la misma longitud.")
else:
st.warning("El extremo superior debe ser mayor al inferior.")
else:
st.warning("No hay datos válidos para procesar.")
if U is not None:
st.subheader("Análisis de curva")
if "CurvaFiltrada" not in st.session_state:
st.session_state["CurvaFiltrada"] = None
usar_curva_filtrada = st.checkbox("Usar curva filtrada", value=False)
# Para el ajuste polinómico:
if opcion == "Ajuste polinómico":
if U is not None and len(U) == len(V):
if xinicial<=xfinal:
volu1, volu2 = st.columns([0.3,0.7])
resultadospoli = fn.RLE_polyfit2(volu1=volu1,volu2=volu2,U=U, V=V, grado=grado, W=W if usar_W else None,
plot=True, titulo=titulo, xlabel=xlabel, ylabel=ylabel, use_weights=True, show_errorbars=True)
umin, umax = np.min(U), np.max(U)
escalar = lambda x: 2 * (x - umin) / (umax - umin) - 1
f = lambda x: np.polyval(resultadospoli['coef'], escalar(x))
#st.subheader("📍 Líneas de referencia")
# Slider para dos líneas verticales (x)
# 2. Evaluar f(x) en todo el rango posible de x (o en el dominio total de datos)
x_full = resultadospoli["U_plot"]#np.linspace(np.min(U), np.max(U), 1000)
if usar_curva_filtrada and st.session_state["CurvaFiltrada"] is not None:
y_full = st.session_state["CurvaFiltrada"]