# -*- coding: utf-8 -*-
"""
Reads in Bayes net 'ChestClinic.dne' built by the BuildNet example,
removes its CPTs, and then learns new ones from the casefile 'ChestClinic.cas'
(built by SimulateCases example).

It outputs the final net to file 'Learned_ChestClinic.dne'.

For netica version 6.05 or later

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

env = netica.Environ()

orig_net = netica.Net(None, "Data Files/ChestClinic.dne")
orig_nodes = orig_net.nodes
orig_netauto_update = 0

learned_net = netica.Net("Learned_ChestClinic")
learned_nodes = learned_net.copy_nodes(orig_nodes)
numnodes = learned_nodes.length

''' Remove CPTables of nodes in learned_net, so new ones can be learned. '''

for i in range(0, numnodes):
    learned_nodes.get_nth_node(i).delete_tables()
	
''' Read in the case file created by the the SimulateCases.py
	   example program, and learn new CPTables. '''

df = pd.read_csv("Data Files/ChestClinic.cas", sep='\t', index_col=0)
# print(df.to_string(header=["IDnum", "VisitAsia", "Tuberculosis", "Smoking", "ancer", "TbOrCa", "XRay", "Bronchitis", "Dyspmeeea"]))
#print(df)

# casefile = netica.Stream("Data Files/ChestClinic.cas")  
casefile = netica.Stream('strm', memory=True)
casefile.set_contents(df.to_string(index=False))        
learned_net.revise_CPTs_by_case_file(casefile, learned_nodes, 1)

learned_net.write(netica.Stream("Data Files/Learned_ChestClinic.dne"))

print("Used the case file to learn all the CPTs, and put the resulting net in 'Data Files/Learned_ChestClinic.cas'\n")

res, mesg = env.close_netica()
print('\n' + mesg)