Error with given arguments and numpy - Python - python

I have the following father class and method:
import SubImage
import numpy as np
from scipy import misc
import random
class Image():
# Class constructor
def __init__(self):
self.__image = np.empty(0)
self.__rows = 0
self.__cols = 0
self.__rows_pixels = 0
self.__cols_pixels = 0
self.__rows_quotient = 0.0
self.__cols_quotient = 0.0
self.__create_image()
self.__subimages = np.empty((self.__rows, self.__cols))
def __create_subimages(self):
i = 0
j = 0
while i != self.__rows_quotient * self.__rows:
print (i+j)
sub_image = SubImage(self.__image[i:i + self.__rows_quotient, j:j + self.__cols_quotient], i + j)
if j == self.__cols_quotient * (self.__cols - 1):
j = 0
i += self.__rows_quotient
else:
j += self.__cols_quotient
And the following subclass which is supposed to be a child from the class above:
import Image
class SubImage(Image):
def __init__(self, image, position):
self.__position = position
self.__image = image
My problem is that when creating a SubImage instance in the __create_subimages method I get the following error:
File "/home/mitolete/PycharmProjects/myprojectSubImage.py", line 3, in <module>
class SubImage(Image):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
I don't get why it says I'm giving 3 arguments, I'm giving 2 which is the subimage (a numpy array) and an integer.
WHy is this?
Regards and thanks.

Your main problem is the way you import both Image and Subimage into each other.
Subimage should be imported this way:
from myprojectSubImage import SubImage
Image should be imported this way:
from FILENAME import Image
that being said, the mutual import seems like bad practice. you should probably either merge the Image and SubImage file, or move the 'create_subimages' function to another file.

If you're importing SubImage from another file, i.e. a module, you will have to reference that in the import. In this case, assuming SubImage is in a file called SubImage.py, the import should be
from SubImage import SubImage
so that SubImage now refers to the class SubImage in SubImage.py. This is also the case for Image in Image.py.
However, I don't think there's a need to do this given how closely related the two classes are. I'd put them in the same file and avoid the circular import.

Related

How to import a cached numba function without a Python definition

Consider the following function in numba, which just serves as an example:
import numba as nb
import numpy as np
#nb.njit('float64(float64[::1])', cache=True)
def total (x):
''' Sum the elements of an array. '''
total = 0
for i in range(x.shape[0]):
total += x[i]
return total
x = np.arange(100,dtype=np.float64)
print(total(x))
Since I have specified the cache=True option, two files are created in the __pycache__ folder, one .nbc file and one .nbi file. I assume that these files contain all (compiled) information about the function. Let's say I delete the Python file that defines the function (i..e, the above code).
Can I still use compiled/cached functions? In other words, can I import them without having the original .py file that defined them?
#Michael Szczesny's comment about ahead of time compilation is exactly what I wanted. To make it work, I have adapted the code as follows:
from numba.pycc import CC
cc = CC('my_module')
#cc.export('total', 'float64(float64[::1])')
def total (x):
''' Sum the elements of an array. '''
total = 0
for i in range(x.shape[0]):
total += x[i]
return total
if __name__ == "__main__":
cc.compile()
After running this file, a binary module file (.pyd) is saved in the directory and you can use it as follows:
import numpy as np
from my_module import total
x = np.arange(100,dtype=np.float64)
print(total(x))

ABAQUS script for a custom field output

I am new to ABAQUS scripting and I am trying to calculate micromotion using COPEN, CSLIP1 and CSLIP2. I came up with the code below:
from abaqusConstants import *
from odbAccess import *
from odbMaterial import *
from odbSection import *
from math import *
from copy import deepcopy
from caeModules import *
from driverUtils import executeOnCaeStartup
from numpy import fabs as fabs
import numpy as np
from types import IntType
odb = session.openOdb(name='E:\PDP02.odb', readOnly=FALSE)
odb = session.odbs['E:\PDP02.odb']
print odb.rootAssembly.instances.keys()
grout_instance = odb.rootAssembly.instances['PROX-1#PROXIMAL-1']
keys = odb.steps.keys()
for key in keys:
step = odb.steps[key]
for frame in step.frames:
print frame.description
Copen = frame.fieldOutputs['COPEN']
Cslip1 = frame.fieldOutputs['CSLIP1']
Cslip2 = frame.fieldOutputs['CSLIP2']
Micromotion = sqrt(power(Copen,2)+power(Cslip1,2)+power(Cslip2,2))
#Micromotion =sqrt(power(Cslip2,2))
#float(Micromotion)
frame.FieldOutput(name='Micromotion', description='Average Micromotion', field=Micromotion)
odb.update()
odb.save()
After executing the code, i get the following error message: "OdiError: Expression evaluates to an overflow or underflow". Please help me understand this error message and how to rectify it. I am happy to provide the .inp and .odb files for reference and verification.
Simply put, overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable. If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.

ValueError: TensorFlow requires that the following symbols must be defined before the loop

I am trying to create an input pipeline using the tf.data API. I have 3D data and using normal NumPy operations I would've ended up with an array with dimensions [?,256x256x3x100], which one can think of as 100 frames each of 256x256x3 size.
import glob
import os
import numpy as np
import tensorflow.compat.v1 as tf
def readfile(filenames):
flag = 0
for name in filenames:
string = tf.read_file(name)
image = tf.image.decode_image(string, channels=3)
if flag == 0:
bunch = image
flag = 1
else:
bunch = tf.concat([bunch,image],1)
return bunch
with tf.device("/cpu:0"):
train_files = []
for s in [x[0] for x in os.walk("path/to/data/folders")]:
if(s == "path/to/data/folders"):
continue
train_files.append(glob.glob(s+"/*.png"))
# shape of train_files is [5,100]
train_dataset = tf.data.Dataset.from_tensor_slices(train_files)
train_dataset = train_dataset.map(readfile, num_parallel_calls=16)
I think the error is occurring because 'bunch' is changing size in for loop. Error:
ValueError Traceback (most recent call last)
<ipython-input-13-c2f88ca344dc> in <module>
22 train_dataset = train_dataset.map(
---> 23 readfile, num_parallel_calls=16)
ValueError: in converted code:
ValueError: TensorFlow requires that the following symbols must be defined before the loop: ('bunch',)
How do I read the data correctly?
EDIT
What worked for me:
def readfile(filenames):
flag = 0
name = filenames[0]
string = tf.read_file(name)
image = tf.image.decode_image(string, channels=3)
bunch = image
for name in filenames:
string = tf.read_file(name)
image = tf.image.decode_image(string, channels=3)
if flag == 0:
bunch = image
flag = 1
else:
bunch = tf.concat([bunch,image],1)
return bunch
So I'm not sure why it is necessary to initialise bunch before the loop, when the first iteration should take care of that bunch = image. It might be because flag is not defined as a tensor so bunch = image is never actually run?
The variable bunch is created inside the function readfile() and therefore the error, because variables cannot be created inside the loop at run time. A fix would be to move the declaration of the variable bunch outside the loop. Code sample follows:
import glob
import os
import numpy as np
import tensorflow.compat.v1 as tf
def readfile(filenames):
flag = 0
bunch = <some_appropriate_initialization>
for name in filenames:
string = tf.read_file(name)
image = tf.image.decode_image(string, channels=3)
if flag == 0:
bunch = image
flag = 1
else:
bunch = tf.concat([bunch,image],1)
return bunch
# Rest of the code
You can't use arbitrary python code inside a dataset.map function, that is readfile in your case. There are two ways to solve this:
By using readfile code as it is and by calling it astf.py_function instead, here you can do eager execution, hence you can write any python logic as normal.
By converting the code in readfile and making use of only tensorflow functions to do the transformation. Performance-wise this is much better than using tf.py_function.
You can find an example on both at https://www.tensorflow.org/api_docs/python/tf/py_function

name 'openpyxl' not defined error

Still learning the ins and outs of python here. I've had minor success with using openpyxl library and started this pet project of using excel file as a "canvas" to read a 1 bit bmp file from directory then to "duplicate-display" the image on the worksheet by getting rid of the guides, decreasing the sizes of each cell and finally by adding a small image in each cell with list of binary data from getdata method from pillow.
I have not gone through the entire logic, but I am having trouble with below code for two nights and I still have no clue why I am getting name 'openpyxl' not defined error in the line almost at the bottom withe the code sheet.add_image(openpyxl.drawing.image.Image('square_blue.jpg'), colnum_string(col)+str(row))
I had success with similar project using almost identical importing of both openpyxl and PIL libraries.
from openpyxl import Workbook
import os
from PIL import Image
# for file in os.listdir():
# if file.endswith('bmp'):
os.chdir('c:/users/Sam/Desktop/py')
img = Image.open('trump.bmp')
img_width, img_height = img.size
pix_val = list(img.getdata())
wb = Workbook()
def colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
r_height = 3
c_width = 3
sheet = wb.create_sheet("Mysheet")
for col in range(1, img_height):
sheet.row_dimensions[img_height].height = r_height
for row in range(1, img_width):
sheet.column_dimensions[colnum_string(col)] = c_width
sheet.add_image(openpyxl.drawing.image.Image('square_blue.jpg'), colnum_string(col)+str(row))
wb.save('out.xlsx')
Can anyone help me out please?
You only import ''Workbook'' sub-module from openpyxel. Try:
from openpyxel import Workbook, drawing # also import drawing namespace
[...]
sheet.add_image(drawing.image.Image('square_blue.jpg'), colnum_string(col)+str(row))
[...]

Python: cannot import name x for importing module

** EDIT: Copy-pasting my actual file to ease confusion. The code snippet below is in a file named train_fm.py:
def eval_fm(x,b,w,V):
# evaluate a degree 2 FM. x is p X B
# V is p x k
# some python code that computes yhat
return(yhat);
Now in my main file: I say the following
from train_fm import eval_fm
and I get the error:
ImportError: cannot import name f1
When I type
from train_fm import train_fm
I do not get an error.
OLD QUESTION BELOW :
def train_fm(x,y,lb,lw,lv,k,a,b,w,V):
# some code
yhat = eval_fm(x,b,w,V);
# OUTPUTS
return(b,w,V);
I have a file called f2.py, where I define 2 functions (note that one of the functions has the same name as the file)
def f1():
some stuff;
return(stuff)
def f2():
more stuff;
y = f1();
return(y)
In my main file, I do
from aaa import f1
from aaa import f2
but when I run the first of the 2 commands above, I get
ImportError: cannot import name f1
Any idea what is causing this? The second function gets imported fine.

Categories