I have an rpy2 script:
from rpy2.robjects.packages import importr
binom = importr('binom')
from rpy2 import robjects
robjects.r('''library(binom)
p = seq(0,1,.01)
coverage = binom.coverage(p, 10, method="bayes", type = "central")$coverage
''')
I'd like to use it to compare the results from a list of methods please:
methods = [("bayes", type = "central"),("asymptotic")]
for method in methods:
robjects.globalenv["method"] = robjects.r(method)
robjects.r('''library(binom)
p = seq(0,1,0.01)
coverage = binom.coverage(p, 10, method=method)$coverage
''')
The first line gives me:
invalid syntax
And I'd like to include the 'type' for the Bayes method please but when I drop that to get the syntax on my list I still get the error:
object 'bayes' not found
robjects.r() receives a string so for this particular task you can just replace the word method with the right string. Using both quotes (single and double) will do the trick because .replace() will ditch the external quote and replace the text, keeping the single quote.
from rpy2.robjects.packages import importr
binom = importr('binom')
from rpy2 import robjects
methods = ["'bayes', type='central'","'asymptotic'"]
for method in methods:
r_string = """library(binom)
p = seq(0,1,0.01)
coverage = binom.coverage(p, 10, method=TECHNIQUE)$coverage
""".replace('TECHNIQUE',method)
robjects.r(r_string)
Related
I am facing an issue when trying to execute the r code below with python rpy2.
from rpy2.robjects import r
import rpy2.robjects as ro
from rpy2.robjects.conversion import localconverter
from rpy2.robjects import pandas2ri
from rpy2.robjects.packages import importr
stats = importr("stats")
with localconverter(ro.default_converter + pandas2ri.converter):
Rdataframe2 = ro.conversion.py2rpy(dtw)
rdism = r["as.dist"](Rdataframe2)
ttclust = r.hclust(rdism)
ttclusterange = r.cutree(ttclust, k='1:3')
I can't find a way to pass the argument k="1:3" in the cutree function.
I keep receiving an error message stating
""elements of 'k' must be between 1 and %d", :
missing value where TRUE/FALSE needed
it seems that I can't find the right syntax to execute the last line.
Can someone please help me to solve this issue
The 1:3 expression is meant to generate a vector of c(1, 2, 3) in R. However, you are not evaluating it in R but passing it as a string/character '1:3' using rpy2. Try passing an equivalent list [1, 2, 3] instead, or using list(range(1, 3 + 1)). This is:
r.cutree(ttclust, k=list(range(1, 3 + 1)))
I want to add a chain with all the residues and one carbon-alpha atom per residue using the OpenMM. Here the link of instances can be used openMM documentation . Currently I have one chain in my pdb file pdb file. Here is what I've tried:
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np
import mdtraj as md
# Here I remove all other atoms except carbon-alpha and stored them in a new file 'CA_only.pdb'
main_pdb = md.load_pdb('1PGB.pdb')
atoms_to_keep = [atom.index for atom in main_pdb.topology.atoms if atom.name == 'CA']
new_pdb = main_pdb.atom_slice(atoms_to_keep)
new_pdb.save('CA_only.pdb')
# Then I try to add a chain and residue, but no results
pdb = PDBFile('CA_only.pdb')
top = topology.Topology
chain=top.addChain(id='A')
residue = top.addResidue(MET, 0)
I might be using wrong names of residues. But I don't know what is wrong. Could someone have any idea how to resolve this? Thanks!!
As far as I checked, the indentation is correct, no brackets are missing and I have only imported packages in the previous lines But I still get invalid syntax error.
#!/usr/bin/python
import bpy
import mathutils
import numpy as np
from math import radians
from mathutils import Vector
from math import radians
from mathutils import Matrix
from bpy import context
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
obj= bpy.data.objects[parent]
obj1= bpy.data.objects[obj_to_be_transformed]
initial_mat = obj1.matrix_world
...some code
(x,y,z) = (translate_x, translate_y, translate_z)
orig_loc_mat = Matrix.Translation(orig_loc+ mathutils.Vector((x,y,z)))
...some more code
eul = mathutils.Euler((radians(rot_x), radians(rot_y), radians(rot_z)), 'XYZ')
rot_mat = eul.to_matrix().to_4x4()
obj.matrix_world = orig_loc_mat * rot_mat * orig_rot_mat * orig_scale_mat
bpy.context.scene.update()
return [initial_loc,initial_rot,initial_scale,loc,rot,scale]
transform_result= transform_mesh('Armature','Coil',(5,0,0),(0,0,1))
print (transform_result)
And error is:
Error: File "D:\users\gayathri\Gayathri\Synthetic_data_generation\Final\HMI_Depth_coilA_final_final.blend\Untitled", line 18
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
^
SyntaxError: invalid syntax
location: <unknown location>:-1
def transform_mesh('parent', 'obj_to_be_transformed',
should be
def transform_mesh(parent, obj_to_be_transformed,
surely?
1- Remove strings from arguments
2- Remove tuples from arguments and attribute them in the function (It might be useful to add some checks)
So, here you are:
def transform_mesh(parent, obj_to_be_transformed, translate, rot):
translate_x, translate_y, translate_z= translate
rot_x,rot_y,rot_z = rot
# etc
transform_result= transform_mesh('Armature','Coil',(5,0,0),(0,0,1))
print (transform_result)
Tuple parameters are not supported in Python3, but you can pass it as a variable and unpack it after defining the function.
def transform_mesh(translate_xyz):
translate_x, translate_y, translate_z = translate_xyz
You need to provide variables as arguments to the function.
try something like:
def transform_mesh(parent, obj_to_be_transformed, t1, t2):
Although in the code you have shared, you are always using t1 and t2 as tuples. But in case you want to use x, y and z separately, you can do it by referencing the index:
x = t1[0]
y = t1[1]
In this line the function parameter are passed in incorrect way,
def transform_mesh('parent', 'obj_to_be_transformed', (translate_x, translate_y, translate_z), (rot_x,rot_y,rot_z)):
The Correct syntax would be:
def transform_mesh(parent, obj_to_be_transformed, *translate_xyz, *rot_xyz): #*translate_xyz and *rot-xyz are tuple parameter
It's easy to use apriori algorithm from package arules as:
import rpy2.interactive as r
arules = r.packages.importr("arules")
from rpy2.robjects.vectors import ListVector
od = OrderedDict()
od["supp"] = 0.0005
od["conf"] = 0.7
od["target"] = 'rules'
result = ListVector(od)
my_rules = arules.apriori(dataset, parameter=result)
However, apriori subset uses a different format in subset param:
rules.sub <- subset(rules, subset = rhs %in% "marital-status=Never-married" & lift > 2)
It's possible to use this subset function with rpy2?
If subset is (re)defined in the R package arules, the object arules obtained from importr will contain it. In your python code this will look like arules.subset.
The parameter subset is a slightly different story because it is an R expression. There can be several ways to tackle this. One of them is to wrap it in an ad-hoc R function.
from rpy2.robjects import r
def mysubset(rules, subset_str):
return r("function(rules) { arules::subset(rules, subset = %s) }" % \
subset_str)
rules_sub = mysubset(rules,
"rhs %in% "marital-status=Never-married" & lift > 2)
Terms:
talib: Technical Analysis Library (stock market indicators, charts etc)
CDL: Candle or Candlestick
Short version: I want to run my_lib.some_function() based on the string 'some_function'
On quantopian.com I want to call all of the 60 talib functions that start with CDL, like talib.CDL2CROWS(), in a loop for brevity. First pull the function names as strings, then run the functions by the name matching the string.
Those CDL functions all take the same inputs, lists of open, high, low and closing prices for a time period and the test here just uses a list of length 1 to simplify.
import talib, re
import numpy as np
# Make a list of talib's function names that start with 'CDL'
cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))
# cdls[:3], the first three like ['CDL2CROWS', 'CDL3BLACKCROWS', 'CDL3INSIDE']
for cdl in cdls:
codeobj = compile(cdl + '(np.array([3]),np.array([4]),np.array([5]),np.array([6]))', 'talib', 'exec')
exec(codeobj)
break
# Output: NameError: name 'CDL2CROWS' is not defined
Try number two:
import talib, re
import numpy as np
cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))
for cdl in cdls:
codeobj = compile('talib.' + cdl + '(np.array([3]),np.array([4]),np.array([5]),np.array([6]))', '', 'exec')
exec(codeobj)
break
# Output: AssertionError: open is not double
I didn't find that error online.
Related, where I asked the question over there: https://www.quantopian.com/posts/talib-indicators (111 views, no replies yet)
For anyone curious about candlesticks: http://thepatternsite.com/TwoCrows.html
Update
This works, after help in chat from Anzel, possibly floats in the lists were key.
import talib, re
import numpy as np
cdls = re.findall('(CDL\w*)', ' '.join(dir(talib)))
# O, H, L, C = Open, High, Low, Close
O = [ 167.07, 170.8, 178.9, 184.48, 179.1401, 183.56, 186.7, 187.52, 189.0, 193.96 ]
H = [ 167.45, 180.47, 185.83, 185.48, 184.96, 186.3, 189.68, 191.28, 194.5, 194.23 ]
L = [ 164.2, 169.08, 178.56, 177.11, 177.65, 180.5, 185.611, 186.43, 188.0, 188.37 ]
C = [ 166.26, 177.8701, 183.4, 181.039, 182.43, 185.3, 188.61, 190.86, 193.39, 192.99 ]
for cdl in cdls: # the string that becomes the function name
toExec = getattr(talib, cdl)
out = toExec(np.array(O), np.array(H), np.array(L), np.array(C))
print str(out) + ' ' + cdl
Choices on how to add arguments to your string-turned-function:
toExec = getattr(talib, cdl)(args)
toExec()
or
toExec = getattr(talib, cdl)
toExec(args)
A simpler way would be using the abstract lib
import talib
# All the CDL functions are under the Pattern Recognition group
for cdl in talib.get_function_groups()['Pattern Recognition']:
# get the function object
cdl_func = talib.abstract.Function(cdl)
# you can use the info property to get the name of the pattern
print('Checking', cdl_func.info['display_name'], 'pattern')
# run the function as usual
cdl_func(np.array(O), np.array(H), np.array(L), np.array(C))
If you want to run my_lib.some_function() based on the string 'some_function', use getattr like this:
some_function = 'your_string'
toExec = getattr(my_lib, some_function)
# to call the function
toExec()
# an example using math
>>> some_function = 'sin'
>>> toExec = getattr(math, some_function)
>>> toExec
<function math.sin>
>>> toExec(90)
0.8939966636005579
update for your code to run
for cdl in cdls:
toExec = getattr(talib, cdl)
# turns out you need to pass narray as the params
toExec(np.narray(yourlist),np.narray(yourlist),np.narray(yourlist),np.narray(yourlist))
I also suggest you need to review yourlist as it's current 1-dimension, whereas you need n-dimensions array.