Beispiel #1
0
def heatmap3py(numDataR, ColSideColors, annoColDicList, fileName=None, outPath=None):
    from rpy2.robjects.packages import importr    
    heatmap = importr("heatmap3")
    grdevices = importr("grDevices")                   
    from rpy2.robjects.functions import SignatureTranslatedFunction
    # explicitly translate the R argument to legal python name 
    heatmap.showLegend = SignatureTranslatedFunction(heatmap.showLegend,
                                           init_prm_translate = {'pt_bg': 'pt.bg'})       
    
    # annoName = ColSideColors.colnames
    # draw heatmap in file
    if (fileName!=None):
        grdevices.pdf(file = fileName )
        heatmap.heatmap3(numDataR,ColSideColors=ColSideColors,showRowDendro=False)
        grdevices.dev_off()
        for i in range(len(annoColDicList)):
            anno = robjects.StrVector(annoColDicList[i].keys())
            col =  robjects.StrVector(annoColDicList[i].values())            
            fileName = outPath +"/heatmapLegend" + str(i) + ".pdf"
            grdevices.pdf(file = fileName )
            heatmap.showLegend(legend= anno,col=col,cex=1.5, title="Annotation Legend: "+ColSideColors.colnames[i], pch=22, lwd = robjects.NA_Integer, pt_bg=col)
            grdevices.dev_off()        
    else:    
        # Draw heatmap in R window
        heatmap.heatmap3(numDataR,ColSideColors=ColSideColors,showRowDendro=False)      
        # Plot legends in another window
        for i in range(len(annoColDicList)):
            grdevices.dev_new()
            anno = robjects.StrVector(annoColDicList[i].keys())
            col =  robjects.StrVector(annoColDicList[i].values())
            heatmap.showLegend(legend= anno,col=col,cex=1.5, title="Annotation Legend: "+ ColSideColors.colnames[i], pch=22, lwd = robjects.NA_Integer, pt_bg=col)
Beispiel #2
0
    def training_step(self, train=None, opt_Q=True, opt_sg=True):
        # self.nb_students = len(train)
        # self.nb_questions = len(train[0])
        # raw_data = list(map(int, reduce(lambda x, y: x + y, train)))
        # self.data = r.matrix(robjects.IntVector(raw_data), nrow=self.nb_students, byrow=True)
        if os.path.isfile(self.get_backup_path()):
            print('Cool, already found!', self.checksum)
            r.load(self.get_backup_path())
            #self.r_scores = r('scores')
            self.load()
        else:
	        model = ltm.rasch(self.r_data)
	        self.coeff = ltm.coef_rasch(model)
	        ltm.factor_scores = SignatureTranslatedFunction(ltm.factor_scores, init_prm_translate={'resp_patterns': 'resp.patterns'})  # Mais dans quel monde vivons-nous ma p'tite dame
	        self.r_scores = ltm.factor_scores(model, resp_patterns=self.r_data).rx('score.dat')[0].rx('z1')[0]
	        robjects.globalenv['scores'] = self.r_scores
	        self.scores = np.array(self.r_scores)
	        r('data <- %s' % self.r_data.r_repr())
	        #r('data[1][1] <- NA')
	        r('coeff <- coef(rasch(data))')
	        r('one <- rep(1, %d)' % self.nb_questions)
	        r('itembank <- cbind(coeff[,2:1], 1 - one, one)')
	        self.itembank = np.array(r('itembank'))
	        # self.compute_all_errors()
	        r('save(itembank, scores, file="{:s}")'.format(self.get_backup_path()))
	        self.save()  # To pickle file
Beispiel #3
0
def default_ri2ro(o):
    """ Convert an :class:`rpy2.rinterface.Sexp` object to a higher-level object,
    without copying the R object.

    :param o: object
    :rtype: :class:`rpy2.robjects.RObject` (and subclasses)
    """

    res = None
    try:
        rcls = o.do_slot("class")
    except LookupError as le:
        rcls = [None]

    if isinstance(o, RObject):
        res = o
    elif isinstance(o, SexpVector):
        if 'data.frame' in rcls:
            res = vectors.DataFrame(o)
        if res is None:
            try:
                dim = o.do_slot("dim")
                if len(dim) == 2:
                    res = vectors.Matrix(o)
                else:
                    res = vectors.Array(o)
            except LookupError as le:
                if o.typeof == rinterface.INTSXP:
                    if 'factor' in rcls:
                        res = vectors.FactorVector(o)
                    else:
                        res = vectors.IntVector(o)
                elif o.typeof == rinterface.REALSXP:
                    if o.rclass[0] == 'POSIXct':
                        res = vectors.POSIXct(o)
                    else:
                        res = vectors.FloatVector(o)
                elif o.typeof == rinterface.STRSXP:
                    res = vectors.StrVector(o)
                elif o.typeof == rinterface.VECSXP:
                    res = vectors.ListVector(o)
                elif o.typeof == rinterface.LANGSXP and 'formula' in rcls:
                    res = Formula(o)
                else:
                    res = vectors.Vector(o)

    elif isinstance(o, SexpClosure):
        res = SignatureTranslatedFunction(o)
    elif isinstance(o, SexpEnvironment):
        res = Environment(o)
    elif isinstance(o, SexpS4):
        res = RS4(o)
    elif isinstance(o, SexpExtPtr):
        res = o
    elif o is NULL:
        res = o
    else:
        res = RObject(o)
    return res
Beispiel #4
0
 def __fill_rpy2r__(self):
     super(SignatureTranslatedPackage, self).__fill_rpy2r__()
     for name, robj in self.__dict__.iteritems():
         if isinstance(
                 robj,
                 rinterface.Sexp) and robj.typeof == rinterface.CLOSXP:
             self.__dict__[name] = SignatureTranslatedFunction(
                 self.__dict__[name])
	for k,v in sorted(fullhash.items()):
		for k1,v1 in sorted(v.items()):
			newhash[k]["mean"].append(meanstdv(v1)[0])
	for k,v in sorted(fullhash.items()):
		for k1,v1 in sorted(v.items()):
			newhash[k]["stdabw"].append(meanstdv(v1)[1])
	for k,v in sorted(fullhash.items()):
		for k1,v1 in sorted(v.items()):
			newhash[k]["se"].append(meanstdv(v1)[2])
	#print newhash
	
	r=robjects.r
	graphics = importr('graphics')
	grdevices = importr('grDevices')
	gplot=importr('gplots')
	graphics.par = SignatureTranslatedFunction(graphics.par,init_prm_translate = {'cex_axis': 'cex.axis'})
	graphics.par1 = SignatureTranslatedFunction(graphics.par,init_prm_translate = {'cex_lab': 'cex.lab'})
	popnames = robjects.StrVector(pop)
	print popnames
	#sys.exit()
	grdevices.pdf(file=out,width=30,height=10)
	a_bf15=[0.5,1.67,2.84,4.01]
	candr=robjects.vectors.StrVector(cand)
	colr=robjects.vectors.StrVector(["green","red","blue"])
	
	base_bf15=robjects.vectors.FloatVector(fullhash["bf15"][pops[0]])
	f15_bf15=robjects.vectors.FloatVector(fullhash["bf15"][pops[1]])
	f27_bf15=robjects.vectors.FloatVector(fullhash["bf15"][pops[2]])
	f37_bf15=robjects.vectors.FloatVector(fullhash["bf15"][pops[3]])
	a_bf37=[0.75,1.92,3.09,4.26]
	base_bf37=robjects.vectors.FloatVector(fullhash["bf37"][pops[0]])
Beispiel #6
0
def _rpy2py_sexpclosure(obj):
    return SignatureTranslatedFunction(obj)
Beispiel #7
0
def _(obj):
    return SignatureTranslatedFunction(obj)
Beispiel #8
0
                        res = vectors.FactorVector(o)
                    else:
                        res = vectors.IntVector(o)
                elif o.typeof == rinterface.REALSXP:
                    res = vectors.FloatVector(o)
                elif o.typeof == rinterface.STRSXP:
                    res = vectors.StrVector(o)
                elif o.typeof == rinterface.VECSXP:
                    res = vectors.ListVector(o)
                elif o.typeof == rinterface.LANGSXP and 'formula' in rcls:
                    res = Formula(o)
                else:
                    res = vectors.Vector(o)

    elif isinstance(o, SexpClosure):
        res = SignatureTranslatedFunction(o)
    elif isinstance(o, SexpEnvironment):
        res = Environment(o)
    elif isinstance(o, SexpS4):
        res = RS4(o)
    elif isinstance(o, SexpExtPtr):
        res = o
    elif o is NULL:
        res = o
    else:
        res = RObject(o)
    return res


conversion.ri2py = default_ri2py
Beispiel #9
0
import numpy as np
from multiprocessing import Pool
import pickle
import os
from sklearn.metrics import pairwise_distances
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
from rpy2.robjects.functions import SignatureTranslatedFunction
rpy2.robjects.numpy2ri.activate()
Rsession = rpy2.robjects.r
DTW = importr('dtw')

Rsession.dtw = SignatureTranslatedFunction(
    Rsession.dtw, init_prm_translate={'window_size': 'window.size'})


def interpolate(x, maxlen):
    if len(x) == maxlen:
        return x
    else:
        return np.interp(np.linspace(0, 1, maxlen), np.linspace(0, 1, len(x)),
                         x)


def compute_dtw_R_sakoechiba(tup):
    s1, s2, wsize = tup
    alignment = Rsession.dtw(gdata[s1],
                             gdata[s2],
                             keep_internals=False,
                             distance_only=True,
                             window_type='sakoechiba',