# -*- coding: utf-8 -*-
"""
This is a good example to run first to check that Netica-Py is working properly

Chest Clinic example program using Netica-Py

Creates a simple bayes net and does bayesian inference

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

net = env.new_net("ChestClinic")

VisitAsia = net.new_node("VisitAsia", "visit, no_visit")
#Alternate way: 
#VisitAsia = net.new_node("VisitAsia", 2)
#VisitAsia.state_names = "visit, no_visit"
Tuberculosis = net.new_node("Tuberculosis", "present, absent")
Smoking = net.new_node("Smoking", "smoker, nonsmoker")
Cancer = net.new_node("Cancer", "present, absent")
TbOrCa = net.new_node("TbOrCa", "true, false")
XRay = net.new_node("XRay", "abnormal, normal")

TbOrCa.title = "Tuberculosis or Cancer"
Cancer.title = "Lung Cancer"

Tuberculosis.add_link_from(VisitAsia)
Cancer.add_link_from(Smoking)
TbOrCa.add_link_from(Tuberculosis)
TbOrCa.add_link_from(Cancer)
XRay.add_link_from(TbOrCa)

VisitAsia.set_CPT(None, [0.01, 0.99])    

Tuberculosis.set_CPT("visit", [0.05, 0.95])
Tuberculosis.set_CPT("no_visit", [0.01, 0.99])

Smoking.set_CPT(None, [0.5, 0.5])

Cancer.set_CPT("smoker", [0.1, 0.9])
Cancer.set_CPT("nonsmoker", [0.01, 0.99])

"""           |Tuberculosis| |Cancer|         """
TbOrCa.set_CPT("present, present", [1.0, 0.0])
TbOrCa.set_CPT("present, absent", [1.0, 0.0])
TbOrCa.set_CPT("absent, present", [1.0, 0.0])
TbOrCa.set_CPT("absent, absent", [0.0, 1.0])

#Alternate way:
#TbOrCa.set_CPT([0, 0], [1.0, 0.0])
#TbOrCa.set_CPT([0, 1], [1.0, 0.0])
#TbOrCa.set_CPT([1, 0], [1.0, 0.0])
#TbOrCa.set_CPT([1, 1], [0.0, 1.0])

#Alternate way:
#TbOrCa.equation = "TbOrCa (Tuberculosis, Cancer) = Tuberculosis == present  ||  Cancer == present"
#TbOrCa.equation_to_table(1, false, false)

#Alternate way (fastest):
#TbOrCa.set_CPT(None, [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0])


"""           |TbOrCa| |Abnormal| |Normal|    """
XRay.set_CPT("true",   [0.98,    0.02])
XRay.set_CPT("false",  [0.05,    0.95])

net.compile_()

belief = Tuberculosis.get_beliefs()

print("\nThe probability of tuberculosis is %.6f" % belief[0])

XRay.enter_finding(0)

print("\nGiven an abnormal X-ray, \n\
         the probability of tuberculosis is %.6f" % 
         Tuberculosis.get_beliefs()[0]);

VisitAsia.enter_finding(0)

print("\nGiven an abnormal X-ray and a visit to Asia, \n\
	     the probability of tuberculosis is %.6f" % 
         Tuberculosis.get_beliefs()[0]);

Cancer.enter_finding(0)

print("\nGiven abnormal X-ray, Asia visit, and lung cancer, \n\
         the probability of tuberculosis is %.6f" % 
         Tuberculosis.get_beliefs()[0]);

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