Virtual Neural Network in Python - python

I just wrote up a simple neural network in python as I have been studying them recently. I am using backpropogation. The activation function is a sigmoid. The inputs and weights generate randomly and the ideal output is 0. I am new to python so the code is written very inefficiently, but it is readable. When I run the code, the output is always zero and I can't seem to find why. Also, I didn't use a module.
from random import uniform
input_one_input_value = 1
input_two_input_value = 0
bias_value = 1
#use global to globalize function-based variables
#use lists to store data in future
def hidden_One():
global weighted_sum_hidden_one
weighted_sum_hidden_one = (input_one_input_value * weights[0]) + (input_two_input_value * weights[1]) + (bias_value * weights[2])
hidden_one_output = activation(weighted_sum_hidden_one)
return hidden_one_output
def hidden_Two():
global weighted_sum_hidden_two
weighted_sum_hidden_two = (input_one_input_value * weights[3]) + (input_two_input_value * weights[4]) + (bias_value * weights[5])
hidden_two_output = activation(weighted_sum_hidden_two)
return hidden_two_output
def output_One():
weighted_sum = (hidden_One() * weights[6]) + (hidden_Two() * weights[7]) + (bias_value * weights[8])
return activation(weighted_sum)
def activation(x):
sigmoid_value = 1 / (1+(2.71828 ** x))
return sigmoid_value
def calculate_gradient():
E = ideal_output - actual_output
output_delta = -E * activation(weights[6] + weights[7] + weights[8])
h1_delta = activation(weighted_sum_hidden_one) * weights[6] * output_delta
h2_delta = activation(weighted_sum_hidden_two) * weights[7] * output_delta
b2_delta = activation(bias_value) * weights[8] * output_delta
i1_delta = activation(input_one_input_value) * ((weights[0] * h1_delta) + (weights[3] * h2_delta))
i2_delta = activation(input_one_input_value) * ((weights[1] * h1_delta) + (weights[4] * h2_delta))
b1_delta = activation(bias_value) * ((weights[2] * h1_delta) + (weights[5] * h2_delta))
global w1_gradient
global w2_gradient
global w3_gradient
global w4_gradient
global w5_gradient
global w6_gradient
global w7_gradient
global w8_gradient
global w9_gradient
w1_gradient = input_one_input_value * h1_delta
w2_gradient = input_two_input_value * h1_delta
w3_gradient = bias_value * h1_delta
w4_gradient = input_one_input_value * h2_delta
w5_gradient = input_two_input_value * h2_delta
w6_gradient = bias_value * h2_delta
w7_gradient = hidden_One() * output_delta
w8_gradient = hidden_Two() * output_delta
w9_gradient = bias_value * output_delta
def backpropogation():
E = .7 #learning rate
a = .3 #momentum to prevent settling for local minima
global weightchanges_previous
global weight_change
weightchanges_previous = []
weight_change = []
if len(weightchanges_previous) == 0:
weight_change.append((E * w1_gradient))
weight_change.append((E * w2_gradient))
weight_change.append((E * w3_gradient))
weight_change.append((E * w4_gradient))
weight_change.append((E * w5_gradient))
weight_change.append((E * w6_gradient))
weight_change.append((E * w7_gradient))
weight_change.append((E * w8_gradient))
weight_change.append((E * w9_gradient))
weightchanges_previous.append(weight_change[0])
weightchanges_previous.append(weight_change[1])
weightchanges_previous.append(weight_change[2])
weightchanges_previous.append(weight_change[3])
weightchanges_previous.append(weight_change[4])
weightchanges_previous.append(weight_change[5])
weightchanges_previous.append(weight_change[6])
weightchanges_previous.append(weight_change[7])
weightchanges_previous.append(weight_change[8])
elif len(weightchanges_previous) != 0:
weight_change[0] = (E * w1_gradient) + (a * weightchanges_previous[0])
weight_change[1] = (E * w2_gradient) + (a * weightchanges_previous[1])
weight_change[2] = (E * w3_gradient) + (a * weightchanges_previous[2])
weight_change[3] = (E * w4_gradient) + (a * weightchanges_previous[3])
weight_change[4] = (E * w5_gradient) + (a * weightchanges_previous[4])
weight_change[5] = (E * w6_gradient) + (a * weightchanges_previous[5])
weight_change[6] = (E * w7_gradient) + (a * weightchanges_previous[6])
weight_change[7] = (E * w8_gradient) + (a * weightchanges_previous[7])
weight_change[8] = (E * w9_gradient) + (a * weightchanges_previous[8])
while len(weightchanges_previous) > 0 : weightchanges_previous.pop()
weightchanges_previous.append((E * w1_gradient) + (a * weightchanges_previous[0]))
weightchanges_previous.append((E * w2_gradient) + (a * weightchanges_previous[1]))
weightchanges_previous.append((E * w3_gradient) + (a * weightchanges_previous[2]))
weightchanges_previous.append((E * w4_gradient) + (a * weightchanges_previous[3]))
weightchanges_previous.append((E * w5_gradient) + (a * weightchanges_previous[4]))
weightchanges_previous.append((E * w6_gradient) + (a * weightchanges_previous[5]))
weightchanges_previous.append((E * w7_gradient) + (a * weightchanges_previous[6]))
weightchanges_previous.append((E * w8_gradient) + (a * weightchanges_previous[7]))
weightchanges_previous.append((E * w9_gradient) + (a * weightchanges_previous[8]))
def edit_weights():
weights[0] += weight_change[0]
weights[1] += weight_change[1]
weights[2] += weight_change[2]
weights[3] += weight_change[3]
weights[4] += weight_change[4]
weights[5] += weight_change[5]
weights[6] += weight_change[6]
weights[7] += weight_change[7]
weights[8] += weight_change[8]
while len(weight_change) > 0 : weight_change.pop()
weights = []
x = 0
while x <=8:
weights.append(uniform(-10, 10))
x += 1
ideal_output = 0
actual_output = output_One()
print "Output %d" % output_One()
x = 0
while x <= 10:
output_One()
calculate_gradient()
backpropogation()
edit_weights()
print "Output %d" % output_One()
print "----------------------"
actual_output = output_One()
x += 1
print "FINAL WEIGHTS:"
print weights[0]
print weights[1]
print weights[2]
print weights[3]
print weights[4]
print weights[5]
print weights[6]
print weights[7]
print weights[8]

Your problem is the output line:
print "Output %d" % output_One()
You're using %d which prints integer values so it rounds float values down to the nearest integer (integer conversion). Use %f instead and you should get the floating point numbers correctly.

Related

how to speed up master.scene._render_pygame_def_update() time

im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using #functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des
from math import *
import pygame
import numpy
from functools import lru_cache
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:return None
px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy
return [round(px),round(py)]
class coordinate:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class verticies_structure:
def __init__(self):
self._verts=[]
def add_vert(self,x,y,z):
self._verts.append(coordinate(x,y,z))
def get_coords(self,indexes):
return self._verts[indexes[0]:indexes[1]]
class camera:
def __init__(self,w,h,render_distance,fov=45):
self.fov=360-fov
self.w=w
self.h=h
self.x=0
self.rx=0
self.cx=0
self.y=0
self.ry=0
self.cy=0
self.z=0
self.rz=0
self.cz=0
self.render_distance=render_distance
def false(f,value):
if value==f:
value=f+0.01
return value
def inf360(value):
if value>359:value=0
if value<0:value=359
return value
class mesh(object):
def __init__(self,file_obj,cam):
self.cam=cam
self.verts=verticies_structure()
self.source=file_obj
self.read_object_file()
self.verts=verticies_structure()
size=100
for x in range(size):
for z in range(size):
self.verts.add_vert(x-size//2,0,z-size//2)
self.w2s_vect=numpy.vectorize(self.w2s)
self.array_verts=numpy.array(self.verts._verts)
def w2s(self,coord):
cam=self.cam
return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)
def projected_des(self,cam):
#return self.w2s_vect(self.array_verts).tolist()
return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))
def read_object_file(self):
self.verts=verticies_structure()
import re
reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
with open(self.source) as f:
data = [txt.group() for txt in reComp.finditer(f.read())]
v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
for line in data:
tokens = line.split(' ')
if tokens[0] == 'v':
v_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vn':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vt':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'f':
f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
vertices, normals = [], []
for face in f_arr:
for tp in face:
self.verts.add_vert(*v_arr[tp[0]-1])
self.array_verts=numpy.array(self.verts._verts)
class draw:
class frame:
class pygame_uitl:
def grid(rowx,rowy,px,color=(255,255,255)):
display=pygame.display.get_surface()
for r in range(rowx):
r+=1
pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
for r in range(rowy):
r+=1
pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)
class system:
class pygame_util:
def get_orientation():
inf=pygame.display.Info()
w,h=inf.current_w,inf.current_h
if w>h:
return 1
else:
return 0
class Drivers:
class Pygame:
DEFAULT="PG-default"
SDL2="PG-sdl2"
class master:
class scene:
def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
self._model={
"class 1":[],
"class 2":[],
"class 3":[],
"class 4":[]}
self._fps=fps
self._window_wh=wh
self._driver=display_driver
self._camera=camera(*wh,render_distance)
self._mode="mesh"
self._super_ls=0
if display_driver==Drivers.Pygame.DEFAULT:
self._render_pygame_def_setup()
def add_model(self,file):
model=mesh(file,self._camera)
vertexes=len(model.verts._verts)
if vertexes>100:
self._model["class 4"].append(model)
elif vertexes>50:
self._model["class 3"].append(model)
elif vertexes>25:
self._model["class 2"].append(model)
else:
self._model["class 1"].append(model)
def regulate_camera(self):
self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
def correct_camera(self,orient=1):
self._orient=orient
if orient:
self._camera.cx=self._window_wh[1]//2
self._camera.cy=self._window_wh[0]
self._camera.ry=0.4
else:
self._camera.cx=self._window_wh[0]//2
self._camera.cy=self._window_wh[1]
self._camera.ry=0.2
def auto_render_distance(self):
if self._driver==Drivers.Pygame.DEFAULT:
if self._pygame_clock.get_fps()+5>self._fps:
self._camera.render_distance+=1
else:
self._camera.render_distance-=1
def landscape_super(self):
self._super_ls=1
self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
self._lss_hdri_file_jpg_surf.fill((200,220,255))
def _render_pygame_def_setup(self):
self._pygame_clock=pygame.time.Clock()
self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)
def _render_pygame_def_update(self):
self._pygame_screen.fill((0,70,0))
self.regulate_camera()
for idx,vclass in self._model.items():
for model in vclass:
for point in model.projected_des(self._camera):
if point!=None:
try:self._pygame_screen.set_at(point,(255,255,255))
except:pass
if self._super_ls:
self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))
def _render_pygame_def_finish(self):
pygame.display.flip()
self._pygame_clock.tick(self._fps)
scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)
scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()
#make the sky mapped to edge of render
pygame.font.init()
while 1:
rx,ry=pygame.mouse.get_rel()
scene._camera.rx+=rx/200
scene._render_pygame_def_update()
#scene.auto_render_distance()
scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))
scene._render_pygame_def_finish()
Something like this would reduce the number of math expressions in project_and_rotate
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:
return None
cos_rotz = cos(rotz)
sin_rotz = sin(rotz)
cos_roty = cos(roty)
sin_roty = sin(roty)
cos_rotx = cos(rotx)
sin_rotx = sin(rotx)
intermediate_1 = (x * cos_rotz - sin_rotz * y)
intermediate_2 = (z * cos_roty + intermediate_1 * sin_roty)
intermediate_3 = (y * cos_rotz + x * sin_rotz) * sin_rotx)
intermediate_4 = (315 / (((intermediate_2 * cos_rotx + intermediate_3 + 5) + cz))) * scale
px = ((intermediate_1 * cos_roty - z * sin_roty) * intermediate_4 + cx
py = (((y * cos_rotz + x * sin_rotz) * cos_rotx - intermediate_2 * sin_rotx) * intermediate_4 + cy
return [round(px), round(py)]
However, to fully improve your script -- it would be wise to profile the code to see where the script is taking the most time.
For a better discussion you should see https://codereview.stackexchange.com/

How to eliminate the click's in my tone generator? PYTHON TONE GENERATOR

When the frequency changes, clicks are sometimes heard.
I tried to eliminate the clicks in a couple of ways, e.g. changing the frequency only when the volume reaches 0 more than once. I tried to calculate when 1 period will end exactly but that didn't work either.
import sys
import sdl2
import sdl2.ext
import math
import struct
import ctypes
basefreq = 110
nframes = 0
tab = [1]
left=0
m= [0]
x=[0]
x2=[0]
x3=[11025]
x4=[0]
i2=[1]
x5=[0]
#ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(sdl2.Uint8), ctypes.c_int)
def playNext(notused, stream, len):
global nframes
for i in range(0, len, 4):
t = (nframes + i) / 44100
i2[0] = i2[0] + 1
t4 = (nframes + i2[0]) / 44100
left2 = math.sin(2 * math.pi * t * (basefreq + int(tab[0])))
left = int(math.sin(2 * math.pi * t * (basefreq + int(tab[0]) )) * 32000)
right = int(math.sin(2 * math.pi * t * (basefreq + 1)) * 32000)
#print(t*100000)
x3[0]=x3[0]+1
t2 = 1 / (basefreq + tab[0])
d2 = i / (44100 * t2)
t3 = x3[0] / (basefreq + tab[0])
d3 = i / (44100 * t3)
width = 344/(basefreq + tab[0])
if (int(t * 100000) % 100000 == 0):
#print(t, " : ", i, " : ", x3[0], " : ", t3," : ", t2," : ",basefreq + tab[0])
x4[0]=0
x3[0] = 0
if (int(d2 * 10) % 2 == 0):
g = x2[0]
x2[0] = 0
dd = g / (44100 * t2)
# print(left, " : ", left)
x2[0] = x2[0] + 1
e = dd * 44100
x4[0]=x4[0]+1
#print(x4[0])
#if(int(left)*1000==0):
#if ((left * 100 <= 0 or left * 100 <= 0) and (left * 100 < 500 or left * 100 > -500)):
print(int(left2*100))
if (int(left2*100) ==0):
if (x5[0] == 10):
#if(int(t*10000)%int(t2*10000)==0):
#if (int(d2 * 10) % 2 == 0 and (i / 100) % int(e / 100) == 0 ):
#if(i*1000%int(t3*220*1000)==0):
tab[0] =math.sin(x[0] / 100)*100+100
x[0]=x[0]+1
i2[0] = i2[0] - 1
x5[0]=0
else:
x5[0]=x5[0]+1
if((nframes + i)%4==0):
stream[i] = left & 0xff
stream[i+1] = (left >> 8) & 0xff
stream[i+2] = right & 0xff
stream[i+3] = (right >> 8) & 0xff
nframes += len
def initAudio():
spec = sdl2.SDL_AudioSpec(0, 0, 0, 0)
spec.callback = playNext
spec.freq = 44100
spec.format = sdl2.AUDIO_S16SYS
spec.channels = 2
spec.samples = 1024
devid = sdl2.SDL_OpenAudioDevice(None, 0, spec, None, 0)
sdl2.SDL_PauseAudioDevice(devid, 0)
def run():
global basefreq
sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO | sdl2.SDL_INIT_TIMER | sdl2.SDL_INIT_VIDEO)
window = sdl2.ext.Window("Tone Generator", size=(800, 600))
window.show()
running = True
initAudio()
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
elif event.type == sdl2.SDL_KEYDOWN:
if event.key.keysym.sym == sdl2.SDLK_UP:
basefreq *= 2
elif event.key.keysym.sym == sdl2.SDLK_DOWN:
basefreq /= 2
break
sdl2.SDL_Delay(1)
return 0
if __name__ == "__main__":
sys.exit(run())
I think this problem is hard to solve.
Can someone help me with this problem?

Printing multiple objects on the same line

I was wondering if anyone could help me create a star pattern of letters. I want to see to have either UP or DOWN on the same line. At the moment, however, the letters are printed underneath each other rather than next on the same line. Any help would be greatly appreciated thank you.
Sample the U function:
def u():
u_str = ''
for row in range (0,7):
for column in range (0,7):
if (((column == 1 or column==5) and row !=6) or ((column==2 or column ==3
or column==4) and row==6)) :
u_str += "*"
else:
u_str += " "
u_str += "\n"
return u_str
function for entering either up or down
def up_or_down():
if len(user_letters) ==4 and user_letters == "DOWN":
print(d()+o()+w()+n())
elif len(user_letters) ==2 and user_letters == "UP":
print(u()+p())
else:
pass
up_or_down()
First, I suggest that you use a dict to store letters ascii art, so you are not recomputing them multiple times:
ascii_letters = {
"D": d(),
"N": n(),
"O": o(),
"P": p(),
"U": u(),
"W": w(),
}
Then create a function that can horizontally concatenate multilines strings:
def hcat_strings(*strings):
"""`strings` must have the same number of lines"""
# in a single line
# return "\n".join((" ".join(l) for l in zip(*(s.splitlines() for s in strings))))
strings_lines = (s.splitlines() for s in strings)
lines_as_tuples = zip(*strings_lines)
lines = (" ".join(l) for l in lines_as_tuples)
return "\n".join(lines)
Which you can finally use as follows:
from operator import itemgetter
text = "UPPUPU"
letters = itemgetter(*text)(ascii_letters)
print(hcat_strings(*letters))
Result:
* * ***** ***** * * ***** * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * ***** ***** * * ***** * *
* * * * * * * * *
* * * * * * * * *
*** * * *** * ***

How to create a vertical graph using lists

number_iterations = input('enter how many times: ')
list_2 = []
list_3 = []
list_4 = []
list_5 = []
list_6 = []
list_7 = []
list_8 = []
list_9 = []
list_10 = []
list_11 = []
list_12 = []
n = int(number_iterations)
for i in range (1, n):
x = random.randint(1,6)
y = random.randint(1,6)
sum_num = x + y
if sum_num == 2:
list_2.append(1)
elif sum_num == 3:
list_3.append(1)
elif sum_num == 4:
list_4.append(1)
elif sum_num == 5:
list_5.append(1)
elif sum_num == 6:
list_6.append(1)
elif sum_num == 7:
list_7.append(1)
elif sum_num == 8:
list_8.append(1)
elif sum_num == 9:
list_9.append(1)
elif sum_num == 10:
list_10.append(1)
elif sum_num == 11:
list_11.append(1)
elif sum_num == 12:
list_12.append(1)
two = '* ' * (len(list_2))
three = '* ' * (len(list_3))
four = '* ' * (len(list_4))
five = '* ' * (len(list_5))
six = '* ' * (len(list_6))
seven = '* ' * (len(list_7))
eight = '* ' * (len(list_8))
nine = '* ' * (len(list_9))
ten = '* ' * (len(list_10))
eleven = '* ' * (len(list_11))
twelve = '* ' * (len(list_12))
print('2 : ' + two)
print('3 : ' + three)
print('4 : ' + four)
print('5 : ' + five)
print('6 : ' + six)
print('7 : ' + seven)
print('8 : ' + eight)
print('9 : ' + nine)
print('10: ' + ten)
print('11: ' + eleven)
print('12: ' + twelve)
Basically what the code does is simulate the rolling of two dice a user defined number of times. The goal is to graph these results. An example output would look like:
enter how many times: 100
2 : * * *
3 : * * * * * *
4 : * * * * * * *
5 : * * * * * * * * * * * * * *
6 : * * * * * * * * * * * * * * * * *
7 : * * * * * * * * * *
8 : * * * * * * * * * * * * *
9 : * * * * * * * * * * * * * * *
10: * * * * * *
11: * * * * * *
12: * *
This of course is a horizontal bar graph. I was wondering if there was a way to make it so that it was a vertical one, with the bars displaying vertically? I've tried using itertools and .zip_longest but it doesn't work at all. Any help would be appreciated, thanks !
You could try to first find the maximum number of asterisks. Then, iterate row in range(max_asterisks, 0, -1).
For each row, you go over your lists, and print an asterisk if the count exceeds the row number, or print a space if not.
For example, this is what I came up with:
# counts is the number of elements in each of your lists
# print(*counts, sep='\t')
for lineno in range(max(counts), 0, -1):
# 2-12: eleven elements
for item in range(11):
# Print only if the count in this column is large enough
if counts[item] >= lineno:
print('*', end='')
# TABs just make formatting easier
print('\t', end='')
# Add newline
print()
# Add the column label
print(*range(2, 13), sep='\t')
And the result:
*
*
* *
* * *
* * * * *
* * * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
2 3 4 5 6 7 8 9 10 11 12

NoneType error with Python class and function

Despite my function returning an array, I get an TypeError: 'NoneType' object is not callable error. I first define classes, and then insert the function.
I'm relatively new to Python, and would appreciate any help/comments.
The Classes are:
from scipy import array, dot, zeros, empty
from scipy.optimize import brentq
from numpy import *
from numpy.random import uniform
from time import time
# from mpi4py import MPI
class UtilTheory:
"""
"""
def utility(self, other):
raise NotImplementedError("You need to implement method 'utility' "
"in the child class.")
def demand(self, p):
raise NotImplementedError("You need to implement method 'demand' "
"in the child class.")
def excessDemand(self, p):
p = array(p)
return self.demand(p) - self.endowment
def indUtility(self, p):
x = self.demand(p)
return self.utility(x)
def __add__(self, other):
economy = Economy([self, other])
return economy
def __radd__(self, other):
economy = Economy([self] + other)
def __rmul__(self, other):
economy = Economy(other * [self])
return economy
class Consumer(UtilTheory, object):
"""
Defines general features of a consumer
"""
def __init__(self, endowment=array([1,1]), alpha=0.5, rho=0.0):
self.endowment = array(endowment)
self.alpha = float(alpha)
self.rho = rho
self.sigma = 1.0 / (1.0 - rho)
def __str__(self):
return ('e=' + str(self.endowment) +
', alpha=' + str(self.alpha) +
', rho=' + str(self.rho))
def demand(self, p):
endowment = self.endowment
alpha = self.alpha
sigma = self.sigma
p = array(p)
m = dot(endowment, p)
x1 = ((alpha / p[0]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
x2 = (((1.0 - alpha) / p[1]) ** sigma * m /
(alpha ** sigma * p[0] ** (1 - sigma) +
(1 - alpha) ** sigma * p[1] ** (1 - sigma)))
return array([x1, x2])
def utility(self, x):
if self.rho != 0:
return ((self.alpha * x[0] ** self.rho +
(1.0 - self.alpha) * x[1] ** self.rho) **
(1.0 / self.rho))
return x[0] ** self.alpha * x[1] ** (1.0 - self.alpha)
class Economy:
"""
Consists of consumers
"""
def __init__(self, consumers):
"""
Consumers should be a list of consumers
"""
self.consumers = consumers
def excessDemand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.excessDemand(p)
return result
def demand(self, p):
result = zeros(2)
for consumer in self.consumers:
result = result + consumer.demand(p)
return result
def excessDemandGood0(self, p0):
p = array([p0, 1.0 - p0])
result = 0
for consumer in self.consumers:
result = result + consumer.excessDemand(p)[0]
return result
def __add__(self,other):
try:
return Economy(self.consumers + other.consumers)
except:
return Economy(self.consumers + [other])
def numEquilibria(self, n=100):
# p = array([p0, 1 - p0])
q = linspace(0, 1, n)
result = empty(len(q))
#print result
for i, p0 in enumerate(q):
a = self.excessDemandGood0(p0)
#print a
result[i] = a
index = zeros(len(q))
for i in range(1, 2):
if result[i] <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(2, n - 1):
test=result[i - 1] * result[i]
#print test
if test <= 0:
index[i - 1] = 1
else:
index[i - 1] = 0
for i in range(n - 2, n - 1):
if result[i] > 0:
index[i - 1] = 1
else:
index[i - 1] = 0
count = sum(index)
# print "The number of equilibria is"
return count
# print "Excess Demand funciton on the grid:"
# print result
# print "Index when excess demand goes from possitive to negative"
# print index
def __rmul__(self, other):
economy = Economy(other * self.consumers)
return economy
def equilibrium(self, startbracket=None):
def g(x):
return self.excessDemandGood0(x)
if startbracket == None:
startbracket = [1e-10, 1-1e-10]
eqPrice1 = brentq(g, startbracket[0], startbracket[1])
return array([eqPrice1, 1 - eqPrice1])
def __len__(self):
return len(self.consumers)
def __str__(self):
resultString = 'Economy with ' + str(len(self)) + ' consumers.\n'
for consumer in self.consumers:
resultString = resultString + str(consumer) + '\n'
return resultString
I get the error when implementing the following stats() function which calls on randomEconEq():
def randomEcon(e1=[1, 0], e2=[0, 1], iterate_max=100):
rho1 = random.uniform(-8, -1)
rho2 = random.uniform(-8, -1)
alpha1 = random.uniform(0, 1)
alpha2 = random.uniform(0, 1)
x = Consumer(endowment=e1, alpha=alpha1, rho=rho1)
y = Consumer(endowment=e2, alpha=alpha2, rho=rho2)
econ = Economy([x, y])
return econ
def randomEconEq(iterate_max=100):
iterate = 0
eq_vec = []
start = time()
while iterate < iterate_max:
iterate += 1
econ = randomEcon()
equilibria = econ.numEquilibria()
eq_vec.append(equilibria)
# print eq_vec
if (econ.numEquilibria() > 1):
print "Number of multiple equilibria is " + \
str(econ.numEquilibria())
print str(econ)
print str(eq_vec)
end = time()
totaltime = end - start
#print('Total Time is ' + str(totaltime))
return eq_vec
def stats(eq_vec, iterate_max):
one_eq = zeros(len(eq_vec))
three_eq = zeros(len(eq_vec))
five_eq = zeros(len(eq_vec))
more_eq = zeros(len(eq_vec))
# print (eq_vec)
for i in range(len(eq_vec)):
if eq_vec[i] == 1:
one_eq[i] = 1
if eq_vec[i] == 3:
three_eq[i] = 1
if eq_vec[i] == 5:
five_eq[i] = 1
if eq_vec[i] > 5:
more_eq[i] = 1
Eq1 = sum(one_eq)
Eq3 = sum(three_eq)
Eq5 = sum(five_eq)
EqMore = sum(more_eq)
prob1 = float((Eq1 / iterate_max) * 100)
prob3 = float((Eq3 / iterate_max) * 100)
prob5 = float((Eq5 / iterate_max) * 100)
probMore = float((EqMore/iterate_max) * 100)
print ('The Vector of the number of equililbria is:' + str(eq_vec))
print ('Probability of 1 equilibrium is (percent) ' + str(prob1))
print ('Probability of 3 equilibria is (percent) ' + str(prob3))
print ('Probability of 5 equilibria is (percent) ' + str(prob5))
print ('Probability of 1 equilibria is (percent) ' + str(probMore))
eq_vec = randomEconEq(100)
stats(eq_vec, 100)
The error appears in the last two lines of code when implementing the function stats().
An example which creates the error is:
stats(randomEconEq(100), 100)
and the complete traceback is:
>>> stats(randomEconEq(100), 100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

Categories