Exemple #1
0
class Network(object):
    def __init__(self, name, lic=None, file=None):
        if file is None:
            self.name = name
            self.ntc = Netica()
            self.env = self.ntc.newenv(lic)
            self.ntc.initenv(self.env)
            self.net = self.ntc.newnet(name, self.env)
            self.nodes = []
        else:
            self.name = name
            self.ntc = Netica()
            self.env = self.ntc.newenv(lic)
            self.ntc.initenv(self.env)
            self.net = self.ntc.opennet(self.env, file)
            nodelist_p = self.ntc.getnetnodes(self.net)
            numnode = self.ntc.lengthnodelist(nodelist_p)
            self.nodes = []
            for i in range(numnode):
                nodei_p = self.ntc.nthnode(nodelist_p, i)
                nodename = self.ntc.getnodename(nodei_p)
                statename = 'init'; statenames = []; istate = 0
                while statename!='error':
                    statename = self.ntc.getnodestatename(nodei_p, istate)
                    statenames.append(statename)
                    istate += 1
                statenames = statenames[:-1]
                # default: no parents and continuous: therefore not the original nodes
                nodei = Node(nodename, parents=[], rvname='continuous')
                nodei.set_node_ptr(nodei_p)
                nodei.set_node_state_name(statenames)
                self.nodes.append(nodei)


    def add_nodes(self, nodes):
        for node in nodes:
            if (node.nodekind==NATURE_NODE) and (node.cpt is None or (node.cpt.size == 0)):
                print "assign {} cpt first before add to network".format(node.name)
            #nodeptr = self.ntc.newnode(node.name, node.cpt.shape[0], self.net)
            #node.set_pointer(nodeptr)
            #node.set_net(self)
            node.add_to_net(self)
            self.nodes.append(node)


    def add_link(self):
        for node in self.nodes:
            if node.parents is not None:
                for parentNode in node.parents:
                    self.ntc.addlink(parent=parentNode.ptr, child=node.ptr)


    def define_nodes(self):
        """define nodes can only be implemented after all links are added
        """
        for node in self.nodes:
            node.define()


    def compile_net(self):
        self.ntc.compilenet(self.net)


    def set_autoupdate(self):
        self.ntc.setautoupdate(self.net)


    def get_node_beliefs(self, node):
        beliefs32 = self.ntc.getnodebeliefs(node.ptr)
        return beliefs32.astype('float')


    def get_node_expectedutils(self, node):
        utils32 = self.ntc.getnodeexpectedutils(node.ptr)
        return utils32.astype('float')


    def enter_finding(self, node, evidence):
        if isinstance(evidence, int):
            stateindx = evidence
        elif isinstance(evidence, basestring):
            lowercaseStates = np.array([name.lower() for name in node.statenames])
            stateindx = np.where(lowercaseStates == evidence.lower())[0][0]
        stateindx = c_int(stateindx)
        self.ntc.enterfinding(node.ptr, stateindx)


    def retract_nodefindings(self, node):
        self.ntc.retractnodefindings(node.ptr)


    def retract_netfindings(self):
        self.ntc.retractnetfindings(self.net)


    def save_net(self, filename):
        self.ntc.savenet(self.env, self.net, filename)


    def set_node_kind(self, node, nodekind=NATURE_NODE):
        self.ntc.set_node_kind(node, nodekind)

    def get_node_funcstate(self, node, parentstate):
        return self.ntc.getnodefuncstate(node.ptr, parentstate)

    def find_nodenamed(self, nodename):
        """
        find node by node name
        """
        found = False
        for i,node in enumerate(self.nodes):
            if node.name == nodename:
                found =True
                break
        if found:
            return node
        else:
            return 'error'
Exemple #2
0
Tuberculosis = ntc.newnode ("Tuberculosis", 2, net_p)
Smoking =      ntc.newnode ("Smoking", 2, net_p)
Cancer =       ntc.newnode ("Cancer", 2, net_p)
TbOrCa =       ntc.newnode ("TbOrCa", 2, net_p)
XRay =         ntc.newnode ("XRay", 2, net_p)

# set node names
ntc.setnodestatenames(VisitAsia,   "visit,   no_visit");
ntc.setnodestatenames(Tuberculosis,"present, absent");
ntc.setnodestatenames(Smoking,     "smoker,  nonsmoker");
ntc.setnodestatenames(Cancer,      "present, absent");
ntc.setnodestatenames(TbOrCa,      "true,    false");
ntc.setnodestatenames(XRay,        "abnormal,normal");

# define links
ntc.addlink(parent=VisitAsia,    child=Tuberculosis)
ntc.addlink(parent=Smoking,      child=Cancer)
ntc.addlink(parent=Tuberculosis, child=TbOrCa)
ntc.addlink(parent=Cancer,       child=TbOrCa)
ntc.addlink(parent=TbOrCa,       child=XRay)

# set node probs

parent_states = np.empty((1,),dtype='int32')
probs = np.array([0.01, 0.99], dtype='float32')
ntc.setnodeprobs (VisitAsia, parent_states, probs)

parent_states = np.array([0],dtype='int32')
probs = np.array([0.05, 0.95], dtype='float32')
ntc.setnodeprobs (Tuberculosis, parent_states, probs)
parent_states = np.array([1],dtype='int32')
ntc.setnodestatetitle(nodeR1, 0, 'Area 1 (has 283 houses)')
ntc.setnodestatetitle(nodeR1, 1, 'Area 2 (has 759 houses)')
ntc.setnodestatetitle(nodeR1, 2, 'Area 3 (has 383 houses)')
ntc.setnodestatetitle(nodeR1, 3, 'Area 4 (has 273 houses)')

nodeH1_R1 = ntc.newnode('MaxInundation_Houses', 0, net_p)
ntc.setnodelevels(nodeH1_R1, 4, np.asarray([0, 0, 0.5, 1, 2], dtype='float64'))
ntc.setnodetitle(nodeH1_R1, 'Houses - Max. Inundation depth (m)')

nodeC1_R1 = ntc.newnode('RelativeDamage_Houses', 0, net_p)
ntc.setnodelevels(nodeC1_R1, 4,
                  np.asarray([0, 0, 23.5, 47, 50], dtype='float64'))
ntc.setnodetitle(nodeC1_R1, 'Houses - Relative Damage (%)')

# define links
ntc.addlink(parent=nodeBC1, child=nodeH1_R1)
ntc.addlink(parent=nodeBC2, child=nodeH1_R1)
ntc.addlink(parent=nodeR1, child=nodeH1_R1)
ntc.addlink(parent=nodeH1_R1, child=nodeC1_R1)

ntc.setnodeprobs(nodeH1_R1, np.asarray([0, 0, 0], dtype='int'),
                 np.asarray([16.7, 44.7, 22.6, 16.1], dtype='float32'))

# obtain node list
#nl_p = ntc.getnetnodes(net_p)
# train with cas file
# ntc.revisecptsbycasefile(filename='BNcases.cas', nl_p=nl_p, updating=0, degree=1)

# compile the net
ntc.compilenet(net_p)
Exemple #4
0
class UnitTests(unittest.TestCase):
    def setUp(self):
        from netica import Netica
        self.netica = Netica()
        self.netfilename = 'curvnet.dne'
        self.env = self.netica.newenv()
        self.netica.initenv(self.env)
        self.net = self.netica.opennet(self.env, self.netfilename)
        self.nl_p = self.netica.getnetnodes(self.net)
        self.netica.compilenet(self.net)

    def test_enternodelikelyhood(self):
        self.netica.retractnetfindings(self.net)
        node_p = self.netica.getnodenamed('radius', self.net)
        self.netica.enternodelikelyhood(node_p, [1, 0, 0, 0, 0, 0])


#        self.netica.savenet(env, net, 'test.dne')

    def test_equationtotable(self):
        node_p = self.netica.getnodenamed('radius', self.net)
        self.netica.equationtotable(node_p, 10, True, True)

    def test_revisecptsbycasefile(self):
        casefilename = 'wavedir.cas'
        file_p = self.netica._newstream(self.env, casefilename)
        self.netica.revisecptsbycasefile(file_p, self.nl_p, 0, 1)

    def test_getnodeequation(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        eqn = self.netica.getnodeequation(node_p)
        print eqn
        # the radius node has no equation, thus should result in an empty string
        node_p = self.netica.getnodenamed('radius', self.net)
        eqn = self.netica.getnodeequation(node_p)
        self.assertEqual(eqn, '')

    def test_setnodeequation(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        eqn_in = 'phi (theta, wavedir) = theta - wavedir'
        self.netica.setnodeequation(node_p, eqn_in)
        eqn_out = self.netica.getnodeequation(node_p)
        self.assertEqual(eqn_in, eqn_out)

    def test_newnode(self):
        nodename = 'test'
        node_p = self.netica.newnode(nodename, 3, self.net)
        self.assertEqual(self.netica.getnodename(node_p), nodename)

    def test_deletenode(self):
        nodename = 'test'
        node_p = self.netica.newnode(nodename, 3, self.net)
        self.netica.deletenode(node_p)

    def test_addlink(self):
        parent = self.netica.getnodenamed('wavedir', self.net)
        child = self.netica.getnodenamed('erosionfactor', self.net)
        link_index = self.netica.addlink(parent, child)
        print 'index', link_index

    def test_deletelink(self):
        child = self.netica.getnodenamed('erosionfactor', self.net)
        link_index = 1
        self.netica.deletelink(link_index, child)

    def test_getnodelevels_continuous(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        print self.netica.getnodelevels(node_p)

    def test_getnodelevels_discrete(self):
        node_p = self.netica.newnode('Time_horizon', 3, self.net)
        #self.netica.setnodestatenames(node_p, "one, five, ten")
        self.netica.getnodelevels(node_p)

    def test_getnodestatename(self):
        node_p = self.netica.newnode('Time_horizon', 3, self.net)
        self.netica.setnodestatenames(node_p, "one, five, ten")
        print 'STATE: "' + self.netica.getnodestatename(node_p, 0) + '"'

    def test_enterfinding(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        self.netica.enterfinding(node_p, 0)

    def test_getnodeexpectedvalue(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        expval = self.netica.getnodeexpectedvalue(node_p)
        print 'expval = ', expval
class UnitTests(unittest.TestCase):
    def setUp(self):
        from netica import Netica
        self.netica = Netica()
        self.netfilename = 'curvnet.dne'
        self.env = self.netica.newenv()
        self.netica.initenv(self.env)
        self.net = self.netica.opennet(self.env, self.netfilename)
        self.nl_p = self.netica.getnetnodes(self.net)
        self.netica.compilenet(self.net)
    def test_enternodelikelyhood(self):
        self.netica.retractnetfindings(self.net)
        node_p = self.netica.getnodenamed('radius', self.net)
        self.netica.enternodelikelyhood(node_p, [1,0,0,0,0,0])
#        self.netica.savenet(env, net, 'test.dne')
    def test_equationtotable(self):
        node_p = self.netica.getnodenamed('radius', self.net)
        self.netica.equationtotable(node_p, 10, True, True)
    def test_revisecptsbycasefile(self):
        casefilename = 'wavedir.cas'
        file_p = self.netica._newstream(self.env, casefilename)
        self.netica.revisecptsbycasefile(file_p, self.nl_p, 0, 1)
    def test_getnodeequation(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        eqn = self.netica.getnodeequation(node_p)
        print eqn
        # the radius node has no equation, thus should result in an empty string
        node_p = self.netica.getnodenamed('radius', self.net)
        eqn = self.netica.getnodeequation(node_p)
        self.assertEqual(eqn, '')
    def test_setnodeequation(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        eqn_in = 'phi (theta, wavedir) = theta - wavedir'
        self.netica.setnodeequation(node_p, eqn_in)
        eqn_out = self.netica.getnodeequation(node_p)
        self.assertEqual(eqn_in, eqn_out)
    def test_newnode(self):
        nodename = 'test'
        node_p = self.netica.newnode(nodename, 3, self.net)
        self.assertEqual(self.netica.getnodename(node_p), nodename)
    def test_deletenode(self):
        nodename = 'test'
        node_p = self.netica.newnode(nodename, 3, self.net)
        self.netica.deletenode(node_p)
    def test_addlink(self):
        parent = self.netica.getnodenamed('wavedir', self.net)
        child = self.netica.getnodenamed('erosionfactor', self.net)
        link_index = self.netica.addlink(parent, child)
        print 'index',link_index
    def test_deletelink(self):
        child = self.netica.getnodenamed('erosionfactor', self.net)
        link_index = 1
        self.netica.deletelink(link_index, child)
    def test_getnodelevels_continuous(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        print self.netica.getnodelevels(node_p)
    def test_getnodelevels_discrete(self):
        node_p = self.netica.newnode('Time_horizon', 3, self.net)
        #self.netica.setnodestatenames(node_p, "one, five, ten")
        self.netica.getnodelevels(node_p)
    def test_getnodestatename(self):
        node_p = self.netica.newnode('Time_horizon', 3, self.net)
        self.netica.setnodestatenames(node_p, "one, five, ten")
        print 'STATE: "' + self.netica.getnodestatename(node_p, 0) + '"'
    def test_enterfinding(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        self.netica.enterfinding(node_p, 0)
    def test_getnodeexpectedvalue(self):
        node_p = self.netica.getnodenamed('phi', self.net)
        expval = self.netica.getnodeexpectedvalue(node_p)
        print 'expval = ',expval
Exemple #6
0
class Network(object):
    def __init__(self, name, lic=None, file=None):
        if file is None:
            self.name = name
            self.ntc = Netica()
            self.env = self.ntc.newenv(lic)
            self.ntc.initenv(self.env)
            self.net = self.ntc.newnet(name, self.env)
            self.nodes = []
        else:
            self.name = name
            self.ntc = Netica()
            self.env = self.ntc.newenv(lic)
            self.ntc.initenv(self.env)
            self.net = self.ntc.opennet(self.env, file)
            nodelist_p = self.ntc.getnetnodes(self.net)
            numnode = self.ntc.lengthnodelist(nodelist_p)
            self.nodes = []
            for i in range(numnode):
                nodei_p = self.ntc.nthnode(nodelist_p, i)
                nodename = self.ntc.getnodename(nodei_p)
                statename = 'init'
                statenames = []
                istate = 0
                while statename != 'error':
                    statename = self.ntc.getnodestatename(nodei_p, istate)
                    statenames.append(statename)
                    istate += 1
                statenames = statenames[:-1]
                # default: no parents and continuous: therefore not the original nodes
                nodei = Node(nodename, parents=[], rvname='continuous')
                nodei.set_node_ptr(nodei_p)
                nodei.set_node_state_name(statenames)
                self.nodes.append(nodei)

    def add_nodes(self, nodes):
        for node in nodes:
            if (node.nodekind == NATURE_NODE) and (node.cpt is None or
                                                   (node.cpt.size == 0)):
                print "assign {} cpt first before add to network".format(
                    node.name)
            #nodeptr = self.ntc.newnode(node.name, node.cpt.shape[0], self.net)
            #node.set_pointer(nodeptr)
            #node.set_net(self)
            node.add_to_net(self)
            self.nodes.append(node)

    def add_link(self):
        for node in self.nodes:
            if node.parents is not None:
                for parentNode in node.parents:
                    self.ntc.addlink(parent=parentNode.ptr, child=node.ptr)

    def define_nodes(self):
        """define nodes can only be implemented after all links are added
        """
        for node in self.nodes:
            node.define()

    def compile_net(self):
        self.ntc.compilenet(self.net)

    def set_autoupdate(self):
        self.ntc.setautoupdate(self.net)

    def get_node_beliefs(self, node):
        beliefs32 = self.ntc.getnodebeliefs(node.ptr)
        return beliefs32.astype('float')

    def get_node_expectedutils(self, node):
        utils32 = self.ntc.getnodeexpectedutils(node.ptr)
        return utils32.astype('float')

    def enter_finding(self, node, evidence):
        if isinstance(evidence, int):
            stateindx = evidence
        elif isinstance(evidence, basestring):
            lowercaseStates = np.array(
                [name.lower() for name in node.statenames])
            stateindx = np.where(lowercaseStates == evidence.lower())[0][0]
        stateindx = c_int(stateindx)
        self.ntc.enterfinding(node.ptr, stateindx)

    def retract_nodefindings(self, node):
        self.ntc.retractnodefindings(node.ptr)

    def retract_netfindings(self):
        self.ntc.retractnetfindings(self.net)

    def save_net(self, filename):
        self.ntc.savenet(self.env, self.net, filename)

    def set_node_kind(self, node, nodekind=NATURE_NODE):
        self.ntc.set_node_kind(node, nodekind)

    def get_node_funcstate(self, node, parentstate):
        return self.ntc.getnodefuncstate(node.ptr, parentstate)

    def find_nodenamed(self, nodename):
        """
        find node by node name
        """
        found = False
        for i, node in enumerate(self.nodes):
            if node.name == nodename:
                found = True
                break
        if found:
            return node
        else:
            return 'error'
Exemple #7
0
Tuberculosis = ntc.newnode("Tuberculosis", 2, net_p)
Smoking = ntc.newnode("Smoking", 2, net_p)
Cancer = ntc.newnode("Cancer", 2, net_p)
TbOrCa = ntc.newnode("TbOrCa", 2, net_p)
XRay = ntc.newnode("XRay", 2, net_p)

# set node names
ntc.setnodestatenames(VisitAsia, "visit,   no_visit")
ntc.setnodestatenames(Tuberculosis, "present, absent")
ntc.setnodestatenames(Smoking, "smoker,  nonsmoker")
ntc.setnodestatenames(Cancer, "present, absent")
ntc.setnodestatenames(TbOrCa, "true,    false")
ntc.setnodestatenames(XRay, "abnormal,normal")

# define links
ntc.addlink(parent=VisitAsia, child=Tuberculosis)
ntc.addlink(parent=Smoking, child=Cancer)
ntc.addlink(parent=Tuberculosis, child=TbOrCa)
ntc.addlink(parent=Cancer, child=TbOrCa)
ntc.addlink(parent=TbOrCa, child=XRay)

# set node probs

parent_states = np.empty((1, ), dtype='int32')
probs = np.array([0.01, 0.99], dtype='float32')
ntc.setnodeprobs(VisitAsia, parent_states, probs)

parent_states = np.array([0], dtype='int32')
probs = np.array([0.05, 0.95], dtype='float32')
ntc.setnodeprobs(Tuberculosis, parent_states, probs)
parent_states = np.array([1], dtype='int32')
ntc.setnodestatenames(nodeR1, "Area1, Area2, Area3, Area4")
ntc.setnodestatetitle(nodeR1, 0, 'Area 1 (has 283 houses)')
ntc.setnodestatetitle(nodeR1, 1, 'Area 2 (has 759 houses)')
ntc.setnodestatetitle(nodeR1, 2, 'Area 3 (has 383 houses)')
ntc.setnodestatetitle(nodeR1, 3, 'Area 4 (has 273 houses)')

nodeH1_R1 = ntc.newnode('MaxInundation_Houses', 0, net_p)
ntc.setnodelevels(nodeH1_R1, 4, np.asarray([0, 0, 0.5, 1, 2], dtype='float64'))
ntc.setnodetitle(nodeH1_R1,'Houses - Max. Inundation depth (m)')

nodeC1_R1 = ntc.newnode('RelativeDamage_Houses', 0, net_p)
ntc.setnodelevels(nodeC1_R1, 4, np.asarray([0, 0, 23.5, 47, 50], dtype='float64')) 
ntc.setnodetitle(nodeC1_R1,'Houses - Relative Damage (%)') 	
 
# define links
ntc.addlink(parent=nodeBC1, child=nodeH1_R1)
ntc.addlink(parent=nodeBC2, child=nodeH1_R1)
ntc.addlink(parent=nodeR1, child=nodeH1_R1)
ntc.addlink(parent=nodeH1_R1, child=nodeC1_R1) 
 
ntc.setnodeprobs(nodeH1_R1, np.asarray([0, 0, 0], dtype='int'), np.asarray([16.7,44.7,22.6,16.1],dtype='float32'))	

 
# obtain node list
#nl_p = ntc.getnetnodes(net_p)
# train with cas file
# ntc.revisecptsbycasefile(filename='BNcases.cas', nl_p=nl_p, updating=0, degree=1)
 

 
# compile the net