示例#1
0
 def foo(queue):
     import rpy2.rinterface as rinterface
     rinterface.endr(1)
     try:
         tmp = ri.SexpVector([1, 2], ri.INTSXP)
         res = (False, None)
     except RuntimeError, re:
         res = (True, re)
 def foo(queue):
     import rpy2.rinterface as rinterface
     rinterface.endr(1)
     try:
         tmp = ri.SexpVector([1,2], ri.INTSXP)
         res = (False, None)
     except RuntimeError, re:
         res = (True, re)
示例#3
0
 def foo(queue):
     import rpy2.rinterface as rinterface
     rdate = rinterface.baseenv['date']
     rinterface.endr(1)
     try:
         tmp = rdate()
         res = (False, None)
     except RuntimeError, re:
         res = (True, re)
 def foo(queue):
     import rpy2.rinterface as rinterface
     rdate = rinterface.baseenv['date']
     rinterface.endr(1)
     try:
         tmp = rdate()
         res = (False, None)
     except RuntimeError, re:
         res = (True, re)
示例#5
0
def _call_with_ended_r(queue):
    import rpy2.rinterface_cffi as rinterface
    rinterface.initr()
    rdate = rinterface.baseenv['date']
    rinterface.endr(0)
    try:
        rdate()
        res = (False, None)
    except RuntimeError as re:
        res = (True, re)
    except Exception as e:
        res = (False, e)
    queue.put(res)
示例#6
0
        def foo(queue):
            import rpy2.rinterface as rinterface

            rdate = rinterface.baseenv["date"]
            rinterface.endr(1)
            try:
                tmp = rdate()
                res = (False, None)
            except RuntimeError as re:
                res = (True, re)
            except Exception as e:
                res = (False, e)
            queue.put(res)
 def testNewWithoutInit(self):
     self.assertTrue(False) # worked when tested, but calling endEmbeddedR causes trouble
     ri.endr(1)
     self.assertRaises(RuntimeError, ri.SexpVector, [1,2], ri.INTSXP)
     #FIXME: trouble... does not initialize R when failing the test
     ri.initr()
示例#8
0
def end_R():
    rinterface.endr()
示例#9
0
 def closeEvent(self,  event = None):
     try:
         ri.endr()
     except:
         pass
示例#10
0
def end_R():
    rinterface.endr()
示例#11
0
 def testCallErrorWhenEndedR(self):
     self.assertTrue(False) # worked when tested, but calling endEmbeddedR causes trouble
     t = rinterface.baseNameSpaceEnv['date']
     rinterface.endr(1)
     self.assertRaises(RuntimeError, t)
     rinterface.initr()
示例#12
0
文件: pyXCMS.py 项目: mfitzp/toolz
 def closeEvent(self, event=None):
     try:
         ri.endr()
     except:
         pass
    def convert_file(self, f, exc_handler=None, buffsize=10000):
        SeqArray = importr("SeqArray")
        file = SeqArray.seqOpen(os.path.realpath(f.name))
        sample = SeqArray.seqGetData(file, "sample.id")
        robjects.r('sampleID = {sample}'.format(sample=sample.r_repr()))
        numOfVariants = SeqArray.seqSummary(file, varname="variant.id")[0]

        robjects.r('''
        output <- function(data) {
        lines <- matrix(, nrow = 0, ncol = 6)
        chrom = data[[1]]
        pos = data[[2]]
        alleles <- c(strsplit(data[[3]][1], ",")[[1]], ".")
        genotype = data[[4]]
        
        internalWrite <- function(alt, hom_het, id) {
            lines <<- rbind(lines, c(chrom, pos, alleles[1], alt, hom_het, id))
        }
        
        genotype[is.na(genotype)] = length(alleles) - 1
        
        for (col in 1:ncol(genotype)) {
            num1 = genotype[1, col] + 1
            num2 = genotype[2, col] + 1
            id = sampleID[col]
            
            if (num1 == 1 & num2 == 1) {
            #nothing to print
            }
            else if (num1 != 1 & num2 == 1) {
            internalWrite(alleles[num1], "het", id)
            }
            else if (num1 == 1 & num2 != 1) {
            internalWrite(alleles[num2], "het", id)
            }
            else if (num1 == num2) {
            internalWrite(alleles[num1], "hom", id)
            }
            else {
            internalWrite(alleles[num1], "het", id)
            internalWrite(alleles[num2], "het", id)
            }
        }
        return(lines)
        }
        ''')
        output = robjects.globalenv['output']

        @ri.rternalize
        def printWithStops(data):
            result = []
            lines = output(data)
            rows = len(lines) // 6

            for line in range(rows):
                result.append(" ".join([
                    lines[line], lines[line + rows], lines[line + (2 * rows)],
                    lines[line + (3 * rows)], lines[line + (4 * rows)],
                    lines[line + (5 * rows)]
                ]))
            return StrVector(result)

        #returns pairs (a,b) such that the first a is equal to i, the last b is equal to n+1. If we look at all a's inclusively and all b's
        #exclusively then this generates intervals that partition the set of numbers from 1 to n (inclusively) such that all intervals
        #contain a buff amount of numbers except for possibly the last interval
        def inclusiveRanges(i, n, buff):
            while i <= n:
                if i + buff > n + 1:
                    buff -= i + buff - n - 1
                yield [i, i + buff]
                i += buff

        for start, end in inclusiveRanges(1, numOfVariants, buffsize):
            try:
                robjects.r('array = c({previous}:{next})'.format(
                    previous=start, next=end - 1))
                SeqArray.seqSetFilter(file,
                                      variant_sel=robjects.globalenv['array'],
                                      verbose=False)

                result = SeqArray.seqApply(
                    file,
                    StrVector(["chromosome", "position", "allele",
                               "genotype"]),
                    FUN=printWithStops,
                    margin="by.variant",
                    as_is="list")

                for variant in result:
                    for charLine in variant:
                        try:
                            line = charLine.split()
                            if line[3] == '.':
                                continue
                            result = [{
                                'chrom': line[0],
                                'pos': line[1],
                                'ref_base': line[2],
                                'alt_base': line[3],
                                'tags': None,
                                'sample_id': line[5],
                                'zygosity': line[4]
                            }]
                            yield 0, line, result
                        except Exception as e:
                            if exc_handler:
                                exc_handler(0, "", e)
                                continue
                            else:
                                raise e
            except Exception as e:
                if exc_handler:
                    exc_handler(0, "", e)
                    continue
                else:
                    raise e

        #closes the embedded R subprocess and deletes rpy2 objects
        ri.endr(0)
        del file, output, printWithStops, sample, variant
示例#14
0
#references for r interface usage from here:
#http://rpy.sourceforge.net/rpy2/doc-2.2/html/rinterface.html

#initialize the embedded r 
ri.initr()
r=ro.r

#generate some random data
mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)

#plot the random data using matplotlib (for comparison to the shiny app)
count, bins, ignored = plt.hist(s, 30, normed=True)
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r')
plt.show(block=False)

#pass the series to R
ro.globalenv["dataseries"] = ro.FloatVector(s)

#call teh shiny app, and return when the user presses a button
#gist on how to exit cleanly: https://gist.github.com/trestletech/5948876
ro.r('''
        library(shiny)
        runApp()
        quit()
        ''' )

#end the embedded interface
ri.endr(0)