# -*- 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('..\\src'))
import neticapy

env = neticapy.Environ()
res, mesg = env.init_netica()
print(mesg)
if res < 0:
    raise SystemExit
    
'''Build the net'''

net = env.new_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 = env.new_caseset('LearnLatentCases')
casefile = env.new_file_stream('Data Files\\LearnLatent.cas')
cases.add_file(casefile, 1.0)

learner = env.new_learner(neticapy.LearningMethod.EM)
learner.set_max_iters(1000000)
learner.set_max_tol(1e-15)

learner.learn_CPTs(nodes, cases, 1.0)

net.write(env.new_file_stream('Data Files\\Learned_Latent.dne'))

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

learner.delete()
casefile.delete()
cases.delete()
net.delete()
res, mesg = env.close_netica()
print(mesg)