Migrating SimpleITK 1.x to 2.x - python

I'm working on a project on GitHub that was made with Python 2.7 (https://github.com/AIM-Harvard/DeepCAC)
I've made most relevant changes as to update it to Python 3.7, but I'm fixed on an error message regarding simpleITK.
Error message:
TypeError: Execute() takes 2 positional arguments but 10 were given
It stems from this code:
res_filter = sitk.ResampleImageFilter()
----> img_sitk = res_filter.Execute(img_sitk, curated_size, sitk.Transform(), method, img_sitk.GetOrigin(), curated_spacing, img_sitk.GetDirection(), 0, img_sitk.GetPixelIDValue())
According to the simpleITK document on switching from 1.x to 2.x (version that is available with python 3.7) it should be done like this (https://simpleitk.readthedocs.io/en/master/migrationGuide2.0.html#filter-s-execute-method) but I can't quite grasp it.
Can someone help out?
Thanks

It looks like you're trying to use the procedural version, Resample, not the class version, ResampleImageFilter.
You can see the documentation for the Resample function here:
https://simpleitk.org/doxygen/latest/html/namespaceitk_1_1simple.html#aadbb243c10d1aedea8e955e8beda4df0
You want to the second version of Resample. So your code would look like this:
img_sitk = sitk.Resample(img_sitk, curated_size, sitk.Transform(), method, img_sitk.GetOrigin(), curated_spacing, img_sitk.GetDirection(), 0, img_sitk.GetPixelIDValue())
If you want to use the ResampleImageFilter, you would set all the parameters using the filter's various Set methods, and then just call the Execute method with the input image as the only parameter.

Related

kubeflow AttributeError: 'ComponentStore' object has no attribute 'uri_search_template'

I am trying to load some prebuit gcp kubeflow components using kfp.components.ComponentStore. However I am getting this error:
line 180, in _load_component_spec_in_component_ref
if self.uri_search_template:
AttributeError: 'ComponentStore' object has no attribute 'uri_search_template'
when at this line of code:
mlengine_train_op = component_store.load_component('ml_engine/train')
KFP version:
kfp 1.8.10
kfp-pipeline-spec 0.1.13
kfp-server-api 1.7.1
Steps to reproduce
import kfp
from kfp.components import func_to_container_op
COMPONENT_URL_SEARCH_PREFIX = "https://raw.githubusercontent.com/kubeflow/pipelines/1.7.1/components/gcp/"
component_store = kfp.components.ComponentStore(
local_search_paths=None, url_search_prefixes=[COMPONENT_URL_SEARCH_PREFIX])
mlengine_train_op = component_store.load_component('ml_engine/train')
mlengine_deploy_op = component_store.load_component('ml_engine/deploy')
I got this code from an example that was running on kfp 0.2.5. This is probably some version problem but does anyone knows how to update this code to the newer version?
I solved the issue. It is something that #Kabilan Mohanraj also mentioned is his comment. It looks like there is a bug if you don't set up uri_search_template when creating the ComponentStore.
I solved it by providing it as parameter, it doesn't really matter what you pass to the constructor really, but it is required because in the code there is the following
if self.url_search_prefixes:
but if you don't pass something that attribute doesn't get created in the constructor.
I fixed it like this:
component_store = kfp.components.ComponentStore(
local_search_paths=["local_search_path"], url_search_prefixes=[COMPONENT_URL_SEARCH_PREFIX]), uri_search_template="{name}/"
I hope it will help someone in the future.
I suggested in the github issue to address this by either make the error more clear or to have better check on uri_search_template attribute.

Imorting zero_gradients from torch.autograd.gradcheck

I want to replicate the code here, and I get the following error while running in Google Colab?
ImportError: cannot import name 'zero_gradients' from
'torch.autograd.gradcheck'
(/usr/local/lib/python3.7/dist-packages/torch/autograd/gradcheck.py)
Can someone help me with how to solve this?
This seems like it's using a very old version of PyTorch, the function itself is not available anymore. However, if you look at this commit, you will see the implementation of zero_gradients. What it does is simply zero out the gradient of the input:
def zero_gradients(i):
for t in iter_gradients(i):
t.zero_()
Then zero_gradients(x) should be the same as x.zero_grad(), which is the current API, assuming x is a nn.Module!
Or it's just:
if x.grad is not None:
x.grad.zero_()

Gurobi Python Error (NoneType has no len())

I need to write an optimization file for Gurobi (Python) that is a modified version of a classic TSP. I tried to run the example file from their website:
examples.gurobi.com/traveling-salesman-problem/
I always get the following error:
TypeError: object of type 'NoneType' has no len()
What do I need to change?
Thx
Full code: https://www.dropbox.com/s/ewisx805b3o2wq5/beispiel_opt.py?dl=0
I can confirm the error with the example code from Gurobi's website. At the first look the problem seems to be inside the subtour function, that returns None if sum(lengths) == n and the missing check for if tour is None inside the subtourlim function.
Instead of providing a fix for the specific code, I first checked the examples that Gurobi installs inside the specific installation directory:
Mac: /Library/gurobi810/mac64/examples/python/
Linux: /opt/gurobi800/linux64/examples/python/
Windows: c:\gurobi800\win64\examples\python\
And surprisingly the tsp.py from there runs without any errors. Note also that the two mentioned functions are revised. So I guess the example from the website is just a old version of the code.

Running a function to mirror an image in python

I keep trying to run this function:
def flipPic():
#Set up source picture
barbf=getMediaPath("barbara.jpg")
barb=makePicture(barbf)
#Now, for the mirroring
mirrorPoint=219
for X in range(0,mirrorPoint):
for Y in range(0,291):
pleft=getPixel(barb,X,Y)
pright=getPixel(barb,Y,mirrorPoint + mirrorPoint - 1 - X)
setColor(pright,(getColor(pleft)))
show(barb)
return(barb)
However, an error comes up on this line:
barb=makePicture(barbf)
It says:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
I'm not sure what the issue is as it is written the same way that is in my textbook.
I am still learning how to program in python, is there something I doing wrong?
I'm not sure what library you are using but this is a simple call in Pillow. The commands are these:
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
Taken from this chapter in the docs.

Loading a document on OpenOffice using an external Python program

I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet.
I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as:
import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext)
# connect to the running office
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
"urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
# get the central desktop object
DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
#The calling it's not exactly this way, just to simplify the code
DESKTOP.loadComponentFromURL('file.ods')
But I get an AttributeError when I try to access loadComponentFromURL. If I make a dir(DESKTOP), I've see only the following attributes/methods:
['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName',
'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto',
'Title', 'Types', 'addEventListener', 'addPropertyChangeListener',
'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId',
'getImplementationName', 'getPropertySetInfo', 'getPropertyValue',
'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface',
'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener',
'setPropertyValue', 'supportsService']
I've read that there are where a bug doing the same, but on OpenOffice 3.0 (I'm using OpenOffice 3.1 over Red Hat5.3). I've tried to use the workaround stated here, but they don't seems to be working.
Any ideas?
It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this:
def urlify(path):
return uno.systemPathToFileUrl(os.path.realpath(path))
desktop.loadComponentFromURL(
urlify(tempfilename), "_blank", 0, ())
Your example is a simplified version, and I'm not sure if you've removed the extra arguments intentionally or not intentionally.
If loadComponentFromURL isn't there, then the API has changed or there's something else wrong, I've read through your code and it looks like you're doing all the same things I have.
I don't believe that the dir() of the methods on the desktop object will be useful, as I think there's a __getattr__ method being used to proxy through the requests, and all the methods you've printed out are utility methods used for the stand-in object for the com.sun.star.frame.Desktop.
I think perhaps the failure could be that there's no method named loadComponentFromURL that has exactly 1 argument. Perhaps giving the 4 argument version will result in the method being found and used. This could simply be an impedance mismatch between Python and Java, where Java has call-signature method overloading.
This looks like issue 90701: http://www.openoffice.org/issues/show_bug.cgi?id=90701
See also http://piiis.blogspot.com/2008/10/pyuno-broken-in-ooo-30-with-system.html and http://udk.openoffice.org/python/python-bridge.html

Categories