# -*- coding: utf-8 -*-
"""
Learns the CPTs of all nodes in a model containing a latent (hidden) variable
that is the parent of several variables.

For netica version 6.05 or later

@author: Sophie
"""
import sys, os
sys.path.append(os.path.abspath('..'))
import neticapy as netica

env = netica.Environ()
    
'''Build the net'''

net = netica.Net('Learned_Latent')

R = net.new_node('R', 'false, true')
S = net.new_node('S', 'false, true')
T = net.new_node('T', 'false, true')

# Alternate Way:
#R = net.new_node('R', 2)
#R.set_state_name(0, 'false')
#R.set_state_name(1, 'true')

A = net.new_node('A', 2)    # The latent node; trying 2 states
# A = net.new_node ('A', 3) # the latent node; trying 3 states

R.add_link_from(A)
S.add_link_from(A)
T.add_link_from(A)

nodes = net.nodes

'''Read the case file into a caseset'''

cases = netica.Caseset('LearnLatentCases')
casefile = netica.Stream('Data Files/LearnLatent.cas')
cases.add_cases_from_file(casefile, 1.0)

learner = netica.Learner("EM")
learner.max_iterations = 1000000
learner.set_tolerance = 1e-15

learner.learn_CPTs(nodes, cases, 1.0)

net.write(netica.Stream('Data Files/Learned_Latent.dne'))

print('Created file Learned_Latent.dne containing the EM learned net.\n')

res, mesg = env.close_netica()
print(mesg)