Esempio n. 1
0
 def setPercentil(self):
     self.spinLowerThreshold = self.histogram.minValue
     net = orngNetwork.Network(self.matrix.dim, 0)
     lower, upper = net.getDistanceMatrixThreshold(self.matrix,
                                                   self.percentil / 100)
     self.spinUpperThreshold = upper
     self.generateGraph()
Esempio n. 2
0
import orngNetwork
from pylab import *

# create graph object of type GraphAsList
net = orngNetwork.Network(5, 0)

# set edges
for i in range(4):
    for j in range(i + 1, 5):
        net[i, j] = 1

# vertices are placed randomly in NetworkOptimization constructor
networkOptimization = orngNetwork.NetworkOptimization(net)

# optimize verices layout with one of included algorithms
networkOptimization.fruchtermanReingold(100, 1000)

# read all edges and plot a line
for u, v in net.getEdges():
    x1, y1 = net.coors[0][u], net.coors[1][u]
    x2, y2 = net.coors[0][v], net.coors[1][v]
    plot([x1, x2], [y1, y2], 'b-')

# read x and y coordinates to Python list
x = net.coors[0]
y = net.coors[1]

# plot vertices
plot(x, y, 'ro')
show()
Esempio n. 3
0
 def generateGraph(self, N_changed = False):
     self.searchStringTimer.stop()
     self.attributeCombo.box.setEnabled(False)
     self.error()
     matrix = None
     self.warning('')
     
     if N_changed:
         self.netOption = 1
         
     if self.matrix == None:
         self.infoa.setText("No data loaded.")
         self.infob.setText("")
         return
     
     #print len(self.histogram.yData), len(self.histogram.xData)
     nEdgesEstimate = 2 * sum([self.histogram.yData[i] for i,e in enumerate(self.histogram.xData) if self.spinLowerThreshold <= e <= self.spinUpperThreshold])
     
     if nEdgesEstimate > 200000:
         self.graph = None
         nedges = 0
         n = 0
         self.error('Estimated number of edges is too high (%d).' % nEdgesEstimate)
     else:
         graph = orngNetwork.Network(self.matrix.dim, 0)
         matrix = self.matrix
         
         if hasattr(self.matrix, "items"):               
             if type(self.matrix.items) == type(orange.ExampleTable(orange.Domain(orange.StringVariable('tmp')))):
                 #graph.setattr("items", self.data.items)
                 graph.items = self.matrix.items
             else:
                 data = [[str(x)] for x in self.matrix.items]
                 items = orange.ExampleTable(orange.Domain(orange.StringVariable('label'), 0), data)
                 #graph.setattr("items", list(items))
                 graph.items = list(items)
             
         # set the threshold
         # set edges where distance is lower than threshold
               
         self.warning(0)
         if self.kNN >= self.matrix.dim:
             self.warning(0, "kNN larger then supplied distance matrix dimension. Using k = %i" % (self.matrix.dim - 1))
         nedges = graph.fromDistanceMatrix(self.matrix, self.spinLowerThreshold, self.spinUpperThreshold, min(self.kNN, self.matrix.dim - 1), self.andor)
         edges = graph.getEdges()
         
         #print graph.nVertices, self.matrix.dim
         
         if self.dstWeight == 1:
             if graph.directed:
                 for u,v in edges:
                     foo = 1
                     if str(graph[u,v]) != "0":
                         foo = 1.0 - float(graph[u,v])
                     
                     graph[u,v] = foo
             else:
                 for u,v in edges:
                     if u <= v:
                         foo = 1
                         if str(graph[u,v]) != "0":
                             foo = 1.0 - float(graph[u,v])
                         
                         graph[u,v] = foo
                 
         n = len(edges)
         #print 'self.netOption',self.netOption
         # exclude unconnected
         if str(self.netOption) == '1':
             components = [x for x in graph.getConnectedComponents() if len(x) > self.excludeLimit]
             if len(components) > 0:
                 include = reduce(lambda x,y: x+y, components)
                 if len(include) > 1:
                     self.graph = orngNetwork.Network(graph.getSubGraph(include))
                     matrix = self.matrix.getitems(include)
                 else:
                     self.graph = None
                     matrix = None
             else:
                 self.graph = None
                 matrix = None
         # largest connected component only        
         elif str(self.netOption) == '2':
             component = graph.getConnectedComponents()[0]
             if len(component) > 1:
                 self.graph = orngNetwork.Network(graph.getSubGraph(component))
                 matrix = self.matrix.getitems(component)
             else:
                 self.graph = None
                 matrix = None
         # connected component with vertex by label
         elif str(self.netOption) == '3':
             self.attributeCombo.box.setEnabled(True)
             self.graph = None
             matrix = None
             #print self.attributeCombo.currentText()
             if self.attributeCombo.currentText() != '' and self.label != '':
                 components = graph.getConnectedComponents()
                     
                 txt = self.label.lower()
                 #print 'txt:',txt
                 nodes = [i for i, values in enumerate(self.matrix.items) if txt in str(values[str(self.attributeCombo.currentText())]).lower()]
                 #print "nodes:",nodes
                 if len(nodes) > 0:
                     vertices = []
                     for component in components:
                         for node in nodes:
                             if node in component:
                                 if len(component) > 0:
                                     vertices.extend(component)
                                     
                     if len(vertices) > 0:
                         #print "n vertices:", len(vertices), "n set vertices:", len(set(vertices))
                         vertices = list(set(vertices))
                         self.graph = orngNetwork.Network(graph.getSubGraph(vertices))
                         matrix = self.matrix.getitems(vertices)
         else:
             self.graph = graph
     
     if matrix != None:
         self.matrix = matrix
         
     self.pconnected = nedges
     self.nedges = n
     if hasattr(self, "infoa"):
         self.infoa.setText("%d vertices" % self.matrix.dim)
     if hasattr(self, "infob"):
         self.infob.setText("%d connected (%3.1f%%)" % (nedges, nedges / float(self.matrix.dim) * 100))
     if hasattr(self, "infoc"):
         self.infoc.setText("%d edges (%d average)" % (n, n / float(self.matrix.dim)))
     
     #print 'self.graph:',self.graph+
     if hasattr(self, "sendSignals"):
         self.sendSignals()
     
     self.histogram.setBoundary(self.spinLowerThreshold, self.spinUpperThreshold)
Esempio n. 4
0
    def exportNetwork(self,
                      absolute_int=10,
                      positive_int=0,
                      negative_int=0,
                      best_attributes=0,
                      significant_digits=2,
                      pretty_names=1,
                      widget_coloring=1,
                      pcutoff=1):
        NA = len(self.names)

        ### SELECTION OF INTERACTIONS AND ATTRIBUTES ###

        # prevent crashes
        best_attributes = min(best_attributes, len(self.attlist))
        positive_int = min(positive_int, len(self.list))
        absolute_int = min(absolute_int, len(self.list))
        negative_int = min(negative_int, len(self.list))

        # select the top interactions
        ins = []
        if positive_int > 0:
            ins += self.list[-positive_int:]
        ins += self.list[:negative_int]
        if absolute_int > 0:
            ins += self.abslist[-absolute_int:]

        # pick best few attributes
        atts = []
        if best_attributes > 0:
            atts += [i for (x, i) in self.attlist[-best_attributes:]]

        # disregard the insignificant attributes, interactions
        if len(self.plist) > 0 and pcutoff < 1:
            # attributes
            oats = atts
            atts = []
            for i in oats:
                if self.plut[(i, -1)] < pcutoff:
                    atts.append(i)
            # interactions
            oins = ins
            ins = []
            for y in oins:
                (ig, i, j) = y[1]
                if self.plut[(i, j, -1)] < pcutoff:
                    ins.append(y)

        ints = []
        max_igain = -1e6
        min_gain = 1e6  # lowest information gain of involved attributes
        # remove duplicates and sorting keys
        for (x, v) in ins:
            if v not in ints:
                ints.append(v)
                # add to attribute list
                (ig, i, j) = v
                max_igain = max(abs(ig), max_igain)
                for x in [i, j]:
                    if x not in atts:
                        atts.append(x)
                        min_gain = min(min_gain, self.gains[x])

        # fill-in the attribute list with all possibly more important attributes
        ## todo

        ### NODE DRAWING ###
        map = {}
        graph = orngNetwork.Network(len(atts), 0)
        table = []

        for i in range(len(atts)):
            map[atts[i]] = i

            ndx = atts[i]
            t = '%s' % self.names[ndx]
            if pretty_names:
                t = string.replace(t, "ED_", "")
                t = string.replace(t, "D_", "")
                t = string.replace(t, "M_", "")
                t = string.replace(t, " ", "\\n")
                t = string.replace(t, "-", "\\n")
                t = string.replace(t, "_", "\\n")
                r = self.gains[ndx] * 100.0 / self.entropy
                table.append([i + 1, t, r])

        d = orange.Domain([
            orange.FloatVariable('index'),
            orange.StringVariable('label'),
            orange.FloatVariable('norm. gain')
        ])
        data = orange.ExampleTable(d, table)
        graph.items = data

        table = []
        for (ig, i, j) in ints:
            j = map[j]
            i = map[i]

            perc = int(
                abs(ig) * 100.0 / max(max_igain, self.attlist[-1][0]) + 0.5)
            graph[i, j] = perc / 30 + 1

            if self.entropy > 1e-6:
                mc = _nicefloat(100.0 * ig / self.entropy,
                                significant_digits) + "%"
            else:
                mc = _nicefloat(0.0, significant_digits)
            if len(self.plist) > 0 and pcutoff < 1:
                mc += "\\nP\<%.3f" % self.plut[(i, j, -1)]

            if ig > 0:
                if widget_coloring:
                    color = "green"
                else:
                    color = '"0.0 %f 0.9"' % (0.3 + 0.7 * perc / 100.0
                                              )  # adjust saturation
                dir = "both"
            else:
                if widget_coloring:
                    color = "red"
                else:
                    color = '"0.5 %f 0.9"' % (0.3 + 0.7 * perc / 100.0
                                              )  # adjust saturation
                dir = 'none'

            table.append([i, j, mc, dir, color])

        d = orange.Domain([
            orange.FloatVariable('u'),
            orange.FloatVariable('v'),
            orange.StringVariable('label'),
            orange.EnumVariable('dir', values=["both", "none"]),
            orange.EnumVariable('color', values=["green", "red"])
        ])
        data = orange.ExampleTable(d, table)
        graph.links = data

        return graph