commit 962d2d7b164d48d0b60c37fd63c4b9414379b891 Author: github-classroom[bot] <66690702+github-classroom[bot]@users.noreply.github.com> Date: Tue Sep 17 10:51:50 2024 +0000 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..79418c1 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# iia-ia-guiao-rc diff --git a/bayes_net.py b/bayes_net.py new file mode 100755 index 0000000..289d2eb --- /dev/null +++ b/bayes_net.py @@ -0,0 +1,38 @@ + + +class BayesNet: + + def __init__(self, ldep=None): # Why not ldep={}? See footnote 1. + if not ldep: + ldep = {} + self.dependencies = ldep + + # The network data is stored in a dictionary that + # associates the dependencies to each variable: + # { v1:deps1, v2:deps2, ... } + # These dependencies are themselves given + # by another dictionary that associates conditional + # probabilities to conjunctions of mother variables: + # { mothers1:cp1, mothers2:cp2, ... } + # The conjunctions are frozensets of pairs (mothervar,boolvalue) + def add(self,var,mothers,prob): + self.dependencies.setdefault(var,{})[frozenset(mothers)] = prob + + # Joint probability for a given conjunction of + # all variables of the network + def jointProb(self,conjunction): + prob = 1.0 + for (var,val) in conjunction: + for (mothers,p) in self.dependencies[var].items(): + if mothers.issubset(conjunction): + prob*=(p if val else 1-p) + return prob + + +# Footnote 1: +# Default arguments are evaluated on function definition, +# not on function evaluation. +# This creates surprising behaviour when the default argument is mutable. +# See: +# http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments + diff --git a/bn_example.py b/bn_example.py new file mode 100755 index 0000000..5598f2f --- /dev/null +++ b/bn_example.py @@ -0,0 +1,25 @@ + +from bayes_net import * + +# Exemplo dos acetatos: + +bn = BayesNet() + +bn.add('r',[],0.001) +bn.add('t',[],0.002) + +bn.add('a',[('r',True ),('t',True )],0.950) +bn.add('a',[('r',True ),('t',False)],0.940) +bn.add('a',[('r',False),('t',True )],0.290) +bn.add('a',[('r',False),('t',False)],0.001) + +bn.add('j',[('a',True )],0.900) +bn.add('j',[('a',False)],0.050) + +bn.add('m',[('a',True )],0.700) +bn.add('m',[('a',False)],0.100) + +conjunction = [('j',True),('m',True),('a',True),('r',False),('t',False)] + +print(bn.jointProb(conjunction)) + diff --git a/guiao-rc-en.pdf b/guiao-rc-en.pdf new file mode 100644 index 0000000..ad36c08 Binary files /dev/null and b/guiao-rc-en.pdf differ diff --git a/guiao-rc.pdf b/guiao-rc.pdf new file mode 100644 index 0000000..e709f06 Binary files /dev/null and b/guiao-rc.pdf differ diff --git a/semantic_network.py b/semantic_network.py new file mode 100755 index 0000000..c641eee --- /dev/null +++ b/semantic_network.py @@ -0,0 +1,99 @@ + + +# Guiao de representacao do conhecimento +# -- Redes semanticas +# +# Inteligencia Artificial & Introducao a Inteligencia Artificial +# DETI / UA +# +# (c) Luis Seabra Lopes, 2012-2020 +# v1.9 - 2019/10/20 +# + + +# Classe Relation, com as seguintes classes derivadas: +# - Association - uma associacao generica entre duas entidades +# - Subtype - uma relacao de subtipo entre dois tipos +# - Member - uma relacao de pertenca de uma instancia a um tipo +# + +class Relation: + def __init__(self,e1,rel,e2): + self.entity1 = e1 +# self.relation = rel # obsoleto + self.name = rel + self.entity2 = e2 + def __str__(self): + return self.name + "(" + str(self.entity1) + "," + \ + str(self.entity2) + ")" + def __repr__(self): + return str(self) + + +# Subclasse Association +class Association(Relation): + def __init__(self,e1,assoc,e2): + Relation.__init__(self,e1,assoc,e2) + +# Exemplo: +# a = Association('socrates','professor','filosofia') + +# Subclasse Subtype +class Subtype(Relation): + def __init__(self,sub,super): + Relation.__init__(self,sub,"subtype",super) + + +# Exemplo: +# s = Subtype('homem','mamifero') + +# Subclasse Member +class Member(Relation): + def __init__(self,obj,type): + Relation.__init__(self,obj,"member",type) + +# Exemplo: +# m = Member('socrates','homem') + +# classe Declaration +# -- associa um utilizador a uma relacao por si inserida +# na rede semantica +# +class Declaration: + def __init__(self,user,rel): + self.user = user + self.relation = rel + def __str__(self): + return "decl("+str(self.user)+","+str(self.relation)+")" + def __repr__(self): + return str(self) + +# Exemplos: +# da = Declaration('descartes',a) +# ds = Declaration('darwin',s) +# dm = Declaration('descartes',m) + +# classe SemanticNetwork +# -- composta por um conjunto de declaracoes +# armazenado na forma de uma lista +# +class SemanticNetwork: + def __init__(self,ldecl=None): + self.declarations = [] if ldecl==None else ldecl + def __str__(self): + return str(self.declarations) + def insert(self,decl): + self.declarations.append(decl) + def query_local(self,user=None,e1=None,rel=None,e2=None): + self.query_result = \ + [ d for d in self.declarations + if (user == None or d.user==user) + and (e1 == None or d.relation.entity1 == e1) + and (rel == None or d.relation.name == rel) + and (e2 == None or d.relation.entity2 == e2) ] + return self.query_result + def show_query_result(self): + for d in self.query_result: + print(str(d)) + + diff --git a/sn_example.py b/sn_example.py new file mode 100755 index 0000000..9f71d34 --- /dev/null +++ b/sn_example.py @@ -0,0 +1,85 @@ + + + + +# Redes semanticas +# -- Exemplo +# +# Inteligencia Artificial & Introducao a Inteligencia Artificial +# DETI / UA +# +# (c) Luis Seabra Lopes, 2012-2019 +# 2019/10/20 +# + + +from semantic_network import * + +a = Association('socrates','professor','filosofia') +s = Subtype('homem','mamifero') +m = Member('socrates','homem') + +da = Declaration('descartes',a) +ds = Declaration('darwin',s) +dm = Declaration('descartes',m) + +z = SemanticNetwork() +z.insert(da) +z.insert(ds) +z.insert(dm) +z.insert(Declaration('darwin',Association('mamifero','mamar','sim'))) +z.insert(Declaration('darwin',Association('homem','gosta','carne'))) + +# novas declaracoes + +z.insert(Declaration('darwin',Subtype('mamifero','vertebrado'))) +z.insert(Declaration('descartes', Member('aristoteles','homem'))) + +b = Association('socrates','professor','matematica') +z.insert(Declaration('descartes',b)) +z.insert(Declaration('simao',b)) +z.insert(Declaration('simoes',b)) + +z.insert(Declaration('descartes', Member('platao','homem'))) + +e = Association('platao','professor','filosofia') +z.insert(Declaration('descartes',e)) +z.insert(Declaration('simao',e)) + +z.insert(Declaration('descartes',Association('mamifero','altura',1.2))) +z.insert(Declaration('descartes',Association('homem','altura',1.75))) +z.insert(Declaration('simao',Association('homem','altura',1.85))) +z.insert(Declaration('darwin',Association('homem','altura',1.75))) + +z.insert(Declaration('descartes', Association('socrates','peso',80))) +z.insert(Declaration('darwin', Association('socrates','peso',75))) +z.insert(Declaration('darwin', Association('platao','peso',75))) + + +z.insert(Declaration('damasio', Association('filosofo','gosta','filosofia'))) +z.insert(Declaration('damasio', Member('socrates','filosofo'))) + + +# Extra - descomentar as restantes declaracoes para o exercicio II.2.15 + +#z.insert(Declaration('descartes', AssocNum('socrates','pulsacao',51))) +#z.insert(Declaration('darwin', AssocNum('socrates','pulsacao',61))) +#z.insert(Declaration('darwin', AssocNum('platao','pulsacao',65))) + +#z.insert(Declaration('descartes',AssocNum('homem','temperatura',36.8))) +#z.insert(Declaration('simao',AssocNum('homem','temperatura',37.0))) +#z.insert(Declaration('darwin',AssocNum('homem','temperatura',37.1))) +#z.insert(Declaration('descartes',AssocNum('mamifero','temperatura',39.0))) + +#z.insert(Declaration('simao',Association('homem','gosta','carne'))) +#z.insert(Declaration('darwin',Association('homem','gosta','peixe'))) +#z.insert(Declaration('simao',Association('homem','gosta','peixe'))) +#z.insert(Declaration('simao',Association('homem','gosta','couves'))) + +#z.insert(Declaration('damasio', AssocOne('socrates','pai','sofronisco'))) +#z.insert(Declaration('darwin', AssocOne('socrates','pai','pericles'))) +#z.insert(Declaration('descartes', AssocOne('socrates','pai','sofronisco'))) + +print(z) + + diff --git a/sof2018h.py b/sof2018h.py new file mode 100644 index 0000000..4555364 --- /dev/null +++ b/sof2018h.py @@ -0,0 +1,8 @@ +from bayes_net import * + +bn = BayesNet() + +#variables = ['sc', 'pt', 'cp', 'fr', 'pa', 'cnl'] + +bn.add(None, [], 0) + diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..7b49369 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,7 @@ +import os +import sys +PROJECT_PATH = os.getcwd() +SOURCE_PATH = os.path.join( + PROJECT_PATH,"." +) +sys.path.append(SOURCE_PATH) diff --git a/tests/test_aula6.py b/tests/test_aula6.py new file mode 100644 index 0000000..eccc28c --- /dev/null +++ b/tests/test_aula6.py @@ -0,0 +1,79 @@ +import pytest +from semantic_network import * + +@pytest.fixture +def sn_net(): + + a = Association('socrates','professor','filosofia') + s = Subtype('homem','mamifero') + m = Member('socrates','homem') + + da = Declaration('descartes',a) + ds = Declaration('darwin',s) + dm = Declaration('descartes',m) + + z = SemanticNetwork() + z.insert(da) + z.insert(ds) + z.insert(dm) + z.insert(Declaration('darwin',Association('mamifero','mamar','sim'))) + z.insert(Declaration('darwin',Association('homem','gosta','carne'))) + + # novas declaracoes + + z.insert(Declaration('darwin',Subtype('mamifero','vertebrado'))) + z.insert(Declaration('descartes', Member('aristoteles','homem'))) + + b = Association('socrates','professor','matematica') + z.insert(Declaration('descartes',b)) + z.insert(Declaration('simao',b)) + z.insert(Declaration('simoes',b)) + + z.insert(Declaration('descartes', Member('platao','homem'))) + + e = Association('platao','professor','filosofia') + z.insert(Declaration('descartes',e)) + z.insert(Declaration('simao',e)) + + z.insert(Declaration('descartes',Association('mamifero','altura',1.2))) + z.insert(Declaration('descartes',Association('homem','altura',1.75))) + z.insert(Declaration('simao',Association('homem','altura',1.85))) + z.insert(Declaration('darwin',Association('homem','altura',1.75))) + + z.insert(Declaration('descartes', Association('socrates','peso',80))) + z.insert(Declaration('darwin', Association('socrates','peso',75))) + z.insert(Declaration('darwin', Association('platao','peso',75))) + + + z.insert(Declaration('damasio', Association('filosofo','gosta','filosofia'))) + z.insert(Declaration('damasio', Member('socrates','filosofo'))) + + return z + +def test_exercicio1(sn_net): + assert sorted(sn_net.list_associations()) == ['altura', 'gosta', 'mamar', 'peso', 'professor'] + +def test_exercicio2(sn_net): + assert sorted(sn_net.list_objects()) == ['aristoteles', 'platao', 'socrates'] + +def test_exercicio3(sn_net): + assert sorted(sn_net.list_users()) == ['damasio', 'darwin', 'descartes', 'simao', 'simoes'] + +def test_exercicio4(sn_net): + assert sorted(sn_net.list_types()) == ['filosofo', 'homem', 'mamifero', 'vertebrado'] + +def test_exercicio5(sn_net): + assert sorted(sn_net.list_local_associations('socrates')) == ['peso', 'professor'] + +def test_exercicio6(sn_net): + assert sorted(sn_net.list_relations_by_user('descartes')) == ['altura', 'member', 'peso', 'professor'] + +def test_exercicio7(sn_net): + assert sn_net.associations_by_user('descartes') == 3 + +def test_exercicio8(sn_net): + assert sorted(sn_net.list_local_associations_by_entity('socrates')) == [('peso', 'darwin'), ('peso', 'descartes'), ('professor', 'descartes'), ('professor', 'simao'), ('professor', 'simoes')] + +def test_exercicio9(sn_net): + assert sn_net.predecessor('vertebrado','socrates') + assert not sn_net.predecessor('vertebrado','filosofo') diff --git a/tests/test_aula7.py b/tests/test_aula7.py new file mode 100644 index 0000000..8fa8f93 --- /dev/null +++ b/tests/test_aula7.py @@ -0,0 +1,63 @@ +import pytest +from semantic_network import * +from tests.test_aula6 import sn_net + +def compare_decl_lists(l1,l2): + l1_tuples = [str(d) for d in l1] + l2_tuples = [str(d) for d in l2] + return len(l1_tuples)==len(l2_tuples) and set(l1_tuples)==set(l2_tuples) + +def test_exercicio10(sn_net): + assert sn_net.predecessor_path('vertebrado','socrates') == ['vertebrado', 'mamifero', 'homem', 'socrates'] + +def test_exercicio11(sn_net): + assert compare_decl_lists(sn_net.query('socrates','altura'),[ +Declaration('descartes',Association('mamifero','altura',1.2)), \ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75))] ) + + assert compare_decl_lists(sn_net.query('platao'), [ +Declaration('darwin',Association('mamifero','mamar','sim')), \ +Declaration('descartes',Association('mamifero','altura',1.2)), \ +Declaration('darwin',Association('homem','gosta','carne')), \ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75)), \ +Declaration('descartes',Association('platao','professor','filosofia')), \ +Declaration('simao',Association('platao','professor','filosofia')), \ +Declaration('darwin',Association('platao','peso',75))] ) + + assert compare_decl_lists(sn_net.query2('platao'), [ +Declaration('darwin',Association('mamifero','mamar','sim')), \ +Declaration('descartes',Association('mamifero','altura',1.2)), \ +Declaration('darwin',Association('homem','gosta','carne')), \ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75)), \ +Declaration('descartes',Association('platao','professor','filosofia')), \ +Declaration('simao',Association('platao','professor','filosofia')), \ +Declaration('darwin',Association('platao','peso',75)), \ +Declaration('descartes',Member('platao','homem'))] ) + +def test_exercicio12(sn_net): + assert compare_decl_lists(sn_net.query_cancel('socrates','altura'), [ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75))] ) + +def test_exercicio13(sn_net): + assert compare_decl_lists(sn_net.query_down('vertebrado', 'altura'), [ +Declaration('descartes',Association('mamifero','altura',1.2)), \ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75))] ) + + assert compare_decl_lists(sn_net.query_down('mamifero', 'altura'), [ +Declaration('descartes',Association('homem','altura',1.75)), \ +Declaration('simao',Association('homem','altura',1.85)), \ +Declaration('darwin',Association('homem','altura',1.75))] ) + + assert compare_decl_lists(sn_net.query_down('homem', 'altura'), []) + + diff --git a/tests/test_aula8.py b/tests/test_aula8.py new file mode 100644 index 0000000..b9d988e --- /dev/null +++ b/tests/test_aula8.py @@ -0,0 +1,92 @@ +import pytest +from semantic_network import * +from tests.test_aula6 import sn_net + + +@pytest.fixture +def sn_net2(): + + a = Association('socrates','professor','filosofia') + s = Subtype('homem','mamifero') + m = Member('socrates','homem') + + da = Declaration('descartes',a) + ds = Declaration('darwin',s) + dm = Declaration('descartes',m) + + z = SemanticNetwork() + z.insert(da) + z.insert(ds) + z.insert(dm) + z.insert(Declaration('darwin',Association('mamifero','mamar','sim'))) + z.insert(Declaration('darwin',Association('homem','gosta','carne'))) + + z.insert(Declaration('darwin',Subtype('mamifero','vertebrado'))) + z.insert(Declaration('descartes', Member('aristoteles','homem'))) + + b = Association('socrates','professor','matematica') + z.insert(Declaration('descartes',b)) + z.insert(Declaration('simao',b)) + z.insert(Declaration('simoes',b)) + + z.insert(Declaration('descartes', Member('platao','homem'))) + + e = Association('platao','professor','filosofia') + z.insert(Declaration('descartes',e)) + z.insert(Declaration('simao',e)) + + z.insert(Declaration('descartes',Association('mamifero','altura',1.2))) + z.insert(Declaration('descartes',Association('homem','altura',1.75))) + z.insert(Declaration('simao',Association('homem','altura',1.85))) + z.insert(Declaration('darwin',Association('homem','altura',1.75))) + + z.insert(Declaration('descartes', Association('socrates','peso',80))) + z.insert(Declaration('darwin', Association('socrates','peso',75))) + z.insert(Declaration('darwin', Association('platao','peso',75))) + + + z.insert(Declaration('damasio', Association('filosofo','gosta','filosofia'))) + z.insert(Declaration('damasio', Member('socrates','filosofo'))) + + z.insert(Declaration('descartes', AssocNum('socrates','pulsacao',51))) + z.insert(Declaration('darwin', AssocNum('socrates','pulsacao',61))) + z.insert(Declaration('darwin', AssocNum('platao','pulsacao',65))) + + z.insert(Declaration('descartes',AssocNum('homem','temperatura',36.8))) + z.insert(Declaration('simao',AssocNum('homem','temperatura',37.0))) + z.insert(Declaration('darwin',AssocNum('homem','temperatura',37.1))) + z.insert(Declaration('descartes',AssocNum('mamifero','temperatura',39.0))) + + z.insert(Declaration('simao',Association('homem','gosta','carne'))) + z.insert(Declaration('darwin',Association('homem','gosta','peixe'))) + z.insert(Declaration('simao',Association('homem','gosta','peixe'))) + z.insert(Declaration('simao',Association('homem','gosta','couves'))) + + z.insert(Declaration('damasio', AssocOne('socrates','pai','sofronisco'))) + z.insert(Declaration('darwin', AssocOne('socrates','pai','pericles'))) + z.insert(Declaration('descartes', AssocOne('socrates','pai','sofronisco'))) + + return z + + +def compare_decl_lists(l1, l2): + l1_tuples = [str(d) for d in l1] + l2_tuples = [str(d) for d in l2] + return len(l1_tuples)==len(l2_tuples) and set(l1_tuples) == set(l2_tuples) + + +def test_exercicio14(sn_net): + assert sn_net.query_induce('vertebrado', 'altura') == 1.75 + + +def test_exercicio15(sn_net2): + assert sn_net2.query_local_assoc('socrates', 'pai') == ('sofronisco', 2/3) + + assert sn_net2.query_local_assoc('socrates', 'pulsacao') == 56 + + assert sn_net2.query_local_assoc('homem', 'gosta') == [('carne', 0.40), ('peixe', 0.40)] + + +def test_exercicio16(sn_net2): + assert sn_net2.query_assoc_value('socrates', 'altura') == 1.75 + assert sn_net2.query_assoc_value('socrates', 'peso') == 80 diff --git a/tests/test_aula9.py b/tests/test_aula9.py new file mode 100644 index 0000000..0919997 --- /dev/null +++ b/tests/test_aula9.py @@ -0,0 +1,21 @@ + +import pytest +import sof2018h + +def test_exercicio15(): + assert all([k in ['sc', 'pt', 'cp', 'fr', 'pa', 'cnl'] for k in sof2018h.bn.dependencies.keys()]) + + assert len(sof2018h.bn.dependencies['sc']) == 1 + assert len(sof2018h.bn.dependencies['pt']) == 1 + assert len(sof2018h.bn.dependencies['cp']) == 4 + assert len(sof2018h.bn.dependencies['fr']) == 4 + assert len(sof2018h.bn.dependencies['pa']) == 2 + assert len(sof2018h.bn.dependencies['cnl']) == 2 + + assert sof2018h.bn.jointProb([(v,True) for v in sof2018h.bn.dependencies]) == 0.0001215 + + assert sof2018h.bn.jointProb([('sc', True)]) == round(sof2018h.bn.individualProb('sc', True),5) + assert sof2018h.bn.jointProb([('pt', False)]) == round(sof2018h.bn.individualProb('pt', False),5) + + assert round(sof2018h.bn.individualProb('pa', True),5) == 0.0163 +