I've managed to get a few functions from R working as I'd expect with rpy2, 
however, I'm trying to move toward embedding some of these functions in a gui 
using PyQt4.  There is no specific reason for PyQt4 other than I'm somewhat 
familiar with it.  Anyway,  I tried placing the rpy2 functions into a gui 
thread (QThread) and while I can pass the output from the thread to the main 
application, during the running of the R functions is takes over my entire 
MainWindow.  I've done threading many times in the past with numpy functions, 
however, this is my first venture with R.  
Can rpy2 be embedded into a thread and does anyone have a working example?   

Are there any issues as to where the rinterface is initated and which thread it 
will takeover?  

I'm pretty stumped, while the program works, the freezing user interface while 
R is chugging seems to defeat the purpose of a GUI.

Cheers,

Brian

---I've attached a snippet of the thread that uses the xcms and faahko 
libraries from bioconductor in R.  Does anyone see any glaring issues that 
would cause the behavior I'm seeing? (I've also tried running the thread 
without the PyQt4 signal emits--same behavior)
###########################

import sys
import rpy2.robjects as ro
import rpy2.rinterface as ri
from eicClass import EIC

from PyQt4 import QtCore, QtGui


class StdOutFaker:
    def __init__(self, parent):
        self.P = parent
    def write(self, string):
#        print string
        if string != '\n' and string != ' ' and string != '':
            self.P.emitUpdate(string)

class XCMSThread(QtCore.QThread):

    def __init__(self, parent = None):
        QtCore.QThread.__init__(self, parent)

        self.finished = False
        self.stopped = False
        self.mutex = QtCore.QMutex()
        self.ready = True
        self.numSteps = 25
        self.Rliblist = ['xcms']
        self.Rlibs = self.initRlibs(self.Rliblist)

        self.matchedFilterParams = {'fwhm':30.,
                                'sigma':30/2.3548,
                                'max': 5.,
                                'snthresh':10.,
                                'step':0.1,
                                'steps':2.,
                                'mzdiff':0.1,
                                }

        self.matchedFilterTypes = {'fwhm':float,
                               'sigma':float,
                               'max':float,
                               'snthresh':float,
                               'step':float,
                               'steps':float,
                               'mzdiff':float
                                }


        self.centWaveParams = {'ppm': 10.,
                               'peakwidth': str([20,50]),#this needs to be 
fixed, the new version of PyQt4 handles this better
                               'snthresh':10.,
                               'prefilter':str([3,100]),
                               'mzdiff':-0.001,
                               }
        self.centWaveTypes = {'ppm': float,
                               'peakwidth': str,
                               'snthresh':float,
                               'prefilter':str,
                               'mzdiff':float,
                           }
        ################################

        self.groupParams = {'bw':30.,
                            'minfrac':0.1,
                            'mzwid':0.1,
                            'max':3
                            }

        self.groupTypes = {}
        ##############################

        self.retcorParams = {'extra':2,
                             'span':.5,
                             'f':'symmetric',
                             'plottype':"mdevden",
                             'missing':2,
                             }
        self.retcorTypes = {}

        #########################
        self.xcmsParamDict = {'Matched Filter':self.matchedFilterParams,
                               'CentWave':self.centWaveParams}
        self.xcmsTypeDict = {'Matched Filter':self.matchedFilterTypes,
                               'CentWave':self.centWaveTypes}


    def add2ROutput(self, rVector):
        for item in rVector:
            self.emitUpdate(item)
        self.emitUpdate('_\n')

    def emitUpdate(self, updateStr):
        self.emit(QtCore.SIGNAL("xcmsOutUpdate(PyQt_PyObject)"),updateStr)

    def run(self):
        try:
            sys.stdout = StdOutFaker(self)
            r = ro.r
            a = r('cdfpath = system.file("cdf", package = "faahKO")')
            cdfpath = ri.globalEnv.get("cdfpath")
            r('cdffiles = list.files(cdfpath, recursive = TRUE, full.names = 
TRUE)')
            r('cdffiles = cdffiles[1:2]')
            cdffiles = ri.globalEnv.get("cdffiles")

            self.add2ROutput(cdffiles)
            xset = r.xcmsSet(cdffiles)
            ri.globalEnv["xset"] = xset
            xset = r.group(xset)
            self.emitUpdate('\n\nXSET')
            self.emitUpdate(str(xset)+'\n')

            xset2 = r.retcor(xset, family = "symmetric", plottype = "mdevden")
            ri.globalEnv["xset2"] = xset2
            self.emitUpdate('\n\nXSET2')
            self.emitUpdate(str(xset2)+'\n')
            xset2 = r.group(xset2, bw = 10)
            xset3 = r.fillPeaks(xset2)
            self.emitUpdate('\n\nXSET3')
            self.emitUpdate(str(xset3)+'\n')
            ri.globalEnv["xset3"] = xset3
            gt = r.groups(xset3)
            tsidx = r.groupnames(xset3)
            ri.globalEnv["tsidx"] = tsidx
            eicmax = r.length(tsidx)
            eic = r.getEIC(xset3, rtrange = 150, groupidx = tsidx, rt = 
"corrected")
            eicClass = EIC(eic)
            self.emit(QtCore.SIGNAL("xcmsGetEIC(PyQt_PyObject)"),eicClass)
            sys.stdout=sys.__stdout__
        except:
            sys.stdout=sys.__stdout__


    def stop(self):
        print "stop try"
        try:
            self.mutex.lock()
            self.stopped = True
        finally:
            self.mutex.unlock()

    def isStopped(self):
        print "stop try"
        try:
            self.mutex.lock()
            return self.stopped
        finally:
            self.mutex.unlock()

    def __del__(self):
        self.exiting = True
        self.wait()

    def initRlibs(self,libList):
        libDict = {}

        for lib in libList:
            try:
                libDict[lib] = ro.r('library(%s)'%lib)
            except:
                errorMsg ='Error loading R library %s\nCheck Library 
Installation\n'%lib
                errorMsg += "Sorry: %s\n\n:%s\n"%(sys.exc_type, sys.exc_value)
                print errorMsg

        return libDict

    def list2rpyFuntions(self,strList):
        funcDict = {}
        for entry in strList:
            try:
                funcDict[entry] = ro.r['%s'%entry]
            except:
                errorMsg ='Error creating function %s'%entry
                errorMsg += "Sorry: %s\n\n:%s\n"%(sys.exc_type, sys.exc_value)
                print errorMsg

        return funcDict



      
------------------------------------------------------------------------------
Create and Deploy Rich Internet Apps outside the browser with Adobe(R)AIR(TM)
software. With Adobe AIR, Ajax developers can use existing skills and code to
build responsive, highly engaging applications that combine the power of local
resources and data with the reach of the web. Download the Adobe AIR SDK and
Ajax docs to start building applications today-http://p.sf.net/sfu/adobe-com
_______________________________________________
rpy-list mailing list
rpy-list@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/rpy-list

Reply via email to