Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
print "pi"
print type(r)
pi = r['pi']
print pi[0]
print type(pi)
print "piplus"
piplus = r('piplus = pi + 1')
print type (piplus)
print piplus
print piplus[0]
# some simple R things
print R.r.median(R.IntVector([1,2,3,4]))[0]
# create two R vectors and do correlation coefficient in R
a = R.IntVector([1,2,3,4])
b = R.IntVector([1,2,3,4])
# need the subscript to get authentic python type?
print R.r.cor(a,b,method="pearson")[0]
my_vec = R.IntVector([1,2,3,4])
my_chr_vec = R.StrVector(['aaa','bbb'])
my_float_vec = R.FloatVector([0.001,0.0002,0.003,0.4])
print "\nconvert to numpy array?"
vector = rpyn.ri2numpy(my_float_vec)
print vector
def test_init_stringsasfactors():
od = {'a': robjects.IntVector((1,2)),
'b': robjects.StrVector(('c', 'd'))}
dataf = robjects.DataFrame(od, stringsasfactor=True)
assert isinstance(dataf.rx2('b'), robjects.FactorVector)
dataf = robjects.DataFrame(od, stringsasfactor=False)
assert isinstance(dataf.rx2('b'), robjects.StrVector)
def test_sample():
vec = robjects.IntVector(range(100))
spl = vec.sample(10)
assert len(spl) == 10
def test_tcrossprod():
m = robjects.r.matrix(robjects.IntVector(range(4)), nrow=2)
mtcp = m.tcrossprod(m)
for i,val in enumerate((4,6,6,10,)):
assert mtcp[i] == val
fields = line.split()
if len(fields) > 0 and ".read." in fields[0]:
id = line.split()[0]
read_poses.append(id.split(".")[-1])
offsets.append(id.split(":")[1].split(".")[0])
#if "read name :" in line:
# id = line.split()[3]
import rpy2.robjects as robj
if len(read_poses):
print len(read_poses)
return robj.r.hist(robj.FloatVector(read_poses), breaks=77, plot=False)
else:
print 0
return robj.IntVector([])
def _fisher_extact_rxc(counts_obs, counts_exp):
if (counts_obs, counts_exp) in FISHER_CACHE:
return FISHER_CACHE[(counts_obs, counts_exp)]
import rpy2.robjects as robjects
env = robjects.r.baseenv()
env['obs'] = robjects.IntVector(counts_obs)
env['expected'] = robjects.IntVector(counts_exp)
pvalue = robjects.r('fisher.test(cbind(obs, expected))$p.value')[0]
FISHER_CACHE[(counts_obs, counts_exp)] = pvalue
return pvalue
tempFastaFile = open(tempFasta, "w")
tempFastaFile.write(">seq\n{}".format(s1))
tempFastaFile.close()
proc = subprocess.Popen("yass -d 3 -o {} {}".format(tempYASSResult, tempFasta), shell=True,
stderr=subprocess.PIPE)
resultCode = proc.wait()
if resultCode != 0:
raise YassException("Check that yass is installed correctly")
stderr = proc.stderr.readlines()[0].decode()
if "Error" in stderr:
print("Error running yass: '{}'".format(stderr))
raise YassException("Error running yass")
ro.r.png(tempPNG, res=150, width=1000, height=1000)
ro.r.plot(ro.IntVector([0]), ro.IntVector([0]), type="n", xaxs="i", yaxs="i",
xlab="Position in reference allele", ylab="Position in reference allele",
xlim=ro.IntVector([0,length]),
ylim=ro.IntVector([0,length]))
for line in open(tempYASSResult):
if line.startswith("#"):continue
res = line.strip().split()
if float(res[-1]) < 0.1:
if res[6]=="f":
ro.r.segments(int(res[0]), int(res[2]), int(res[1]), int(res[3]), col="blue", lwd=1)
else:
ro.r.segments(int(res[1]), int(res[2]), int(res[0]), int(res[3]), col="red", lwd=1)
for breakpoint in breakpoints:
ro.r.abline(h=breakpoint, lty=2, col="gray")
ro.r.abline(v=breakpoint, lty=2, col="gray")
if num_obs is not None:
raw_signal = raw_signal[:num_obs]
if add_vlines:
corr_subgrp = fast5_data['/Analyses/' + corr_grp]
event_starts = corr_subgrp['Events']['start']
events_end = event_starts[-1] + corr_subgrp['Events']['length'][-1]
raw_start = corr_subgrp['Events'].attrs.get('read_start_rel_to_raw')
raw_end = raw_start + events_end
if rna:
tmp_raw_end = raw_signal.shape[0] - raw_start
raw_start = raw_signal.shape[0] - raw_end
raw_end = tmp_raw_end
vlineDat = r.DataFrame({'Position':r.IntVector([
raw_start, raw_end]),})
elif manual_vlines is not None:
vlineDat = r.DataFrame({'Position':r.IntVector(manual_vlines),})
norm_signal, _ = ts.normalize_raw_signal(
raw_signal, norm_type=norm_type, scale_values=scale_values)
sigDat = r.DataFrame({
'Position':r.IntVector(range(norm_signal.shape[0])),
'Signal':r.FloatVector(norm_signal)})
hDat = r.r('NULL')
if highlight_pos is not None:
if num_obs is not None:
highlight_pos = highlight_pos[highlight_pos < num_obs]
hDat = r.DataFrame({
'Position':r.IntVector(highlight_pos),
'Signal':r.FloatVector(norm_signal[highlight_pos])})
hrDat = r.r('NULL')
if highlight_ranges is not None:
for sig_mean, read_i in all_trimers[kmer]]
trimerDat = r.DataFrame({
'Trimer':r.FactorVector(
r.StrVector(zip(*plot_data)[0]),
ordered=True, levels=r.StrVector(kmer_levels)),
'Base':r.StrVector(zip(*plot_data)[1]),
'Signal':r.FloatVector(zip(*plot_data)[2]),
'Read':r.StrVector(zip(*plot_data)[3])})
# code to plot kmers as tile of colors but adds gridExtra dependency
if False:
kmer_plot_data = [
(kmer_i, pos_i, base) for kmer_i, kmer in enumerate(kmer_leves)
for pos_i, base in enumerate(kmer)]
kmerDat = r.DataFrame({
'Kmer':r.IntVector(zip(*kmer_plot_data)[0]),
'Position':r.IntVector(zip(*kmer_plot_data)[1]),
'Base':r.StrVector(zip(*kmer_plot_data)[2])})
if read_mean:
r.r('pdf("' + fn_base + '.read_mean.pdf", height=7, width=10)')
plotKmerDistWReadPath(trimerDat)
r.r('dev.off()')
else:
r.r('pdf("' + fn_base + '.pdf", height=7, width=10)')
plotKmerDist(trimerDat)
r.r('dev.off()')
return
def get_meta_analysis_from_r(gene_estimates):
r.library("meta")
m = r.metacont(
robjects.IntVector(gene_estimates.caseDataCount),
robjects.FloatVector(gene_estimates.caseDataMu),
robjects.FloatVector(gene_estimates.caseDataSigma),
robjects.IntVector(gene_estimates.controlDataCount),
robjects.FloatVector(gene_estimates.controlDataMu),
robjects.FloatVector(gene_estimates.controlDataSigma),
studlab=robjects.StrVector(gene_estimates.gse),
byvar=robjects.StrVector(gene_estimates.subset),
bylab="subset",
title=gene_estimates.title
)
return m