Skip to content

Commit

Permalink
feat: #40 assign units/guess for constant eqns
Browse files Browse the repository at this point in the history
-Assign automatically unit’s variables for constant function
written in textbox with units
-If the variable is solved, also it’s possible assign the guess
-For now, it’s not working if the variable is solved on the left side
  • Loading branch information
xmagor committed Jan 13, 2021
1 parent 60a151c commit 6ee24d7
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 9 deletions.
15 changes: 13 additions & 2 deletions pyENL.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,20 +1044,31 @@ def actualizaInfo(self):
# self.infoLabel.setText((len(texto)))
# Ahora definir la cantidad de ecuaciones y de variables en la caja
try:
cantidad_eqn, var_reco = cantidadEqnVar(texto)
cantidad_eqn, var_reco, var_properties = cantidadEqnVar(texto)
cantidad_var = len(var_reco)
a_mostrar = str(cantidad_eqn) + self.traduccion[' ecuaciones / ' ] + \
str(cantidad_var) + self.traduccion[' variables']
self.infoLabel.setText(a_mostrar)
# Ahora actualizar la lista de variables si es necesario
# Recordar que var_reco contiene las variables reconocidas en la
# actualización.
varsSelf = [obj.name for obj in self.variables]
varsSelf = []
for obj in self.variables:
varName = obj.name
varsSelf += [varName]
if varName in var_properties.keys():
obj.guess = var_properties[varName].get('guess',obj.guess)
obj.units = var_properties[varName].get('units',obj.units)

for varGUI in var_reco:
if varGUI not in varsSelf:
# Si no está entonces agregar!
new_var = pyENL_variable(varGUI)
if varGUI in var_properties.keys():
new_var.guess = var_properties[varGUI].get('guess',new_var.guess)
new_var.units = var_properties[varGUI].get('units',new_var.units)
self.variables.append(new_var)

# Si no está en var_reco pero está en self.variables...
for i, varSelf in enumerate(self.variables):
if varSelf.name not in var_reco:
Expand Down
63 changes: 56 additions & 7 deletions utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#/usr/bin/env python3
import random
import copy
import os
import appdirs
import sys
Expand All @@ -21,7 +20,7 @@
ln = log
prop = log # Solo importa el nombre de la función para comprobación...
haprop = log

import copy # recordar que copy entra en conflicto con el copy importado de numpy

from tarjan import tarjan

Expand Down Expand Up @@ -130,9 +129,11 @@ def probar(texto_var):
return True


def variables(texto_eqn):
def variables(texto_eqn, return_posibles_vars = False):
'''
Regresa en texto las variables del string texto_eqn
Regresa:
- Texto las variables del string texto_eqn
- Lista de caracteres que posiblemente son variables (opcional)
'''
# Reconocer lo que hay entre paréntesis
# Cambiar todos los nombres de las funciones por números
Expand Down Expand Up @@ -191,7 +192,10 @@ def variables(texto_eqn):
if variable not in salida:
salida.append(variable)

return salida
if return_posibles_vars:
return salida, posibles
else:
return salida


def random_lim(a, b):
Expand Down Expand Up @@ -270,11 +274,16 @@ def cantidadEqnVar(texto_caja):
'-(' + izq_der[1] + ')' # Igualación de cero
lista.append(paraRaiz)
lista_vars = []
dict_vars_properties = {}
for ecuacion in lista:
lista_vars = lista_vars + variables(ecuacion)
vars_ecuacion, posibles = variables(ecuacion,True)
vars_eqn_properties = variablesProperties(ecuacion,vars_ecuacion, posibles)
lista_vars = lista_vars + vars_ecuacion
dict_vars_properties.update(vars_eqn_properties)
lista_vars = list(set(lista_vars))
# Regresa el número de ecuaciones y de variables.
return ecuaciones, lista_vars

return ecuaciones, lista_vars, dict_vars_properties

def actualizar_directorio(cuDir):
'''Guarda en config la ultima ruta de la carpeta donde se abrió o guardó un archivo'''
Expand Down Expand Up @@ -511,3 +520,43 @@ def removeBigComments(texto):

return texto_sin_comentarios

def variablesProperties(texto_eqn,vars_ecuacion,posibles):
'''
Identifica a partir de una ecación si es posible asociar la magnitud
y/o unidad a la variable.
Retorna un diccionario donde la llave es la variable y el contenido
es otro diccionario asociado a la propiedad identificada
Ejemplo:
a = 1[cm] + 0.5[m]
Resultado:
{'a': {
'guess': 51.0,
'units': Unit('centimeter'),}
}
'''

# validar si hay una sola variable y no se repite
dic_vars = {}
if len(vars_ecuacion) == 1 and posibles.count(vars_ecuacion[0]) == 1:
variable_unique = vars_ecuacion[0]

# validar que la variable esté despejada
terminos_eqn = texto_eqn.replace('-','+').split('+')
if variable_unique in terminos_eqn:
to_eval = texto_eqn.replace(variable_unique,'')
to_eval =to_eval.replace("[", "*pyENLu.parse_units('").replace("]", "')")
result_var = eval(to_eval)

dic_vars = {variable_unique: {}}
# si no hay unidades el eval retornara un int or float
if 'pyENLu' in to_eval:
dic_vars[variable_unique]['guess'] = - result_var.magnitude
dic_vars[variable_unique]['units'] = result_var.units
else:
dic_vars[variable_unique]['guess'] = - result_var

return dic_vars

0 comments on commit 6ee24d7

Please sign in to comment.