I'm currently trying to access Math functions such as DeltaR from rootpy, but I'm not sure how this is done. I've seen nothing in the documentation or in any examples. The C++ equivalent would be something like:
double dR = ROOT::Math::VectorUtil::DeltaR((jets)[i],(partons)[i]);
But I'm unable to find a rootpy or even pyroot equivalent that'll work. If I try in pyroot with
import ROOT as r
r.Math.VectorUtil.DeltaR(jets[i],partons[i])
I get the error:
AttributeError: type object 'ROOT::Math' has no attribute 'VectorUtil'
When it quite clearly should, unless I don't understand correctly what it means by 'Attribute'. Anyway, I don't want to ask pyroot questions here :) I just put this down to a quirk in the way that pyroot handles such things, which is why I thought I'd give rootpy a try. I'm not sure if this is possible however.
Cheers,
Joseph
The functions from ROOT::Math::VectorUtil are in libGenVector which is loaded automatically in neither CINT nor PyROOT. Manually loading it (like you probably do in your root_logon.C) makes the functions available, e.g.
import ROOT as r
r.gSystem.Load('libGenVector')
# ...
r.Math.VectorUtil.DeltaR(jets[i],partons[i])
If jets and partons are TLorentzVectors then you should be able to do:
from ROOT import *
dR = jet.DeltaR(parton)
Related
I am using PyObjC bindings to try to get a spoken sound file from phonemes.
I figured out that I can turn speech into sound as follows:
import AppKit
ss = AppKit.NSSpeechSynthesizer.alloc().init()
ss.setVoice_('com.apple.speech.synthesis.voice.Alex')
ss.startSpeakingString_toURL_("Hello", AppKit.NSURL.fileURLWithPath_("hello.aiff"))
# then wait until ve.isSpeaking() returns False
Next for greater control I'd like to turn the text first into phonemes, and then speak them.
phonemes = ss.phonemesFromText_("Hello")
But now I'm stuck, because I know from the docs that to get startSpeakingString to accept phonemes as input, you first need to set NSSpeechSynthesizer.SpeechPropertyKey.Mode to "phoneme". And I think I'm supposed to use setObject_forProperty_error_ to set that.
There are two things I don't understand:
Where is NSSpeechSynthesizer.SpeechPropertyKey.Mode in PyObjC? I grepped the entire PyObjC directory and SpeechPropertyKey is not mentioned anywhere.
How do I use setObject_forProperty_error_ to set it? I think based on the docs that the first argument is the value to set (although it's called just "an object", so True in this case?), and the second is the key (would be phoneme in this case?), and finally there is an error callback. But I'm not sure how I'd pass those arguments in Python.
Where is NSSpeechSynthesizer.SpeechPropertyKey.Mode in PyObjC?
Nowhere.
How do I use setObject_forProperty_error_ to set it?
ss.setObject_forProperty_error_("PHON", "inpt", None)
"PHON" is the same as NSSpeechSynthesizer.SpeechPropertyKey.Mode.phoneme
"inpt" is the same as NSSpeechSynthesizer.SpeechPropertyKey.inputMode
It seems these are not defined anywhere in PyObjC, but I found them by firing up XCode and writing a short Swift snippet:
import Foundation
import AppKit
let synth = NSSpeechSynthesizer()
let x = NSSpeechSynthesizer.SpeechPropertyKey.Mode.phoneme
let y = NSSpeechSynthesizer.SpeechPropertyKey.inputMode
Now looking at x and y in the debugger show that they are the strings mentioned above.
As for how to call setObject_forProperty_error_, I simply tried passing in those strings and None as the error handler, and that worked.
I'm currently using a python module called petsc4py (https://pypi.org/project/petsc4py/). My main issue is that none of the typical intellisense features seems to work with this module.
I'm guessing it might have something to do with it being a C extension module, but I am not sure exactly why this happens. I initially thought that intellisense was unable to look inside ".so" files, but it seems that numpy is able to do this with the array object, which in my case is inside a file called multiarray.cpython-37m-x86_64-linux-gnu (check example below).
Does anyone know why I see this behaviour in the petsc4py module. Is there anything that I (or the developers of petsc4py) can do to get intellisense to work?
Example:
import sys
import petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc
x_p = PETSc.Vec().create()
x_p.setSizes(10)
x_p.setFromOptions()
u_p = x_p.duplicate()
import numpy as np
x_n = np.array([1,2,3])
u_n = x_n.copy()
In this example, when trying to work with a Vec object from petsc4py, doing u_p.duplicate() cannot find the function and the suggestion is simply a repetition of the function immediately before. However, using an array from numpy, doing u_n.copy() works perfectly.
If you're compiling in-place then you're bumping up against https://github.com/microsoft/python-language-server/issues/197.
I'm trying to read the help on what various things do as I'm reading through code. I'm getting a bit lost in how to determine which module a function comes from. Here is my current example:
import quandl
import numpy as np
import matplotlib.pyplot as plt
amzn = quandl.get("WIKI/AMZN", start_date="2018-01-01", end_date="2019-01-01")
amzn_daily_close = amzn[['Adj. Close']]
amzn_daily_log_returns = np.log(amzn_daily_close.pct_change()+1)
monthly = amzn.resample('BM').apply(lambda x: x[-1])
So given this block of code, I can do help (quandl.get) to see information about that and help (np.log) to see what that does. But when I get to amzn.resample, where is that resample coming from? What should I be entering to see some help information on the resample stuff?
Look at the docstring of quandl.get method to get the help message about the return object. This will contain a statement as returns x-object. Googling about x-object will give you more info on this.
Alternatively, you can do this. To identify what is the object you can do the below.
amzn_type = type(amzn)
This gives the monthly object type. Googling for this type value will give you more insights about that object.Example -
a = 10
print(type(a))
The above code returns <class 'int'> output. Googling about int class in python3 will be helpful.
Inspection
You can 'inspect' the method to find the implementation:
import inspect
print(inspect.getfile(amzn.resample))
# /opt/miniconda/envs/stackoverflow/lib/python3.6/site-packages/pandas/core/generic.py
IDE
Or you can use a good IDE (e.g. PyCharm or IntelliJ) which supports you with some neat features:
Generally, these modules should be documented somewhere. They are usually "packaged" and made available on Python Package Index (pypi). You can search there for your package name and find the quandl page. That may have a link to the projects home page with more documentation.
I’m currently developing a script using the python script editor in Rhino. As I’m currently working in a Windows machine, the script editor uses IronPython as language.
In the same script, I want to interact with an FE software (Straus7) which has a Python API. When doing so, I have experienced some problems as the ctypes module does not seem to work in IronPython the same way it does in regular Python. Especially, I’m finding problems when initializing arrays using the command:
ctypes.c_double*3
For example, if I want to obtain the XYZ coordinates of a node #1 in the FE model, I regular Python I would write the following:
XYZType = ctypes.c_double*3
XYZ = XYZType()
node_num = 1
st.St7GetNodeXYZ(1,node_num,XYZ)
And this returns me a variable XYZ which is a 3D array such that:
XYZ -> <straus_userfunctions.c_double_Array_3 at 0xc5787b0>
XYZ[0] = -0.7xxxxx -> (X_coord)
XYZ[1] = -0.8xxxxx -> (Y_coord)
XYZ[2] = -0.9xxxxx -> (Z_coord)
On the other side, I copy the same exact script in IronPython, the following error message appears
Message: expected c_double, got c_double_Array_3
Obviously, If I change the variable XYZ to c_double; then it becomes a double variable which contains only a single entry, which corresponds to the first element of the array (in this case, the X-coordinate)
This situation is quite annoying as all FEM softwares, the usage of matrices and arrays is widely used. Consequently, I wanted to ask if anyone nows a simple fix to this situation.
I was thinking of using the memory allocation of the first element of the array to obtain the rest but I’m not so sure how to do so.
Thanks a lot. Gerard
I've found when working with IronPython you need to explicitly cast the "Array of three doubles" to a "Pointer to double". So if you're using Grasshopper with the Strand7 / Straus7 API you will need to add an extra bit like this:
import St7API
import ctypes
# Make the pointer conversion functions
PI = ctypes.POINTER(ctypes.c_long)
PD = ctypes.POINTER(ctypes.c_double)
XYZType = ctypes.c_double*3
XYZ = XYZType()
node_num = 1
# Cast arrays whenever you pass them to St7API from IronPython
St7API.St7GetNodeXYZ(1, node_num, PD(XYZ))
I don't have access to IronPython or Strand7 / Straus7 at the moment but from memory that will do it. If that doesn't work for you you can email Strand7 Support - you would typically get feedback on something like this within a day or so.
I'm building a tiny Python 2.7.9 script that takes a list of JPEG images as an input and outputs a PDF file. I'm googling for hours but can't find a solution:
I tried pypdf, but it says I don't have PIL installed although i have.
I tried Reportlab, but the page size is bigger than the image itself and I couldn't find a way to fix it. I also find it hard...
I tried img2pdf, but couldn't understand how to use it
I'm really tired of all these libraries, and I'm looking for a good solution.
Good means:
As pythonic as possible
fit page size to image size
Support big amount of images (maybe even 500)
Easy enough
If you can help with with the modules I already tried/code examples it would be awesome.
Also, if you have experience with a module I would be glad if you could share it.
Edit:
As suggested in the comments, I decided to give another chance to img2pdf. I'm using the following code from the official GitHub README:
import img2pdf
pdf_bytes = img2pdf('test.jpg', dpi=150)
But it throws an exception:
`TypeError: 'module' object is not callable
Do someone knows how to use img2pdf as a module to several images?`
Nothing in the GitHub code suggests to me that this module is callable. It's possible that's a mistake in the readme; they have meant for the example to use the convert function. Try this instead:
import img2pdf
pdf_bytes = img2pdf.convert(('test.jpg',), dpi=150, x=None, y=None)
In the source code, this function requires positional arguments x and y:
def convert(images, dpi, x, y, title=None, author=None, creator=None, producer=None,
creationdate=None, moddate=None, subject=None, keywords=None,
colorspace=None, verbose=False):
But as long as you provide the dpi argument, it's set up with a default case that makes it look (to me, at least) like both x and y were intended to be optional arguments:
if not x and not y:
pdf_x, pdf_y = 72.0*width/ndpi[0], 72.0*height/ndpi[1]
The package you got on PIP isn't necessarily identical to the code on GitHub, though. You could try it without supplying x and y as arguments to convert as well—or even better, find the source file on your own machine and check it out yourself.