AttributeError: object has no attribute in for loop - python

In my simulation of a FIFO algorithm, I am currently trying to create an object for each of the seven simulated tasks, which will later be used to display some time parameters graphically in Excel. So I create all objects in a for loop, and in another one, I execute with each of these objects the corresponding function for transfer to Excel in another class.
But in the second for loop I always get the error message
File "G:\Schedulibg\PyScheduler\pyFIFOAlgorithm.py", line 48, in sched_StartScheduler
self.worksheet1.write('A' + str((self.tasksAdded * 4) + 1), 'Turn Around Time:')
AttributeError: 'pyFIFOAlgorithm' object has no attribute 'worksheet1' "
I don't know why it looks for worksheet1 in pyFIFOAlgorithm, although the object is from pyToExcel and the corresponding method comes from the class. I have already changed the name of taskTest, because I read that this could also be a problem. Before it was just called tsk.
import pyScheduler
from pyToExcel import pyToExcel
def alg_SortArrivedTasks(arrivedTasks):
sortedTasks = []
for taskx in arrivedTasks:
sortedTasks.append(taskx)
sortedTasks.sort(key=lambda x: x.tskArrival)
return sortedTasks
class pyFIFOAlgorithm(pyScheduler.pyScheduler):
def __init__(self, taskSet, sched_Alg, idleTime):
self.alg_Identifier = 2
self.alg_Name = 'FIFO'
self.completionTime = 0
self.turnAroundTime = 0
self.totalWaitingTime = 0
self.totalTurnAroundTime = 0
self.tasksAdded = 0
super(pyFIFOAlgorithm, self).__init__(taskSet, sched_Alg, idleTime)
def sched_StartScheduler(self, taskSet):
self.sched_SchedulingPoints.insert(0, self.sched_Clock)
taskList = []
taskNumber = 1
for task in alg_SortArrivedTasks(taskSet):
print("\nArrival time of ", task.tskName, ": ", task.tskArrival)
self.sched_ExecuteAvailableTasks(task)
self.completionTime = task.completiontime
self.turnAroundTime = ((self.completionTime) - task.tskArrival)
#taskList.append(pyToExcel(taskNumber, self.completionTime, self.turnAroundTime))
self.totalTurnAroundTime += self.turnAroundTime
print("Turn Around Time: ""{:.2f}".format(self.turnAroundTime))
print("Completion Time: ""{:.2f}".format(self.completionTime))
taskList.append(pyToExcel(task.tskName, self.completionTime, self.turnAroundTime))
for taskTest in taskList:
pyToExcel.inputData(pyToExcel, taskNumber, taskTest.turn, taskTest.completion) #Line with Error
taskNumber += 1
print("\nAll tasks executed at: ", "{:.2f}".format(self.sched_Clock))
print("Average Waiting Time: ", "{:.2f}".format((self.totalWaitingTime /len(taskSet))))
print("Average Turn Around Time: ", "{:.2f}".format((self.totalTurnAroundTime / len(taskSet))))
self.worksheet1.write('A' + str((self.tasksAdded * 4) + 1), 'Turn Around Time:')
self.worksheet1.write('B' + str((self.tasksAdded * 4) + 1), self.totalTurnAroundTime / len(taskSet))
self.workbook.close()
import xlsxwriter
class pyToExcel:
def __init__(self, task, completion, turn):
self.task = task
self.completion = completion
self.turn = turn
workbook = xlsxwriter.Workbook('AlgorithmData.xlsx')
worksheet1 = workbook.add_worksheet('FIFO')
worksheet2 = workbook.add_worksheet('Graphics')
cell_format = workbook.add_format(
{
"border": 1,
"border_color": "#000000"
}
)
cell_format.set_font_color('green')
cell_format.set_bold()
cell_format.set_align('center')
cell_format.set_align('vcenter')
worksheet1.set_column(0, 0, 17)
worksheet1.set_column(1, 1, 12)
worksheet2.write('A' + str(1), 'Task', cell_format)
worksheet2.write('B' + str(1), 'Completion Time', cell_format)
worksheet2.write('C' + str(1), 'Turn Around Time', cell_format)
worksheet2.write('D' + str(1), 'Waiting Time', cell_format)
worksheet2.set_column(0, 0, 4)
worksheet2.set_column(1, 1, 15)
worksheet2.set_column(2, 2, 17)
worksheet2.set_column(3, 3, 12)
def inputData(self, task, turnaround, completion):
pyToExcel.worksheet1.write('A' + str((task * 4) + 1), 'Turn Around Time:')
pyToExcel.worksheet1.write('B' + str((task * 4) + 1), turnaround)
pyToExcel.worksheet1.write('A' + str((task * 4) + 2), 'Completion Time:')
pyToExcel.worksheet1.write('B' + str((task * 4) + 2), completion)
pyToExcel.worksheet2.write('A' + str((task + 1)), task)
pyToExcel.worksheet2.write('B' + str((task + 1)), completion)
pyToExcel.worksheet2.write('C' + str((task + 1)), turnaround)
pyToExcel.worksheet2.write('D' + str((task + 1)), 'waiting time')

It's looking up the worksheet1 attribute because you told it to:
self.worksheet1.write('A' + str((self.tasksAdded * 4) + 1), 'Turn Around Time:')
^^^^^^^^^^
That line, which is also quoted in the error message, is line 48 of the program, as per the text you quote. The line you mark as being the location of the error is line 38, but the traceback certainly says line 48.
The method is part of the class definition for pyFIFOAlgorithm, so self is almost certainly a pyFIFOAlgorithm object. Perhaps self was a typo.

Related

How can I obtain the middle layer results in tf2?

I write a model in subclassing way,
'''
class block(tf.keras.Model):
def __init__(self,index,is_train_bn,channel_axis):
super().__init__()
prefix = 'block' + str(index + 5)
self.is_train_bn=is_train_bn
self.sepconv1_act = layers.Activation('relu', name=prefix + '_sepconv1_act')
self.sepconv1 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv1')
self.sepconv1_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv1_bn')
self.sepconv2_act = layers.Activation('relu', name=prefix + '_sepconv2_act')
self.sepconv2 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv2')
self.sepconv2_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv2_bn')
self.sepconv3_act = layers.Activation('relu', name=prefix + '_sepconv3_act')
self.sepconv3 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv3')
self.sepconv3_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv3_bn')
def __call__(self,x,training=False):
residual = x
x=self.sepconv1_act(x)
x=self.sepconv1(x)
x=self.sepconv1_bn(x,self.is_train_bn)
x=self.sepconv2_act(x)
x=self.sepconv2 (x)
x=self.sepconv2_bn(x,self.is_train_bn)
x=self.sepconv3_act (x)
x=self.sepconv3 (x)
x=self.sepconv3_bn (x,self.is_train_bn)
return x+residual
'''
When I want to print x, I get this error:
' Cannot convert a symbolic Tensor (block1_conv1_act_1/Relu:0) to a numpy array'.
To print out "x" from "middle of model" you can apply the approach exemplified below (code modified from your example). When creating that kind of "monitoring model" you simple get the "x_to_probe" out by a procedure like:
...where in this example the input of the model is exemplified by a random tensor.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
channel_axis=1
prefix='hmmm...'
sepconv1_act = layers.Activation('relu', name=prefix + '_sepconv1_act')
sepconv1 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv1')
sepconv1_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv1_bn')
sepconv2_act = layers.Activation('relu', name=prefix + '_sepconv2_act')
sepconv2 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv2')
sepconv2_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv2_bn')
sepconv3_act = layers.Activation('relu', name=prefix + '_sepconv3_act')
sepconv3 = layers.SeparableConv2D(728, (3, 3),padding='same',use_bias=False,name=prefix + '_sepconv3')
sepconv3_bn = layers.BatchNormalization(axis=channel_axis, name=prefix + '_sepconv3_bn')
#This should be "vice-versa" ...the x need to be taken from the function input...
#residual = x
is_train_bn=1
#x=self.sepconv1_act(x)
inputs=keras.Input(shape=(1,16,16))
x=sepconv1_act(inputs)
x=sepconv1(x)
x=sepconv1_bn(x,is_train_bn)
x=sepconv2_act(x)
x=sepconv2 (x)
x=sepconv2_bn(x,is_train_bn)
x=sepconv3_act (x)
x_to_probe=sepconv3 (x)
x=sepconv3_bn (x_to_probe,is_train_bn)
model=keras.Model(inputs=inputs,outputs=x,name="example for Wayne")
model.summary()
#Let's take x out..
model_for_monitoring_selected_x=keras.Model(inputs=inputs,outputs=x_to_probe,name="example for Wayne to print x")
model_for_monitoring_selected_x.summary()

How to automatize the variables definition in PuLP

I´m trying to automatize the model definition in PuLP.
Right now, I have the following model:
import pulp as pl
" Cost parameters"
p1 = 200 # Cost per unit 1
p2 = 300 # Cost per unit 2
" VARIABLES"
k0101 = pl.LpVariable("k0101", 0, 1, pl.LpInteger)
k0102 = pl.LpVariable("k0102", 0, 1, pl.LpInteger)
k0201 = pl.LpVariable("k0201", 0, 1, pl.LpInteger)
k0202 = pl.LpVariable("k0202", 0, 1, pl.LpInteger)
###### DEMAND
x010101 = pl.LpVariable("x010101", lowBound = 0)
x010102 = pl.LpVariable("x010102", lowBound = 0)
x010103 = pl.LpVariable("x010103", lowBound = 0)
x010104 = pl.LpVariable("x010104", lowBound = 0)
x010201 = pl.LpVariable("x010201", lowBound = 0)
x010202 = pl.LpVariable("x010202", lowBound = 0)
x010203 = pl.LpVariable("x010203", lowBound = 0)
x010204 = pl.LpVariable("x010204", lowBound = 0)
x020101 = pl.LpVariable("x020101", lowBound = 0)
x020102 = pl.LpVariable("x020102", lowBound = 0)
x020103 = pl.LpVariable("x020103", lowBound = 0)
x020104 = pl.LpVariable("x020104", lowBound = 0)
x020201 = pl.LpVariable("x020201", lowBound = 0)
x020202 = pl.LpVariable("x020202", lowBound = 0)
x020203 = pl.LpVariable("x020203", lowBound = 0)
x020204 = pl.LpVariable("x020204", lowBound = 0)
# Problem
z = pl.LpProblem("optimizator", pl.LpMinimize)
"OBJECTIVE FUNCTION"
z += ((p1) * (x010101 + x010102 + x010103 + x010104) + (p1) * (x010201 + x010202 + x010203 + x010204) + (p2) * (x020101 + x020102 + x020103 + x020104) + (p2) * (x020201 + x020202 + x020203 + x020204) + (p1) * (x010101 + x010102 + x010103 + x010104) + (p1) * (x010201 + x010202 + x010203 + x010204) + (p2) * (x020101 + x020102 + x020103 + x020104) + (p2) * (x020201 + x020202 + x020203 + x020204))
" CONSTRAINTS "
z += x010101 + x020101 >= 15 * k0101
" SOLUTION "
print(z)
estado = z.solve()
print(pl.LpStatus[estado])
"TOTAL COST:"
print(pl.value(z.objective))
I would like to simplify this variable definitions, in order to be able to define more variable in an easier description.
Does anyone now how can I define my variables and parameters as a dictionary, and consider that in the objective function and the constraints?
It would help to explain the problem more. The objective function as written right now has duplicate terms and it is hard to understand conceptually what you are trying to minimize.
That being said, you can use lpSum to express the sum of the variable * cost.
# create the variables
k_variable_names = ('k0101', 'k0102', 'k0201', 'k0202')
k_variables = {var: pl.LpVariable(var, cat=pl.LpBinary)
for var in k_variable_names}
x_variables_names = ('x010101' ...)
x_variables = {var: pl.LpVariable(var, lowBound=0)
for var in x_variable_names}
# objective function
z += (
lpSum([var * 2 * p1 for var_name, var in x_variables.items() if 'x010' in var_name]) +
lpSum([var * 2 * p2 for var_name, var in x_variables.items() if 'x020' in var_name])
)

for name in names: TypeError: 'NoneType' object is not iterable

i'm having this issue of TypeError: 'NoneType' object is not iterablein my code for writting a method inside a class named as Qrelyand it takes some instances in the __init__ method as following:def __init__(self,ah=(),bh=(),av=(),bv=(),aph=(),bph=(), apv=(),bpv=()):
the method where i'm having the issue is:
i've tried to change the type of instances by using the dispatch for example ah:Tuplebut i get the same error
def qrelay_op(self,n, phi, alpha, delta):
self.ah = symbols(print("a_H1={:d}".format(n + 1)))
self.bh = symbols(print("b_H1={:d}".format(n + 1)))
self.av = symbols(print("a_V1={:d}".format(n + 1)))
self.bv = symbols(print("b_V1={:d}".format(n + 1)))
op = 0
for i in range(0,n-1):
op += phi[i] * (self.ah[i]*self.bh[i] + self.av[i]*self.bv[i])
B = 1/sqrt(2)*np.array([[1, 1],[-1, 1]])
self.aph = symbols(print("a'_H1={:d}".format(n + 1)))
self.bph = symbols(print("b'_H1={:d}".format(n + 1)))
self.apv = symbols(print("a'_V1={:d}".format(n + 1)))
self.bpv = symbols(print("b'_V1={:d}".format(n + 1)))
for i in range(0,n-1):
op = np.transpose(op, self.bh[i], self.ah[i+1], self.bph[i], self.aph[i+1], B)
op = np.transpose(op, self.bv[i], self.av[i+1], self.bpv[i], self.apv[i+1], B)
op = np.transpose(op, self.ah[0], self.av[0], self.aph[0], self.apv[0], self.rotatmatrix(alpha))
op = np.transpose(op, self.bh[n-1], self.bv[n-1], self.bph[n-1], self.bpv[n-1], self.rotatmatrix(delta))
syms = Qrely(self.ah, self.bh, self.av, self.bv, self.aph, self.bph, self.apv, self.bpv)
return syms, op
when i test the code for example:
A=Qrely()
print(A.qrelay_op(3, np.array([np.pi, np.pi/2, np.pi/5]), np.pi/4, np.pi/3))
i get this error:
line 693, in symbols for name in names:TypeError: 'NoneType' object is not iterable
i can(t find this none type object in my code or i'm missing something even everything seems fine to me
If you're saying that self.ah = symbols(print("a_H1={:d}".format(n + 1))) is the issue we need to understand what symbols is doing.
It looks like symbols wants you to pass it something iterable, but instead you're passing it the output of the print() function which is None.
>>> a = print('Sample Text')
>>> print(a)
None
Try changing
self.ah = symbols(print("a_H1={:d}".format(n + 1)))
to
self.ah = symbols("a_H1={:d}".format(n + 1))

FontForge Python extension: Can't get gsub_multiple lookup to work

I'm experimenting with the fontforge Python library/wrapper thing and I don't seem to get multiple character substitution to work.
Maybe you gals and guys could help to point me at what I'm doing wrong?
Basically, I'm trying to replace "ABC" with the character representation of "a", but I'm going to extend that with proper subsitutions once this is working.
from random import randint
from datetime import datetime
def add_pixel(pen, x, y, scale = 100):
pen.moveTo(((x + 0) * scale, (y + 0) * scale))
pen.lineTo(((x + 0) * scale, (y + 1) * scale))
pen.lineTo(((x + 1) * scale, (y + 1) * scale))
pen.lineTo(((x + 1) * scale, (y + 0) * scale))
pen.closePath()
def add_character(font, code, name):
if not name in list(font):
font.createChar(code, name)
pen = font[code].glyphPen()
for i in range(1, 15):
add_pixel(pen, randint(0, 15), randint(0, 15), 100 * 10 / 15)
try:
import fontforge
except Exception, e:
raise
else:
font = fontforge.font()
font.familyname = "font"
font.fontname = "font x15"
font.fullname = "font x15"
font.version = datetime.now().strftime("%Y-%m-%d %H:%M")
# lower
for c in range(0x61, 0x61 + 26):
add_character(font, c, unichr(c))
# upper
for c in range(0x41, 0x41 + 26):
add_character(font, c, unichr(c))
font.addLookup("gsub", "gsub_multiple", (), (("dlig",(("latn",("dflt")),)),))
font.addLookupSubtable("gsub", "gsub_n")
glyph = font["a"]
glyph.addPosSub("gsub_n", ("A", "B", "C"))
# font.save("font.x15.sfd")
font.generate("font.x15.otf", flags=("PfEd-lookups", "opentype"))
finally:
pass
I think your lookup type doens't match the feature.
# Try "gsub_ligature" as type.
font.addLookup("gsub", "gsub_ligature", (), (("dlig",(("latn",("dflt")),)),))
Tip: You can inspect your features by generating a feature file:
font.generateFeatureFile("features.fea")

Geotagging JPEGs with pyexiv2

I am geotagging JPEGs using the pyexiv2 Python module using code I found in another SO answer (see: What is the best way to geotag jpeg-images using Python?) and I have a question about the GPSTag value.
The code given in the answer has the following lines:
exiv_image["Exif.Image.GPSTag"] = 654
exiv_image["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"
exiv_image["Exif.GPSInfo.GPSVersionID"] = '2 0 0 0'
I have looked at the Exiv2 documentation and found descriptions of GPSTag, GPSMapDatum, and GPSVersionID but am still confused about the value for GPSTag.
From the documentation it says:
A pointer to the GPS Info IFD. The Interoperability structure of the GPS Info IFD, like that of Exif IFD, has no image data.
This description does not really explain how to determine what value to use and I have not been able to find a better description of GPSTag online.
So my questions are:
Given a new image, how do you determine the value of Exif.Image.GPSTag?
Why is the code sample using a value of 654 (this may be answered by question one)?
Thanks for your help.
Best way to geotag photos using pyexiv2 is definitely with my program, GottenGeography ;-)
But seriously though, if you're wanting to access GPS data from pyexiv2, that code looks like this:
GPS = 'Exif.GPSInfo.GPS'
try:
self.latitude = dms_to_decimal(
*self.exif[GPS + 'Latitude'].value +
[self.exif[GPS + 'LatitudeRef'].value]
)
self.longitude = dms_to_decimal(
*self.exif[GPS + 'Longitude'].value +
[self.exif[GPS + 'LongitudeRef'].value]
)
except KeyError:
pass
try:
self.altitude = float(self.exif[GPS + 'Altitude'].value)
if int(self.exif[GPS + 'AltitudeRef'].value) > 0:
self.altitude *= -1
except KeyError:
pass
And writing looks like this:
self.exif[GPS + 'AltitudeRef'] = '0' if self.altitude >= 0 else '1'
self.exif[GPS + 'Altitude'] = Fraction(self.altitude)
self.exif[GPS + 'Latitude'] = decimal_to_dms(self.latitude)
self.exif[GPS + 'LatitudeRef'] = 'N' if self.latitude >= 0 else 'S'
self.exif[GPS + 'Longitude'] = decimal_to_dms(self.longitude)
self.exif[GPS + 'LongitudeRef'] = 'E' if self.longitude >= 0 else 'W'
self.exif[GPS + 'MapDatum'] = 'WGS-84'
With these support functions:
class Fraction(fractions.Fraction):
"""Only create Fractions from floats.
>>> Fraction(0.3)
Fraction(3, 10)
>>> Fraction(1.1)
Fraction(11, 10)
"""
def __new__(cls, value, ignore=None):
"""Should be compatible with Python 2.6, though untested."""
return fractions.Fraction.from_float(value).limit_denominator(99999)
def dms_to_decimal(degrees, minutes, seconds, sign=' '):
"""Convert degrees, minutes, seconds into decimal degrees.
>>> dms_to_decimal(10, 10, 10)
10.169444444444444
>>> dms_to_decimal(8, 9, 10, 'S')
-8.152777777777779
"""
return (-1 if sign[0] in 'SWsw' else 1) * (
float(degrees) +
float(minutes) / 60 +
float(seconds) / 3600
)
def decimal_to_dms(decimal):
"""Convert decimal degrees into degrees, minutes, seconds.
>>> decimal_to_dms(50.445891)
[Fraction(50, 1), Fraction(26, 1), Fraction(113019, 2500)]
>>> decimal_to_dms(-125.976893)
[Fraction(125, 1), Fraction(58, 1), Fraction(92037, 2500)]
"""
remainder, degrees = math.modf(abs(decimal))
remainder, minutes = math.modf(remainder * 60)
return [Fraction(n) for n in (degrees, minutes, remainder * 60)]
Although I am currently working on an alternative to pyexiv2 that uses GObject introspection to access the exiv2 library much more directly, called GExiv2, and would love to have some feedback on it. Both gexiv2 and pyexiv2 are wrappers around the same exiv2 library, but the difference is that pyexiv2 is a very large project with lots of glue, only works in python, and is on the brink of abandonment*; whereas gexiv2 is light and nimble, accessible from any programming language, and is well maintained thanks to it's use by Shotwell.
Hope this helps!
* pyexiv2's author, Olivier Tilloy, has asked me for help with maintainership as he no longer has much time
My version, a little lengthy...
from fractions import Fraction
import pyexiv2
try:
metadata = pyexiv2.metadata.ImageMetadata(image_file)
metadata.read();
thumb = metadata.exif_thumbnail
try:
latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")
latitude = str(latitude).split("=")[1][1:-1].split(" ");
latitude = map(lambda f: str(float(Fraction(f))), latitude)
latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]
longitude = str(longitude).split("=")[1][1:-1].split(" ");
longitude = map(lambda f: str(float(Fraction(f))), longitude)
longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]
latitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLatitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef").value]);
longitude_value = dms_to_decimal(*metadata.__getitem__("Exif.GPSInfo.GPSLongitude").value + [metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef").value]);
print "--- GPS ---"
print "Coordinates: " + latitude + ", " + longitude
print "Coordinates: " + str(latitude_value) + ", " + str(longitude_value)
print "--- GPS ---"
except Exception, e:
print "No GPS Information!"
#print e
# Check for thumbnail
if(thumb.data == ""):
print "No thumbnail!"
except Exception, e:
print "Error processing image..."
print e;

Categories