I'm using the R DTW package with rpy2. I would like to be able specify a window type and size for running the DTW analysis.
I have run the following code:
import numpy as np
import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
r = robjects.r
r('library("dtw")')
query = np.array([0.0,1.0,2.0,3.0])
reference = np.array([0.0,1.9,2.4,3.0])
# Attempt 1:
kwargs = {'step':r("asymmetric"),'window_type':r("sakoeChibaWindow"),'window_size':r("as.integer(\"3\")")}
alig = r.dtw(query, reference, **kwargs)
# Attempt 2:
alig = r.dtw(query, reference, keep=r('TRUE'), step=r('asymmetric'),window_type=r('sakoeChibaWindow'),window_size="as.integer(\"3\")")
# Attempt 3:
alig = r.dtw(query, reference, keep=r('TRUE'), step=r('asymmetric'),window_type=r('sakoeChibaWindow'),window_size=3)
# Note: The line of code below works correctly.
# alig = r.dtw(query, reference, keep=r('TRUE'), step=r('asymmetric'))
robjects.globalenv["alignment"] = alig
print r('alignment$distance')
I get the following error message:
Error in abs(jw - iw) <= window.size : 'window.size' is missing
Traceback (most recent call last):
File "testrdtw.py", line 19, in <module>
alig = r.dtw(query, reference, **kwargs)
File "/Users/jsmith/Dropbox/IW/env/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 86, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "/Users/jsmith/Dropbox/IW/env/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 35, in __call__
res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in abs(jw - iw) <= window.size : 'window.size' is missing
How do I properly specify the window.size argument such that it is passed correctly?
I'm quite new to R and rpy so I could very well be using these libraries incorrectly.
Any suggestions,hints, or help greatly appreciated.
-- js
Use importr():
from rpy2.robjects.packages import importr
dtw = importr('dtw')
alig = dtw.dtw(query, reference, keep=True,
step='asymmetric',
window_type='sakoeChibaWindow',
window_size=3)
This works for me:
import numpy as np
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
rpy2.robjects.numpy2ri.activate()
R = rpy2.robjects.r
DTW = importr('dtw')
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([0.0, 1.9, 2.4, 3.0])
alignment1 = R.dtw(x, y, keep=True, dist_method="Euclidean",step_pattern=DTW.asymmetric,type="sakoechiba")
alignment2 = R.dtw(x, y, keep=True, dist_method="Euclidean",step_pattern=DTW.symmetric1,type="itakura")
alignment3 = R.dtw(x, y, keep=True, dist_method="Euclidean", step_pattern=DTW.symmetric2, type=DTW.sakoeChibaWindow, window_size=2)
dist1 = alignment1.rx('distance')[0][0]
dist2 = alignment2.rx('distance')[0][0]
dist3= alignment3.rx('distance')[0][0]
print(dist1)
#1.0
print(dist2)
#1.3
print(dist3)
#1.3
The documentation states:"window.type can also be an user-defined windowing function. See dtwWindowingFunctions for all available windowing functions"
There u can fix the window.size.
Hope it helps
Related
This program gives an error when it gets to the "#vectorize(['float32(float32)'], target='cuda')" function with the error:
File "/home/idf/anaconda3/envs/gpu/lib/python3.9/site-packages/numba/cuda/vectorizers.py", line 206, in _compile_core
return cudevfn, cudevfn.overloads[sig.args].signature.return_type
AttributeError: 'FakeOverload' object has no attribute 'signature'
Notice that I am not even calling the function. It seems to be an error at the interpreter stage:
import math
import numpy as np
from numba import vectorize,guvectorize,cuda
import timeit
def numpy_sqrt_x(x):
return np.sqrt(x)
def math_sqrt_x(x):
return [math.sqrt(xx) for xx in x]
#vectorize
def cpu_sqrt(x):
return math.sqrt(x)
#vectorize(['float32(float32)'], target='cuda')
def gpu_sqrt(x):
return math.sqrt(x)
if __name__ == '__main__':
x = np.arange(10)
print(x**2)
#print(np.exp(x))
#x = np.arange(int(1e2))
#print(timeit.timeit("numpy_sqrt_x(x)", globals=globals()))
#print(timeit.timeit("math_sqrt_x(x)", globals=globals()))
#print(gpu_sqrt(x))
Not sure what I am doing wrong?
I am writing this code for simulation of earths magnetic field:
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy
import pyvista as pv
ts = np.linspace(-8,8, 150)
t = np.linspace(-6,6, 150)
axis = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), ts]
aux = np.c_[2*np.cos(ts*2*np.pi), 2*np.sin(ts*2*np.pi), t]
def make_coil(pos, vertices):
coil = magpy.current.Line(
current = 100,
vertices = vertices,
position= pos,
style_color="green",
)
return coil
theta = np.sqrt(2)/2
r = 4
coil1 = make_coil((0,0,0), axis)
coil2 = make_coil((r*1,0,0), aux)
coil3 = make_coil((r*theta,r*theta,0), aux)
coil4 = make_coil((0,1*r,0), aux)
coil5 = make_coil((-r*theta,r*theta,0), aux)
coil6 = make_coil((-r*1,0,0), aux)
coil7 = make_coil((-r*theta,-r*theta,0), aux)
coil8 = make_coil((0,-r*1,0), aux)
coil9 = make_coil((r*theta,-r*theta,0), aux)
coil = coil1 + coil2 + coil3 + coil4 + coil5 + coil6 + coil7 + coil8 + coil9
coil.show()
grid = pv.UniformGrid(
dimensions=(41, 41, 41),
spacing=(2, 2, 2),
origin=(-40, -40, -40),
)
# compute B-field and add as data to grid
grid["B"] = coil.getB(grid.points)
# compute field lines
seed = pv.Disc(inner=1, outer=5.2, r_res=3, c_res=12)
strl = grid.streamlines_from_source(
seed,
vectors='B',
max_time=180,
initial_step_length=0.01,
integration_direction='both',
)
# create plotting scene
pl = pv.Plotter()
# add field lines and legend to scene
legend_args = {
'title': 'B [mT]',
'title_font_size': 20,
'color': 'black',
'position_y': 0.25,
'vertical': True,
}
# draw coils
magpy.show(coil, color="orange", canvas=pl, backend='pyvista')
# add streamlines
pl.add_mesh(
strl.tube(radius=.2),
cmap="bwr",
scalar_bar_args=legend_args,
)
# display scene
pl.camera.position=(160, 10, -10)
pl.set_background("white")
pl.show()
and I get this error message
danieltran#eduroam-193-157-168-102 OneDrive-UniversitetetiOslo % /usr/local/bin/python3 "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/d
ouble_solenoids.py"
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 547, in <module>
from vtk.vtkCommonKitPython import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/danieltran/Library/CloudStorage/OneDrive-UniversitetetiOslo/H22/FYS1120/Comp Essay/double_solenoids.py", line 4, in <module>
import pyvista as pv
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/__init__.py", line 12, in <module>
from pyvista.plotting import *
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/__init__.py", line 4, in <module>
from .charts import Chart2D, ChartMPL, ChartBox, ChartPie
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/plotting/charts.py", line 13, in <module>
from pyvista import _vtk
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyvista/_vtk.py", line 549, in <module>
from vtk.vtkCommonCore import buffer_shared, vtkAbstractArray, vtkWeakReference
ModuleNotFoundError: No module named 'vtk'.
First, you need to post a question, not just code + error message.
Based off of your error message, this is what I would try:
Ensure VTK is installed. https://pypi.org/project/vtk/
Try a different Python version. 3.11 is fresh off the shelf and it looks like the VTK library was last updated prior to 3.11's release.
There are other things that you could try but this is likely the best starting point based on your post...
VTK currently does not have a supported python 3.11 compatible version published. See files available for latest version 9.2.2 https://pypi.org/project/vtk/9.2.2/#files which has no 3.11 compatible files [as of today]. Some options are to build VTK yourself (may or may not be possible without fixes to support python 3.11) or use a different python version or wait until a new vtk release that is compatible with python 3.11.
I am trying to reproduce this R code in python using rpy2:
library(gamlss)
library(gamlss.dist)
library(gamlss.add)
x <- c(37.50,46.79,48.30,46.04,43.40,39.25,38.49,49.51,40.38,36.98,40.00,
38.49,37.74,47.92,44.53,44.91,44.91,40.00,41.51,47.92,36.98,43.40,
42.26,41.89,38.87,43.02,39.25,40.38,42.64,36.98,44.15,44.91,43.40,
49.81,38.87,40.00,52.45,53.13,47.92,52.45,44.91,29.54,27.13,35.60,
45.34,43.37,54.15,42.77,42.88,44.26,27.14,39.31,24.80,16.62,30.30,
36.39,28.60,28.53,35.84,31.10,34.55,52.65,48.81,43.42,52.49,38.00,
38.65,34.54,37.70,38.11,43.05,29.95,32.48,24.63,35.33,41.34)
fit <- fitDist(x, k = 2, type = "realplus", trace = FALSE, try.gamlss = TRUE)
summary(fit)
My attempt is:
from rpy2.robjects.packages import importr
from rpy2.robjects import numpy2ri
numpy2ri.activate()
utils = importr('utils')
utils.install_packages('gamlss')
gamlss = importr('gamlss')
base = importr('base')
x = np.array([7.50,46.79,48.30,46.04,43.40,39.25,38.49,49.51,40.38,36.98,40.00,
38.49,37.74,47.92,44.53,44.91,44.91,40.00,41.51,47.92,36.98,43.40,
42.26,41.89,38.87,43.02,39.25,40.38,42.64,36.98,44.15,44.91,43.40,
49.81,38.87,40.00,52.45,53.13,47.92,52.45,44.91,29.54,27.13,35.60,
45.34,43.37,54.15,42.77,42.88,44.26,27.14,39.31,24.80,16.62,30.30,
36.39,28.60,28.53,35.84,31.10,34.55,52.65,48.81,43.42,52.49,38.00,
38.65,34.54,37.70,38.11,43.05,29.95,32.48,24.63,35.33,41.34])
base.fitDist(x, k = 2, type = "realplus", trace = FALSE, try.gamlss = TRUE)
This is a syntax error however because of try.gamlss = TRUE.
How should I do this?
Replace the dot in try.gamlss with an underscore.
The documentation has explanations: https://rpy2.github.io/doc/v3.3.x/html/robjects_rpackages.html
I want to use the scipy.optimize.minimize function. The function contains commands from a DLL which require a ctypes array. The goal is to vary the inputs in the ctypes array to optimize a specific output which is also a ctypes array (see code below).
import os
import ctypes
import tkinter as tk
from PIL import ImageTk
from tkinter import filedialog
import numpy as np
from scipy.optimize import minimize
dll = ctypes.cdll.LoadLibrary(library)
LoadModelDef = dll.addModelDef(model)
nrExperiments = 1
nrin = dll.getNumInputs(LoadModelDef)
PDBL2ARR = ctypes.c_double * nrin * nrExperiments
inputs = PDBL2ARR()
inputs_init = PDBL2ARR()
def evaluaterel(library,Model,InputArray):
nrExp = len(InputArray)
DBL2ARR = ctypes.c_double * nrExp
outputs = DBL2ARR()
for i in range(2,13):
Name= outputName(Model,i)
library.evalVBA(Model,InputArray,nrExp,i,outputs)
for i in range(nrExp):
Value = str(outputs[i])
# text = label.cget("text") + '\n' + str(Name)+ ' ' + str(Value)
# label.configure(text=text)
return outputs
data = np.array([line.split()[-1] for line in open("DATA.txt")], dtype=np.float64)
for i in range(nrExperiments):
for j in range(nrin):
inputs_init[i][j]= 0
for i in range(nrExperiments):
for j in range(0,nrin):
inputs[i][j]=data[j]
solution=minimize(evaluaterel(dll,LoadModelDef,inputs),inputs_init,method='SLSQP')
print(solution)
File "c:\app\python27\lib\site-packages\scipy\optimize\optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
TypeError: 'c_double_Array_1' object is not callable
According to [SciPy.Docs]: scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None), the 1st argument should be a callable (function, in your case). But, you're calling the function yourself when passing it, and therefore you're passing the function return value.
Modify your code (faulty line) to:
solution = minimize(evaluaterel, inputs_init, args=(dll, LoadModelDef, inputs), method="SLSQP")
I want to run this python script. I installed the SDF reader in linux by the following command in my home directory
python -m pip install --upgrade sdf
and it seems to be installed successfully.
The python script is the following
import sdf
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
import os
from numpy import ma
from matplotlib import colors, ticker, cm
from matplotlib.mlab import bivariate_normal
from matplotlib.colors import ListedColormap
if __name__ == "__main__":
print ('This is main of module "test2d.py"')
######## Constant defined here ########
pi = 3.1415926535897932384626
q0 = 1.602176565e-19 # C
m0 = 9.10938291e-31 # kg
v0 = 2.99792458e8 # m/s^2
kb = 1.3806488e-23 # J/K
mu0 = 4.0e-7*pi # N/A^2
epsilon0 = 8.8541878176203899e-12 # F/m
h_planck = 6.62606957e-34 # J s
wavelength= 1.0e-6
frequency = v0*2*pi/wavelength
exunit = m0*v0*frequency/q0
bxunit = m0*frequency/q0
denunit = frequency**2*epsilon0*m0/q0**2
print 'electric field unit: '+str(exunit)
print 'magnetic field unit: '+str(bxunit)
print 'density unit nc: '+str(denunit)
font = {'family' : 'helvetica',
'color' : 'black',
'weight' : 'normal',
'size' : 20,
}
n=47
data = sdf.read("./"+str(n).zfill(4)+".sdf",dict=True)
header=data['Header']
time=header['time']
x = data['Grid/Grid_mid'].data[0]/1.0e-6
y = data['Grid/Grid_mid'].data[1]/1.0e-6
y = y[600:1799]
X, Y = np.meshgrid(x, y)
It gives me following error:
Traceback (most recent call last):
File "epochvis.py", line 45, in <module>
data = sdf.read("./"+str(n).zfill(4)+".sdf",dict=True)
AttributeError: 'module' object has no attribute 'read'
Any ideas? Thank you in advance.
sdf does not have a read function.
try typing the following in your python shell
import sdf
help(sdf)
you will see
FUNCTIONS
load(filename, objectname='/', unit=None, scale_units=None)
Load a dataset or group from an SDF file
save(filename, group)
Save an SDF group to a file
validate(obj)
Validate an sdf.Group or sdf.Dataset