import os os.system('pip install gradio seaborn scipy scikit-learn openpyxl networkx pydantic==1.10.0') from pydantic import BaseModel, ConfigDict class YourModel(BaseModel): class Config: arbitrary_types_allowed = True import numpy as np import networkx as nx import matplotlib.pyplot as plt import gradio as gr from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import r2_score from itertools import combinations import tempfile # Clase para el modelo de regresión class RegressionModel: def __init__(self, degree=1): self.degree = degree self.model = LinearRegression() self.poly = PolynomialFeatures(degree=degree, include_bias=False) def fit(self, X, y): X_poly = self.poly.fit_transform(X) self.model.fit(X_poly, y) def predict(self, X): X_poly = self.poly.transform(X) return self.model.predict(X_poly) def r2_score(self, X, y): y_pred = self.predict(X) return r2_score(y, y_pred) # Clase para el diseño experimental class ExperimentalDesign: def __init__(self, regression_degree=1): self.pb_design = None self.bb_design = None self.factor_values = None self.variable1_values = None self.variable2_values = None self.active_factors = None self.regression_degree = regression_degree def set_design(self, pb_design, bb_design): self.pb_design = pb_design self.bb_design = bb_design def set_factors(self, factor_values): self.factor_values = factor_values def set_dependent_variables(self, variable1_values, variable2_values): self.variable1_values = variable1_values self.variable2_values = variable2_values def set_active_factors(self, active_factors): self.active_factors = active_factors def fit_models(self): active_columns = [i for i, factor in enumerate(self.factor_values.keys()) if factor in self.active_factors] X = self.pb_design[:, active_columns] self.model_variable1 = RegressionModel(degree=self.regression_degree) self.model_variable2 = RegressionModel(degree=self.regression_degree) self.model_variable1.fit(X, self.variable1_values) self.model_variable2.fit(X, self.variable2_values) self.r2_variable1 = self.model_variable1.r2_score(X, self.variable1_values) self.r2_variable2 = self.model_variable2.r2_score(X, self.variable2_values) # Clase para el análisis de teoría de grafos class GraphTheoryAnalysis: def __init__(self, experiment): self.experiment = experiment self.graph = nx.Graph() self.all_factors = None def set_matrices_and_values(self): self.all_factors = list(self.experiment.factor_values.keys()) def build_graph(self, level=3): if level > len(self.all_factors): level = len(self.all_factors) # Ajustar el nivel al número de factores disponibles for pair in combinations(self.all_factors, level): if len(pair) >= 2: # Asegurarse de que hay suficientes elementos para formar un par self.experiment.set_active_factors(list(pair)) self.experiment.fit_models() r2 = (self.experiment.r2_variable1 + self.experiment.r2_variable2) / 2 self.graph.add_edge(pair[0], pair[1], weight=r2) def visualize_graph(self, style='Style 1'): pos = nx.spring_layout(self.graph) plt.figure(figsize=(10, 8)) # Estilos para el grafo if style == 'Style 1': node_color = 'lightblue' edge_color = 'gray' node_size = 3000 font_size = 12 elif style == 'Style 2': node_color = 'lightgreen' edge_color = 'purple' node_size = 2500 font_size = 10 elif style == 'Style 3': node_color = 'orange' edge_color = 'black' node_size = 3500 font_size = 14 elif style == 'Style 4': node_color = 'red' edge_color = 'blue' node_size = 2800 font_size = 12 nx.draw_networkx_nodes(self.graph, pos, node_size=node_size, node_color=node_color) nx.draw_networkx_labels(self.graph, pos, font_size=font_size) edge_weights = [self.graph[u][v]['weight'] for u, v in self.graph.edges()] nx.draw_networkx_edges(self.graph, pos, width=edge_weights, edge_color=edge_color) edge_labels = nx.get_edge_attributes(self.graph, 'weight') nx.draw_networkx_edge_labels(self.graph, pos, edge_labels=edge_labels, font_size=font_size) plt.title(f"Grafo de relaciones entre factores basado en R² ({style})") plt.axis('off') plt.tight_layout() # Guardar la imagen temporalmente usando tempfile temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False) plt.savefig(temp_file.name) plt.close() return temp_file.name # Definición de la interfaz de Gradio def analyze_design(level, pb_design, bb_design, variable1_values, variable2_values, style): experiment = ExperimentalDesign(regression_degree=2) optimizer = GraphTheoryAnalysis(experiment) factor_values = { 'X1': [1, 5], 'X2': [0.05, 0.5], 'X3': [0.1, 1], 'X4': [0.05, 0.5] } experiment.set_design(np.array(pb_design), np.array(bb_design)) experiment.set_factors(factor_values) experiment.set_dependent_variables(np.array(variable1_values), np.array(variable2_values)) optimizer.set_matrices_and_values() optimizer.build_graph(level=level) graph_image_path = optimizer.visualize_graph(style=style) return graph_image_path, bb_design # Matriz Plackett-Burman (por defecto) default_pb_design = [ [+1, -1, -1, +1], [+1, -1, +1, +1], [+1, +1, -1, -1], [-1, +1, -1, +1], [+1, +1, +1, -1], [-1, +1, +1, -1], [-1, -1, +1, +1], [-1, -1, -1, -1] ] # Matriz Box-Behnken (por defecto) default_bb_design = [ [-1, -1, 0, 0], [1, -1, 0, 0], [-1, 1, 0, 0], [1, 1, 0, 0], [-1, 0, -1, 0], [1, 0, -1, 0], [-1, 0, 1, 0], [1, 0, 1, 0], [-1, 0, 0, -1], [1, 0, 0, -1], [-1, 0, 0, 1], [1, 0, 0, 1], [0, -1, -1, 0], [0, 1, -1, 0], [0, -1, 1, 0], [0, 1, 1, 0], [0, -1, 0, -1], [0, 1, 0, -1], [0, -1, 0, 1], [0, 1, 0, 1], [0, 0, -1, -1], [0, 0, 1, -1], [0, 0, -1, 1], [0, 0, 1, 1], [0, 0, 0, 0] ] # Valores por defecto para las variables dependientes default_variable1_values = [0.066, 0.061, 0.155, 0.209, 0.158, 0.014, 0.055, 0.007] default_variable2_values = [0.362, 0.856, 0.177, 0.261, 0.946, 0.695, 0.892, 0.084] # Interfaz de Gradio interface = gr.Interface( fn=analyze_design, inputs=[ gr.Slider(1, 4, step=1, label="Level of Combination (1 to 4)"), gr.Dataframe(headers=["X1", "X2", "X3", "X4"], value=default_pb_design, label="Matrix 1 (Plackett-Burman)"), gr.Dataframe(headers=["X1", "X2", "X3", "X4"], value=default_bb_design, label="Matrix 2 (Box-Behnken)"), gr.Dataframe(headers=["Variable 1"], value=[[val] for val in default_variable1_values], label="Variable 1 Values"), gr.Dataframe(headers=["Variable 2"], value=[[val] for val in default_variable2_values], label="Variable 2 Values"), gr.Dropdown(["Style 1", "Style 2", "Style 3", "Style 4"], label="Graph Style", value="Style 1") ], outputs=["image", "dataframe"], title="Graph Theory Analysis for Experimental Design", description="Analyze and visualize the relationships between factors in an experimental design using graph theory." ) # Ejecutar la interfaz interface.launch(share=True)