Esempio n. 1
0
asia_graph = DiscreteBayesNet([
    asia, tuberculosis, tborca, x_ray, dyspnea, bronchitis, smoking,
    lung_cancer
])
exp_var = [
    'Lung_Cancer', 'VisitToAsia', 'Tuberculosis', 'Smoking', 'Bronchitis'
]
explanadum = {'X_ray': 'abnormal'}

print "Testing MRE:"
MRE = generate_MRE(asia_graph, exp_var, explanadum)
print MRE
print "========================="

print "Testing K-MRE:"
K_MRE = generate_K_MRE(MRE)
print K_MRE
print "========================="

print "Testing Explanation Tree:"
test_tree = generate_explanation_tree(asia_graph, exp_var, explanadum, [],
                                      0.01, 0.2)
print test_tree
print "========================="

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(asia_graph, asia_graph, exp_var,
                                             {}, explanadum, [], 0.001)
print test_tree
print "========================="
Esempio n. 2
0
print "Testing K-MRE:"
K_MRE = generate_K_MRE(MRE)
for x in K_MRE:
    print x
print "========================="

print "Testing Causal Intervention:"
print "Intervene Bird to true"
intervened = lake_graph.create_graph_with_intervention({'Bird' : 'T'})
print "post intervention probability of Bird being true", intervened.prob( {'Bird' : 'T'} )
print "post intervention prob of Pox being true", intervened.prob( {'Pox':'T'} )
print "========================="

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(lake_graph, lake_graph, ['Bird', 'Island'], {}, {'Pox':'T'}, [], 0.0001) 
print test_tree
print "========================="


print "Testing Explanation Forest:"
forest = generate_CET_forest(lake_graph, lake_graph, ['Bird', 'Island'], {}, {'Pox':'T'}, []) 
for tree in forest:
    print tree
print "========================="


print "Testing scores calculations of different methods:"
print "BGF of [Island being true]: ", calculate_GBF( lake_graph, {"Island" : "T" }, {"Pox" : "T"} )
print "BGF of [Bird being true, Island being false]: ", calculate_GBF( lake_graph, {"Island" : "T", "Bird" : "T" }, {"Pox" : "T"} )
print "ET score of [Island being true], which is essentially posterior probability of the explanation given explanadum : ", calculate_ET_score( lake_graph, {"Island" : "T"}, {"Pox" : "T"})
Esempio n. 3
0
                ("off", "on", "off"): [1, 0],
                ("off", "on", "on"): [1, 0],
                ("off", "off", "on"): [1, 0],
                ("off", "off", "off"): [0, 1],
            },
        ),
    )

cur_input = DiscreteBayesNode("Input", [], DiscreteCPT(["on", "off"], [1, 0]))

circuit_graph = DiscreteBayesNet([a, b, c, d, a_out, b_out, c_out, d_out, out, cur_input])


print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(
    circuit_graph, circuit_graph, ["A_switch", "B_switch", "C_switch", "D_switch"], {}, {"Output": "on"}, [], 0.001
)
print test_tree
print "========================="

# print "Testing Explanation Tree:"
# test_tree = generate_explanation_tree(circuit_graph, ['A_switch', 'B_switch', 'C_switch', 'D_switch'], {'Output':'on'}, [], 0.01, 0.2)
# print test_tree
# print "========================="


# print "Testing MRE:"
# MRE = generate_MRE(circuit_graph, ['A_switch', 'B_switch', 'C_switch', 'D_switch'], {'Output':'on', 'Input':'on'})
# for x in MRE:
#     print x
# #print MRE
Esempio n. 4
0
K_MRE = generate_K_MRE(MRE)
for x in K_MRE:
    print x
print "========================="

print "Testing Causal Intervention:"
print "Intervene Bird to true"
intervened = lake_graph.create_graph_with_intervention({'Bird': 'T'})
print "post intervention probability of Bird being true", intervened.prob(
    {'Bird': 'T'})
print "post intervention prob of Pox being true", intervened.prob({'Pox': 'T'})
print "========================="

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(lake_graph, lake_graph,
                                             ['Bird', 'Island'], {},
                                             {'Pox': 'T'}, [], 0.0001)
print test_tree
print "========================="

print "Testing Explanation Forest:"
forest = generate_CET_forest(lake_graph, lake_graph, ['Bird', 'Island'], {},
                             {'Pox': 'T'}, [])
for tree in forest:
    print tree
print "========================="

print "Testing scores calculations of different methods:"
print "BGF of [Island being true]: ", calculate_GBF(lake_graph,
                                                    {"Island": "T"},
                                                    {"Pox": "T"})
Esempio n. 5
0
    ["TborCa", "Bronchitis"],
    DiscreteCPT(
        ["yes", "no"],
        {("yes", "yes"): [0.9, 0.1], ("yes", "no"): [0.7, 0.3], ("no", "yes"): [0.8, 0.2], ("no", "no"): [0.1, 0.9]},
    ),
)

asia_graph = DiscreteBayesNet([asia, tuberculosis, tborca, x_ray, dyspnea, bronchitis, smoking, lung_cancer])
exp_var = ["Lung_Cancer", "VisitToAsia", "Tuberculosis", "Smoking", "Bronchitis"]
explanadum = {"X_ray": "abnormal"}

print "Testing MRE:"
MRE = generate_MRE(asia_graph, exp_var, explanadum)
print MRE
print "========================="

print "Testing K-MRE:"
K_MRE = generate_K_MRE(MRE)
print K_MRE
print "========================="

print "Testing Explanation Tree:"
test_tree = generate_explanation_tree(asia_graph, exp_var, explanadum, [], 0.01, 0.2)
print test_tree
print "========================="

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(asia_graph, asia_graph, exp_var, {}, explanadum, [], 0.001)
print test_tree
print "========================="
def fill_in_csv(graph, exp_var, explanadum, path = "temp.csv", lake = 0):
	# Assume for now that the codes in csv use the some scheme as implied
    # by this script
    assignments = []
    code_hash = encode_nodes_to_hash([graph.variables[name] for name in exp_var])
    MPE_space = generate_MPE(graph, exp_var, explanadum)
    MAP_threshold = 0.1
    MAP_space = generate_MAP_Ind_Simplification(graph, exp_var, explanadum, MAP_threshold)
    MRE_space = generate_MRE(graph, exp_var, explanadum)

    alpha = 0.01
    beta = 0.2
    ET = generate_explanation_tree(graph, exp_var, explanadum, [], alpha, beta)
    ET_space = sorted(ET.assignment_space(), key = lambda x: -x[1])
    ET_score_space = sorted(
    		[(code_hash[key], calculate_ET_score(graph, code_hash[key], explanadum)) for key in code_hash.keys() if len(code_hash[key])],
    		key = lambda x: -x[1])
    # print ET_score_space

    alpha_CET = 0.0001
    CET = generate_causal_explanation_tree(graph, graph, exp_var, {}, explanadum, [], alpha_CET)
    # print "Printing cet", CET
    CET_space = sorted(CET.assignment_space(), key = lambda x: -x[1])
    CET_score_space = sorted(
    		[(code_hash[key], calculate_CET_score(graph, code_hash[key], {}, explanadum)) for key in code_hash.keys() if len(code_hash[key])],
    		key = lambda x: -x[1] if not math.isnan(x[1]) else 9999999999999)
    # print CET_score_space

    with open(path, 'r') as csvfile:
    	reader = csv.reader(csvfile, dialect = 'excel')
    	for row in reader:
    		processed_code = join([row[0][i] for i in range(len(exp_var))], "")
    		assignments.append((row[0], code_hash[processed_code]))

    # print assignments
    with open(path, 'w') as csvfile:
   		writer = csv.writer(csvfile, dialect = 'excel') 
   		writer.writerow(["CondensedString","MPE_rank","MPE_score","MAP_I_rank","MAP_I_score","MAP_I_para_theta","MRE_rank","MRE_score","ET_rank_for_tree","ET_rank_for_score","ET_score","ET_leaf","ET_ALPHA","ET_BETA","CET_rank_for_tree","CET_rank_for_score","CET_score","CET_leaf","CET_ALPHA"])
   		for code, assignment in assignments:
   			row = ['"' + code + '"']
   			# escape all empty explanations
   			# and all invalid assignemnts for lake.py
   			print lake, code[2] != '9', code[3] != '9'
   			if (not len(assignment)) or (lake and (code[2] != '9' or code[3] != '9')):
   				print "escaping"
   				row += ["NaN" for _ in range(18)]
   				writer.writerow(row)
   				continue

   			rank = space_rank(MPE_space, assignment)
   			if rank:
	   			row.append(rank)# MPE rank
	   			row.append(MPE_space[int(rank) - 1][1]) # MPE score
	   		else:
	   			row.append("NaN")
	   			row.append("NaN")

	   		rank = space_rank(MAP_space, assignment)
	   		if rank:
	   			row.append(rank)# map rank
	   			row.append(MAP_space[int(rank) - 1][1]) # MAP score
	   		else:
	   			row.append("NaN")
	   			row.append("NaN")

	   		row.append(MAP_threshold)

	   		rank = space_rank(MRE_space, assignment)
	   		if rank:
	   			row.append(rank)# mre rank
	   			row.append(MRE_space[int(rank) - 1][1]) # MRE score
	   		else:
	   			row.append("NaN")
	   			row.append("NaN")

	   		rank = space_rank(ET_space, assignment)
	   		if rank:
	   			row.append(rank)# et tree rank
	   		else:
	   			row.append("NaN")

	   		rank = space_rank(ET_score_space, assignment)
	   		# print code, assignment, rank, ET_score_space[int(rank) - 1][1]
	   		if rank:
	   			row.append(rank) # et score rank
	   			row.append(ET_score_space[int(rank) - 1][1]) # ET score
	   		else:
	   			row.append("ERROR ! should not happen") #should not happen

	   		row += [1] if ET.is_leaf(assignment) else [0]
	   		row.append(alpha)
	   		row.append(beta)

	   		rank = space_rank(CET_space, assignment)
	   		if rank:
	   			row.append(rank)# et tree rank
	   		else:
	   			row.append("NaN")

	   		rank = space_rank(CET_score_space, assignment)
	   		if rank:
	   			row.append(rank) # et score rank
	   			row.append(CET_score_space[int(rank) - 1][1]) # ET score
	   		else:
	   			row.append("ERROR ! should not happen") #should not happen

	   		# print "determining leaf for", code
	   		row += [1] if CET.is_leaf(assignment) else [0]
	   		row.append(alpha_CET)

   			writer.writerow(row)
Esempio n. 7
0
						DiscreteCPT(['f', 'm'], [.5, .5]))

drug = DiscreteBayesNode('Drug', ['Sex'], \
						DiscreteCPT(['yes', 'no'], 
							{('f', ):[.25, .75], 
							 ('m', ):[.75, .25]}))
recovery = DiscreteBayesNode('Recovery', ['Sex', 'Drug'], \
							DiscreteCPT(['recovery', 'death'],
								{
								('f', 'yes'):[.2, .8],
								('f', 'no'):[.3, .7],
								('m', 'yes'):[.6, .4],
								('m', 'no'):[.7, .3]
								}))

drug_graph = DiscreteBayesNet( [sex, drug, recovery])

print "Testing Explanation Tree:"
test_tree = generate_explanation_tree(drug_graph, ['Sex', 'Drug'], {'Recovery':'recovery'}, [], 0.01, 0.2) 
print test_tree
print "========================="

print "Testing MRE:"
MRE = generate_MRE(drug_graph, ['Sex', 'Drug'], {'Recovery':'recovery'})
print MRE
print "========================="

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(drug_graph, drug_graph, ['Sex', 'Drug'], {},{'Recovery':'recovery'}, [], 0.001) 
print test_tree
print "========================="
Esempio n. 8
0
                                    ('on', 'off', 'on') : [1, 0],
                                    ('on', 'off', 'off') : [1, 0],
                                    ('off', 'on', 'off') : [1, 0],
                                    ('off', 'on', 'on') : [1, 0],
                                    ('off', 'off', 'on') : [1, 0],
                                    ('off', 'off', 'off') : [0, 1],
                                }))

cur_input = DiscreteBayesNode('Input', [], DiscreteCPT(['on', 'off'], [1, 0]))

circuit_graph = DiscreteBayesNet(
    [a, b, c, d, a_out, b_out, c_out, d_out, out, cur_input])

print "Testing Causal Explanation Tree:"
test_tree = generate_causal_explanation_tree(
    circuit_graph, circuit_graph,
    ['A_switch', 'B_switch', 'C_switch', 'D_switch'], {}, {'Output': 'on'}, [],
    0.001)
print test_tree
print "========================="

# print "Testing Explanation Tree:"
# test_tree = generate_explanation_tree(circuit_graph, ['A_switch', 'B_switch', 'C_switch', 'D_switch'], {'Output':'on'}, [], 0.01, 0.2)
# print test_tree
# print "========================="

# print "Testing MRE:"
# MRE = generate_MRE(circuit_graph, ['A_switch', 'B_switch', 'C_switch', 'D_switch'], {'Output':'on', 'Input':'on'})
# for x in MRE:
#     print x
# #print MRE
# print "========================="
Esempio n. 9
0
def fill_in_csv(graph, exp_var, explanadum, path="temp.csv", lake=0):
    # Assume for now that the codes in csv use the some scheme as implied
    # by this script
    assignments = []
    code_hash = encode_nodes_to_hash(
        [graph.variables[name] for name in exp_var])
    MPE_space = generate_MPE(graph, exp_var, explanadum)
    MAP_threshold = 0.1
    MAP_space = generate_MAP_Ind_Simplification(graph, exp_var, explanadum,
                                                MAP_threshold)
    MRE_space = generate_MRE(graph, exp_var, explanadum)

    alpha = 0.01
    beta = 0.2
    ET = generate_explanation_tree(graph, exp_var, explanadum, [], alpha, beta)
    ET_space = sorted(ET.assignment_space(), key=lambda x: -x[1])
    ET_score_space = sorted([
        (code_hash[key], calculate_ET_score(graph, code_hash[key], explanadum))
        for key in code_hash.keys() if len(code_hash[key])
    ],
                            key=lambda x: -x[1])
    # print ET_score_space

    alpha_CET = 0.0001
    CET = generate_causal_explanation_tree(graph, graph, exp_var, {},
                                           explanadum, [], alpha_CET)
    # print "Printing cet", CET
    CET_space = sorted(CET.assignment_space(), key=lambda x: -x[1])
    CET_score_space = sorted(
        [(code_hash[key],
          calculate_CET_score(graph, code_hash[key], {}, explanadum))
         for key in code_hash.keys() if len(code_hash[key])],
        key=lambda x: -x[1] if not math.isnan(x[1]) else 9999999999999)
    # print CET_score_space

    with open(path, 'r') as csvfile:
        reader = csv.reader(csvfile, dialect='excel')
        for row in reader:
            processed_code = join([row[0][i] for i in range(len(exp_var))], "")
            assignments.append((row[0], code_hash[processed_code]))

    # print assignments
    with open(path, 'w') as csvfile:
        writer = csv.writer(csvfile, dialect='excel')
        writer.writerow([
            "CondensedString", "MPE_rank", "MPE_score", "MAP_I_rank",
            "MAP_I_score", "MAP_I_para_theta", "MRE_rank", "MRE_score",
            "ET_rank_for_tree", "ET_rank_for_score", "ET_score", "ET_leaf",
            "ET_ALPHA", "ET_BETA", "CET_rank_for_tree", "CET_rank_for_score",
            "CET_score", "CET_leaf", "CET_ALPHA"
        ])
        for code, assignment in assignments:
            row = ['"' + code + '"']
            # escape all empty explanations
            # and all invalid assignemnts for lake.py
            print lake, code[2] != '9', code[3] != '9'
            if (not len(assignment)) or (lake and
                                         (code[2] != '9' or code[3] != '9')):
                print "escaping"
                row += ["NaN" for _ in range(18)]
                writer.writerow(row)
                continue

            rank = space_rank(MPE_space, assignment)
            if rank:
                row.append(rank)  # MPE rank
                row.append(MPE_space[int(rank) - 1][1])  # MPE score
            else:
                row.append("NaN")
                row.append("NaN")

            rank = space_rank(MAP_space, assignment)
            if rank:
                row.append(rank)  # map rank
                row.append(MAP_space[int(rank) - 1][1])  # MAP score
            else:
                row.append("NaN")
                row.append("NaN")

            row.append(MAP_threshold)

            rank = space_rank(MRE_space, assignment)
            if rank:
                row.append(rank)  # mre rank
                row.append(MRE_space[int(rank) - 1][1])  # MRE score
            else:
                row.append("NaN")
                row.append("NaN")

            rank = space_rank(ET_space, assignment)
            if rank:
                row.append(rank)  # et tree rank
            else:
                row.append("NaN")

            rank = space_rank(ET_score_space, assignment)
            # print code, assignment, rank, ET_score_space[int(rank) - 1][1]
            if rank:
                row.append(rank)  # et score rank
                row.append(ET_score_space[int(rank) - 1][1])  # ET score
            else:
                row.append("ERROR ! should not happen")  #should not happen

            row += [1] if ET.is_leaf(assignment) else [0]
            row.append(alpha)
            row.append(beta)

            rank = space_rank(CET_space, assignment)
            if rank:
                row.append(rank)  # et tree rank
            else:
                row.append("NaN")

            rank = space_rank(CET_score_space, assignment)
            if rank:
                row.append(rank)  # et score rank
                row.append(CET_score_space[int(rank) - 1][1])  # ET score
            else:
                row.append("ERROR ! should not happen")  #should not happen

# print "determining leaf for", code
            row += [1] if CET.is_leaf(assignment) else [0]
            row.append(alpha_CET)

            writer.writerow(row)