orange-network / orangecontrib / network / widgets / OWNxFile.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
"""
<name>Net File</name>
<description>Reads data from a graf file (Pajek networks (.net) files and GML network files).</description>
<icon>icons/NetworkFile.svg</icon>
<contact>Miha Stajdohar (miha.stajdohar(@at@)gmail.com)</contact> 
<priority>6410</priority>
"""
import sys
import os.path
import user

import Orange
import OWGUI

from OWWidget import *

NAME = "Net File"
DESCRIPTION = "Reads data from a graf file (Pajek networks (.net) files and GML network files)."
ICON = "icons/NetworkFile.svg"
PRIORITY = 6410

OUTPUTS = [("Network", Orange.network.Graph),
           ("Items", Orange.data.Table)]

REPLACES = ["_network.widgets.OWNxFile.OWNxFile"]


class OWNxFile(OWWidget):

    settingsList = ["recentFiles", "recentDataFiles", "recentEdgesFiles", "auto_table"]

    def __init__(self, parent=None, signalManager=None):
        OWWidget.__init__(self, parent, signalManager, "Nx File", wantMainArea=False)

        self.inputs = []
        self.outputs = [("Network", Orange.network.Graph), ("Items", Orange.data.Table)]

        #set default settings
        self.recentFiles = ["(none)"]
        self.recentDataFiles = ["(none)"]
        self.recentEdgesFiles = ["(none)"]
        self.auto_table = True

        self.domain = None
        self.graph = None
        self.auto_items = None

        #get settings from the ini file, if they exist
        self.loadSettings()

        #GUI
        self.controlArea.layout().setMargin(4)
        self.box = OWGUI.widgetBox(self.controlArea, box="Graph File", orientation="vertical")
        hb = OWGUI.widgetBox(self.box, orientation="horizontal")
        self.filecombo = OWGUI.comboBox(hb, self, "filename")
        self.filecombo.setMinimumWidth(250)
        button = OWGUI.button(hb, self, '...', callback=self.browseNetFile, disabled=0)
        button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        OWGUI.checkBox(self.box, self, "auto_table", "Build graph data table automatically", callback=lambda: self.selectNetFile(self.filecombo.currentIndex()))

        self.databox = OWGUI.widgetBox(self.controlArea, box="Vertices Data File", orientation="horizontal")
        self.datacombo = OWGUI.comboBox(self.databox, self, "dataname")
        self.datacombo.setMinimumWidth(250)
        button = OWGUI.button(self.databox, self, '...', callback=self.browseDataFile, disabled=0)
        button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)

        self.edgesbox = OWGUI.widgetBox(self.controlArea, box="Edges Data File", orientation="horizontal")
        self.edgescombo = OWGUI.comboBox(self.edgesbox, self, "edgesname")
        self.edgescombo.setMinimumWidth(250)
        button = OWGUI.button(self.edgesbox, self, '...', callback=self.browseEdgesFile, disabled=0)
        button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        button.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)

        # info
        box = OWGUI.widgetBox(self.controlArea, "Info")
        self.infoa = OWGUI.widgetLabel(box, 'No data loaded.')
        self.infob = OWGUI.widgetLabel(box, ' ')
        self.infoc = OWGUI.widgetLabel(box, ' ')
        self.infod = OWGUI.widgetLabel(box, ' ')

        OWGUI.rubber(self.controlArea)
        self.resize(150, 100)
        self.activateLoadedSettings()

        # connecting GUI to code
        self.connect(self.filecombo, SIGNAL('activated(int)'), self.selectNetFile)
        self.connect(self.datacombo, SIGNAL('activated(int)'), self.selectDataFile)
        self.connect(self.edgescombo, SIGNAL('activated(int)'), self.selectEdgesFile)

    # set the comboboxes
    def setFileLists(self):
        self.filecombo.clear()
        if not self.recentFiles:
            self.filecombo.addItem("(none)")
        for file in self.recentFiles:
            if file == "(none)":
                self.filecombo.addItem("(none)")
            else:
                self.filecombo.addItem(os.path.split(file)[1])
        self.filecombo.addItem("Browse documentation networks...")

        self.datacombo.clear()
        if not self.recentDataFiles:
            self.datacombo.addItem("(none)")
        for file in self.recentDataFiles:
            if file == "(none)":
                self.datacombo.addItem("(none)")
            else:
                self.datacombo.addItem(os.path.split(file)[1])

        self.edgescombo.clear()
        if not self.recentEdgesFiles:
            self.edgescombo.addItem("(none)")
        for file in self.recentEdgesFiles:
            if file == "(none)":
                self.edgescombo.addItem("(none)")
            else:
                self.edgescombo.addItem(os.path.split(file)[1])

        self.filecombo.updateGeometry()
        self.datacombo.updateGeometry()
        self.edgescombo.updateGeometry()

    def activateLoadedSettings(self):
        # remove missing data set names
        self.recentFiles = filter(os.path.exists, self.recentFiles)
        self.recentDataFiles = filter(os.path.exists, self.recentDataFiles)
        self.recentEdgesFiles = filter(os.path.exists, self.recentEdgesFiles)

        self.recentFiles.append("(none)")
        self.recentDataFiles.append("(none)")
        self.recentEdgesFiles.append("(none)")
        self.setFileLists()

        if len(self.recentFiles) > 0 and os.path.exists(self.recentFiles[0]):
            self.selectNetFile(0)

        # if items not loaded with the network, load previous items
        if len(self.recentDataFiles) > 1 and \
            self.recentDataFiles[0] == 'none' and \
                os.path.exists(self.recentDataFiles[1]):
            self.selectDataFile(1)

        # if links not loaded with the network, load previous links    
        if len(self.recentEdgesFiles) > 1 and \
            self.recentEdgesFiles[0] == 'none' and \
                os.path.exists(self.recentEdgesFiles[1]):
            self.selectEdgesFile(1)

    # user selected a graph file from the combo box
    def selectNetFile(self, n):
        if n < len(self.recentFiles) :
            name = self.recentFiles[n]
            self.recentFiles.remove(name)
            self.recentFiles.insert(0, name)
        elif n:
            self.browseNetFile(1)

        if len(self.recentFiles) > 0:
            self.setFileLists()
            self.openFile(self.recentFiles[0])

    # user selected a data file from the combo box
    def selectEdgesFile(self, n):
        if n < len(self.recentEdgesFiles) :
            name = self.recentEdgesFiles[n]
            self.recentEdgesFiles.remove(name)
            self.recentEdgesFiles.insert(0, name)

        if len(self.recentEdgesFiles) > 0:
            self.setFileLists()
            self.addEdgesFile(self.recentEdgesFiles[0])

    def selectDataFile(self, n):
        if n < len(self.recentDataFiles) :
            name = self.recentDataFiles[n]
            self.recentDataFiles.remove(name)
            self.recentDataFiles.insert(0, name)

        if len(self.recentDataFiles) > 0:
            self.setFileLists()
            self.addDataFile(self.recentDataFiles[0])

    def readingFailed(self, infoa='No data loaded', infob='', infoc='', infod=''):
        self.graph = None
        self.send("Network", None)
        self.send("Items", None)
        self.infoa.setText(infoa)
        self.infob.setText(infob)
        self.infoc.setText(infoc)
        self.infod.setText(infod)

    def openFile(self, fn):
        """Read network from file."""

        # read network file
        if fn == "(none)":
            self.readingFailed()
            return

        fileExt = lower(os.path.splitext(fn)[1])
        if not fileExt in (".net", ".gml", ".gpickle"):
            self.readingFailed(infob='Network file type not supported')
            return

        #try:
        net = Orange.network.readwrite.read(fn, auto_table=self.auto_table)

        #except:
        #    self.readingFailed(infob='Could not read file')
        #    return

        if net == None:
            self.readingFailed(infob='Error reading file')
            return

        if self.auto_table:
            self.infoc.setText("Vertices data generated and added automatically")
            self.auto_items = net.items()
        else:
            self.auto_items = None

        self.infoa.setText("%d nodes" % net.number_of_nodes())

        if net.is_directed():
            self.infob.setText("Directed graph")
        else:
            self.infob.setText("Undirected graph")

        # make new data and send it
        fName = os.path.split(fn)[1]
        if "." in fName:
            #data.name = string.join(string.split(fName, '.')[:-1], '.')
            pass
        else:
            #data.name = fName
            pass

        self.graph = net

        # Find items data file for selected network
        items_candidate = os.path.splitext(fn)[0] + ".tab"
        if os.path.exists(items_candidate):
            self.readDataFile(items_candidate)
            if items_candidate in self.recentDataFiles:
                self.recentDataFiles.remove(items_candidate)
            self.recentDataFiles.insert(0, items_candidate)
        elif os.path.exists(os.path.splitext(fn)[0] + "_items.tab"):
            items_candidate = os.path.splitext(fn)[0] + "_items.tab"
            self.readDataFile(items_candidate)
            if items_candidate in self.recentDataFiles:
                self.recentDataFiles.remove(items_candidate)
            self.recentDataFiles.insert(0, items_candidate)
        else:
            if '(none)' in self.recentDataFiles:
                self.recentDataFiles.remove('(none)')
            self.recentDataFiles.insert(0, '(none)')

        # Find links data file for selected network
        links_candidate = os.path.splitext(fn)[0] + "_links.tab"
        if os.path.exists(links_candidate):
            self.readEdgesFile(links_candidate)
            self.recentEdgesFiles.insert(0, links_candidate)
        else:
            if '(none)' in self.recentEdgesFiles:
                self.recentEdgesFiles.remove('(none)')
            self.recentEdgesFiles.insert(0, '(none)')

        self.setFileLists()

        self.send("Network", self.graph)
        if self.graph != None and self.graph.items() != None:
            self.send("Items", self.graph.items())
        else:
            self.send("Items", None)

    def addDataFile(self, fn):
        if fn == "(none)" or self.graph == None:

            if self.auto_items is not None:
                self.infoc.setText("Vertices data generated and added automatically")
                self.graph.set_items(self.auto_items)
            else:
                self.infoc.setText("No vertices data file specified")
                self.graph.set_items(None)

            self.send("Network", self.graph)
            self.send("Items", self.graph.items())
            return

        self.readDataFile(fn)

        self.send("Network", self.graph)
        self.send("Items", self.graph.items())

    def readDataFile(self, fn):
        table = ExampleTable(fn)

        if len(table) != self.graph.number_of_nodes():
            self.infoc.setText("Vertices data length does not match number of vertices")

            if '(none)' in self.recentDataFiles:
                self.recentDataFiles.remove('(none)')

            self.recentDataFiles.insert(0, '(none)')
            self.setFileLists()
            return

        items = self.graph.items()
        if items is not None and \
                'x' in items.domain and \
                'y' in items.domain and \
                len(self.graph.items()) == len(table) and \
                'x' not in table.domain and 'y' not in table.domain:
            xvar = items.domain['x']
            yvar = items.domain['y']
            tmp = Orange.data.Table(Orange.data.Domain([xvar, yvar], False), items)
            table = Orange.data.Table([table, tmp])

        self.graph.set_items(table)
        self.infoc.setText("Vertices data file added")

    def addEdgesFile(self, fn):
        if fn == "(none)" or self.graph == None:
            self.infod.setText("No edges data file specified")
            #self.graph.setattr("links", None)
            self.send("Network", self.graph)
            self.send("Items", None)
            return

        self.readEdgesFile(fn)

        self.send("Network", self.graph)
        self.send("Items", self.graph.items())

    def readEdgesFile(self, fn):
        table = ExampleTable(fn)
        if self.graph.is_directed():
            nEdges = len(self.graph.getEdges())
        else:
            nEdges = len(self.graph.getEdges()) / 2

        if len(table) != nEdges:
            self.infod.setText("Edges data length does not match number of edges")

            if '(none)' in self.recentEdgesFiles:
                self.recentEdgesFiles.remove('(none)')

            self.recentEdgesFiles.insert(0, '(none)')
            self.setFileLists()
            return

        self.graph.set_links(table)
        self.infod.setText("Edges data file added")

    def browseNetFile(self, inDemos=0):
        """user pressed the '...' button to manually select a file to load"""

        "Display a FileDialog and select a file"
        if inDemos:
            import os
            try:
                import pkg_resources
                startfile = pkg_resources.load_entry_point("Orange-Network", "orange.data.io.search_paths", "network")().next()[1]
            except:
                startfile = ""

#            if not startfile or not os.path.exists(startfile):
#                try:
#                    import win32api, win32con
#                    t = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SOFTWARE\\Python\\PythonCore\\%i.%i\\PythonPath\\Orange" % sys.version_info[:2], 0, win32con.KEY_READ)
#                    t = win32api.RegQueryValueEx(t, "")[0]
#                    startfile = t[:t.find("orange")] + "orange\\doc\\networks"
#                except:
#                    startfile = ""
#
#            if not startfile or not os.path.exists(startfile):
#                d = OWGUI.__file__
#                if d[-8:] == "OWGUI.py":
#                    startfile = d[:-22] + "doc/networks"
#                elif d[-9:] == "OWGUI.pyc":
#                    startfile = d[:-23] + "doc/networks"
#
#            if not startfile or not os.path.exists(startfile):
#                d = os.getcwd()
#                if d[-12:] == "OrangeCanvas":
#                    startfile = d[:-12] + "doc/networks"
#                else:
#                    if d[-1] not in ["/", "\\"]:
#                        d += "/"
#                    startfile = d + "doc/networks"

            if not os.path.exists(startfile):
                QMessageBox.information(None, "File", "Cannot find the directory with example networks", QMessageBox.Ok + QMessageBox.Default)
                return
        else:
            if len(self.recentFiles) == 0 or self.recentFiles[0] == "(none)":
                if sys.platform == "darwin":
                    startfile = user.home
                else:
                    startfile = "."
            else:
                startfile = self.recentFiles[0]

        filename = unicode(QFileDialog.getOpenFileName(self, 'Open a Network File', startfile, "All network files (*.gpickle *.net *.gml)\nNetworkX graph as Python pickle (*.gpickle)\nPajek files (*.net)\nGML files (*.gml)\nAll files (*.*)"))

        if filename == "": return
        if filename in self.recentFiles: self.recentFiles.remove(filename)
        self.recentFiles.insert(0, filename)
        self.setFileLists()
        self.selectNetFile(0)

    def browseDataFile(self, inDemos=0):
        if self.graph == None:
            return

        #Display a FileDialog and select a file
        if len(self.recentDataFiles) == 0 or self.recentDataFiles[0] == "(none)":
            if len(self.recentFiles) == 0 or self.recentFiles[0] == "(none)":
                if sys.platform == "darwin":
                    startfile = user.home
                else:
                    startfile = "."
            else:
                startfile = os.path.dirname(self.recentFiles[0])

        else:
            startfile = self.recentDataFiles[0]

        filename = unicode(QFileDialog.getOpenFileName(self, 'Open a Vertices Data File', startfile, 'Data files (*.tab)\nAll files(*.*)'))

        if filename == "": return
        if filename in self.recentDataFiles: self.recentDataFiles.remove(filename)
        self.recentDataFiles.insert(0, filename)
        self.setFileLists()
        self.addDataFile(self.recentDataFiles[0])

    def browseEdgesFile(self, inDemos=0):
        if self.graph == None:
            return

        #Display a FileDialog and select a file
        if len(self.recentEdgesFiles) == 0 or self.recentEdgesFiles[0] == "(none)":
            if len(self.recentFiles) == 0 or self.recentFiles[0] == "(none)":
                if sys.platform == "darwin":
                    startfile = user.home
                else:
                    startfile = "."
            else:
                startfile = os.path.dirname(self.recentFiles[0])

        else:
            startfile = self.recentEdgesFiles[0]

        filename = unicode(QFileDialog.getOpenFileName(self, 'Open a Edges Data File', startfile, 'Data files (*.tab)\nAll files(*.*)'))

        if filename == "": return
        if filename in self.recentEdgesFiles: self.recentEdgesFiles.remove(filename)
        self.recentEdgesFiles.insert(0, filename)
        self.setFileLists()
        self.addEdgesFile(self.recentEdgesFiles[0])

    def setInfo(self, info):
        for (i, s) in enumerate(info):
            self.info[i].setText(s)

    def sendReport(self):
        self.reportSettings("Network file",
                            [("File name", self.filecombo.currentText()),
                             ("Vertices", self.graph.number_of_nodes()),
                             hasattr(self.graph, "is_directed") and ("Directed", OWGUI.YesNo[self.graph.is_directed()])])
        self.reportSettings("Vertices meta data", [("File name", self.datacombo.currentText())])
        self.reportData(self.graph.items(), None)
        self.reportSettings("Edges meta data", [("File name", self.edgescombo.currentText())])
        self.reportData(self.graph.links(), None, None)

if __name__ == "__main__":
    a = QApplication(sys.argv)
    owf = OWNxFile()
    owf.activateLoadedSettings()
    owf.show()
    a.exec_()
    owf.saveSettings()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.