Commit ae833cb2 by Stalin Munoz

Proyecto inicial de bios club

parents
/*******************************************************************************
*
* GRIFFIN Software,
* Copyright (c) 2015-2019
* Instituto de Investigaciones en Matematicas Aplicadas y en Sistemas
* (IIMAS http://www.iimas.unam.mx).
* Centro de Ciencias de la Complejidad
* Universidad Nacional Autónoma de México.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*******************************************************************************/
/**
* Grammar for boolean sentences
*
**/
grammar BooleanSentence;
init: sentence
;
sentence: TRUE #TrueSentence
| FALSE #FalseSentence
| VAR #AtomSentence
| '(' sentence ')' #ParentSentence
| NOT sentence #NotSentence
| sentence AND sentence #AndSentence
| sentence OR sentence #OrSentence
| sentence IMP sentence #ImplicationSentence
| sentence EQ sentence #EquivalenceSentence
;
TRUE: '1'
;
FALSE: '0'
;
VAR: [a-zA-Z_]+[a-zA-Z_0-9/]*
;
NOT: '~'
| '!'
| '¬'
;
AND: '&'
| '^'
| '*'
;
OR: '|'
| '||'
| '+'
;
IMP: '->'
| '=>'
;
EQ: '='
| '<->'
| '<=>'
;
BLANK: [ \t\r\n]+ -> skip
;
T__0=1
T__1=2
TRUE=3
FALSE=4
VAR=5
NOT=6
AND=7
OR=8
IMP=9
EQ=10
BLANK=11
'('=1
')'=2
'1'=3
'0'=4
# Generated from BooleanSentence.g4 by ANTLR 4.5.1
from antlr4 import *
from io import StringIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\r")
buf.write("L\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\3\2\3\2\3\3")
buf.write("\3\3\3\4\3\4\3\5\3\5\3\6\6\6#\n\6\r\6\16\6$\3\6\7\6(\n")
buf.write("\6\f\6\16\6+\13\6\3\7\3\7\3\b\3\b\3\t\3\t\3\t\3\t\5\t")
buf.write("\65\n\t\3\n\3\n\3\n\3\n\5\n;\n\n\3\13\3\13\3\13\3\13\3")
buf.write("\13\3\13\3\13\5\13D\n\13\3\f\6\fG\n\f\r\f\16\fH\3\f\3")
buf.write("\f\2\2\r\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f")
buf.write("\27\r\3\2\7\5\2C\\aac|\6\2\61;C\\aac|\5\2##\u0080\u0080")
buf.write("\u00ae\u00ae\5\2((,,``\5\2\13\f\17\17\"\"S\2\3\3\2\2\2")
buf.write("\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r")
buf.write("\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3")
buf.write("\2\2\2\2\27\3\2\2\2\3\31\3\2\2\2\5\33\3\2\2\2\7\35\3\2")
buf.write("\2\2\t\37\3\2\2\2\13\"\3\2\2\2\r,\3\2\2\2\17.\3\2\2\2")
buf.write("\21\64\3\2\2\2\23:\3\2\2\2\25C\3\2\2\2\27F\3\2\2\2\31")
buf.write("\32\7*\2\2\32\4\3\2\2\2\33\34\7+\2\2\34\6\3\2\2\2\35\36")
buf.write("\7\63\2\2\36\b\3\2\2\2\37 \7\62\2\2 \n\3\2\2\2!#\t\2\2")
buf.write("\2\"!\3\2\2\2#$\3\2\2\2$\"\3\2\2\2$%\3\2\2\2%)\3\2\2\2")
buf.write("&(\t\3\2\2\'&\3\2\2\2(+\3\2\2\2)\'\3\2\2\2)*\3\2\2\2*")
buf.write("\f\3\2\2\2+)\3\2\2\2,-\t\4\2\2-\16\3\2\2\2./\t\5\2\2/")
buf.write("\20\3\2\2\2\60\65\7~\2\2\61\62\7~\2\2\62\65\7~\2\2\63")
buf.write("\65\7-\2\2\64\60\3\2\2\2\64\61\3\2\2\2\64\63\3\2\2\2\65")
buf.write("\22\3\2\2\2\66\67\7/\2\2\67;\7@\2\289\7?\2\29;\7@\2\2")
buf.write(":\66\3\2\2\2:8\3\2\2\2;\24\3\2\2\2<D\7?\2\2=>\7>\2\2>")
buf.write("?\7/\2\2?D\7@\2\2@A\7>\2\2AB\7?\2\2BD\7@\2\2C<\3\2\2\2")
buf.write("C=\3\2\2\2C@\3\2\2\2D\26\3\2\2\2EG\t\6\2\2FE\3\2\2\2G")
buf.write("H\3\2\2\2HF\3\2\2\2HI\3\2\2\2IJ\3\2\2\2JK\b\f\2\2K\30")
buf.write("\3\2\2\2\t\2$)\64:CH\3\b\2\2")
return buf.getvalue()
class BooleanSentenceLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
T__1 = 2
TRUE = 3
FALSE = 4
VAR = 5
NOT = 6
AND = 7
OR = 8
IMP = 9
EQ = 10
BLANK = 11
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'('", "')'", "'1'", "'0'" ]
symbolicNames = [ "<INVALID>",
"TRUE", "FALSE", "VAR", "NOT", "AND", "OR", "IMP", "EQ", "BLANK" ]
ruleNames = [ "T__0", "T__1", "TRUE", "FALSE", "VAR", "NOT", "AND",
"OR", "IMP", "EQ", "BLANK" ]
grammarFileName = "BooleanSentence.g4"
def __init__(self, input=None):
super().__init__(input)
self.checkVersion("4.5.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
T__0=1
T__1=2
TRUE=3
FALSE=4
VAR=5
NOT=6
AND=7
OR=8
IMP=9
EQ=10
BLANK=11
'('=1
')'=2
'1'=3
'0'=4
# Generated from BooleanSentence.g4 by ANTLR 4.5.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .BooleanSentenceParser import BooleanSentenceParser
else:
from BooleanSentenceParser import BooleanSentenceParser
# This class defines a complete listener for a parse tree produced by BooleanSentenceParser.
class BooleanSentenceListener(ParseTreeListener):
# Enter a parse tree produced by BooleanSentenceParser#init.
def enterInit(self, ctx:BooleanSentenceParser.InitContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#init.
def exitInit(self, ctx:BooleanSentenceParser.InitContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#NotSentence.
def enterNotSentence(self, ctx:BooleanSentenceParser.NotSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#NotSentence.
def exitNotSentence(self, ctx:BooleanSentenceParser.NotSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#TrueSentence.
def enterTrueSentence(self, ctx:BooleanSentenceParser.TrueSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#TrueSentence.
def exitTrueSentence(self, ctx:BooleanSentenceParser.TrueSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#AtomSentence.
def enterAtomSentence(self, ctx:BooleanSentenceParser.AtomSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#AtomSentence.
def exitAtomSentence(self, ctx:BooleanSentenceParser.AtomSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#AndSentence.
def enterAndSentence(self, ctx:BooleanSentenceParser.AndSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#AndSentence.
def exitAndSentence(self, ctx:BooleanSentenceParser.AndSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#ParentSentence.
def enterParentSentence(self, ctx:BooleanSentenceParser.ParentSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#ParentSentence.
def exitParentSentence(self, ctx:BooleanSentenceParser.ParentSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#EquivalenceSentence.
def enterEquivalenceSentence(self, ctx:BooleanSentenceParser.EquivalenceSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#EquivalenceSentence.
def exitEquivalenceSentence(self, ctx:BooleanSentenceParser.EquivalenceSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#OrSentence.
def enterOrSentence(self, ctx:BooleanSentenceParser.OrSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#OrSentence.
def exitOrSentence(self, ctx:BooleanSentenceParser.OrSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#FalseSentence.
def enterFalseSentence(self, ctx:BooleanSentenceParser.FalseSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#FalseSentence.
def exitFalseSentence(self, ctx:BooleanSentenceParser.FalseSentenceContext):
pass
# Enter a parse tree produced by BooleanSentenceParser#ImplicationSentence.
def enterImplicationSentence(self, ctx:BooleanSentenceParser.ImplicationSentenceContext):
pass
# Exit a parse tree produced by BooleanSentenceParser#ImplicationSentence.
def exitImplicationSentence(self, ctx:BooleanSentenceParser.ImplicationSentenceContext):
pass
name = "boolparse"
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 09:18:23 2019
@author: stan
"""
from antlr4 import CommonTokenStream,InputStream,ParseTreeWalker
from BooleanSentenceLexer import BooleanSentenceLexer
from BooleanSentenceParser import BooleanSentenceParser
from sentece_listener import SentenceListener
class FormulaParser:
@staticmethod
def parse(formula):
input_stream = InputStream(formula)
lexer = BooleanSentenceLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = BooleanSentenceParser(stream)
tree = parser.init()
listener = SentenceListener()
walker = ParseTreeWalker()
walker.walk(listener, tree)
return (listener.get_expression(),listener.get_var_names())
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 09:19:22 2019
@author: stan
"""
from logic import TRUE,FALSE,Var,Not,And,Or,\
Implication,Equivalence
class CNF:
def __init__(self,formula,variables):
self.P = "__"
self.V = "Z"
self.formula = formula
self.formulaCNF = None
self.variables = variables
self.encode ={v:i+1 for i,v in enumerate(variables)}
self.index = len(variables)+1
self.dimacs = []
def next_index(self):
i = self.index
self.index +=1
return i
def switching_var(self):
var = Var(self.P+self.V+str(self.next_index())+self.P)
self.encode[var.nombre]=self.index-1
return var
def rewrite(self,formula):
if isinstance(formula,TRUE):
return formula
elif isinstance(formula,FALSE):
return formula
elif isinstance(formula,Var):
return formula
elif isinstance(formula, Not):
return Not(self.rewrite(formula.param))
elif isinstance(formula,And):
return And(
self.rewrite(formula.left),self.rewrite(formula.right))
elif isinstance(formula,Or):
return Or(
self.rewrite(formula.left),self.rewrite(formula.right))
elif isinstance(formula,Implication):
return Or(
Not(self.rewrite(formula.left)),
self.rewrite(formula.right))
elif isinstance(formula,Equivalence):
return And(
Or(
Not(self.rewrite(formula.left)),
self.rewrite(formula.right)),
Or(
Not(self.rewrite(formula.right)),
self.rewrite(formula.left)))
def apply_not(self,formula):
if isinstance(formula,Not):
if isinstance(formula.param,And):
return Or(
self.apply_not(Not(formula.param.left)),
self.apply_not(Not(formula.param.right)))
elif isinstance(formula.param,Or):
return And(
self.apply_not(Not(formula.param.left)),
self.apply_not(Not(formula.param.right)))
elif isinstance(formula.param,Not):
return self.apply_not(formula.param.param)
else:
return formula
elif isinstance(formula,And):
return And(
self.apply_not(formula.left),
self.apply_not(formula.right))
elif isinstance(formula,Or):
return Or(
self.apply_not(formula.left),
self.apply_not(formula.right))
else:
return formula
def literal(self,formula):
if isinstance(formula,Var):
return True
elif isinstance(formula,Not):
return isinstance(formula.param,Var)
else:
return False
def distribute_ors(self,formula):
if self.literal(formula):
return formula
if isinstance(formula,Or):
if self.literal(formula.left) and self.literal(formula.right):
return formula
if self.literal(formula.left):
if isinstance(formula.right,And):
return self.distribute(
formula.left,self.distribute_ors(formula.right))
else:
return Or(formula.left,
self.distribute_ors(formula.right))
if self.literal(formula.right):
if isinstance(formula.left,And):
return self.distribute(
formula.right,self.distribute_ors(formula.left))
else:
return Or(formula.right,
self.distribute_ors(formula.left))
else:
Z = self.switching_var()
return And(
self.distribute(Not(Z),self.distribute_ors(formula.left)),
self.distribute(Z,self.distribute_ors(formula.right)))
elif isinstance(formula,And):
return And(
self.distribute_ors(formula.left),
self.distribute_ors(formula.right)
)
else:
return formula
def distribute(self,variable,formula):
if self.literal(formula):
return Or(variable,formula)
elif isinstance(formula,And):
return And(
self.distribute(variable,formula.left),
self.distribute(variable,formula.right))
elif isinstance(formula,Or):
return Or(variable,formula)
def convert(self):
f = self.rewrite(self.formula)
f = self.apply_not(f)
f = self.distribute_ors(f)
self.decode = {i:v for v,i in self.encode.items()}
self.formulaCNF = f
return f
def to_dimacs(self,formula=None):
formula = self.formulaCNF if formula==None else formula
if not isinstance(formula,And):
clausula = self.encode_clausula(formula,[])
self.dimacs.append(clausula)
else:
self.to_dimacs(formula.left)
self.to_dimacs(formula.right)
return self.dimacs
def encode_clausula(self,formula,clausula=[]):
if self.literal(formula):
self.agregar_literal(formula,clausula)
else:
self.encode_clausula(formula.left,clausula)
self.encode_clausula(formula.right,clausula)
return clausula
def agregar_literal(self,literal,clausula):
if isinstance(literal,Not):
variable = literal.param
indice = -self.encode[variable.nombre]
else:
indice = self.encode[literal.nombre]
clausula.append(indice)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 09:56:34 2019
@author: stan
"""
from abc import ABC,abstractmethod
class ExpresionBooleana(ABC):
@abstractmethod
def evaluate(self,assignment):
pass
def __repr__(self):
return str(self)
class TRUE(ExpresionBooleana):
def evaluate(self,assignment):
return True
def __str__(self):
return "1"
class FALSE(ExpresionBooleana):
def evaluate(false,assignment):
return False
def __str__(self):
return "0"
class Var(ExpresionBooleana):
def __init__(self,nombre):
self.nombre = nombre
def evaluate(self,assignment):
return assignment[self.nombre]
def __str__(self):
return self.nombre
class Not(ExpresionBooleana):
def __init__(self, expresion):
self.param = expresion
def evaluate(self,assignment):
return not self.param.evaluate(assignment)
def get_symbol(self):
return "~"
def __str__(self):
return self.get_symbol()+str(self.param)
class ExpresionBinaria(ExpresionBooleana,ABC):
def __init__(self,left,right):
self.left = left
self.right = right
@abstractmethod
def get_symbol(self):
pass
def __str__(self):
return "("+str(self.left)+self.get_symbol()+str(self.right)+")"
class And(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) and\
self.right.evaluate(assignment)
def get_symbol(self):
return "&"
class Or(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) or\
self.right.evaluate(assignment)
def get_symbol(self):
return "|"
class Implication(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return not self.left.evaluate(assignment) or\
self.right.evaluate(assignment)
def get_symbol(self):
return "->"
class Equivalence(ExpresionBinaria):
def __init__(self,left,right):
super().__init__(left,right)
def evaluate(self,assignment):
return self.left.evaluate(assignment) ==\
self.right.evaluate(assignment)
def get_symbol(self):
return "="
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 08:21:19 2019
@author: stan
"""
#%%
from logic import And, Or, Implication, Equivalence, Not, Var,TRUE,FALSE
#phi = And(Var('A'),Or(Var('B'),Not(Var('C'))))
#definiendo una constante
phi = TRUE()
print(phi,type(phi))
#%%
phi = FALSE()
print(phi,type(phi))
#%%
#definiendo una variable
phi = Var('A')
print(phi,type(phi))
#%%
#negación
phi = Not(phi)
print(phi,type(phi))
#%%
#conjunción
psi = Var('C')
phi = And(phi,psi)
print(phi)
#%%
#disyunción
phi = Or(phi,psi)
print(phi)
#%%
#implicación
phi = Implication(psi,phi)
print(phi)
#%%
#equivalencia
phi = Equivalence(phi,psi)
print(phi)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 08:18:45 2019
@author: stan
"""
from itertools import product
from formula_parser import FormulaParser as parser
class TruthTable:
"""
Tabla de verdad
"""
def __init__(self,variables,name,values=None,formula=None,formulastr=None):
self.n = len(variables)
self.values = values
self.name = name
self.variables = variables
self.formula = formula
self.formulastr = formulastr
t = [False,True]
g = (t for _ in range(self.n))
left = product(*g)
if values:
self.table = {k:v for k,v in zip(left,values)}
else:
self.table = {}
for tupla in left:
assignment = {var:val for var,val in zip(variables,tupla)}
self.table[tupla]=formula.evaluate(assignment)
def __getitem__(self,estado):
return self.table[estado]
def __str__(self):
s = "\n"
sep = " "
encabezado = sep.join(self.variables)+ sep+"\\"+sep + self.name + "\n"
encabezado += "-"*len(encabezado) + "\n"
s += encabezado
for tupla in sorted(self.table.items()):
l = ""
izq,der = tupla
l += sep.join("1" if i else "0" for i in izq)
l += sep+"\\"+sep
l += "1" if der else "0"
l += "\n"
s += l
return s
def __repr__(self):
return str(self)
@staticmethod
def from_formula(formula,name):
ftree,variables = parser.parse(formula)
return TruthTable(variables,name,formula=ftree,formulastr=formula)
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 09:11:57 2019
@author: stan
"""
from BooleanSentenceListener import BooleanSentenceListener
from collections import deque
from logic.logic import Var,TRUE,FALSE,Not,And,Or,Equivalence,Implication
class SentenceListener(BooleanSentenceListener):
def __init__(self):
self.pila = deque()
self.vars = set()
def exitTrueSentence(self, ctx):
self.pila.append(TRUE())
def exitFalseSentence(self, ctx):
self.pila.append(FALSE())
def exitAtomSentence(self, ctx):
nombre = str(ctx.VAR())
self.vars.add(nombre)
self.pila.append(Var(nombre))
def exitNotSentence(self,ctx):
self.pila.append(Not(self.pila.pop()))
def exitAndSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(And(left,right))
def exitOrSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Or(left,right))
def exitEquivalenceSentence(self, ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Equivalence(left,right))
def exitImplicationSentence(self,ctx):
right = self.pila.pop()
left = self.pila.pop()
self.pila.append(Implication(left,right))
def get_expression(self):
return self.pila.pop()
def get_var_names(self):
return sorted(self.vars)
from setuptools import setup
setup(name='pypack',
version='0.1',
description='Test package',
url='http://c3.unam.mx/',
author='Stan',
author_email='stalin.munoz@c3.unam.mx',
license='LGPL',
packages=['pypack'],
zip_safe=False)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment