sarapy 2.3.0__py3-none-any.whl → 3.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sarapy/analysis/FeaturesResume.py +151 -47
- sarapy/dataProcessing/OpsProcessor.py +47 -32
- sarapy/dataProcessing/TLMSensorDataProcessor.py +5 -2
- sarapy/mlProcessors/FertilizerTransformer.py +139 -9
- sarapy/mlProcessors/PlantinClassifier.py +65 -23
- sarapy/mlProcessors/PlantinFMCreator.py +25 -12
- sarapy/preprocessing/TransformInputData.py +3 -2
- sarapy/version.py +1 -1
- {sarapy-2.3.0.dist-info → sarapy-3.1.0.dist-info}/METADATA +64 -12
- {sarapy-2.3.0.dist-info → sarapy-3.1.0.dist-info}/RECORD +16 -13
- {sarapy-2.3.0.dist-info → sarapy-3.1.0.dist-info}/WHEEL +1 -1
- sarapy-3.1.0.dist-info/top_level.txt +5 -0
- test/checking_regresor.py +162 -0
- test/probabilidades_test.py +77 -0
- test/test_import.py +5 -0
- sarapy-2.3.0.dist-info/top_level.txt +0 -1
- {sarapy-2.3.0.dist-info → sarapy-3.1.0.dist-info/licenses}/LICENCE +0 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import pickle
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
from sklearn.preprocessing import PolynomialFeatures
|
|
6
|
+
from sklearn.linear_model import LinearRegression
|
|
7
|
+
from sklearn.preprocessing import StandardScaler
|
|
8
|
+
|
|
9
|
+
regresor = "modelos//regresor.pkl"
|
|
10
|
+
poly_features = "modelos//poly_features.pkl"
|
|
11
|
+
|
|
12
|
+
with open(regresor, "rb") as file:
|
|
13
|
+
loaded_regresor = pickle.load(file)
|
|
14
|
+
|
|
15
|
+
with open(poly_features, "rb") as file:
|
|
16
|
+
loaded_poly_features = pickle.load(file)
|
|
17
|
+
|
|
18
|
+
coeficientes = loaded_regresor.coef_.flatten()
|
|
19
|
+
intercept = loaded_regresor.intercept_
|
|
20
|
+
index = np.arange(len(coeficientes)) + 1
|
|
21
|
+
distorsiones = np.linspace(0, 15, 1000)
|
|
22
|
+
X_poly = loaded_poly_features.transform(distorsiones.reshape(-1, 1))
|
|
23
|
+
predicciones = loaded_regresor.predict(X_poly)
|
|
24
|
+
|
|
25
|
+
##genero un dataframe con los coeficientes
|
|
26
|
+
labels = [f"Exponente/Coeficiente {i}" for i in index]
|
|
27
|
+
tabla = pd.DataFrame(coeficientes, labels).rename(columns={0:"Valores"})
|
|
28
|
+
tabla.loc[len(tabla)+1] = intercept
|
|
29
|
+
tabla = tabla.rename(index={len(tabla):"intercepción"})
|
|
30
|
+
|
|
31
|
+
#grafico de líneas de los coeficientes vs su índice
|
|
32
|
+
plt.figure(figsize=(10, 6))
|
|
33
|
+
plt.plot(index, coeficientes, marker='o', linestyle='-', color='b')
|
|
34
|
+
plt.title('Coeficientes del Regresor Polinómico')
|
|
35
|
+
plt.xlabel('Índice del Coeficiente')
|
|
36
|
+
plt.ylabel('Valor del Coeficiente')
|
|
37
|
+
plt.grid(True)
|
|
38
|
+
plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
|
|
39
|
+
plt.show()
|
|
40
|
+
|
|
41
|
+
# gráfico de dispersión de distorsión vs predicciones
|
|
42
|
+
plt.figure(figsize=(10, 6))
|
|
43
|
+
plt.scatter(distorsiones, predicciones, color='r', alpha=0.6)
|
|
44
|
+
plt.title('Score de Fertilizante vs Predicciones en Gramos')
|
|
45
|
+
plt.xlabel('Score de Fertilizante (SC_FT)')
|
|
46
|
+
plt.ylabel('Predicciones de Gramos de Fertilizante')
|
|
47
|
+
plt.grid(True)
|
|
48
|
+
plt.show()
|
|
49
|
+
|
|
50
|
+
inf, sup = 7, 13
|
|
51
|
+
distorsiones[int(inf/0.1):int(sup/0.1+1)].mean()
|
|
52
|
+
predicciones[int(inf/0.1):int(sup/0.1+1)].mean()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# Definición de tramos: (x1, x2, y1, y2)
|
|
56
|
+
segmentos1 = [(0, 4, 0, 0.821),
|
|
57
|
+
(4, 7, 0.821, 5),
|
|
58
|
+
(7, 9.5, 5, 5.41),
|
|
59
|
+
(9.5, 13, 5.41, 8),
|
|
60
|
+
(13, 15, 8, 9)]
|
|
61
|
+
segmentos2 = [(0, 4, 0, 0.821),
|
|
62
|
+
(4, 7, 0.821, 5),
|
|
63
|
+
# (7, 9.5, 5, 5.41),
|
|
64
|
+
(7, 13, 5, 8),
|
|
65
|
+
(13, 15, 8, 9)]
|
|
66
|
+
|
|
67
|
+
def get_line(x1, x2, y1, y2):
|
|
68
|
+
m = (y2 - y1) / (x2 - x1)
|
|
69
|
+
b = y1 - m * x1
|
|
70
|
+
return m, b
|
|
71
|
+
|
|
72
|
+
def piecewise_linear(x, segmentos, lines):
|
|
73
|
+
for (x1, x2, _, _), (m, b) in zip(segmentos, lines):
|
|
74
|
+
if x1 <= x <= x2:
|
|
75
|
+
return m * x + b
|
|
76
|
+
raise ValueError("x fuera de rango")
|
|
77
|
+
|
|
78
|
+
lines1 = [get_line(*seg) for seg in segmentos1]
|
|
79
|
+
lines2 = [get_line(*seg) for seg in segmentos2]
|
|
80
|
+
|
|
81
|
+
# Ejemplo
|
|
82
|
+
ys1 = np.array([piecewise_linear(x, segmentos1, lines1) for x in distorsiones])
|
|
83
|
+
ys2 = np.array([piecewise_linear(x, segmentos2, lines2) for x in distorsiones])
|
|
84
|
+
|
|
85
|
+
# gráfico de dispersión de distorsión vs predicciones
|
|
86
|
+
plt.figure(figsize=(10, 6))
|
|
87
|
+
handles, labels = plt.gca().get_legend_handles_labels()
|
|
88
|
+
order = [2, 0, 1]
|
|
89
|
+
plt.scatter(distorsiones, predicciones, color='r', alpha=0.5, label="Predicciones actuales",zorder=2)
|
|
90
|
+
plt.scatter(distorsiones, ys1, color='g', alpha=0.5, label="Propuesta 1",zorder=1)
|
|
91
|
+
plt.scatter(distorsiones, ys2, color='b', alpha=0.5, label="Propuesta 2",zorder=0)
|
|
92
|
+
plt.title('Score de Fertilizante vs Predicciones en Gramos')
|
|
93
|
+
plt.xlabel('Score de Fertilizante (SC_FT)')
|
|
94
|
+
plt.ylabel('Predicciones de Gramos de Fertilizante')
|
|
95
|
+
plt.grid(True)
|
|
96
|
+
plt.legend()
|
|
97
|
+
plt.show()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
### ************* Obteniendo nuevos regresores a partir de ys1 y ys2 ************* ###
|
|
101
|
+
X = distorsiones.reshape(-1, 1)
|
|
102
|
+
|
|
103
|
+
poly = PolynomialFeatures(
|
|
104
|
+
degree=12,
|
|
105
|
+
include_bias=True # incluye el término β0
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
X_poly = poly.fit_transform(X)
|
|
109
|
+
|
|
110
|
+
modelo1 = LinearRegression(fit_intercept=False)
|
|
111
|
+
modelo1.fit(X_poly, ys1)
|
|
112
|
+
modelo2 = LinearRegression(fit_intercept=False)
|
|
113
|
+
modelo2.fit(X_poly, ys2)
|
|
114
|
+
|
|
115
|
+
ys1_pred = modelo1.predict(X_poly)
|
|
116
|
+
ys2_pred = modelo2.predict(X_poly)
|
|
117
|
+
|
|
118
|
+
# gráfico de dispersión de distorsión vs predicciones
|
|
119
|
+
plt.figure(figsize=(10, 6))
|
|
120
|
+
handles, labels = plt.gca().get_legend_handles_labels()
|
|
121
|
+
order = [2, 0, 1]
|
|
122
|
+
plt.scatter(distorsiones, ys1, color='g', alpha=0.1, label="Función 1 Hardcodeada ",zorder=1)
|
|
123
|
+
plt.scatter(distorsiones, ys1_pred, color="#5612af", alpha=0.5, label="Regresor 1 - Orden 12",zorder=2)
|
|
124
|
+
plt.title('Comparación Función de Propuesta vs Regresor 1 de orden 12')
|
|
125
|
+
plt.xlabel('Score de Fertilizante (SC_FT)')
|
|
126
|
+
plt.ylabel('Predicciones de Gramos de Fertilizante')
|
|
127
|
+
plt.grid(True)
|
|
128
|
+
plt.legend()
|
|
129
|
+
plt.show()
|
|
130
|
+
|
|
131
|
+
# gráfico de dispersión de distorsión vs predicciones
|
|
132
|
+
plt.figure(figsize=(10, 6))
|
|
133
|
+
handles, labels = plt.gca().get_legend_handles_labels()
|
|
134
|
+
order = [2, 0, 1]
|
|
135
|
+
plt.scatter(distorsiones, ys2, color='b', alpha=0.1, label="Función 2 Hardcodeada ",zorder=1)
|
|
136
|
+
plt.scatter(distorsiones, ys2_pred, color="#12af12", alpha=0.5, label="Regresor 2 - Orden 12",zorder=2)
|
|
137
|
+
plt.title('Comparación Función de Propuesta vs Regresor 2 de orden 12')
|
|
138
|
+
plt.xlabel('Score de Fertilizante (SC_FT)')
|
|
139
|
+
plt.ylabel('Predicciones de Gramos de Fertilizante')
|
|
140
|
+
plt.grid(True)
|
|
141
|
+
plt.legend()
|
|
142
|
+
plt.show()
|
|
143
|
+
|
|
144
|
+
# gráfico de dispersión de distorsión vs predicciones
|
|
145
|
+
plt.figure(figsize=(10, 6))
|
|
146
|
+
handles, labels = plt.gca().get_legend_handles_labels()
|
|
147
|
+
order = [2, 0, 1]
|
|
148
|
+
plt.scatter(distorsiones, ys1_pred, color="#5612af", alpha=0.1, label="Regresor 1 - Orden 12",zorder=1)
|
|
149
|
+
plt.scatter(distorsiones, ys2_pred, color="#12af12", alpha=0.5, label="Regresor 2 - Orden 12",zorder=2)
|
|
150
|
+
plt.title('Regresor 1 vs Regresor 2 de orden 12')
|
|
151
|
+
plt.xlabel('Score de Fertilizante (SC_FT)')
|
|
152
|
+
plt.ylabel('Predicciones de Gramos de Fertilizante')
|
|
153
|
+
plt.grid(True)
|
|
154
|
+
plt.legend()
|
|
155
|
+
plt.show()
|
|
156
|
+
|
|
157
|
+
## Guardo el modelo 2 y las características polinómicas
|
|
158
|
+
with open("modelos//regfresor_v2.pkl", "wb") as file:
|
|
159
|
+
pickle.dump(modelo2, file)
|
|
160
|
+
|
|
161
|
+
with open("modelos//poly_features_v2.pkl", "wb") as file:
|
|
162
|
+
pickle.dump(poly, file)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from sarapy.utils.plotting import plotTemporalData
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import os
|
|
5
|
+
import sarapy.utils.getRawOperations as getRawOperations
|
|
6
|
+
from sarapy.dataProcessing import OpsProcessor
|
|
7
|
+
from sarapy.preprocessing import TransformInputData
|
|
8
|
+
from sarapy.dataProcessing import TLMSensorDataProcessor
|
|
9
|
+
import sarapy.stats.stats as stats
|
|
10
|
+
|
|
11
|
+
tlmsde = TLMSensorDataProcessor.TLMSensorDataProcessor()
|
|
12
|
+
|
|
13
|
+
nodo = "UPM017N"
|
|
14
|
+
|
|
15
|
+
data_path = os.path.join(os.getcwd(), f"examples\\2025-04-10\\{nodo}\\data.json")
|
|
16
|
+
historical_data_path = os.path.join(os.getcwd(), f"examples\\2025-04-10\\{nodo}\\historical-data.json")
|
|
17
|
+
|
|
18
|
+
raw_data = pd.read_json(data_path, orient="records").to_dict(orient="records")
|
|
19
|
+
raw_data2 = pd.read_json(historical_data_path, orient="records").to_dict(orient="records")
|
|
20
|
+
|
|
21
|
+
transform_input_data = TransformInputData.TransformInputData()
|
|
22
|
+
|
|
23
|
+
raw_ops = getRawOperations.getRawOperations(raw_data, raw_data2)
|
|
24
|
+
datum = transform_input_data.fit_transform(raw_ops)[:,2]
|
|
25
|
+
telemetria = tlmsde.fit_transform(datum)
|
|
26
|
+
mode = telemetria[:,tlmsde.dataPositions["MODEFlag"]]
|
|
27
|
+
dstpt = telemetria[:,tlmsde.dataPositions["DSTRPT"]]
|
|
28
|
+
|
|
29
|
+
op = OpsProcessor.OpsProcessor(classifier_file='modelos\\pipeline_rf.pkl', imputeDistances = False,
|
|
30
|
+
regresor_file='modelos\\regresor.pkl', poly_features_file='modelos\\poly_features.pkl')
|
|
31
|
+
op.operationsDict
|
|
32
|
+
data_processed = op.processOperations(raw_ops)
|
|
33
|
+
|
|
34
|
+
#paso la lista de operaciones a un dataframe
|
|
35
|
+
df = pd.DataFrame(data_processed)
|
|
36
|
+
df["mode"] = mode
|
|
37
|
+
df["dstpt"] = dstpt
|
|
38
|
+
df["nodo"] = nodo
|
|
39
|
+
ma = stats.getMA(df["dstpt"].values, window_size=104, mode='same')
|
|
40
|
+
df["dstpt_ma"] = ma
|
|
41
|
+
##me quedo con los datos donde mode==0
|
|
42
|
+
df = df[df["mode"] == 0]
|
|
43
|
+
|
|
44
|
+
#calculo el resumen del sensor
|
|
45
|
+
resumen = stats.resumen_sensor(df, values_col="dstpt_ma", pctbajo_value=1, pctalto_value=14)
|
|
46
|
+
print(resumen)
|
|
47
|
+
#calculo la probabilidad de saturación
|
|
48
|
+
prob_saturacion = stats.calcular_prob_saturacion(ma[2000:], saturation_mode="alto", umbrales=(1, 14),
|
|
49
|
+
alpha=0.2, beta=0.2)
|
|
50
|
+
print(f"Probabilidad de saturación: {prob_saturacion}")
|
|
51
|
+
|
|
52
|
+
# Definimos grilla de alpha y beta
|
|
53
|
+
alpha_vals = np.linspace(0, 1, 20)
|
|
54
|
+
beta_vals = np.linspace(0, 1, 20)
|
|
55
|
+
|
|
56
|
+
# Creamos matriz de resultados
|
|
57
|
+
Psat_matrix = np.zeros((len(alpha_vals), len(beta_vals)))
|
|
58
|
+
|
|
59
|
+
for i, alpha in enumerate(alpha_vals):
|
|
60
|
+
for j, beta in enumerate(beta_vals):
|
|
61
|
+
Psat = prob_saturacion = stats.calcular_prob_saturacion(ma, saturation_mode="alto", umbrales=(1, 14),
|
|
62
|
+
alpha=alpha, beta=beta)
|
|
63
|
+
Psat_matrix[i, j] = Psat
|
|
64
|
+
|
|
65
|
+
import matplotlib.pyplot as plt
|
|
66
|
+
import seaborn as sns
|
|
67
|
+
|
|
68
|
+
plt.figure(figsize=(10, 8))
|
|
69
|
+
sns.heatmap(Psat_matrix, xticklabels=np.round(beta_vals, 2), yticklabels=np.round(alpha_vals, 2), cmap="coolwarm")
|
|
70
|
+
plt.title("Evolución de Psat en función de α (vertical) y β (horizontal)")
|
|
71
|
+
plt.xlabel("β (peso de kurtosis)")
|
|
72
|
+
plt.ylabel("α (peso de skewness)")
|
|
73
|
+
plt.show()
|
|
74
|
+
|
|
75
|
+
colors = ["#0b3256","#fa0000"]
|
|
76
|
+
plotTemporalData(df, nodos = [nodo], columnas = ["dstpt_ma"], title = "DSTPT",sameFig = False, show = True,
|
|
77
|
+
save = False, filename = "dstpt_plot.png", figsize=(15, 10), colors=colors)
|
test/test_import.py
ADDED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
sarapy
|
|
File without changes
|