AttributeError: 'compound' object has no attribute '_origin' in vpython.py - python

What needs to be done to fix this problem?
At https://www.glowscript.org/#/user/murray.garth/folder/Public/program/Eyeballs I found a GlowScript example that i tried to use as a python3 script.
I modified the header to
#https://www.glowscript.org/#/user/murray.garth/folder/Public/program/Eyeballs
#GlowScript 2.1 VPython
from vpython import *
and changed the true/false references to uppercase.
running
python3 eyeballs.py
starts a static image
and then gives the error message:
compound event return
compound event return
compound event return
Traceback (most recent call last):
File "eyeballs.py", line 39, in <module>
world_pos = Head.compound_to_world( vRightEye.pos )
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/vpython/vpython.py", line 1553, in compound_to_world
v = v-self._origin
AttributeError: 'compound' object has no attribute '_origin'
According to https://www.glowscript.org/docs/VPythonDocs/compound.html
the syntax for compound_to_world is:
world_pos = c.compound_to_world(v)
Which seems to be o.k. to me.
The environment is macports python3
python3 --version
Python 3.7.4
I had installed vpython with
pip install vpython
pip --version
pip 18.1 from /opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)

Thanks for reporting this bug, which I'll report as an issue in the vpython repository. As you say, a workaround is to specify an origin.

This was a tough one.
There are some 1.2 million questions on python on stackoverflow.
If you search for
[python]"object has no attribute"
you get some 12066 results. So that's probably why this question didn'get much attention.
I tried out the issue with a smaller example according to https://www.glowscript.org/docs/VPythonDocs/compound.html
from vpython import *
handle = cylinder( size=vec(1,.2,.2),color=vec(0.72,0.42,0) )
head = box( size=vec(.2,.6,.2), pos=vec(1.1,0,0),color=color.gray(.6) )
hammer = compound([handle, head])
hammer.axis = vec(1,1,0)
world_pos = hammer.compound_to_world(hammer.axis)
giving the error mentioned in the question:
compound event return
Traceback (most recent call last):
File "hammer.py", line 10, in <module>
print (hammer.origin)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/vpython/vpython.py", line 1536, in origin
return self._origin
AttributeError: 'compound' object has no attribute '_origin'
The relevant source code lines of vpython.py are:
#property
def origin(self):
return self._origin
#origin.setter
def origin(self,value): # compound origin cannot be reset
if not self._constructing:
raise AttributeError('The compound "origin" attribute is read-only; change "pos" instead.')
self._origin = value
def world_to_compound(self, v):
v = v-self._pos
x_axis = self._axis.hat
y_axis = self._up.hat
z_axis = x_axis.cross(y_axis)
ox = self._size0.x/self._size.x # _size0 is the original size
oy = self._size0.y/self._size.y
oz = self._size0.z/self._size.z
return self._origin + vector(v.dot(x_axis)*ox, v.dot(y_axis)*oy, v.dot(z_axis)*oz)
def compound_to_world(self, v):
v = v-self._origin
x_axis = self._axis.hat
y_axis = self._up.hat
z_axis = x_axis.cross(y_axis)
ox = self._size.x/self._size0.x # _size0 is the original size
oy = self._size.y/self._size0.y
oz = self._size.z/self._size0.z
return self._pos + v.x*ox*x_axis + v.y*oy*y_axis + v.z*oz*z_axis
and indeed a few lines further up the constructor does not set any origin.
So adding a default origin:
class compound(standardAttributes):
compound_idx = 0 # same numbering scheme as in GlowScript
def __init__(self, objList, **args):
self._origin = vector(0,0,0)
makes the syntax error go away.
from vpython import *
handle = cylinder( size=vec(1,.2,.2), color=vec(0.72,0.42,0) )
head = box( size=vec(.2,.6,.2), pos=vec(1.1,0,0), color=color.gray(.6) )
hammer = compound([handle, head])
hammer.axis = vec(1,1,0)
print (hammer.origin)
world_pos = hammer.compound_to_world(hammer.axis)
print (world_pos)
then gives the result:
compound event return
<0, 0, 0>
<0.6, 1.41421, 0>
and the eyeballs.py code works as expected:
I do not know there to report this bug but I posted a message to the vpython-users group

Related

Cannot generate subsets of feature class with arcpy (ArcGIS library in Python 2.7)

I'm having a hard time here on processing GIS data in Python, using library ArcPy.
I've been trying to generate independent features from a feature class based on a field of the attribute table which is a unique code representing productive forest units, but I can't get it done.
I've already done this in other situations, but this time I don't know what I am missing.
Here is the code and the error I get:
# coding utf-8
import arcpy
arcpy.env.overwriteOutput = True
ws = r'D:\Projeto_VANT\SIG\proc_parc.gdb'
arcpy.env.workspace = ws
talhoes = r'copy_talhoes'
estados = ('SP', 'MG')
florestas = ('PROPRIA', 'PARCERIA')
arcpy.MakeFeatureLayer_management(talhoes,
'talhoes_layer',
""" "ESTADO" IN {} AND "FLORESTA" IN {} """.format(estados, florestas),
ws)
arcpy.FeatureClassToFeatureClass_conversion(in_features = 'talhoes_layer',
out_path = ws,
out_name = 'talhoes1')
talhoes1 = r'talhoes1'
arcpy.AddField_management(talhoes1, 'CONCAT_T', 'TEXT')
arcpy.CalculateField_management(talhoes1, 'CONCAT_T', """ [ESTADO] & "_" & [CODIGO] & "_" & [TALHAO] """, 'VB')
with arcpy.da.SearchCursor(talhoes1, ['CONCAT_T', 'AREA']) as tal_cursor:
for x in tal_cursor:
print(x[0] + " " + str(x[1])) # This print is just to check if the cursor works and it does!
arcpy.MakeFeatureLayer_management(x,
'teste',
""" CONCAT_T = '{}' """.format(str(x[0]))) # Apparently the problem is here!
arcpy.CopyFeatures_management('teste',
'Layer{}'.format(x[0]))
Here is the error:
Traceback (most recent call last):
File "D:/ArcPy_Classes/Scripts/sampling_sig.py", line 32, in <module>
""" CONCAT_T = '{}' """.format(str(x[0])))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 6965, in MakeFeatureLayer
raise e
RuntimeError: Object: Error in executing tool
I think the issue is with your In feature. you will want your in feature to be talhoes1 since x is the cursor object and not a feature.
arcpy.MakeFeatureLayer_management(talhoes1,'teste',""" CONCAT_T =
'{}'""".format(str(x[0])))

python3.6: gdal.Open('*.tif') succeed, but ReadAsArray() got 'NoneType' error

I'm using gdal to read jp2 by lines, here is the code:
def open(self):
if self.ds is None:
self.ds = gdal.Open(self.file_path, gdal.GA_ReadOnly)
self.geo_transform = self.ds.GetGeoTransform()
self.rows = self.ds.RasterYSize
self.cols = self.ds.RasterXSize
def read_strip(self, y_start, read_y_size):
"""
y_start : y in projection coordinate
"""
self.open()
if not self.ds:
raise IOError("Could not open '%s'" % self.file_path)
y_off = int((y_start - self.geo_transform[3]) / self.geo_transform[5])
if y_off < 0 or y_off >= self.rows:
return None
else:
read_y_size_in_data = min(self.rows - y_off, read_y_size)
try:
read_data = self.ds.ReadAsArray(0, y_off, ysize=read_y_size_in_data)
band_data = read_data.astype(float)
self.logger.info('{}, {}, {}'.format(read_y_size, y_off, read_y_size_in_data))
return band_data
except Exception:
self.logger.exception('this file is Nonetype, file: {}'.format(self.file_path))
self.logger.info('{}, {}, {}'.format(read_y_size, y_off, read_y_size_in_data))
self.close()
Here is the error message:
Traceback (most recent call last): File "scene_reader.py", line 62, in read_strip band_data = read_data.astype(float), 'NoneType' object has no attribute 'astype'
Every time I run the code, I did not get any IOError, which means the jp2 file is opened successfully, while the ReadAsArray() got an 'Nonetype' error. by the way, I have tried to just use gdal.Open() and ReadAsArray() to read the same file by several lines in ipython, everything is ok, so, I'm pretty sure there is nothing wrong with the jp2 file itself.
so, can anyone help me?
I think you have to pick a band, even if it is a single band data set. ds.GetRasterBand(1).ReadAsArray() like that. I always refer to this GDAL API Tutorial which has simple examples.

Python TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'

Im brand new to python and coding, im trying to get below working.
this is test code and if I can get this working I should be able to build on it.
Like I said im new to this so sorry if its a silly mistake.
# coding=utf-8
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
enter code herestatus, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")
match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)
if not match:
print("Could not determine the state.")
return 0
physical_state = match[1] # Gets the first group from the match.
print (physical_state)
if physical_state == "down":
print("down")
result = o.cli.close(handle)
else :
print("up")
return 0
Error
<setup>('OPS opens the process of command:', 'success')
Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is test.py, current event is tag, instance is 1515334652, exception reason is Trac eback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test.py", line 22, in ops_execute
physical_state = match[1] # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
The __getitem__ method for the regex match objects was only added since Python 3.6. If you're using an earlier version, you can use the group method instead.
Change:
physical_state = match[1]
to:
physical_state = match.group(1)
Please refer to the documentation for details.

VTK changes for "GetImage" and "Update"

I'm trying to get into Extension programming in 3DSlicer using Python.
There is a tutorial online. Unfortunately there is a problem with the third example script "HelloSharpen". I did the exact same thing they did but I get this error:
Traceback (most recent call last):
File "C:/Users/johan/Desktop/HelloPythonSlicer4/helloPython/code/HelloSharpen.py", line 105, in onApply
laplacian.SetInput(inputVolume.GetImageData())
AttributeError: 'vtkImagingGeneralPython.vtkImageLaplacian' object has no attribute 'SetInput'
I solved this by changing laplacian.SetInput(inputVolume.GetImageData()) to laplacian.SetInputData(inputVolume.GetImageData()) because I read that they changed this in the newer versions of VTK.
However when I try to run this a new error comes up:
Traceback (most recent call last):
File "C:/Users/johan/Desktop/HelloPythonSlicer4/helloPython/code/HelloSharpen.py", line 107, in onApply
laplacian.GetOutput().Update()
AttributeError: 'vtkCommonDataModelPython.vtkImageData' object has no attribute 'Update'
It seems that laplacian.GetOutput().Update() is causing problems so
I tried to find something on the Internet if they also changed this in the newer versions of VTK but I couldn't find anything. I tried to change this into "UpdateData" but this doesn't work.
Do you know if they also changed this and if yes, do you know what I should replace this with?
Here is the full code for "HelloSharpen":
from __main__ import vtk, qt, ctk, slicer
#
# HelloSharpen
#
class HelloSharpen:
def __init__(self, parent):
parent.title = "Hello Python Part D - Sharpen"
parent.categories = ["Examples"]
parent.dependencies = []
parent.contributors = ["Jean-Christophe Fillion-Robin (Kitware)",
"Steve Pieper (Isomics)",
"Sonia Pujol (BWH)"] # replace with "Firstname Lastname (Org)"
parent.helpText = """
Example of scripted loadable extension for the HelloSharpen tutorial.
"""
parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.,
Steve Pieper, Isomics, Inc., and Sonia Pujol, Brigham and Women's Hospital and was
partially funded by NIH grant 3P41RR013218-12S1 (NAC) and is part of the National Alliance
for Medical Image Computing (NA-MIC), funded by the National Institutes of Health through the
NIH Roadmap for Medical Research, Grant U54 EB005149.""" # replace with organization, grant and thanks.
self.parent = parent
#
# qHelloPythonWidget
#
class HelloSharpenWidget:
def __init__(self, parent = None):
if not parent:
self.parent = slicer.qMRMLWidget()
self.parent.setLayout(qt.QVBoxLayout())
self.parent.setMRMLScene(slicer.mrmlScene)
else:
self.parent = parent
self.layout = self.parent.layout()
if not parent:
self.setup()
self.parent.show()
def setup(self):
# Collapsible button
self.laplaceCollapsibleButton = ctk.ctkCollapsibleButton()
self.laplaceCollapsibleButton.text = "Sharpen Operator"
self.layout.addWidget(self.laplaceCollapsibleButton)
# Layout within the laplace collapsible button
self.laplaceFormLayout = qt.QFormLayout(self.laplaceCollapsibleButton)
#
# the volume selectors
#
self.inputFrame = qt.QFrame(self.laplaceCollapsibleButton)
self.inputFrame.setLayout(qt.QHBoxLayout())
self.laplaceFormLayout.addWidget(self.inputFrame)
self.inputSelector = qt.QLabel("Input Volume: ", self.inputFrame)
self.inputFrame.layout().addWidget(self.inputSelector)
self.inputSelector = slicer.qMRMLNodeComboBox(self.inputFrame)
self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
self.inputSelector.addEnabled = False
self.inputSelector.removeEnabled = False
self.inputSelector.setMRMLScene( slicer.mrmlScene )
self.inputFrame.layout().addWidget(self.inputSelector)
self.outputFrame = qt.QFrame(self.laplaceCollapsibleButton)
self.outputFrame.setLayout(qt.QHBoxLayout())
self.laplaceFormLayout.addWidget(self.outputFrame)
self.outputSelector = qt.QLabel("Output Volume: ", self.outputFrame)
self.outputFrame.layout().addWidget(self.outputSelector)
self.outputSelector = slicer.qMRMLNodeComboBox(self.outputFrame)
self.outputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
self.outputSelector.setMRMLScene( slicer.mrmlScene )
self.outputFrame.layout().addWidget(self.outputSelector)
self.sharpen = qt.QCheckBox("Sharpen", self.laplaceCollapsibleButton)
self.sharpen.toolTip = "When checked, subtract laplacian from input volume"
self.sharpen.checked = True
self.laplaceFormLayout.addWidget(self.sharpen)
# Apply button
laplaceButton = qt.QPushButton("Apply")
laplaceButton.toolTip = "Run the Laplace or Sharpen Operator."
self.laplaceFormLayout.addWidget(laplaceButton)
laplaceButton.connect('clicked(bool)', self.onApply)
# Add vertical spacer
self.layout.addStretch(1)
# Set local var as instance attribute
self.laplaceButton = laplaceButton
def onApply(self):
inputVolume = self.inputSelector.currentNode()
outputVolume = self.outputSelector.currentNode()
if not (inputVolume and outputVolume):
qt.QMessageBox.critical(
slicer.util.mainWindow(),
'Sharpen', 'Input and output volumes are required for Laplacian')
return
# run the filter
laplacian = vtk.vtkImageLaplacian()
laplacian.SetInputData(inputVolume.GetImageData())
laplacian.SetDimensionality(3)
laplacian.GetOutput().Update()
ijkToRAS = vtk.vtkMatrix4x4()
inputVolume.GetIJKToRASMatrix(ijkToRAS)
outputVolume.SetIJKToRASMatrix(ijkToRAS)
outputVolume.SetAndObserveImageData(laplacian.GetOutput())
# optionally subtract laplacian from original image
if self.sharpen.checked:
parameters = {}
parameters['inputVolume1'] = inputVolume.GetID()
parameters['inputVolume2'] = outputVolume.GetID()
parameters['outputVolume'] = outputVolume.GetID()
slicer.cli.run( slicer.modules.subtractscalarvolumes, None, parameters, wait_for_completion=True )
selectionNode = slicer.app.applicationLogic().GetSelectionNode()
selectionNode.SetReferenceActiveVolumeID(outputVolume.GetID())
slicer.app.applicationLogic().PropagateVolumeSelection(0)
TL;DR Change laplacian.GetOutput().Update() to laplacian.Update().
Explanation:
As per this link, there was a major change introduced in VTK 6. In summary, newer versions of VTK have separated algorithms and the data in two different class hierarchies. In newer versions of VTK, the Update() function can be called only on objects which have been derived from the vtkAlgorithm class. You can look at the inheritance diagram of vtkImageLaplacian here and it is indeed derived from vtkAlgorithm class. So laplacian.Update() will work.
As the name suggests vtkImageData is a data object. laplacian.GetOutput() returns a vtkImageData object and that's why you cannot call Update() function on it and therefore you get the error.

Weird TypeError in jython/python?

I'm bukkit jython/python plugin programmer. Last few days, I'm struggling with this problem. I have to add an potion effect to an user, it's not problem if I enter effect name, duration and amplifier manually in code, but when I want to get them from config, I get this error:
13:38:20 [SEVERE] Could not pass event PlayerInteractEvent to ItemEffect v1.0
Traceback (most recent call last):
File "<iostream>", line 126, in onPlayerInteractEvent
TypeError: addPotionEffect(): 1st arg can't be coerced to org.bukkit.potion.Poti
onEffect
Here's that part of code:
effectname = section.getString("%s.effect"%currentKey)
duration = section.getInt("%s.duration"%currentKey)
durationinticks = duration * 20
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
geteffectname = "PotionEffectType.%s"%effectname
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
When I print getpotioneffect out, I get:
13:38:20 [INFO] PotionEffect(PotionEffectType.SPEED, 600, 1)
which is okay, and should work. I tested it without getting informations from config, and it works perfectly... To sum up, code above is not working, but below one works:
getpotioneffect = PotionEffect(PotionEffectType.SPEED, 600, 1)
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
Link to javadocs of this event!
http://jd.bukkit.org/rb/apidocs/org/bukkit/entity/LivingEntity.html#addPotionEffect(org.bukkit.potion.PotionEffect)
Thanks!
In your first snippet, getpotioneffect is a string. You can check it adding print type(getpotioneffect) somewhere.
What you want is to replace this :
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
with this:
effect_type = getattr(PotionEffectType, effectname)
potion_effect = PotionEffect(effect_type, durationinticks, 1)

Categories