merge graphs
authorPierre Ratinaud <ratinaud@univ-tlse2.fr>
Tue, 9 Jun 2015 09:34:38 +0000 (11:34 +0200)
committerPierre Ratinaud <ratinaud@univ-tlse2.fr>
Tue, 9 Jun 2015 09:34:38 +0000 (11:34 +0200)
PrintRScript.py
analyse_merge.py [new file with mode: 0644]
dialog.py
iramuteq.py

index fbcf5cf..53c2aae 100644 (file)
@@ -4,7 +4,7 @@
 #License: GNU/GPL
 
 import tempfile
-from chemins import ffr
+from chemins import ffr, PathOut
 import os
 import locale
 from datetime import datetime
@@ -162,13 +162,15 @@ def RchdTxt(DicoPath, RscriptPath, mincl, classif_mode, nbt = 9, svdmethod = 'sv
         row.names(data2) <- 1:nrow(data2)
         """ % ffr(DicoPath['TableUc2'])
     txt += """
-    chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
-    """
+    log1 <- "%s"
+    chd1<-CHD(data1, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, log.file = log1)
+    """ % ffr(DicoPath['log-chd1.txt'])
     
     if classif_mode == 0:
         txt += """
-    chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path)
-    """
+    log2 <- "%s"
+    chd2<-CHD(data2, x = nbt, mode.patate = mode.patate, svd.method = svd.method, libsvdc.path = libsvdc.path, log.file = log2)
+    """ % ffr(DicoPath['log-chd2.txt'])
     
     txt += """
     #lecture des uce
@@ -1201,6 +1203,41 @@ class ExportAfc(PrintRScript) :
         txt = """
         """
 
+class MergeGraphes(PrintRScript) :
+    def __init__(self, parametres):
+        self.script = u"#Script genere par IRaMuTeQ - %s\n" % datetime.now().ctime()
+        self.pathout = PathOut()
+        self.parametres = parametres
+        self.scriptout = self.pathout['temp']
+        
+    def make_script(self) :
+        #FIXME
+        
+        txt = """
+        library(igraph)
+        library(Matrix)
+        graphs <- list()
+        """
+        load = """
+        load("%s")
+        g <- graph.simi$graph
+        V(g)$weight <- (graph.simi$mat.eff/nrow(dm))*100
+        graphs[['%s']] <- g
+        """
+        for i, graph in enumerate(self.parametres['lgraphes']) :
+            path = os.path.dirname(graph)
+            gname = ''.join(['g', `i`])
+            RData = os.path.join(path,'RData.RData')
+            txt += load % (ffr(RData), gname)
+        self.add(txt)
+        self.sources(['/home/pierre/workspace/iramuteq/Rscripts/simi.R'])
+        txt = """
+        ng <- merge.graph(graphs)
+        ngraph <- list(graph=ng, layout=layout.fruchterman.reingold(ng, dim=3), labex.cex=V(ng)$weight)
+        write.graph(ng, "%s", format = 'graphml')
+        """ % ffr(self.parametres['grapheout'])
+        self.add(txt)
+    
 class TgenSpecScript(PrintRScript):
     def make_script(self):
         self.packages(['textometry'])
diff --git a/analyse_merge.py b/analyse_merge.py
new file mode 100644 (file)
index 0000000..549ac79
--- /dev/null
@@ -0,0 +1,54 @@
+# -*- coding: utf-8 -*-
+#Author: Pierre Ratinaud
+#Copyright (c) 2015 Pierre Ratinaud
+#License: GNU/GPL
+
+import os
+from chemins import PathOut
+from functions import exec_rcode, check_Rresult
+from dialog import MergeDialog
+import wx
+from time import sleep
+from PrintRScript import MergeGraphes
+
+def merge_graphes(lgraphes):
+    script = MergeGraphes({'lgraphes':lgraphes, 'grapheout' : '/tmp/graphe.graphml'}) 
+    script.make_script()
+    script.write()
+    return script
+
+class AnalyseMerge :
+    def __init__(self, ira, parametres, dlg = None):
+        self.ira = ira
+        self.dlg = dlg
+        self.parametres = parametres
+        if 'pathout' not in self.parametres :
+            self.parametres['pathout'] = PathOut(self.parametres['fileout'], analyse_type = self.parametres['type'], dirout = os.path.dirname(self.parametres['fileout'])).mkdirout()
+            self.pathout = PathOut(analyse_type = self.parametres['type'], dirout = self.parametres['pathout'])
+        else :
+            self.pathout = PathOut(dirout = self.parametres['pathout'], analyse_type = self.parametres['type'])
+        if self.doparametres(dlg=dlg) is not None :
+            script = merge_graphes(self.parametres['graphs'])
+            self.doR(script.scriptout, dlg=False)
+            print 'fini'
+            
+
+    def doparametres(self, dlg=None):
+        if dlg is not None :
+            dial = MergeDialog(self.ira)
+            res = dial.ShowModal()
+            if res == wx.ID_OK :
+                self.parametres['graphs'] = [graph.GetPath() for graph in dial.graphs if graph.GetPath() != '']
+                return True
+        return True
+            
+    def doR(self, Rscript, wait = False, dlg = None, message = '') :
+        #log.info('R code...')
+        pid = exec_rcode(self.ira.RPath, Rscript, wait = wait)
+        while pid.poll() is None :
+            if dlg :
+                self.dlg.Pulse(message)
+                sleep(0.2)
+            else :
+                sleep(0.2)
+        return check_Rresult(self.ira, pid)
\ No newline at end of file
index 82dc089..6eec615 100755 (executable)
--- a/dialog.py
+++ b/dialog.py
@@ -544,9 +544,9 @@ class PrefGraph(wx.Dialog):
         self.paramgraph=paramgraph
         self.labeltype = wx.StaticText(self, -1, _(u"Graphic type").decode('utf8'))
         if self.paramgraph['clnb'] <= 3 :
-            choix = [u'2D']#, 'web 2D']
+            choix = [u'2D', 'web 2D']
         else :
-            choix=[u'2D' ,u'3D']#, 'web 2D', 'web 3D']
+            choix=[u'2D' ,u'3D', 'web 2D', 'web 3D']
         self.choicetype = wx.Choice(self, -1, (100,50), choices=choix)
         self.label_format = wx.StaticText(self, -1, _(u"Picture format").decode('utf8'))
         self.choix_format =  wx.Choice(self, -1, (100,50), choices = ['png', 'svg'])        
@@ -1577,7 +1577,7 @@ class SearchDial ( wx.Frame ):
         self.search = wx.SearchCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_PROCESS_ENTER )
         self.search.ShowSearchButton( True )
         self.search.ShowCancelButton( True )
-        bSizer1.Add( self.search, 0, wx.ALL, 5 )
+        bSizer1.Add( self.search, 0, wx.ALL|wx.EXPAND, 5 )
         sizer2 = wx.BoxSizer(wx.HORIZONTAL)
         self.backward = wx.Button(self, wx.ID_BACKWARD, _(u"Previous").decode('utf8'))
         self.forward = wx.Button(self, wx.ID_FORWARD, _(u"Next").decode('utf8'))
@@ -1707,6 +1707,49 @@ def UnSelectList(liste) :
             last = liste.GetNextSelected(last)
             liste.Select(liste.GetFirstSelected(),False)
 
+class SearchCorpus(SearchDial):
+    def OnSearch(self, evt):
+        search_word = self.search.GetValue()
+        if search_word.strip() != '' :
+            self.corpus_ok = self.listctrl.GetCorpusByName(search_word)
+            if self.corpus_ok != [] :
+                if len(self.corpus_ok) == 1 :
+                    self.listctrl.GiveFocus(None, self.corpus_ok[0]['uuid'])
+                    self.Destroy()
+                else :
+                    self.listctrl.GiveFocus(None, self.corpus_ok[-1]['uuid'])
+                    self.forward.Enable(True)
+                    self.backward.Enable(False)                        
+                    self.forwitem = 1
+                    self.backitem = -1
+                    #for corpus in corpus_ok :
+                    #    self.listctrl.SetContentBackground(uuid = corpus['uuid'])
+            else :
+                print 'no results'
+        else :
+            self.Destroy()
+            
+    def onforward(self, evt) :
+        self.forwitem += 1
+        self.listctrl.GiveFocus(uuid=self.corpus_ok[-self.forwitem]['uuid'])
+        if self.forwitem == len(self.corpus_ok) :
+            self.forward.Enable(False)
+            self.backward.Enable(True)
+            self.backitem = self.forwitem - 1
+        else :
+            self.backitem = self.forwitem - 1
+            self.backward.Enable(True)
+
+    def onbackward(self, evt) :
+        self.listctrl.GiveFocus(uuid=self.corpus_ok[-self.backitem]['uuid'])
+        self.backitem -= 1
+        if self.backitem == 0 :
+            self.forwitem -= 1
+            self.forward.Enable(True)
+            self.backward.Enable(False)
+        else :
+            self.forwitem -= 1
+            self.forward.Enable(True)
 
 class OptLexi(wx.Dialog):
     def __init__(self, parent, force_chi = False):
@@ -2527,9 +2570,10 @@ class CorpusPref ( wx.Dialog ):
         self.Centre( wx.BOTH )
 
     def OnChangeDir(self, evt) :
-        dlg = wx.DirDialog(self.parent, _(u"Choose a folder").decode('utf8'), style = wx.DD_DEFAULT_STYLE)
-        if dlg.ShowModal() == wx.ID_OK :
+        sdlg = wx.DirDialog(self.parent, _(u"Choose a folder").decode('utf8'), style = wx.DD_DEFAULT_STYLE)
+        if sdlg.ShowModal() == wx.ID_OK :
             self.repout_choices.SetValue(dlg.GetPath())
+        sdlg.Destroy()
     
     def __del__( self ):
         pass
@@ -3286,7 +3330,7 @@ class ImageViewer ( wx.Frame ):
             self, message=_(u"Save as...").decode('utf8'), defaultDir=os.getcwd(),
             defaultFile= self.imagename, wildcard=self.parametres['wildcard'], style=wx.SAVE | wx.OVERWRITE_PROMPT
             )
-        dlg.SetFilterIndex(2)
+        dlg.SetFilterIndex(0)
         dlg.CenterOnParent()
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
@@ -3329,4 +3373,105 @@ class BarFrame :
             exec_rcode(ira.RPath, tmpscript, wait = True)
             win = ImageViewer(ira, parametres, _(u"Graphic").decode('utf8'), size=(700, 500))
             win.Show(True)
-        dial.Destroy()           
\ No newline at end of file
+        dial.Destroy()           
+
+class MergeDialog ( wx.Dialog ):
+    
+    def __init__( self, parent ):
+        wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX )
+        
+        self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
+        
+        bSizer1 = wx.BoxSizer( wx.VERTICAL )
+        
+        self.m_scrolledWindow1 = wx.ScrolledWindow( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 600,200 ), wx.HSCROLL|wx.VSCROLL )
+        self.m_scrolledWindow1.SetScrollRate( 5, 5 )
+        #self.m_scrolledWindow1.SetMinSize( wx.Size( 500,200 ) )
+        
+        fgSizer2 = wx.FlexGridSizer( 0, 2, 0, 0 )
+        fgSizer2.AddGrowableCol( 1 )
+        fgSizer2.SetFlexibleDirection( wx.BOTH )
+        fgSizer2.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_ALL )
+        
+        self.m_staticText3 = wx.StaticText( self.m_scrolledWindow1, wx.ID_ANY, u"graphe 1", wx.DefaultPosition, wx.DefaultSize, 0 )
+        self.m_staticText3.Wrap( -1 )
+        fgSizer2.Add( self.m_staticText3, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
+        
+        self.m_filePicker3 = wx.FilePickerCtrl( self.m_scrolledWindow1, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE|wx.FLP_FILE_MUST_EXIST|wx.FLP_USE_TEXTCTRL )
+        self.m_filePicker3.SetMinSize( wx.Size( 400,-1 ) )
+        
+        fgSizer2.Add( self.m_filePicker3, 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND, 5 )
+        
+        self.m_staticText4 = wx.StaticText( self.m_scrolledWindow1, wx.ID_ANY, u"graphe 2", wx.DefaultPosition, wx.DefaultSize, 0 )
+        self.m_staticText4.Wrap( -1 )
+        fgSizer2.Add( self.m_staticText4, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
+        
+        self.m_filePicker4 = wx.FilePickerCtrl( self.m_scrolledWindow1, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE|wx.FLP_FILE_MUST_EXIST|wx.FLP_USE_TEXTCTRL )
+        self.m_filePicker4.SetMinSize( wx.Size( 400,-1 ) )
+        
+        fgSizer2.Add( self.m_filePicker4, 1, wx.ALL|wx.EXPAND, 5 )
+        
+        
+        self.m_scrolledWindow1.SetSizer( fgSizer2 )
+        self.m_scrolledWindow1.Layout()
+        bSizer1.Add( self.m_scrolledWindow1, 0, wx.ALL, 5 )
+        
+        self.button_add = wx.Button( self, wx.ID_ANY, u"Add graphe", wx.DefaultPosition, wx.DefaultSize, 0 )
+        bSizer1.Add( self.button_add, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
+        
+        m_sdbSizer1 = wx.StdDialogButtonSizer()
+        self.m_sdbSizer1OK = wx.Button( self, wx.ID_OK )
+        m_sdbSizer1.AddButton( self.m_sdbSizer1OK )
+        self.m_sdbSizer1Cancel = wx.Button( self, wx.ID_CANCEL )
+        m_sdbSizer1.AddButton( self.m_sdbSizer1Cancel )
+        m_sdbSizer1.Realize();
+        
+        bSizer1.Add( m_sdbSizer1, 1, wx.EXPAND, 5 )
+        
+        
+        self.SetSizer( bSizer1 )
+        self.Layout()
+        bSizer1.Fit( self )
+        
+        self.Centre( wx.BOTH )
+        
+        # Connect Events
+        self.button_add.Bind( wx.EVT_BUTTON, self.OnAddGraphe )
+        self.m_filePicker3.Bind(wx.EVT_FILEPICKER_CHANGED, self.OnFileChange)
+        self.m_filePicker4.Bind(wx.EVT_FILEPICKER_CHANGED, self.OnFileChange)
+        self.finish(fgSizer2, bSizer1)
+    
+    def __del__( self ):
+        pass
+    
+    def finish(self, fgSizer2, bSizer1):
+        self.graphs = [self.m_filePicker3, self.m_filePicker4]
+        self.fgSizer2 = fgSizer2
+        self.bSizer1 = bSizer1
+    
+    def OnFileChange(self, evt):
+        obj = evt.GetEventObject()
+        if obj.GetPath() != '' :
+            for graph in self.graphs :
+                graph.SetInitialDirectory(os.path.dirname(obj.GetPath()))
+    
+    # Virtual event handlers, overide them in your derived class
+    def OnAddGraphe( self, event ):
+        lab =  wx.StaticText( self.m_scrolledWindow1, wx.ID_ANY, ' '.join(['graphe', `len(self.graphs) + 1`]), wx.DefaultPosition, wx.DefaultSize, 0 )
+        lab.Wrap(-1)
+        self.graphs.append( wx.FilePickerCtrl( self.m_scrolledWindow1, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.*", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE|wx.FLP_FILE_MUST_EXIST|wx.FLP_USE_TEXTCTRL ) )
+        self.graphs[-1].SetMinSize( wx.Size( 400, -1))
+        if self.graphs[-2].GetPath() != '' :
+            self.graphs[-1].SetInitialDirectory(os.path.dirname(self.graphs[-2].GetPath()))
+        self.graphs[-1].Bind(wx.EVT_FILEPICKER_CHANGED, self.OnFileChange)
+        self.fgSizer2.Add( lab, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5 )
+        self.fgSizer2.Add( self.graphs[-1], 1, wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND, 5 )
+        self.m_scrolledWindow1.Layout()
+        self.m_scrolledWindow1.SetSizer( self.fgSizer2 )
+        #self.fgSizer2.Fit( self.m_scrolledWindow1 )
+        self.Layout()
+        #self.bSizer1.Fit(self)
+        event.Skip()
+    
+    def RemoveGraphe(self, evt ):
+        pass
\ No newline at end of file
index fc77952..ef99d20 100644 (file)
@@ -58,6 +58,7 @@ from chemins import RscriptsPath, ConstructConfigPath, ConstructDicoPath, Constr
 from parse_factiva_xml import ImportFactiva
 from parse_dmi import ImportDMI
 from tools import Extract
+from analyse_merge import AnalyseMerge
 
 from tree import LeftTree
 ##########################################################
@@ -99,6 +100,7 @@ ID_Fact_mail = wx.NewId()
 ID_Fact_copy = wx.NewId()
 ID_exportmeta = wx.NewId()
 ID_importdmi = wx.NewId()
+ID_merge = wx.NewId()
 ##########################################################
 #elements de configuration
 ##########################################################
@@ -120,10 +122,10 @@ ConfigGlob.read(DictConfigPath['global'])
 DefaultConf = ConfigParser()
 DefaultConf.read(DictConfigPath['preferences'])
 #repertoire de l'utilisateur
-if os.getenv('HOME') != None:
-    user_home = os.getenv('HOME')
-else:
-    user_home = os.getenv('HOMEPATH')
+user_home = os.getenv('HOME')
+if user_home is None :
+    user_home = os.path.expanduser('~')
+
 UserConfigPath = os.path.abspath(os.path.join(user_home, '.iramuteq'))
 #Si pas de fichiers de config utilisateur, on cree le repertoire
 CreateIraDirectory(UserConfigPath, AppliPath)
@@ -206,7 +208,8 @@ class IraFrame(wx.Frame):
                  size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | 
                                             wx.SUNKEN_BORDER | 
                                             wx.CLIP_CHILDREN):
-        log.info('Starting...')
+        log.info('Starting... ' )
+        log.info('version : %s' % ConfigGlob.get('DEFAULT', 'version'))
         wx.Frame.__init__(self, parent, id, title, pos, size, style)
         #configuration
         self.AppliPath = AppliPath
@@ -271,6 +274,9 @@ class IraFrame(wx.Frame):
         item.SetBitmap(self.images_analyses['importdmi'])
         file_menu.AppendItem(item)        
         
+        item = wx.MenuItem(file_menu, ID_merge, _(u'Merge graphs').decode('utf8'), _(u'Merge graphs').decode('utf8'))
+        file_menu.AppendItem(item)
+        
         menuFactiva = wx.Menu()
         fact_from_xml = wx.MenuItem(menuFactiva, ID_Fact_xml, _(u"from xml").decode('utf8'))
         fact_from_xml.SetBitmap(self.images_analyses['factiva_xml'])
@@ -604,6 +610,7 @@ class IraFrame(wx.Frame):
         self.Bind(wx.EVT_MENU, self.OnImportEuropress, id=ID_ImportEuro)
         self.Bind(wx.EVT_MENU, self.OnImportDMI, id=ID_importdmi)
         self.Bind(wx.EVT_MENU, self.OnExportMeta, id=ID_exportmeta)
+        self.Bind(wx.EVT_MENU, self.OnMergeGraph, id = ID_merge)
         self.Bind(wx.EVT_CLOSE, self.OnClose)
 ##################################################################
         flags = self._mgr.GetAGWFlags()
@@ -801,9 +808,7 @@ class IraFrame(wx.Frame):
             del busy
             
     def OpenText(self):
-        dlg = progressbar(self, 5) 
-        
-        builder =  Builder(self, dlg)
+        builder =  Builder(self, 5)
         if builder.res == wx.ID_OK :
             try :
                 corpus = builder.doanalyse()
@@ -811,11 +816,11 @@ class IraFrame(wx.Frame):
                 self.tree.OnItemAppend(corpus.parametres)
                 OpenAnalyse(self, corpus.parametres)
             except :
-                dlg.Destroy()
+                builder.dlg.Destroy()
                 BugReport(self)
             else :
                 count = 1
-                keepGoing = dlg.Update(count, u"Lecture du fichier")
+                keepGoing = builder.dlg.Update(count, u"Lecture du fichier")
                 self.ShowMenu('view')
                 self.ShowMenu('text')
                 self.ShowMenu('matrix', False)
@@ -823,8 +828,8 @@ class IraFrame(wx.Frame):
                 self.DataTxt = False
                 self.Text = ''
                 count += 1
-                keepGoing = dlg.Update(count, u"Chargement du dictionnaire")
-                dlg.Destroy()
+                keepGoing = builder.dlg.Update(count, u"Chargement du dictionnaire")
+                builder.dlg.Destroy()
         
     def OnExit(self, event):
         self.Close()
@@ -1002,6 +1007,9 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
 #                 PlaySound(self)
 #         except:
 #             BugReport(self)
+    def OnMergeGraph(self, evt):
+        #FIXME
+        AnalyseMerge(self, {'type': 'merge', 'fileout' : '/tmp/test.txt'}, dlg = 5)
     
     def OnProto(self, evt, matrix = None) :
         self.analyse_matrix(Prototypical, matrix = matrix, analyse_type = 'proto', dlgnb = 3) 
@@ -1194,7 +1202,7 @@ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, États-Unis."""
             else:
                 truepath = False
         else:
-            pass
+            return
         if truepath :
             if os.path.splitext(self.filename)[1] in ['.csv', '.xls', '.ods']:
                 self.tableau = Tableau(self, self.filename)
@@ -1345,7 +1353,7 @@ class MySplashScreen(wx.SplashScreen):
         bmp = wx.Image(os.path.join(ImagePath, 'splash.png')).ConvertToBitmap()
         wx.SplashScreen.__init__(self, bmp,
                                  wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
-                                 2000, None, -1)
+                                 1000, None, -1)
         self.Bind(wx.EVT_CLOSE, self.OnClose)
         self.fc = wx.FutureCall(1, self.ShowMain)