Exemplo n.º 1
0
	def _plot(self, x_list, y_list, x_range, y_range):
		self.no_of_curves += 1
		if self.no_of_curves==1:
			r.plot(x_list, y_list, type='o',pch='*',xlab='dataset no.',xlim=x_range,ylim=y_range, \
			ylab='expression value', col=self.no_of_curves)
		else:
			r.lines(x_list, y_list, type='o',pch='*',col=self.no_of_curves)
Exemplo n.º 2
0
 def plotSk(self, xlab='', ylab='', type='l', col=1, ylim=(0, 15),
            **other):
     from rpy import r
     r.plot(self.kmags(), self.SkAverages(),
            xlab=xlab, ylab=ylab, type=type, col=col,
            ylim=ylim, **other
            )
Exemplo n.º 3
0
def funcion(dato,opciones):  
    from rpy import r
    diccionario={}
    if opciones.has_key("Cuantiles"):
        if opciones["Cuantiles"][u"DirecciónCola"]=='izquierda':
            sentido=True
        else:
            sentido=False
        diccionario["cuantiles"]=r.qnorm([float(opciones["Cuantiles"]["Probabilidad"])],mean=float(opciones["Cuantiles"]["Media"]),sd=float(opciones["Cuantiles"][u"Desviación"]),lower_tail=sentido)
    if opciones.has_key("Probabilidades"):
        if opciones["Probabilidades"][u"DirecciónCola"]=='izquierda':
            sentido=True
        else:
            sentido=False
        diccionario["probabilidades"]=r.pnorm([float(opciones["Probabilidades"]["Valores"])],mean=float(opciones["Probabilidades"]["Media"]),sd=float(opciones["Probabilidades"][u"Desviación"]),lower_tail=sentido)
    if opciones.has_key(u"Gráfica"):
        import random
        nombrefichero="/tmp/driza"+str(random.randint(1,99999))+".png"
        diccionario["ruta"]=nombrefichero
        r.png(nombrefichero) #Directorio temporal de la config
        lista=r.seq(-3.291, 3.291, length=100)
        if opciones[u"Gráfica"]["Tipografica"]=="Densidad":
            etiquetay="Densidad"
            mifuncion=r.dnorm
        else:
            etiquetay="Probabilidad acumulada"
            mifuncion=r.pnorm
        r.plot(lista, mifuncion(lista, mean=float(opciones[u"Gráfica"]["Media"]), sd=float(opciones[u"Gráfica"][u"Desviación"])), xlab="x", ylab=etiquetay, main=r.expression(r.paste("Normal Distribution: ", "mu", " = 0, ", "sigma", " = 1")), type="l")
        r.abline(h=0, col="gray")
        r.dev_off()
    return diccionario
Exemplo n.º 4
0
	def scatter_plot(self, gene_id_list, output_fname='/tmp/scatter_plot.ps'):
		"""
		02-15-06
			1st gene is regarded as X, all others genes are treated as Y
		"""
		vector_list = []
		#gene_id_list may contain some inexistent genes
		real_gene_id_list = []
		for gene_id in gene_id_list:
			if gene_id in self.gene_id2expr_array:
				real_gene_id_list.append(gene_id)
				vector_list.append(self.gene_id2expr_array[gene_id])	
			else:
				sys.stderr.write("%s doesn't appear in the dataset\n"%(gene_id))
		
		if len(real_gene_id_list)>0:
		
			r.postscript("%s"%output_fname)
			axis_range = self.get_min_max(vector_list)
			no_of_curves = 1	#counting starts from 1st gene itself.
			
			no_of_curves += 1
			r.plot(vector_list[0], vector_list[1], xlab='value of %s'%real_gene_id_list[0], xlim=axis_range, ylim=axis_range, \
				ylab='other genes values', col=no_of_curves)
			for i in range(2, len(vector_list)):
				no_of_curves += 1
				r.points(vector_list[0], vector_list[i], col=no_of_curves)
			r.legend(axis_range[1], axis_range[1], gene_id_list, col=range(1, no_of_curves+1), lty=1, xjust=1)
			r.dev_off()
			return output_fname
		else:
			return None
Exemplo n.º 5
0
def drawCpuUsage(d,xat,xlbs,pic):
	data=r.c(d)

	pch = 22         # point like like a square
	lty = 1          # line style solid line
	col = "blue"     # line color
	ltype = "o"      # line only http://stat.ethz.ch/R-manual/R-devel/library/graphics/html/plot.html
	ylim = (0,100)   # y domain
	xaxis=1
	yaxis=2
	vertical_text=2
	horizontal_text=1
	text_size=0.8
	yat=[x for x in range(0,110,10)]
	ylbs=["%d%%"%x for x in yat]
	legend_x=1
	legend_y=100

	# for r.text method
	warn_val=40      # val over this value will display a text on point
	xtext=[idx for idx,val in enumerate(d) if val > warn_val]    # text x pos
	ytext=[val for idx,val in enumerate(d) if val > warn_val]    # text y pos
	labtext=["%d%%"%val for idx,val in enumerate(d) if val > warn_val] # label for text

	# summary
	dmax=max(d)
	sumry="max %.2f%%" % dmax
	sumrycol="red" if dmax>50 else "green"

	# plot
	r.png(pic, width=900,height=450*0.6)
	r.plot(data, type=ltype, col=col, ylim=ylim, pch=pch, lty=lty, axes=False, ann=False)

	# draw text that over 40
	# http://stat.ethz.ch/R-manual/R-devel/library/graphics/html/text.html
	r.text(xtext, ytext, labels=labtext, pos=3, cex=0.8, col="red")

	# summary text
	r.mtext(sumry, side=3, cex=1, col=sumrycol)

	# axis
	r.axis(xaxis, las=vertical_text, at=xat, lab=r.c(xlbs))
	r.axis(yaxis, las=horizontal_text, at=yat, lab=r.c(ylbs))

	r.box()

	# titles
	r.title(main="CPU Sampling")
	r.title(xlab="Time")
	r.title(ylab="CPU Usage")

	# reference line
	# r.abline(h=50, col="gray") # at 50%

	# legend
	r.legend(legend_x, legend_y, r.c(("trunk")), col=col, cex=text_size, pch=pch, lty=lty)

	r.dev_off()
Exemplo n.º 6
0
def main():

    in_fname = sys.argv[1]
    out_fname = sys.argv[2]
    try:
        columns = int( sys.argv[3] ) - 1, int( sys.argv[4] ) - 1
    except:
        stop_err( "Columns not specified, your query does not contain a column of numerical data." )
    title = sys.argv[5]
    xlab = sys.argv[6]
    ylab = sys.argv[7]

    matrix = []
    skipped_lines = 0
    first_invalid_line = 0
    invalid_value = ''
    invalid_column = 0
    i = 0
    for i, line in enumerate( file( in_fname ) ):
        valid = True
        line = line.rstrip( '\r\n' )
        if line and not line.startswith( '#' ):
            row = []
            fields = line.split( "\t" )
            for column in columns:
                try:
                    val = fields[column]
                    if val.lower() == "na":
                        row.append( float( "nan" ) )
                    else:
                        row.append( float( fields[column] ) )
                except:
                    valid = False
                    skipped_lines += 1
                    if not first_invalid_line:
                        first_invalid_line = i + 1
                        try:
                            invalid_value = fields[column]
                        except:
                            invalid_value = ''
                        invalid_column = column + 1
                    break
        else:
            valid = False
            skipped_lines += 1
            if not first_invalid_line:
                first_invalid_line = i + 1

        if valid:
            matrix.append( row )

    if skipped_lines < i:
        try:
            r.pdf( out_fname, 8, 8 )
            r.plot( array( matrix ), type="p", main=title, xlab=xlab, ylab=ylab, col="blue", pch=19 )
            r.dev_off()
        except Exception, exc:
            stop_err( "%s" % str( exc ) )
Exemplo n.º 7
0
def qqplot_density(samples, density_x, density_y):
    from rpy import r
    # LAME: should do better quantile calculation.  r.quantile() returns a
    # hard-to-use dictionary unfortunately.  r.approx() as per ?quantile, maybe.
    percs = list(np.arange(1,100, .1))
    data_perc=np.percentile(samples, percs)
    real_perc=np.percentile(r.sample(density_x, len(samples)*10, prob=density_y, replace=True), percs)
    r.plot(real_perc, data_perc,  xlab='',ylab='',main='');
    r.abline(a=0,b=1,col='blue')
Exemplo n.º 8
0
	def plot(self, outputfname, fix_index_ls, parameter_list, var_index, variant_ls, parameter_index2label, y_axis_ls, y_label):
		outputfname = '%s_%s2%s.png'%(outputfname, y_label, parameter_index2label[var_index])
		sys.stderr.write('Plotting %s'%outputfname)
		r.png(outputfname)
		r.plot(variant_ls, y_axis_ls, main='%s vs %s (%s=%s, %s=%s)'%(y_label, parameter_index2label[var_index],\
			parameter_index2label[fix_index_ls[0]], parameter_list[fix_index_ls[0]], parameter_index2label[fix_index_ls[1]],\
			parameter_list[fix_index_ls[1]]), xlab=parameter_index2label[var_index], ylab=y_label)
		r.dev_off()
		sys.stderr.write('Done.\n')
Exemplo n.º 9
0
	def hist_plot(self, dict, filename, xlabel, ylabel):
		#convert self.go_no2cluster and self.go_no2gene into histograms
		r.png('%s'%filename)
		x_list = []
		y_list = []
		for (key, value) in dict.iteritems():
			x_list.append(key)
			y_list.append(len(value))
		r.plot(x_list, y_list, type='h', xlab=xlabel, ylab=ylabel, main='%s v.s. %s'%(ylabel, xlabel))
		r.dev_off()
Exemplo n.º 10
0
def trace_plots(history, burnin):
    from rpy import r
    h = np.array(history)
    print "{} total, {} burning, {} remaining".format(len(history), burnin, len(history)-burnin)
    r.par(mfrow=[2,2])
    r.acf(h[burnin:])
    r.plot(h,xlab='',ylab='',main='')
    r.abline(v=burnin, col='blue')
    #r.hist(h[burnin:],breaks=30,xlab='',ylab='',main='histogram')
    r.plot(r.density(h[burnin:]), xlab='',ylab='',main='density')
Exemplo n.º 11
0
def qqplot_density(samples, density_x, density_y):
    from rpy import r
    # LAME: should do better quantile calculation.  r.quantile() returns a
    # hard-to-use dictionary unfortunately.  r.approx() as per ?quantile, maybe.
    percs = list(np.arange(1, 100, .1))
    data_perc = np.percentile(samples, percs)
    real_perc = np.percentile(
        r.sample(density_x, len(samples) * 10, prob=density_y, replace=True),
        percs)
    r.plot(real_perc, data_perc, xlab='', ylab='', main='')
    r.abline(a=0, b=1, col='blue')
Exemplo n.º 12
0
def plot_binning(entries, main=None):
    for entry in entries:
        number, fullname, tarray = entry

        if main==None:
            this_main = fullname
        else:
            this_main = main

        if len(tarray)>0:
            r.plot(range(len(tarray)), tarray, xlab="bin index", ylab="center value", main=this_main)
Exemplo n.º 13
0
def trace_plots(history, burnin):
    from rpy import r
    h = np.array(history)
    print "{} total, {} burning, {} remaining".format(len(history), burnin,
                                                      len(history) - burnin)
    r.par(mfrow=[2, 2])
    r.acf(h[burnin:])
    r.plot(h, xlab='', ylab='', main='')
    r.abline(v=burnin, col='blue')
    #r.hist(h[burnin:],breaks=30,xlab='',ylab='',main='histogram')
    r.plot(r.density(h[burnin:]), xlab='', ylab='', main='density')
Exemplo n.º 14
0
def plots(regression_o, getData_o):
    """Plots the dataset with a regression line and a boxplot using R."""
    fname1 = 'car_regress.pdf'
    r.pdf(fname1)
    r.plot(getData_o, ylab='dist', xlab='speed')
    r.abline(regression_o['(Intercept)'], regression_o['y'], col='red')
    r.dev_off()

    fname2 = 'car_hist.pdf'
    r.pdf(fname2)
    r.boxplot(getData_o, names=['dist', 'speed'])
    r.dev_off()

    return fname1, fname2
Exemplo n.º 15
0
	def hist_plot_ratio(self, dict1, dict2, filename, xlabel, ylabel):
		#convert self.go_no2cluster and self.go_no2gene into histograms
		r.png('%s'%filename)
		x_list = []
		y_list = []
		keys = Set(dict1.keys()).union( Set(dict2.keys()) )
		for key in keys:
			value1 = dict1.get(key, [])
			value2 = dict2.get(key, [])
			ratio = float(len(value1))/(len(value1)+len(value2))
			x_list.append(key)
			y_list.append(ratio)
		r.plot(x_list, y_list, type='h', xlab=xlabel, ylab=ylabel, main='%s v.s. %s'%(ylabel, xlabel))
		r.dev_off()
Exemplo n.º 16
0
	def output(self):
		self.matrix = array(self.result_array)
		p_value_list = map(str, self.p_value_list)
		self.of.write('p_value\t%s\n'%'\t'.join(p_value_list))
		df = self.df_lower
		for cor_list in self.result_array:
			cor_list = map(str, cor_list)	#string can be 'join'ed. easy to output
			self.of.write('%d\t%s\n'%(df, '\t'.join(cor_list)))
			df += 1
		r.pdf('p_value_cor.pdf')
		#select a column to plot
		cor_list = self.matrix[:,self.column]
		p_value_label = self.p_value_list[self.column]
		df_list = range(self.df_lower, self.df_upper+1)
		r.plot(df_list, cor_list, type='o', pch='*', xlab='df', ylab='correlation', main='p_value: %s'%p_value_label)
		r.dev_off()
Exemplo n.º 17
0
def test():
	data=r.c([1.25,3.45,6.75,20.2,9.9])
	# draw image using rpy
	r.png("test.png", width=300,height=300)

	r.plot(data, type="o", col="blue", ylim=(0,100), pch=22, lty=1, axes=False, ann=False)
	r.axis(1, at=(1,2,3,4,5), lab=r.c("a","b","c","d","e"))
	r.axis(2, las=1, at=(0,50,100))
	r.box()

	r.title(main="CPU usage sampling result")
	r.title(xlab="Time")
	r.title(ylab="CPU")

	r.legend(1,100,r.c("trunk"), cex=0.8, col=r.c("blue"), pch=22, lty=1)
	r.dev_off()
Exemplo n.º 18
0
	def plot(self):
		vertex_list = self.graph.node_list()
		number_of_nodes = len(vertex_list)
		for vertex in vertex_list:
			degree = self.graph.inc_degree(vertex) + self.graph.out_degree(vertex)
			if degree not in self.degree_dict:
				self.degree_dict[degree] = 1
			else:
				self.degree_dict[degree] += 1
		r.pdf('degree_distribution.pdf')
		x_list = []
		y_list = []
		for degree in self.degree_dict:
			x_list.append(r.log(degree))
			y_list.append(r.log(float(self.degree_dict[degree])/number_of_nodes))
		r.plot(x_list, y_list, type='p', xlab='log(k)', ylab='log(p(k))')
		r.dev_off()
Exemplo n.º 19
0
def plot_bin_widths(entries, log_space=False, main=None):
    for entry in entries:
        number, fullname, tarray = entry

        if log_space:
            tarray = numpy.log(tarray)
            ylab = r("expression(ln(Delta[bin]))")
        else:
            ylab = r("expression(Delta[bin])")

        if main==None:
            this_main = fullname
        else:
            this_main = main
        
        if len(tarray)>0:
            r.plot(range(len(tarray)), tarray, xlab="bin number", ylab=ylab, main=this_main)
Exemplo n.º 20
0
    def __print_entropies(self, entropies):

        """
        This is for debugging purposes.
        """

        try:
            from rpy import r
        except:
            print "Could not import rpy module"
            return

        r.postscript(DEBUG_ENTROPIES_FILE)
        r.plot(entropies, type='b', xlab="Iterations", ylab="Entropy")
        r.dev_off()

        return
    def plotLabelLegend(self, colVecL, labelPhenoD, filename=None, legendDir=None, type='png'):

        if filename is None:
            filename = 'legend_label_%i' % len(labelPhenoD.keys())
        if legendDir is None:
            legendDir = self.legendDir
            
        full_filename = os.path.join(legendDir, filename)

        labelL = labelPhenoD.keys()
        labelL.sort()
        phenoL = [labelPhenoD[x] for x in labelL]
        
        rdev = plot_utilities.RDevice(name = full_filename, title='', plotType=type, 
            width=300, height=200)
        r("par(mar=c(0,0,0,0))")
        r.plot([1, 2, 3], type="n", xlab="", ylab="", main="", ann=False, axes=False)
        r.legend(x="center", legend = phenoL, fill=colVecL, bg = "white", bty="n", cex=0.7)
        rdev.close()
Exemplo n.º 22
0
	def _plot(self, row):
		self.no_of_curves += 1
		#position 3 in row is the varying value
		self.varying_list.append(row[3])
		x_list = []
		y_list = []
		self.curs.execute("select tp, tp_m, tp1, tp1_m, tn, fp, fp_m, fn from stat_plot_data where\
			%s=%s and %s=%s and %s=%s and %s=%s and tag='%s' order by p_value_cut_off"%\
			(self.option_num_dict[0].label, row[0], self.option_num_dict[1].label, row[1], self.option_num_dict[2].label,\
			row[2], self.option_num_dict[3].label, row[3], row[4]))
		plot_data = self.curs.fetchall()
		for entry in plot_data:
			tn = entry[4]
			fn = entry[7]
			if self.based_on_clusters:
				#using the tp_m, tp1_m and fp_m
				tp = entry[1]
				tp1 = entry[3]
				fp = entry[6]
			else:
				#using the tp, tp1, fp
				tp = entry[0]
				tp1 = entry[2]
				fp = entry[5]
			if self.l1:
				#tp1 is counted as true positive
				tp += tp1
			else:
				#tp1 is counted as false positive
				fp += tp1
			x_list.append(tp)
			y_list.append(float(tp)/(tp+fp))

		if self.no_of_curves==1:
			r.plot(x_list, y_list, type='o',pch='*',xlab='consistent predictions',xlim=self.x_range,ylim=self.y_range, \
			ylab='percentage', main='%s'%(self.option_num_dict[3].label), col=self.no_of_curves)
		else:
			r.lines(x_list, y_list, type='o',pch='*',col=self.no_of_curves)
Exemplo n.º 23
0
    def __init__(self, bedfile, dir, win, ma, out, ymin=0, ymax=0):
        self.L = 17  # number of letters per line
        Bed.__init__(self, bedfile)
        self.dir = dir
        self.win = win + ma
        self.ma = ma  # window for moving average

        try:
            from rpy import r
            r.pdf(out + '.ConservationPlot.pdf')
            self.Run()
            if not ymin:
                ymin = self.mscore[self.mscore > 0].min() - 0.05
            if not ymax:
                ymax = self.mscore.max() + 0.05

            r.plot(range(-1*win, win+1), self.mscore, type = 'l', xlab = \
                   'Distance from the Center of Enriched Regions', \
                   ylab = 'Conservation Score', lwd= 3,  ylim = (ymin, ymax))
            r.dev_off()
        except:
            print >> sys.stderr, 'error import r using rpy, will not generate phastCons plot'
            print sys.exc_info()[0], sys.exc_info()[1]
Exemplo n.º 24
0
	def single_plot(self):
		#this function deals with 4 fixed parameters and 1 varying parameter
		r.png('%s'%self.ofname)
		x_list = []
		y_list = []
		self.curs.execute("select  tp, tp_m, tp1, tp1_m, tn, fp, fp_m, fn from\
			stat_plot_data where %s=%s and %s=%s and %s=%s and %s=%s and tag='%s' order by %s \
			"%(self.option_num_dict[0].label, self.option_num_dict[0].value, \
			self.option_num_dict[1].label, self.option_num_dict[1].value, self.option_num_dict[2].label, \
			self.option_num_dict[2].value, self.option_num_dict[3].label, self.option_num_dict[3].value, \
			self.tag, self.option_num_dict[4].label))
		plot_data = self.curs.fetchall()
		for entry in plot_data:
			tn = entry[4]
			fn = entry[7]
			if self.based_on_clusters:
				#using the tp_m, tp1_m and fp_m
				tp = entry[1]
				tp1 = entry[3]
				fp = entry[6]
			else:
				#using the tp, tp1, fp
				tp = entry[0]
				tp1 = entry[2]
				fp = entry[5]
			if self.l1:
				#tp1 is counted as true positive
				tp += tp1
			else:
				#tp1 is counted as false positive
				fp += tp1
			x_list.append(tp)
			y_list.append(float(tp)/(tp+fp))
		
		r.plot(x_list, y_list, type='o',pch='*',xlab='consistent predictions',xlim=self.x_range,ylim=self.y_range, \
				ylab='percentage', main='%s'%(self.option_num_dict[4].label), col=1)
		r.dev_off()
Exemplo n.º 25
0
	def plot(self):
		r.pdf("per_p_value05.pdf")
		r.plot(self.dataset_no, self.per_05, type='o', pch='*', xlab='dataset no.',\
			ylab='percentage', main='p_value: 0.05. #edges compared with correlation cut_off 0.6')
		r.dev_off()
		r.pdf("per_p_value025.pdf")
		r.plot(self.dataset_no, self.per_025, type='o', pch='*', xlab='dataset no.',\
			ylab='percentage', main='p_value: 0.025. #edges compared with correlation cut_off 0.6')
		r.dev_off()
		r.pdf("per_p_value01.pdf")
		r.plot(self.dataset_no, self.per_01, type='o', pch='*', xlab='dataset no.',\
			ylab='percentage', main='p_value: 0.01. #edges compared with correlation cut_off 0.6')
		r.dev_off()
Exemplo n.º 26
0
    def generateCountsGraph(self, counts, sitename, widthpx=648, resol=72,  ):
        '''
            Static function to generate graph file via R.
            Graphs *all* of the counts records contained in counts List
        
    
        '''
        from rpy import r as robj
              
        # Calculate graph image information
        widthpx = int(widthpx)
        imgwidth = int( float(widthpx) / float(resol) )      
        ratio = float(self.config.get('data','graphratio'))
        imgheight =  int( (float(widthpx) * ratio) / float(resol) ), 
                
        counts_data = {"datetime":[],
                     "c1":[]}
        (fd, tmpgraphfile)= mkstemp()
        logobject.debug("DataHandler.generateCountsGraph(): Temp graph filename = %s" % tmpgraphfile)
    
        for cr in counts:
                #logobject.debug("%s" % c)
                epochsecs = time.mktime(cr.datetime.timetuple())
                counts_data["datetime"].append(  epochsecs  )
                #counts_data["datetime"].append( "%s" % c.datetime   )
                #logobject.debug("Datetime %s converted to epoch %d" % (c.datetime, epochsecs ))
                counts_data["c1"].append(cr.c1)

        
        cts = counts_data['c1']
        ctm = counts_data['datetime']
        if len(cts) > 0:
            robj.bitmap(tmpgraphfile, 
                     type = "png256", 
                     width = imgwidth , 
                     height = imgheight,
                     res = resol,
                     )
        
            ymin = int(self.config.get('data','counts.graph.ylim.min'))
            ymax = int(self.config.get('data','counts.graph.ylim.max'))
            robj.plot(ctm, cts, 
                       col="black", 
                       main="Counts: %s" % sitename ,
                       xlab="Time: (secs since 1970)", 
                       ylab="Counts/min",
                       type="l",
                       ylim=(ymin,ymax)
                       )
            robj.dev_off()
            import imghdr
            imgtype = imghdr.what(tmpgraphfile)
            logobject.debug("DataHandler.generateCountsGraph(): OK: What is our tempfile? = %s" % tmpgraphfile )
            f = open(tmpgraphfile)
        else:
            logobject.debug("DataHandler.generateCountsGraph(): No data. Generating proper error image...")
            #logobject.debug("DataHandler.generateCountsGraph(): Temp error image filename = %s" % tmpgraphfile)
            
            #import Image
            #import imghdr
            #imf = Image.open(self.config.get('data','nodatapng'))
            #imf.save(tmpgraphfile)
                        
            #imgtype = imghdr.what(tmpgraphfile)
            #logobject.debug("DataHandler.generateCountsGraph(): ERROR: What is our tempfile? = %s" % imgtype )
            f = open(self.config.get('data','nodatapng'))
        return f
Exemplo n.º 27
0
  for cond in data_raw[1][20:]:
    if cond == 'brigh':
      Cond.append(0)
    elif cond == 'undef':
      Cond.append(1)
    elif cond == 'dark':
      Cond.append(2)
  C = 3
  RT = map(float, data_raw[4][20:])
  for i in range(0,len(RT)):
    if data_raw[2][20:][i] == 'a':
      RT[i] = - float(RT[i])
  N = len(RT)
  
  # Create model and sample from it
  M = pymc.MCMC(wiener_model(RT, Cond, N, C))
  M.sample(iter=5000, burn=0, thin=1)

  # plot results with R
  from rpy import r 
  r.x11()
  r('par(mfrow=c(3,1))')
  r.plot(M.trace('delta_0')[:], col="deepskyblue3", type="l", xlab="", ylab="")
  r.plot(M.trace('delta_1')[:], col="deepskyblue3", type="l", xlab="", ylab="")
  r.plot(M.trace('delta_2')[:], col="deepskyblue3", type="l", xlab="", ylab="")
  r.x11()
  r('par(mfrow=c(3,1))')
  r.plot(r.density(M.trace('delta_0')[:]), col="deepskyblue4", type="l", xlab="", ylab="", xlim=[-3,3])
  r.plot(r.density(M.trace('delta_1')[:]), col="deepskyblue4", type="l", xlab="", ylab="", xlim=[-3,3])
  r.plot(r.density(M.trace('delta_2')[:]), col="deepskyblue4", type="l", xlab="", ylab="", xlim=[-3,3])
Exemplo n.º 28
0
    for S in (S, ):
        StructCorr.calcSk(S)

    v_kmag = StructCorr.kmags()
    v_sk = StructCorr.SkAverages()

    #thisRun.sort()
    print "top modes:"

    print "%6s %6s %7s %9s"%('kmag', 'Sk', 'kmag/L', 'L/kmag')
    for Sk, kmag in zip(v_sk, v_kmag)[-10:]:
        print "%6.3f %6.3f %7.5f %9.5f"%(kmag, Sk, kmag/L, L/kmag)

    r.plot(v_kmag, v_sk,
           xlab="", ylab="", type="l",
           ylim=(0., 15)
           #ylim=(0., 15000)
           )
    # plots a line at each k-vector point.
    for kmag in v_kmag:
        r.abline(v=kmag, lty=3, col="lightgray")
    # plots each individual k-vector
    for kmag, SkArray in zip(v_kmag, StructCorr.SkArrays()):
        r.points(x=[kmag]*len(SkArray), y=SkArray,
                 col="blue", pch="x")
    # plots the standard deviation of the by-kvector lists.
    for kmag, SkArray in zip(v_kmag, StructCorr.SkArrays()):
        r.points(x=kmag, y=numpy.std(SkArray),
                 col="red", pch="s")
    # plots it using the average of all k-vectors -- this should line up
    # exactly
Exemplo n.º 29
0
def plot(outfile, data, out_format='png'):
    w = int(round(len(data) / 4.0))

    if out_format == 'png':
        r.png(outfile, width=w * 100, height=1000, res=72)
    elif out_format == 'pdf':
        r.pdf(outfile, width=w, height=10)
    else:
        raise Exception('Unrecognised format: ' + str(out_format))

    print("total: " + str(len(data)))

    series = []
    points = {'translate': [], 'preprocessing': []}

    for dat in data:
        points['translate'].append(float(dat['translate']))
        points['preprocessing'].append(float(dat['preprocessing']))

    xlabels = []
    for k, v in data[0].iteritems():
        if k not in ["problem", 'translate', 'preprocessing']:
            series.append(k)
            points[k] = []

    index = 0
    for dat in data:
        for k in series:
            if dat[k] != 'no-plan':
                points[k].append(float(dat[k]) + \
                                 points['translate'][index] + \
                                 points['preprocessing'][index])
            else:
                points[k].append(-1000)
        xlabels.append(dat['problem'])
        index += 1

    max_value = max(iter([max(iter(points[k])) for k in series]))
    yrange = (0, max_value)
    legend_labels = []

    x = [i for i in range(1, len(points['translate']) + 1)]
    y = [-1000 for i in x]
    r.par(mar=(7, 5, 4, 2))
    r.plot(x,
           y,
           main='',
           xlab="",
           ylab='',
           xaxt='n',
           yaxt='n',
           pch=0,
           ylim=yrange,
           mgp=(5, 1, 0))
    r.mtext("Problem", side=1, line=5)
    r.mtext("CPU Time (s)", side=2, line=3)

    pch_start = 1
    pch_index = pch_start
    # plotting "translate"
    #r.plot(x, points['translate'], main='',
    #       xlab='', ylab='Time (s)',
    #       xaxt='n', yaxt='n',
    #       pch=0, ylim=yrange)
    #legend_labels.append('translate')
    r.lines(x, points['translate'], lty=1)

    # preprocessing -- Removed since it's insignificant
    #r.points(x, points['preprocessing'], pch=pch_index)
    #pch_index =+ 1

    # planner output
    for k in series:
        if k != 'translate' and k != 'preporcessing':
            r.points(x, points[k], pch=pch_index)
            pch_index += 1
            legend_labels.append("FD+" + k.upper())

    # put x-axis labels
    for i in range(0, len(xlabels)):
        r.axis(side=1, at=i + 1, labels=xlabels[i], las=2)

    # put y-axis labels
    base, step = get_y_step(max_value)
    print("base: " + str(base) + " -- step: " + str(step))
    y = base
    for i in range(0, step):
        r.axis(side=2, at=y, labels=str(y), las=2)
        y += base

    # legend
    r.legend(1,
             max_value,
             legend_labels,
             pch=[i for i in range(pch_start, pch_index)])

    r.dev_off()
Exemplo n.º 30
0
from rpy import r
my_x = [5.05, 6.75, 3.21, 2.66]
my_y = [1.65, 26.5, -5.93, 7.96]
ls_fit = r.lsfit(my_x,my_y)
gradient = ls_fit['coefficients']['X']
yintercept= ls_fit['coefficients']['Intercept']

r.png("scatter_regression.png", width=400, height=350)
r.plot(x=my_x, y=my_y, xlab="x", ylab="y", xlim=(0,7), ylim=(-16,27),
       main="Example Scatter with regression")
r.abline(a=yintercept, b=gradient, col="red")
r.dev_off()
Exemplo n.º 31
0
    # Store all the plotting data
    data = []

    # Print which is used
    print "Using:", cp.fullname


    # Plot the required output
    r.pdf(options.output, width=options.width, height=options.height)      
    r.par(cex=options.cex)

    inv_beta = arange(options.inv_beta_min, options.inv_beta_max, 0.01)
    beta = 1.0/inv_beta

    lnZ = vectorize(cp.lnZ)(beta)
    r.plot(inv_beta, lnZ, type='l', xlab=r("expression(beta**-1)"), ylab=r("""expression(paste("ln ", Z(beta)))"""))
    data.append((cp.number, "lnZ", (inv_beta, lnZ)))

    betaF = vectorize(cp.betaF)(beta)
    r.plot(inv_beta, betaF, type='l', xlab=r("expression(beta**-1)"), ylab=r("expression(F(beta) * beta)"))
    data.append((cp.number, "betaF", (inv_beta, betaF)))

    S = vectorize(cp.S)(beta)
    r.plot(inv_beta, S, type='l', xlab=r("expression(beta**-1)"), ylab=r("expression(S(beta) / k[B])"))
    data.append((cp.number, "S", (inv_beta, S)))

    E = vectorize(cp.E)(beta)
    r.plot(inv_beta, E, type='l', xlab=r("expression(beta**-1)"), ylab=r("expression(bar(E)(beta))"))
    data.append((cp.number, "E", (inv_beta, E)))

    C = vectorize(cp.C)(beta)
Exemplo n.º 32
0
education and they could have different salaries.
'''
education_years = [19,20,16,16,18,12,14,12,16,17];
income = [125000,100000,40000, 35000, 41000, 29000, 35000, 24000, 50000, 60000];

# do the scatter plot
# Specify the output picture size and format.
print "Writing output graph to file: scatterplot.png"
print "To view it in Linux, you can use the File Browser and double-click."
print "For command-line viewing, use the gthumb image viewer as follows:"
print "% gthumb scatterplot.png"

r.png("scatterplot.png", width=400, height=350);
# Draw the plot. xlim and ylim specify the range for the axis. We
# prefer to keep the graph origin at 0,0.
r.plot(x=education_years, y=income, xlab="Education Years", ylab = "Income",
       main = "Scatter Plot with Least Squares Fit");

# Compute the least-square fit object between education_years and income.
leastsquarefit = r.lsfit(education_years, income);

#print "leastsquarefit = ", leastsquarefit; # for debugging.

# Compute the slope of the line and the y-intercept from the least-square
# fit object.
gradient = leastsquarefit['coefficients']['X'];
yintercept = leastsquarefit['coefficients']['Intercept'];

# Now plot the least square fit line.
r.abline(a=yintercept, b=gradient, col="red");
# Now turn off the graphics device. This is a R operation to "close"
# the graph.
    def plotBundle(self, bundleD, full_filename, colorsD=None, bundlePointsD=None, legendL=None, title=None, y_max=None):

        if y_max is None:
            y_max = 0.4
            
        if legendL is None:
            legendL = bundleD.keys()
            legendL.sort()
            
        if title is None:
            title = 'data'            

        bundleIdL = bundleD.keys()
        bundleIdL.sort()

        if colorsD is None:            
            colorsL = r.rainbow(len(bundleIdL))
            colorsD = dict(zip(bundleIdL, colorsL))
        
        colorsL = [colorsD[x] for x in bundleIdL]
        
        time_min = min([len(bundleD[x]) for x in bundleD.keys()])
        timeVec = [0.5 * x for x in range(time_min)]

        try:
            r.png(full_filename, width=800, height=600)
            oldPar = r.par(xpd = True, mar = [x + y for (x,y) in zip(r.par()['mar'], [0,0,0,6])])
        
            print 'plot %s' % full_filename
            r.plot(timeVec, timeVec,
                   type='n',
                   main=title, ylim=(0, y_max),
                   xlab="time in hours after transfection", ylab="Relative Cell Counts",
                   pch=20, lwd=1, lty = 1, 
                   cex=1.0, cex_lab=1.2, cex_main=1.5)
        
        
            for bundleId in bundleIdL:
                
                if not bundlePointsD is None:
                    r.points(timeVec, bundlePointsD[bundleId],
                             col=colorsD[bundleId], pch=20,
                             lwd=1)
                    r.lines(timeVec, bundlePointsD[bundleId],
                            col=colorsD[bundleId],
                            lwd=1, lty = 1)

                r.lines(timeVec, bundleD[bundleId],
                        col=colorsD[bundleId],
                        lwd=3, lty = 1)

            r.legend(max(timeVec) * 1.1, y_max, legend=legendL, fill=colorsL, cex=1.0, bg= 'whitesmoke')
            r.par(oldPar)
            r.grid(col="darkgrey")
        
            r.dev_off() 
        except:
            r.dev_off()
            print full_filename + ' has not been printed.'
            

        return
Exemplo n.º 34
0
def plot(outfile, data, out_format='png'):
    w = int(round(len(data)/4.0))

    if out_format == 'png':
        r.png(outfile, width=w*100, height=1000, res=72)
    elif out_format == 'pdf':
        r.pdf(outfile, width=w, height=10)
    else:
        raise Exception('Unrecognised format: ' + str(out_format))

    print("total: " + str(len(data)))

    series = []
    points = {'translate': [], 'preprocessing': []}

    for dat in data:
        points['translate'].append(float(dat['translate']))
        points['preprocessing'].append(float(dat['preprocessing']))

    xlabels = []
    for k, v in data[0].iteritems():
        if k not in ["problem", 'translate', 'preprocessing']:
            series.append(k)
            points[k] = []

    index = 0
    for dat in data:
        for k in series:
            if dat[k] != 'no-plan':
                points[k].append(float(dat[k]) + \
                                 points['translate'][index] + \
                                 points['preprocessing'][index])
            else:
                points[k].append(-1000)
        xlabels.append(dat['problem'])
        index += 1

    max_value = max(iter([max(iter(points[k]))  for k in series]))
    yrange = (0, max_value)
    legend_labels = []

    x = [i for i in range(1,len(points['translate'])+1)]
    y = [-1000 for i in x]
    r.par(mar=(7,5,4,2))
    r.plot(x, y, main='', xlab="", ylab='',
           xaxt='n', yaxt='n', pch=0, ylim=yrange,
           mgp=(5,1,0))
    r.mtext("Problem", side=1, line=5)
    r.mtext("CPU Time (s)", side=2, line=3)

    pch_start = 1
    pch_index = pch_start
    # plotting "translate"
    #r.plot(x, points['translate'], main='',
    #       xlab='', ylab='Time (s)',
    #       xaxt='n', yaxt='n',
    #       pch=0, ylim=yrange)
    #legend_labels.append('translate')
    r.lines(x, points['translate'], lty=1)
    
    # preprocessing -- Removed since it's insignificant
    #r.points(x, points['preprocessing'], pch=pch_index)
    #pch_index =+ 1

    # planner output
    for k in series:
        if k != 'translate' and k != 'preporcessing':
            r.points(x, points[k], pch=pch_index)
            pch_index += 1
            legend_labels.append("FD+" + k.upper())

    # put x-axis labels
    for i in range(0, len(xlabels)):
        r.axis(side=1, at=i+1, labels=xlabels[i], las=2)

    # put y-axis labels
    base, step = get_y_step(max_value)
    print("base: " + str(base) + " -- step: " + str(step))
    y = base
    for i in range(0, step):
        r.axis(side=2, at=y, labels=str(y), las=2)
        y += base

    # legend
    r.legend(1, max_value, legend_labels, pch=[i for i in range(pch_start, pch_index)])

    r.dev_off()
Exemplo n.º 35
0
from rpy import r

# first plot
x = range(1,11)
y = [i**2 for i in x]

r.plot(x, y, xlab='x', ylab='y', main='My first plot',
      pch=21, col='blue', bg='lightblue', type='o') 


# second plot
x = range(1,11)
y = [i**2 for i in x]
z = [i**3 for i in x]
r.plot(x, y, main='My second plot', xlab='x', ylab='y', type='l', col='blue')
r.lines(x, z, col='red') 

# cosine function, save to file
import math
r.png('cosine.png')
x = r.seq(0,50, by=0.1)
y = [math.cos(i) for i in x]
r.plot(x, y, main='COS(X)', xlab='x', ylab='cos(x)', type='l', col='blue')
r.dev_off() 

# histogram
x = range(10) + range(3,6) + range(5,10)
r.hist(x, main='A histogram', xlab='x', col='lightblue') 

# adust plotting area
from rpy import r
Exemplo n.º 36
0
from rpy import r
import os.path

# find out where the temp directory is
tempdir = r.tempdir()

# write its name into a file
f = open('tempdir','w')
f.write(tempdir)
f.close()

# put something there..
r.postscript(os.path.join(tempdir,"foo.ps"))
r.plot(1,1)
r.dev_off()