def pytest_funcarg__monty_hall_graph(request):
    g = build_bbn(
        f_guest_door, f_prize_door, f_monty_door,
        domains={
            'guest_door': ['A', 'B', 'C'],
            'monty_door': ['A', 'B', 'C'],
            'prize_door': ['A', 'B', 'C']})
    return g
Example #2
0
    def __export__(self, iterations, screen=True, file=True, pdf=True):
        _str = 'Finished inference in ' + str(iterations) + ' iterations.\n'
        _str += 'Evaluations: ' + str(iterations * self.population_size) + '\n'
        _str += 'Population size: ' + str(self.population_size) + '\n'
        _str += 'Nodes: ' + str(self.model_graph.count_nodes) + '\n'
        _str += 'Colors: ' + str(len(self.palette)) + '\n'
        _str += 'Best individual fitness: ' + str(round(self.__best_individual__().fitness, 2)) + "\n"
        _str += 'Marginalization matrix:\n'

        some_bbn = build_bbn(
            *self._bbn_functions.values(),  # unzips list
            domains=dict([(x, self.palette) for x in self.node_names])
        )

        print _str
        some_bbn.q()

        _dict = copy.deepcopy(self.dependencies)
        del _dict[None]

        if pdf:
            bbn = graphviz.Digraph()
            [bbn.node(x) for x in self.node_names]

            bbn.edges(_dict.items())
            bbn.render('bbn.gv')

            self.__best_individual__().export('optimal')

        if file:
            query = some_bbn.query().items()
            query = '\n'.join([str(x) for x in query])

            with open('output.txt', 'w') as file:
                file.write(_str)
                file.write(query)

        if screen:
            def plot_bbn():
                plt.figure(1)
                G = nx.DiGraph()
                G.add_edges_from(_dict.items())
                layout = nx.shell_layout(G)
                nx.draw_networkx(G, pos=layout, cmap=plt.get_cmap('jet'), node_color=list(itertools.repeat('cyan', len(self.node_names))))

            def plot_optimal():
                plt.figure(2)
                individual = self.__best_individual__()
                G = nx.Graph()
                G.add_nodes_from(individual.names)
                some_edges = [tuple(list(x)) for x in individual.edges]
                G.add_edges_from(some_edges)
                layout = nx.shell_layout(G)
                nx.draw_networkx(G, pos=layout, cmap=plt.get_cmap('jet'), node_color=individual.colors)

            plot_bbn()
            plot_optimal()
            plt.show()
def pytest_funcarg__monty_hall_graph(request):
    g = build_bbn(f_guest_door,
                  f_prize_door,
                  f_monty_door,
                  domains={
                      'guest_door': ['A', 'B', 'C'],
                      'monty_door': ['A', 'B', 'C'],
                      'prize_door': ['A', 'B', 'C']
                  })
    return g
Example #4
0
    if tabs == ['t', 't', 't']:
        return 0.99
    elif tabs == ['t', 't', 'f']:
        return 0.01
    elif tabs == ['t', 'f', 't']:
        return 0.9
    elif tabs == ['t', 'f', 'f']:
        return 0.1
    elif tabs == ['f', 't', 't']:
        return 0.9
    elif tabs == ['f', 't', 'f']:
        return 0.1
    elif tabs == ['f', 'f', 't']:
        return 0
    elif tabs == ['f', 'f', 'f']:
        return 1

    pass


if __name__ == '__main__':

    g = build_bbn(f_cloudy,
                  f_rain,
                  f_sprinkler,
                  f_wetgrass,
                  domains=dict(cloudy=['t', 'f'],
                               rain=['t', 'f'],
                               sprinkler=['t', 'f'],
                               wetgrass=['t', 'f']))
        ttt=0.99,
        tft=0.9,
        ftt=0.97,
        fft=0.3)   # Note typo in article!
    key = make_key(fo, bp, do)
    if key in tt:
        return tt[key]
    key = make_key(fo, bp, not do)
    return 1 - tt[key]


def hear_bark(do, hb):
    tt = dict(
        tt=0.7,
        ft=0.01)
    key = make_key(do, hb)
    if key in tt:
        return tt[key]
    key = make_key(do, not hb)
    return 1 - tt[key]


if __name__ == '__main__':
    g = build_bbn(
        family_out,
        bowel_problem,
        light_on,
        dog_out,
        hear_bark)
    g.q()
Example #6
0
        return 0.5
    elif temp_yesterday == 'medium':
        return 0.25
    elif temp_yesterday == 'cold':
        return 0.25


def f_rain_yesterday(rain_yesterday):
    return 0.5


def f_temp(season, temp_yesterday, temp):
    return season_temp[season][(temp_yesterday, temp)]


def f_rain(season, rain_yesterday, rain):
    return season_rain[season][(rain_yesterday, rain)]


if __name__ == '__main__':
    g = build_bbn(f_temp_yesterday,
                  f_rain_yesterday,
                  f_season,
                  f_temp,
                  f_rain,
                  domains=dict(temp_yesterday=('hot', 'medium', 'cold'),
                               temp=('hot', 'medium', 'cold'),
                               season=('spring', 'summer', 'autumn',
                                       'winter')))
    g.q()
        return 0.41
    elif tabs == ['f', 't', 'f']:
        return 1 - f_alarm('f', 't', 't')
    elif tabs == ['f', 'f', 't']:
        return 0.001
    elif tabs == ['f', 'f', 'f']:
        return 1 - f_alarm('f', 'f', 't')


def f_radio(earthquake, radio):
    tabs = [earthquake, radio]

    if earthquake == radio:
        return 1
    else:
        return 0


if __name__ == '__main__':

    g = build_bbn(f_burglar,
                  f_earthquake,
                  f_alarm,
                  f_radio,
                  domains=dict(burglar=['t', 'f'],
                               earthquake=['t', 'f'],
                               alarm=['t', 'f'],
                               radio=['t', 'f']))

    g.q()
def f_prize_door(prize_door):
    return 0.3333333


def f_guest_door(guest_door):
    return 0.3333333


def f_monty_door(prize_door, guest_door, monty_door):
    if prize_door == guest_door:
        if monty_door == prize_door:
            return 0
        return 0.5
    elif prize_door == monty_door:
        return 0
    elif guest_door == monty_door:
        return 0
    return 1


if __name__ == "__main__":
    g = build_bbn(
        f_prize_door,
        f_guest_door,
        f_monty_door,
        domains=dict(
                prize_door=['A','B','C'],
                guest_door=['A','B','C'],
                monty_door=['A','B','C']
                ))
def pytest_funcarg__cancer_graph(request):
    g = build_bbn(
        fP, fS, fC, fX, fD,
        domains={
            'P': ['low', 'high']})
    return g
 def net(self, inputnodes=None):
     function_list = list(self.functions(inputnodes=inputnodes))
     net = build_bbn(function_list, domains=self.variables)
     return net
Example #11
0
    table['tt'] = 1.
    table['tf'] = 0.
    table['ft'] = 0.
    table['ff'] = 1.
    key = ''
    key = key + 't' if earthquake else key + 'f'
    key = key + 't' if radioBroadcast else key + 'f'
    return table[key]


def f_alarm(burglary, earthquake, alarm):
    table = dict()
    table['fft'] = 0.001
    table['fff'] = 0.999
    table['ftt'] = 0.41
    table['ftf'] = 0.59
    table['tft'] = 0.95
    table['tff'] = 0.05
    table['ttt'] = 0.98
    table['ttf'] = 0.02
    key = ''
    key = key + 't' if burglary else key + 'f'
    key = key + 't' if earthquake else key + 'f'
    key = key + 't' if alarm else key + 'f'
    return table[key]


if __name__ == '__main__':
    g = build_bbn(f_burglary, f_earthquake, f_radioBroadcast, f_alarm)
    g.q()
def pytest_funcarg__cancer_graph(request):
    g = build_bbn(fP, fS, fC, fX, fD, domains={'P': ['low', 'high']})
    return g
Example #13
0
    def __export__(self, iterations, screen=True, file=True, pdf=True):
        _str = 'Finished inference in ' + str(iterations) + ' iterations.\n'
        _str += 'Evaluations: ' + str(iterations * self.population_size) + '\n'
        _str += 'Population size: ' + str(self.population_size) + '\n'
        _str += 'Nodes: ' + str(self.model_graph.count_nodes) + '\n'
        _str += 'Colors: ' + str(len(self.palette)) + '\n'
        _str += 'Best individual fitness: ' + str(
            round(self.__best_individual__().fitness, 2)) + "\n"
        _str += 'Marginalization matrix:\n'

        some_bbn = build_bbn(
            *self._bbn_functions.values(),  # unzips list
            domains=dict([(x, self.palette) for x in self.node_names]))

        print _str
        some_bbn.q()

        _dict = copy.deepcopy(self.dependencies)
        del _dict[None]

        if pdf:
            bbn = graphviz.Digraph()
            [bbn.node(x) for x in self.node_names]

            bbn.edges(_dict.items())
            bbn.render('bbn.gv')

            self.__best_individual__().export('optimal')

        if file:
            query = some_bbn.query().items()
            query = '\n'.join([str(x) for x in query])

            with open('output.txt', 'w') as file:
                file.write(_str)
                file.write(query)

        if screen:

            def plot_bbn():
                plt.figure(1)
                G = nx.DiGraph()
                G.add_edges_from(_dict.items())
                layout = nx.shell_layout(G)
                nx.draw_networkx(G,
                                 pos=layout,
                                 cmap=plt.get_cmap('jet'),
                                 node_color=list(
                                     itertools.repeat('cyan',
                                                      len(self.node_names))))

            def plot_optimal():
                plt.figure(2)
                individual = self.__best_individual__()
                G = nx.Graph()
                G.add_nodes_from(individual.names)
                some_edges = [tuple(list(x)) for x in individual.edges]
                G.add_edges_from(some_edges)
                layout = nx.shell_layout(G)
                nx.draw_networkx(G,
                                 pos=layout,
                                 cmap=plt.get_cmap('jet'),
                                 node_color=individual.colors)

            plot_bbn()
            plot_optimal()
            plt.show()
Example #14
0
        return 0.01
    return 0.99


def light_on(fo, lo):
    tt = dict(tt=0.6, tf=0.4, ft=0.05, ff=0.96)
    return tt[make_key(fo, lo)]


def dog_out(fo, bp, do):
    tt = dict(ttt=0.99, tft=0.9, ftt=0.97, fft=0.3)  # Note typo in article!
    key = make_key(fo, bp, do)
    if key in tt:
        return tt[key]
    key = make_key(fo, bp, not do)
    return 1 - tt[key]


def hear_bark(do, hb):
    tt = dict(tt=0.7, ft=0.01)
    key = make_key(do, hb)
    if key in tt:
        return tt[key]
    key = make_key(do, not hb)
    return 1 - tt[key]


if __name__ == '__main__':
    g = build_bbn(family_out, bowel_problem, light_on, dog_out, hear_bark)
    g.q()
def pytest_funcarg__earthquake_bbn(request):
    g = build_bbn(
        f_burglary, f_earthquake, f_alarm,
        f_johncalls, f_marycalls)
    return g
Example #16
0
        if rain:
            if grass_wet:
                return 0.99
            else:
                return 0.01
        else:
            if grass_wet:
                return 0.9
            else:
                return 0.1
    else:
        if rain:
            if grass_wet:
                return 0.8
            else:
                return 0.2
        else:
            if grass_wet:
                return 0.0
            else:
                return 1


if __name__ == '__main__':
    g = build_bbn(f_rain,
                  f_sprinkler,
                  f_grass_wet,
                  domains=dict(rain=[True, False],
                               sprinkler=[True, False],
                               grass_wet=[True, False]))
Example #17
0
    elif tabs == ['f', 'f']:
        return 1 - 0.05


def f_mary(mary, alarm):
    tabs = [mary, alarm]
    if tabs == ['t', 't']:
        return 0.70
    elif tabs == ['t', 'f']:
        return 0.01
    elif tabs == ['f', 't']:
        return 1 - 0.70
    elif tabs == ['f', 'f']:
        return 1 - 0.01


if __name__ == '__main__':

    g = build_bbn(f_burglar,
                  f_earthquake,
                  f_alarm,
                  f_john,
                  f_mary,
                  domains=dict(burglar=['t', 'f'],
                               earthquake=['t', 'f'],
                               alarm=['t', 'f'],
                               john=['t', 'f'],
                               mary=['t', 'f']))

    g.q()
    return table[key]


def f_johncalls(alarm, johncalls):
    table = dict()
    table["tt"] = 0.9
    table["tf"] = 0.1
    table["ft"] = 0.05
    table["ff"] = 0.95
    key = ""
    key = key + "t" if alarm else key + "f"
    key = key + "t" if johncalls else key + "f"
    return table[key]


def f_marycalls(alarm, marycalls):
    table = dict()
    table["tt"] = 0.7
    table["tf"] = 0.3
    table["ft"] = 0.01
    table["ff"] = 0.99
    key = ""
    key = key + "t" if alarm else key + "f"
    key = key + "t" if marycalls else key + "f"
    return table[key]


if __name__ == "__main__":
    g = build_bbn(f_burglary, f_earthquake, f_alarm, f_johncalls, f_marycalls)
    g.q()
    return table[key]


def f_johncalls(alarm, johncalls):
    table = dict()
    table['tt'] = 0.9
    table['tf'] = 0.1
    table['ft'] = 0.05
    table['ff'] = 0.95
    key = ''
    key = key + 't' if alarm else key + 'f'
    key = key + 't' if johncalls else key + 'f'
    return table[key]


def f_marycalls(alarm, marycalls):
    table = dict()
    table['tt'] = 0.7
    table['tf'] = 0.3
    table['ft'] = 0.01
    table['ff'] = 0.99
    key = ''
    key = key + 't' if alarm else key + 'f'
    key = key + 't' if marycalls else key + 'f'
    return table[key]


if __name__ == '__main__':
    g = build_bbn(f_burglary, f_earthquake, f_alarm, f_johncalls, f_marycalls)
    g.q()
Example #20
0
"""

from bayesian.bbn import build_bbn


def f_coina(flipa):
    if (flipa == 'H'):
        return 0.5
    elif (flipa == 'T'):
        return 0.5


def f_coinb(flipa, flipb):
    if (flipa == 'H'):
        if (flipb == 'H'):
            return 0.6
        elif (flipb == 'T'):
            return 0.4

    elif (flipa == 'T'):
        if (flipb == 'H'):
            return 0.5
        elif (flipb == 'T'):
            return 0.5


if __name__ == '__main__':

    coins = build_bbn(f_coina,
                      f_coinb,
                      domains=dict(flipa=['H', 'T'], flipb=['H', 'T']))
Example #21
0
def pytest_funcarg__huang_darwiche_bbn(request):
    g = build_bbn(f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h)
    return g
Example #22
0
                    human_action=str(req.human_action),
                    human_expression=str(req.human_expression)).get(
                        ('robot_expression', 'n'))
        c = g.query(object_size=str(req.object_size),
                    human_action=str(req.human_action),
                    human_expression=str(req.human_expression)).get(
                        ('robot_expression', 's'))
    return predict_robot_expressionResponse(a, b, c)


#section for service
# node is initialised
# service is declared
def main_server():
    rospy.init_node('robot_expression_prediction')
    s = rospy.Service('predictrobotexpression', predict_robot_expression,
                      handle_server)
    rospy.spin()


if __name__ == '__main__':
    g = build_bbn(f_human_expression,
                  f_human_action,
                  f_object_size,
                  f_robot_expression,
                  domains=dict(human_expression=['1', '2', '3'],
                               human_action=['1', '2', '3'],
                               object_size=['1', '2'],
                               robot_expression=['h', 's', 'n']))
    main_server()
def pytest_funcarg__huang_darwiche_bbn(request):
    g = build_bbn(f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h)
    return g
Example #24
0
def pytest_funcarg__earthquake_bbn(request):
    g = build_bbn(f_burglary, f_earthquake, f_alarm, f_johncalls, f_marycalls)
    return g
Example #25
0
    table['ff'] = 1.
    key = ''
    key = key + 't' if earthquake else key + 'f'
    key = key + 't' if radioBroadcast else key + 'f'
    return table[key]


def f_alarm(burglary, earthquake, alarm):
    table = dict()
    table['fft'] = 0.001
    table['fff'] = 0.999
    table['ftt'] = 0.41
    table['ftf'] = 0.59
    table['tft'] = 0.95
    table['tff'] = 0.05
    table['ttt'] = 0.98
    table['ttf'] = 0.02
    key = ''
    key = key + 't' if burglary else key + 'f'
    key = key + 't' if earthquake else key + 'f'
    key = key + 't' if alarm else key + 'f'
    return table[key]

if __name__ == '__main__':
    g = build_bbn(
        f_burglary,
        f_earthquake,
        f_radioBroadcast,
        f_alarm)
    g.q()
Example #26
0
    elif prize_door == monty_door:
        return 0  # Again, Monty wont reveal the prize
    elif guest_door == monty_door:
        return 0  # Monty will never choose the guest door
    else:
        # This covers all case where
        # the guest has *not* guessed
        # correctly and Monty chooses
        # the only remaining door that
        # wont reveal the prize.
        return 1


g = build_bbn(
    f_prize_door,
    f_guest_door,
    f_monty_door,
    domains=dict(prize_door=["A", "B", "C"], guest_door=["A", "B", "C"], monty_door=["A", "B", "C"]),
)


def json_convert(query):
    """
    function used to convert queries into useful json files
    that can be served by bottle and imported into the game
    using ajax.
    """
    d = {k[0]: {} for k in query.keys()}
    [d[k[0]].update({k[1]: r}) for k, r in query.items()]
    return json.dumps(d)

    if restore:
        return p
    else:
        return 1.0 - p


if __name__ == '__main__':
    levels = [True, False]
    net = build_bbn(
        f_landscape,
        f_site,
        f_current,
        f_future,
        f_restore,

        # assume simple binary
        domains=dict(
            landscape=levels,
            environment=levels,
            eco=levels,
            restore=levels
        )
    )

    import itertools
    prod = itertools.product(
        xrange(0, 101, 25),  # landscape metric
        xrange(0, 101, 25),  # site metric
        xrange(0, 101, 25),  # current metric
        xrange(0, 101, 25),  # potential metric
    )
Example #28
0
 def build_bnet(self):
   functions, domains = self.build_functions_for_nodes()
   self.g = build_bbn(*functions, domains=domains)
    elif temp_yesterday == 'medium':
        return 0.25
    elif temp_yesterday == 'cold':
        return 0.25


def f_rain_yesterday(rain_yesterday):
    return 0.5


def f_temp(season, temp_yesterday, temp):
    return season_temp[season][(temp_yesterday, temp)]


def f_rain(season, rain_yesterday, rain):
    return season_rain[season][(rain_yesterday, rain)]


if __name__ == '__main__':
    g = build_bbn(
        f_temp_yesterday,
        f_rain_yesterday,
        f_season,
        f_temp,
        f_rain,
        domains=dict(
            temp_yesterday=('hot', 'medium', 'cold'),
            temp=('hot', 'medium', 'cold'),
            season=('spring', 'summer', 'autumn', 'winter')))
    g.q()
Example #30
0

def f_relva_molhada(chuva, aspersor, relva_molhada):
    if relva_molhada:
        if chuva and aspersor:
            return 0.99
        elif not chuva and aspersor:
            return 0.9
        elif chuva and not aspersor:
            return 0.8
        elif not chuva and not aspersor:
            return 0
    else:
        if chuva and aspersor:
            return 0.01
        elif not chuva and aspersor:
            return 0.1
        elif chuva and not aspersor:
            return 0.2
        elif not chuva and not aspersor:
            return 1


if __name__ == '__main__':
    g = build_bbn(f_chuva,
                  f_aspersor,
                  f_relva_molhada,
                  domains=dict(chuva=[True, False],
                               aspersor=[True, False],
                               relva_molhada=[True, False]))
Example #31
0
def f_guest_door(guest_door):
    return 0.33333333


def f_monty_door(prize_door, guest_door, monty_door):
    if prize_door == guest_door:  # 参赛者猜对了
        if prize_door == monty_door:
            return 0  # Monty不会打开有车的那扇门,不可能发生
        else:
            return 0.5  # Monty会打开其它两扇门,二选一
    elif prize_door == monty_door:
        return 0  #  Monty不会打开有车的那扇门,不可能发生
    elif guest_door == monty_door:
        return 0  # 门已经由参赛者选定,不可能发生
    else:
        return 1  # Monty打开另一扇有羊的门


if __name__ == '__main__':
    g = build_bbn(f_prize_door,
                  f_guest_door,
                  f_monty_door,
                  domains=dict(prize_door=['A', 'B', 'C'],
                               guest_door=['A', 'B', 'C'],
                               monty_door=['A', 'B', 'C']))

    g.q()
    g.q(guest_door='A')
g.q(guest_door='A', monty_door='B')
Example #32
0
        if prize_door == monty_door:
            return 0  # 没有获得奖项
        else:
            return 1 / 2  # 选择下一个有山羊的门,现在只有两个选择
    elif prize_door == monty_door:
        return 0  # 仍然没有选中含有奖项的门
    elif guest_door == monty_door:
        return 0
    else:
        # 其他情况
        return 1


if __name__ == '__main__':
    get_result = build_bbn(
        door_with_prize,
        door_choosed,
        door_monty,
        domains=dict(
            # 定义每种选项的可选择情况
            prize_door=['1', '2', '3'],
            guest_door=['1', '2', '3'],
            monty_door=['1', '2', '3']))

get_result.q()
get_result.q(guest_door='1')
get_result.q(guest_door='1', monty_door='2')
get_result.q(guest_door='3', monty_door='2')
get_result.q(guest_door='1', monty_door='3')
get_result.q(guest_door='2', monty_door='1')