コード例 #1
0
 def __init__(self, structure, family, param1, param2=None):
     self.structure = structure
     self.family = family
     self.param1 = param1
     self.param2 = param2
     ri.initr()
     self.build_vine()
コード例 #2
0
def analyze_log_file_in_phases(file_id, nstates, trials, iter):
    print_n_flush("Starting phase by phase analysis...")
    # id_to_log = lambda x: "logs/%s.exp.log" % x
    filename_log = id_to_log(file_id)
    responses, tests, responses_t, tests_t, images = toCSV(filename_log)
    from IPython.parallel import Client
    #     from functools import partial
    from rpy2.rinterface import initr

    rinterface.set_initoptions(("--max-ppsize=100000"))
    initr()
    client = Client(profile="default")
    # client[:].push(dict(initr=initr))
    # client[:].apply_sync(lambda: initr())
    lview = client.load_balanced_view()  # default load-balanced view
    lview.block = True
    # func = lambda args: train_hmm_n_times(file_id=args[0], nstates=args[1], trials=args[2], iter=args[3])
    # trials = 4
    client[:].push(dict(train_hmm_once=train_hmm_once))
    # args = [(file_id, nstates, trials, 1000) for nstates in range(5,10)]
    # results = lview.map(func, args)# hmm, d, results = train_hmm_n_times(file_id, nstates, trials=20, iter=1000)
    # pool.join()
    results = {}
    for i in range(3):
        results[i] = train_hmm_n_times(file_id, nstates=nstates, trials=trials, iter=iter, phase=i)
    return results
コード例 #3
0
    def plot(self, data_array, width, height):
        """
        Create a plot with R
        """

        # Start R timing
        startTime = time.time()

        rinterface.initr()

        r = robjects.r
        grdevices = importr('grDevices')

        # Import the bfast package
        bfast = importr('bfast')

        b = robjects.FloatVector(data_array)

        # arry by b to time serie vector
        b_ts = r.ts(b, start=robjects.IntVector([2000, 4]), frequency=23)

        # calculate bfast
        h = 23.0 / float(len(b_ts))
        b_bfast = r.bfast(b_ts, h=h, season="harmonic", max_iter=2)

        # Get the index names of the ListVector b_bfast
        names = b_bfast.names
        log.debug(names)

        temp_datadir = self.config.get('main', 'temp.datadir')
        temp_url = self.config.get('main', 'temp.url')
        file = NamedTemporaryFile(suffix=".png", dir=temp_datadir, delete=False)

        log.debug(file.name)
        grdevices.png(file=file.name, width=width, height=height)
        # Plotting code here
        r.par(col="black")
        r.plot(b_bfast)
        # Close the device
        grdevices.dev_off()

        # End R timing and log it
        endTime = time.time()
        log.debug('It took ' + str(endTime - startTime) + ' seconds to initalize R and draw a plot.')

        file.close()

        result = {"file": "%s/%s" % (temp_url, file.name.split("/")[-1])}
        try:
            result['magnitude'] = str(tuple(b_bfast[names.index("Magnitude")])[0])
        except ValueError:
            pass
        try:
            result['time'] = str(tuple(b_bfast[names.index("Time")])[0])
        except ValueError:
            pass

        self.outputs['plot']['value'] = json.dumps({"file": "%s/%s" % (temp_url, file.name.split("/")[-1])})
        return SERVICE_SUCCEEDED
コード例 #4
0
ファイル: rconvert.py プロジェクト: ARPA-SIMC/dballe
def volnd_data_to_r(data):
    """
    Convert a volnd data object to an R object
    """
    rinterface.initr()

    dn = []
    for i in data.dims:
        dn.append([str(x) for x in i])
    return ma_to_r(data.vals, dimnames=dn)
コード例 #5
0
def getRasterValues(lon, lat, layer, buffervalue):
    startTime = time.time()
    rinterface.initr()
    r = robjects.r
    r.require('raster')
    ras = r.raster(layer)
    rasvalues = r.extract(ras, r.cbind(lon,lat), buffer=buffervalue, small=True)
    values = npri.ri2numpy(rasvalues[0])
    endTime = time.time()
    print(str(endTime - startTime))
    return values
コード例 #6
0
    def run(self):
        sample1 = pickle.load( gzip.open(self.sampleobjfile1, "rb") )
        sample2 = pickle.load( gzip.open(self.sampleobjfile2, "rb") )
        
        print self.size, os.path.basename(self.sampleobjfile1).split('.')[0], sample1.total, os.path.basename(self.sampleobjfile2).split('.')[0], sample2.total
        #sampling "size" sequences from sample:
        subsample1 = iseqlib.samplingSample( sample1, self.size ) #sampled sample
        subsample2 = iseqlib.samplingSample( sample2, self.size ) #sampled sample
        
        #Get different statistics:
        stats = PairSamplingStats() #initialize stats for the current subsample

        #Find Sizes of the Union of clones between subsample1 and subsample2:
        counts1 = []
        counts2 = []
        for header, seq in subsample1.seqs.iteritems():
            counts1.append( seq.count )
            if header in subsample2.seqs:
                counts2.append( subsample2.seqs[header].count )
            else:
                counts2.append( 0 )
        for header, seq in subsample2.seqs.iteritems():
            if header not in subsample1.seqs:
                counts1.append( 0 )
                counts2.append( seq.count )
        
        if len(counts1) != len(counts2):
            raise ValueError("The count vectors of two compared samples must have equal length. Found %d and %d\n" %(len(counts1), len(counts2)))

        ## Initialize the R interface
        import rpy2.rinterface as rinterface
        rinterface.set_initoptions(('rpy2', '--no-save'))
        rinterface.initr()

        import rpy2.robjects as robjs
        from rpy2.robjects.packages import importr
        vegan = importr('vegan')
        vegdist = vegan.vegdist

        counts = counts1
        counts.extend(counts2)
        rcountsVec = robjs.IntVector( counts ) #convert python list into R vector
        rcountsMatrix = robjs.r['matrix'](rcountsVec, nrow = 2, byrow=True)
        
        #indices = ['bray', 'horn', 'mountford', 'chao']
        indices = self.options.similarityIndices
        #"manhattan", "euclidean", "canberra", "bray", "kulczynski", "jaccard", "gower", "morisita", "horn", "mountford", "raup" , "binomial" or "chao"
        for index in indices:
            disimilarity = vegdist( rcountsMatrix, method=index )
            stats[index] = disimilarity[0]
            
        #Write to temp file:
        picklefile = os.path.join( self.outdir, "%d.pickle" % self.id)
        pickle.dump( stats, gzip.open(picklefile, "wb") )
コード例 #7
0
ファイル: graph.py プロジェクト: Akanksha18/eden
def usage (fname):
    R.initr ()
    fname = R.StrSexpVector ([fname])

    try:
        location = R.globalEnv.get ('help') (fname)[0]
    except IndexError:
        raise RuntimeError ('Function not found')

    file = open (location)
    m = search ('_\x08U_\x08s_\x08a_\x08g_\x08e:\n([^\x08]+)(?=_)', file.read ())
    
    if m is None:
        raise RuntimeError ('Usage not found')
    else:
        return m.group (1)
コード例 #8
0
ファイル: graph.py プロジェクト: Akanksha18/eden
def boxPlotData (response, data, tmpdir = '.', params = {}):
    R.initr ()
    svg = R.globalEnv.get ('svg')
    off = R.globalEnv.get ('graphics.off')
    boxplot = R.globalEnv.get ('boxplot')
    vectors = []
    for dataList in data:
        vectors.append (R.FloatSexpVector (dataList))

    params = formatForR (params)

    filename = tmpdir + '/' + str(uuid4 ().int) + '.svg'
    svg (R.StrSexpVector([filename]), width=R.FloatSexpVector ([10.5]),
         height=R.FloatSexpVector ([7]))
    boxplot (*vectors, **params)
    off ()
    cp (response, filename)
コード例 #9
0
def calc_bfast(data_array):
    """
    Calculate the BFast statistics
    """

    # Start R timing
    startTime = time.time()

    # Initialize R
    rinterface.initr()

    r = robjects.r

    # Import the bfast package
    bfast = importr('bfast')

    # Create a R vector from the Python array
    b = robjects.FloatVector(data_array)

    # Create a R timeseries from R vector
    b_ts = r.ts(b, start=robjects.IntVector([2000, 4]), frequency=23)

    # Calculate BFast
    h = 23.0 / float(len(b_ts))
    b_bfast = r.bfast(b_ts, h=h, season="harmonic", max_iter=2)

    # Get the "output" attribute from the BFast result
    output = b_bfast[b_bfast.names.index("output")]
    # Number of iteration
    nbrOfIter = len(output)
    # Get the break points
    breakpointsOutput = output.rx2(nbrOfIter).rx("bp.Vt")[0]
    # Get the break points as a "breakpoints" R object, see also:
    # http://cran.r-project.org/web/packages/strucchange/strucchange.pdf#Rfn.breakpoints
    breakpoints = breakpointsOutput[breakpointsOutput.names.index("breakpoints")]

    endTime = time.time()
    # Figure out how long the script took to run
    log.debug('It took ' + str(endTime - startTime) + ' seconds to calculate the BFast breakpoints.')

    if(breakpoints[0] == robjects.NA_Logical):
        return []

    # Return the list of breakpoints as Python array
    return [int(breakpoints[b]) for b in range(len(breakpoints))]
コード例 #10
0
ファイル: rconvert.py プロジェクト: ARPA-SIMC/dballe
def volnd_save_to_r(vars, file):
    """
    Convert the result of a volnd read into various R objects, and save them to the given file
    """
    rinterface.initr()

    tosave = []
    for k, d in vars.items():
        #print "s2r", k
        robjects.r.assign(k, volnd_data_to_r(d))
        tosave.append(k)
        for aname, adata in d.attrs.items():
            robjects.r.assign(k+"."+aname, volnd_data_to_r(adata))
            tosave.append(k+"."+aname)
    tosave = robjects.vectors.StrVector(tosave)
    robjects.r.save(list=tosave, file=file)
    # Cleanup the names from the environment
    robjects.r.remove(list=tosave)
コード例 #11
0
ファイル: transform.py プロジェクト: Koperj/SahanaEden
    def create (self):
        R.initr ()
        R.globalEnv['x'] = R.FloatSexpVector (self.xdata)
        R.globalEnv['y'] = R.FloatSexpVector (self.ydata)
        formula = RFormula ('y ~ x')
        rLine = R.globalEnv.get ('lm')(formula)
        slope = rLine[0][1]
        intercept = rLine[0][0]

        y1 = slope * self.currentView.min.x + intercept
        y2 = slope * self.currentView.max.x + intercept

        p1 = V (self.currentView.min.x, y1)
        p2 = V (self.currentView.max.x, y2)

        self.draw (Line (p1, p2, className='regression-line'))
        self.draw (Line (p1, p2, className='regression-shadow'))

        TransformableGroup.create (self)
コード例 #12
0
ファイル: reg.py プロジェクト: Akanksha18/eden
    def __init__ (self, xdata, ydata, xbounds, ybounds):
        from rpy2.robjects import RFormula
        from rpy2 import rinterface as R

        R.initr ()
        R.globalEnv['x'] = R.FloatSexpVector (xdata)
        R.globalEnv['y'] = R.FloatSexpVector (ydata)
        formula = RFormula ('y ~ x')
        rLine = R.globalEnv.get ('lm')(formula)
        slope = rLine[0][1]
        intercept = rLine[0][0]

        y1 = slope * xbounds[0] + intercept
        y2 = slope * xbounds[1] + intercept

        p1 = (xbounds[0], y1)
        p2 = (xbounds[1], y2)

        Line.__init__ (self, point1 = p1, point2 = p2)
コード例 #13
0
    def run(self):
        sample = pickle.load( gzip.open(self.sampleobjfile, "rb") )
        #sampling "size" sequences from sample:
        subsample = iseqlib.samplingSample( sample, self.size ) #sampled sample
        
        #Get different statistics:
        stats = SingleSamplingStats() #initialize stats for the current subsample

        #1/ Number of uniq clones:
        stats.uniqClones = len( subsample.seqs )

        #2/ Diversity Indices
        counts = [ seq.count for seq in subsample.seqs.values() ] #list of clone sizes

        ## Initialize the R interface
        import rpy2.rinterface as rinterface
        rinterface.set_initoptions(('rpy2', '--no-save'))
        rinterface.initr()

        import rpy2.robjects as robjs
        from rpy2.robjects.packages import importr
        vegan = importr('vegan')
        rcounts = robjs.IntVector( counts ) #convert python list into R vector
        
        ##Diversity indices (Simpson, InverseSimpson, Shannon)
        indices = self.options.diversityIndices
        #['simpson', 'invsimpson', 'shannon']
        for index in indices:
            if index == 'uniqClones' or index == 'fisherAlpha':
                continue
            rval = vegan.diversity( rcounts, index )
            stats[index] = rval[0]
            
        ## Fisher Alpha:
        rfisher = vegan.fisher_alpha( rcounts )
        stats.fisherAlpha = rfisher[0]

        #Write to temp file:
        picklefile = os.path.join( self.outdir, "%d.pickle" % self.id)
        pickle.dump( stats, gzip.open(picklefile, "wb") )
コード例 #14
0
ファイル: graph.py プロジェクト: Akanksha18/eden
def multiRScatter (response, data, groups, tmpdir = '.',  params = {}):
    R.initr ()
    svg = R.globalEnv.get ('svg')
    off = R.globalEnv.get ('graphics.off')
    pairs = R.globalEnv.get ('pairs')
    for g in groups:
        dataList = []
        for key, value in data:
            try:
                dataList.append (value[g])
            except KeyError:
                dataList.append (None)
        R.globalEnv[str(g)] = R.FloatSexpVector (dataList)
    f = '~' + '+'.join (map (str, groups))
    formula = RFormula (f)

    params = formatForR (params)

    filename = tmpdir + '/' + str(uuid4 ().int) + '.svg'
    svg (R.StrSexpVector([filename]), width=R.FloatSexpVector ([10.5]),
         height=R.FloatSexpVector ([7]))
    pairs (formula, **params)
    off ()
    cp (response, filename)
コード例 #15
0
ファイル: analyze_matchup.py プロジェクト: orban/pops
#!/usr/bin/env python
import os, sys, time, re, json, pdb, random, datetime, subprocess
from sys import modules
# third parties
import numpy as np
import pandas as pd
import pandas.io.sql as psql
from scipy import stats
import psycopg2
# R interface
import rpy2.robjects as robjects
import rpy2.rinterface as RI
import warnings
warnings.filterwarnings('ignore')
R = robjects.r
RI.initr()
# personal utilities
import utils.pandas_psql as pdpsql

# ------------------------------------------
# setting up the computation environment
# -------------------------------------------

# the postgres database connection is made
# global to avoid confusion when we
# switch location
try:
    # local postgresql database
    cnx = psycopg2.connect(host='localhost', database='popsfundamental', 
                           user='******') 
コード例 #16
0
ファイル: test_EmbeddedR.py プロジェクト: jjhoyt/gengis
 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()
コード例 #17
0
ファイル: analyze_matchup.py プロジェクト: orban/pops
import os, sys, time, re, json, pdb, random, datetime, subprocess
from sys import modules
# third parties
import numpy as np
import pandas as pd
import pandas.io.sql as psql
from scipy import stats
import psycopg2
# R interface
import rpy2.robjects as robjects
import rpy2.rinterface as RI
import warnings

warnings.filterwarnings('ignore')
R = robjects.r
RI.initr()
# personal utilities
import utils.pandas_psql as pdpsql

# ------------------------------------------
# setting up the computation environment
# -------------------------------------------

# the postgres database connection is made
# global to avoid confusion when we
# switch location
try:
    # local postgresql database
    cnx = psycopg2.connect(host='localhost',
                           database='popsfundamental',
                           user='******')
コード例 #18
0
def analyze_log_file(file_id, nstates, trials, iter):
    # id_to_log = lambda x: "logs/%s.exp.log" % x
    filename_log = id_to_log(file_id)
    responses, tests, responses_t, tests_t, images = toCSV(filename_log)

    from IPython.parallel import Client
    #     from functools import partial
    from rpy2.rinterface import initr

    try:
        rinterface.set_initoptions(("--max-ppsize=500000"))
    except RuntimeError, e:
        print_n_flush("Runtime error, probably redundant call to set_initoptions()")
        print_n_flush(e)
    initr()
    client = Client(profile="default")
    # client[:].push(dict(initr=initr))
    # client[:].apply_sync(lambda: initr())
    lview = client.load_balanced_view()  # default load-balanced view
    lview.block = True
    # func = lambda args: train_hmm_n_times(file_id=args[0], nstates=args[1], trials=args[2], iter=args[3])
    # trials = 4
    client[:].push(dict(train_hmm_once=train_hmm_once))
    # args = [(file_id, nstates, trials, 1000) for nstates in range(5,10)]
    # results = lview.map(func, args)# hmm, d, results = train_hmm_n_times(file_id, nstates, trials=20, iter=1000)
    # pool.join()
    results = train_hmm_n_times(file_id, nstates=nstates, trials=trials, iter=iter)
    return results

コード例 #19
0
ファイル: utils.py プロジェクト: Akanksha18/eden
 def _start ():
     if not R._running:
         R._running = True
         r.initr ()
         R._execute = r.globalEnv.get
         R._library = R._execute ('library')
コード例 #20
0
 def __init__(self):
     if R._instance is None:
         rinterface.initr()
         R._instance = self
     else:
         pass
コード例 #21
0
 def init_r():
     from rpy2 import rinterface
     rinterface.initr()
コード例 #22
0
ファイル: __init__.py プロジェクト: carloliveros/CloudForest
 def __new__(cls):
     if cls._instance is None:
         rinterface.initr()
         cls._instance = object.__new__(cls)
     return cls._instance
コード例 #23
0
 def init_r(preserve_hash):
     from rpy2 import rinterface
     rinterface.initr(r_preservehash=preserve_hash)
コード例 #24
0
    def plot(self, data_array, width, height):
        """
        Create a plot with R
        """

        # Start R timing
        startTime = time.time()
        
        rinterface.initr()

        r = robjects.r
        grdevices = importr('grDevices')

        vector = robjects.FloatVector(data_array)
        
        temp_datadir = self.config.get('main', 'temp.datadir')
        temp_url = self.config.get('main', 'temp.url')
        file = NamedTemporaryFile(suffix=".png", dir=temp_datadir, delete=False)

        grdevices.png(file=file.name, width=width, height=height)

        ts = r.ts(vector, start=robjects.IntVector([2000, 4]), frequency=23)
        #r.layout(r.matrix(robjects.IntVector([1, 2, 3, 4]), ncol=1, nrow=4))

        ## PLOT 1: Raw NDVI values

        #r.par(mar=robjects.FloatVector([0, 4, .2, 4]))   # mar für die Abstände ausserhalb des plots in der Reihenfolge unten - links - oben - rechts. Oben Null, der Rest sind default-Werte

        r.plot(ts, type="l", axes=False, ylab="Raw NDVI value", xlab="", ylim=robjects.FloatVector([0.0, 1.0]))
        r.box()
        r.axis(2, labels=robjects.StrVector(['0.0', '0.2', '0.4', '0.6', '0.8', '1.0']), at=robjects.FloatVector([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]))
        r.axis(1, labels=robjects.StrVector(['2000', '2002', '2004', '2006', '2008', '2010', '2012', '2014']), at=robjects.FloatVector([2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014]))
        r.abline(v=[2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014], col="lightgrey", lty=2) # vertikale linien bei jedem jahr, lty ist line type
        r.abline(h=robjects.FloatVector([0, 0.2000, 0.4000, 0.6000, 0.8000, 1.0000]), col="lightgrey", lty=2)

        ## PLOT 2:

        #r.par(mar=robjects.IntVector([0, 4, 0, 4]))
        #r.plot(ts, type="l", col="grey", axes=False, ylab="Asym Gaussian fitting", xlab="")
        #r.box()
        #r.axis(4, labels=robjects.StrVector(['0', '0.2', '0.4', '0.6', '0.8', '1']), at=robjects.FloatVector([0, 0.2, 0.4, 0.6, 0.8, 1]))
        #r.abline(v=[2000, 2014, 1], col="lightgrey", lty=2)
        #r.abline(h=robjects.FloatVector([0, 0.2000, 0.4000, 0.6000, 0.8000]), col="lightgrey", lty=2)

        ## PLOT 3:

        #r.par(mar=robjects.IntVector([0, 4, 0, 4]))
        #r.plot(ts, type="l", col="grey", axes=False, ylab="Double logistic fitting", xlab="")
        #r.box()
        #r.axis(2, labels=robjects.StrVector(['0', '0.2', '0.4', '0.6', '0.8', '1']), at=robjects.FloatVector([0, 0.2, 0.4, 0.6, 0.8, 1]))
        #r.abline(v=[2000, 2014, 1], col="lightgrey", lty=2)
        #r.abline(h=robjects.FloatVector([0, 0.2000, 0.4000, 0.6000, 0.8000]), col="lightgrey", lty=2)

        ## PLOT 4:

        #r.par(mar=robjects.IntVector([2, 4, 0, 4]))
        #r.plot(ts, type="l", col="grey", axes=False, ylab="Trends", xlab="")
        #r.box()
        #r.axis(4, labels=robjects.StrVector(['0', '0.2', '0.4', '0.6', '0.8', '1']), at=robjects.FloatVector([0, 0.2, 0.4, 0.6, 0.8, 1]))
        #r.axis(1, labels=robjects.StrVector(['2000', '2002', '2004', '2006', '2008', '2010', '2012', '2014']), at=robjects.FloatVector([2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014]))
        #r.abline(v=[2000, 2014, 1], col="lightgrey", lty=2)
        #r.abline(h=robjects.FloatVector([0, 0.2000, 0.4000, 0.6000, 0.8000]), col="lightgrey", lty=2)

        # Close the device
        grdevices.dev_off()

        file.close()


        # End R timing and log it
        endTime = time.time()
        log.debug('It took ' + str(endTime - startTime) + ' seconds to initalize R and draw a plot.')

        self.outputs['plot']['value'] = json.dumps({"file": "%s/%s" % (temp_url, file.name.split("/")[-1])})
        return SERVICE_SUCCEEDED
コード例 #25
0
ファイル: __init__.py プロジェクト: Trixter9994/lazero
 def __new__(cls):
     if cls._instance is None:
         rinterface.initr()
         cls._instance = object.__new__(cls)
     return cls._instance
コード例 #26
0
ファイル: rpy2test.py プロジェクト: OspreyX/statplay
 def setUp(self):
     # Initialized embedded R
     ri.initr()
コード例 #27
0
ファイル: test_Sexp.py プロジェクト: jjhoyt/gengis
import unittest
import copy
import gc
import rpy2.rinterface as rinterface

rinterface.initr()

class SexpTestCase(unittest.TestCase):

    def testNew_invalid(self):

        x = "a"
        self.assertRaises(ValueError, rinterface.Sexp, x)

    def testNew(self):        
        sexp = rinterface.globalEnv.get("letters")
        sexp_new = rinterface.Sexp(sexp)

        idem = rinterface.globalEnv.get("identical")
        self.assertTrue(idem(sexp, sexp_new)[0])

        sexp_new2 = rinterface.Sexp(sexp)
        self.assertTrue(idem(sexp, sexp_new2)[0])
        del(sexp)
        self.assertTrue(idem(sexp_new, sexp_new2)[0])


    def testTypeof_get(self):
        sexp = rinterface.globalEnv.get("letters")
        self.assertEquals(sexp.typeof, rinterface.STRSXP)
        
コード例 #28
0
import unittest
import copy
import gc
from rpy2 import rinterface

rinterface.initr()


class SexpTestCase(unittest.TestCase):
    def testNew_invalid(self):

        x = "a"
        self.assertRaises(ValueError, rinterface.Sexp, x)

    def testNew(self):
        sexp = rinterface.baseenv.get("letters")
        sexp_new = rinterface.Sexp(sexp)

        idem = rinterface.baseenv.get("identical")
        self.assertTrue(idem(sexp, sexp_new)[0])

        sexp_new2 = rinterface.Sexp(sexp)
        self.assertTrue(idem(sexp, sexp_new2)[0])
        del (sexp)
        self.assertTrue(idem(sexp_new, sexp_new2)[0])

    def testTypeof_get(self):
        sexp = rinterface.baseenv.get("letters")
        self.assertEqual(sexp.typeof, rinterface.STRSXP)

        sexp = rinterface.baseenv.get("pi")
コード例 #29
0
 def __init__(self):
     if R._instance is None:
         rinterface.initr()
         R._instance = self
     else:
         pass
コード例 #30
0
import array
import pytest
import rpy2.rinterface as ri

ri.initr()


def test_init_from_seqr():
    seq = [True, False, False]
    v = ri.BoolSexpVector(seq)
    assert len(v) == 3
    for x, y in zip(seq, v):
        assert x == y


def test_from_int_memoryview():
    a = array.array('i', (True, False, True))
    mv = memoryview(a)
    vec = ri.BoolSexpVector.from_memoryview(mv)
    assert (True, False, True) == tuple(vec)


def test_from_bool_memoryview():
    a = array.array('b', (True, False, True))
    mv = memoryview(a)
    with pytest.raises(ValueError):
        ri.BoolSexpVector.from_memoryview(mv)


def test_getitem():
    vec = ri.BoolSexpVector([True, False, False])
コード例 #31
0
ファイル: test_EmbeddedR.py プロジェクト: scottcode/rpy2
 def init_r(preserve_hash):
     from rpy2 import rinterface
     rinterface.initr(r_preservehash=preserve_hash)
コード例 #32
0
#---------------------------------------------------------
# Name: matrix_seriation.py
# Purpose: Implementation of amtrix seriation using rpy2 and seriation package
# Author:	Jacob Retallick
# Created: 2015.10.06
# Last Modified: 2015.10.07
#---------------------------------------------------------

import numpy as np
import rpy2.rinterface as rint
import rpy2.robjects as robj
from rpy2.robjects.packages import importr


# initialise R
rint.initr()

# load packages
seriation = importr("seriation")
stats = importr("stats")


def mat_to_R(M):
    '''convert a numpy matrix to R format'''
    d = M.reshape([1, -1]).tolist()[0]
    return robj.r.matrix(d, nrow=M.shape[0])


def deres_mat(M, res):
    '''Reduce the numerical resolution of a matrix.
    inputs: res     -> resolution (smallest relative diffence between values)
コード例 #33
0
    def plot(self, data_array, width, height):
        """
        Create a plot with R
        """

        # Start R timing
        startTime = time.time()

        rinterface.initr()

        r = robjects.r
        grdevices = importr("grDevices")

        # Import the bfast package
        log.debug(os.environ["R_SCRIPTS_USER"])
        r.source("%s/4253H_twice.R" % os.environ["R_SCRIPTS_USER"])

        b = robjects.FloatVector(data_array)

        # Make a time series from the vector
        b_ts = r.ts(b, start=robjects.IntVector([2000, 4]), frequency=23)

        b_fitting = r.my4253Htwice(x=b_ts)

        temp_datadir = self.config.get("main", "temp.datadir")
        temp_url = self.config.get("main", "temp.url")
        file = NamedTemporaryFile(suffix=".png", dir=temp_datadir, delete=False)

        log.debug("Writing resulting diagram to file %s" % file.name)
        grdevices.png(file=file.name, width=width, height=height)
        # Plotting code here
        # r.par(col="black")
        r.plot(b_fitting, type="l", axes=False, ylab="Double logistic fitting", ylim=robjects.FloatVector([0.0, 1.0]))
        r.box()
        r.axis(
            2,
            labels=robjects.StrVector(["0.0", "0.2", "0.4", "0.6", "0.8", "1.0"]),
            at=robjects.FloatVector([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]),
        )
        r.axis(
            1,
            labels=robjects.StrVector(["2000", "2002", "2004", "2006", "2008", "2010", "2012", "2014"]),
            at=robjects.FloatVector([2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014]),
        )
        r.abline(
            v=robjects.IntVector([2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014]), col="lightgrey", lty=2
        )  # vertikale linien bei jedem jahr, lty ist line type
        r.abline(h=robjects.FloatVector([0, 0.2000, 0.4000, 0.6000, 0.8000, 1.0000]), col="lightgrey", lty=2)
        # Close the device
        grdevices.dev_off()

        # End R timing and log it
        endTime = time.time()
        log.debug("It took " + str(endTime - startTime) + " seconds to initalize R and draw a plot.")

        file.close()

        result = {"file": "%s/%s" % (temp_url, file.name.split("/")[-1])}

        self.outputs["plot"]["value"] = json.dumps({"file": "%s/%s" % (temp_url, file.name.split("/")[-1])})
        return SERVICE_SUCCEEDED
コード例 #34
0
 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()
コード例 #35
0
ファイル: RPY2eg.py プロジェクト: GBelzoni/BigGits
import rpy2.robjects as ro

from rpy2.robjects.packages import importr

import rpy2.rinterface as ri
ri.set_initoptions(('rpy2', '--verbose', '--no-save'))
ri.initr()

graphics = importr('graphics')
grdevices = importr('grDevices')
base = importr('base')
stats = importr('stats')
zoo = importr('zoo')

#Need to add params to importr as xts and quantmod have conflicts
xts = importr("xts", robject_translations = {".subset.xts": "_subset_xts2",                                            "to.period": "to_period2"})
quantmod = importr('quantmod', robject_translations = {"skeleton.TA": "skeleton_TA2"})

AORD = ro.r('read.table("~/Documents/R/StrategyTester/Data/AORD.csv",header=T, sep=",")')

#WIP - using quantmod, zoo, xts in Python.
#Create Zoo object
#indexZoo = ro.r.rownames(AORD)
AORD = zoo.as_zoo(AORD)
AORD = xts.as_xts(AORD)

#Create MA zoo object
#Creating EMA using quantmod
chartData = AORD#.rx['2008-02::2008-08']
quantmod.chartSeries(chartData, theme="white")
EMA1=quantmod.addEMA(n=10,col=2)
コード例 #36
0
ファイル: multiproc_lab.py プロジェクト: rpy2/rpy2.github.io
def initializer():
    if rpy2.rinterface_lib.embedded.isready():
        print('R is is already initialized!')
    ri.initr()