AttributeError: 'module' object has no attribute 'new' - python

I have some code that I would like to run.
Im new to python, as well as stackoverflow
Here is the python program:
# Circle Inversion Fractals (Apollonian Gasket) (Escape-time Algorithm)
# FB36 - 20131031
import math
import random
from collections import deque
from PIL import Image
imgx = 512; imgy = 512
image = Image.new("RGB", (imgx, imgy))
pixels = image.load()
n = random.randint(3, 6) # of main circles
a = math.pi * 2.0 / n
r = math.sin(a) / math.sin((math.pi - a) / 2.0) / 2.0 # r of main circles
h = math.sqrt(1.0 - r * r)
xa = -h; xb = h; ya = -h; yb = h # viewing area
cx = [0.0]; cy = [0.0]; cr = [1.0 - r] # center circle
for i in range(n): # add main circles
cx.append(math.cos(a * i))
cy.append(math.sin(a * i))
cr.append(r)
maxIt = 64 # of iterations
for ky in range(imgy):
print str(100 * ky / (imgy - 1)).zfill(3) + "%"
for kx in range(imgx):
x = float(kx) / (imgx - 1) * (xb - xa) + xa
y = float(ky) / (imgy - 1) * (yb - ya) + ya
queue = deque([])
queue.append((x, y, 0))
while len(queue) > 0: # iterate points until none left
(x, y, i) = queue.popleft()
for k in range(n + 1):
dx = x - cx[k]; dy = y - cy[k]
d = math.hypot(dx, dy)
if d <= cr[k]:
dx = dx / d; dy = dy / d
dnew = cr[k] ** 2.0 / d
xnew = dnew * dx + cx[k]
ynew = dnew * dy + cy[k]
if xnew >= xa and xnew <= xb and ynew >= ya and ynew <= yb:
if i + 1 == maxIt: break
queue.append((xnew, ynew, i + 1))
pixels[kx, ky] = (i % 16 * 16 , i % 8 * 32, i % 4 * 64)
image.save("CircleInversionFractal_" + str(n) + ".png", "PNG")
When I run it, I get an error message but I don't know how to resolve it.
Traceback (most recent call last):
File "U:\Personal\PythonFiles\Python Program Examples\Circle Inversion Fractals.py", line 9, in <module>
image = Image.new("RGB", (imgx, imgy))
AttributeError: 'module' object has no attribute 'new'
What does this traceback mean?

It means that you are trying to use the name new on a module object:
>>> import sys
>>> sys.new
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'new'
It means the sys module has no attribute new here. It doesn't matter if you are treating new as a callable (function, method, class, etc.), in the expression sys.new() the name new will first be looked up as an attribute.
If you are trying to use a module that is documented to have a .new() method (such as sha.new() or hashlib.new(), then make sure you don't have another module by the same name in your path. Don't name your own script sha.py when you try to import the standard library module sha!
You can check where a module was imported from by printing the .__file__ filename:
print sha.__file__
and if it is not a filename in your Python installation you perhaps need to investigate why you have an extra file in your path and rename that file or move it aside.

Related

nsolve constantly throwing ValueError

I'm currently trying to run this block of code.
# %% Imports
import numpy as np
import sympy as sy
import scipy as sc
alpha = sy.Symbol('alpha', real=True)
beta = sy.Symbol('beta', real=True)
s_0 = sy.Symbol('s_0', real=True)
s_1 = sy.Symbol('s_1', real=True)
s_2 = sy.Symbol('s_2', real=True)
t = sy.Symbol('t', real=True)
#run checks on S(t) whether S(t) > S0 for current iteration
def main():
# A. Defining equations to constant variables to be called later
#S(t) > S0, (S(t) + β/α)*S(t) > 0
MODEL_1_1 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) > S0, (S(t) + β/α)*S(t) < 0
MODEL_1_2 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_3 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_4 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#---------------------------------------------------------------
# B. Initializing values
stock_price = [25725, 25600, 24600]
#---------------------------------------------------------------
# C. Get 2 functions for every t = 1 and t = 2
## C.1. processing t1
if (stock_price[1] > stock_price[0]):
eq1 = MODEL_1_1.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_2.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq1 = MODEL_1_3.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_4.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq1)
#print(eq2)
## C.2. processing t2
if (stock_price[2] > stock_price[0]):
eq3 = MODEL_1_1.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_2.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq3 = MODEL_1_3.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_4.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq3)
#print(eq4)
#------------------------------------------------
# D. Run 4 different solution, get 4 sets of possible (α,β) pair
## D.1. eq1 vs. eq3 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) > 0
print(eq1)
print(eq3)
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
print(sol1)
## D.2. eq2 vs. eq3 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) > 0
## D.3. eq1 vs. eq4 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) < 0
## D.4. eq2 vs. eq4 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) < 0
#check for contradictions against initial condition
#return values that satisfies all condition
#run t = 3 based on the iteration
#repeat
main()
However it keeps throwing
Could not find root within given tolerance. (655317900.776688019361 >
2.16840434497100886801e-19) Try another starting point or tweak arguments.
or
matrix is numerically singular
whenever I try to tweak around the initial starting point.
Could anyone help / suggest alternatives to nsolve for this particular function?
Edit 1:
adding tracebacks
Traceback (most recent call last):
File "D:\SKRIPSI ANDREE\Code\model1.py", line 76, in <module>
main()
File "D:\SKRIPSI ANDREE\Code\model1.py", line 64, in main
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\utilities\decorator.py", line 88, in func_wrapper
return func(*args, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 2954, in nsolve
x = findroot(f, x0, J=J, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 969, in findroot
for x, error in iterations:
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 660, in __iter__
s = self.ctx.lu_solve(Jx, fxn)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 226, in lu_solve
A, p = ctx.LU_decomp(A)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 136, in LU_decomp
raise ZeroDivisionError('matrix is numerically singular')
ZeroDivisionError: matrix is numerically singular

Cannot add scalar and a vector error in VPyhton (GlowScript)

I'm implementing a solar system with VPython in GlowScript. Now I have received this error when running: Error cannot add scalar and a vector. I think I've done all correctly. Do I have to change something with the pos. ?
Here is the code:
GlowScript 2.7 VPython
from visual import *
scene = display(width = 800, height = 800, center = vec(0,0.5,0))
#sun
sonne = sphere(pos = vec (0,0,0), radius=8, color = color.orange, shininess=1)
#earth
erde = sphere(pos = vec (50,0,0), radius=1.5, color = color.blue, make_trail=True)
erdeV = vector(0,0,5)
#masses
erdeM = 5.97*10**24
sonneM = 1.989*10**30
#Grav-constant
G = 6.67259*10**-11
for i in range (1000):
rate(1000)
erde.pos = erde.pos + erdeV
#distance
entfernung = sqrt(erde.pos.y**2 + erde.pos.z**2)
#Gravitational law F = G * m * M / r*r --> G*s*e/AE*AE ae=Astr. Einheit
Fgrav = G *( erdeM * sonneM) / (entfernung*entfernung)
erdeV = erdeV + Fgrav
erde.pos += erdeV
if entfernung <= sonne.radius: break
Problem lines:
Fgrav = G *( erdeM * sonneM) / (entfernung*entfernung)
erdeV = erdeV + Fgrav
Fgrav here is a scalar (strength of gravitational force) whereas erdeV is a vector. To remedy this, include the direction of the force:
Fgrav = (-G * (erdeM * sonneM) / (entfernung ** 3)) * erde.pos
erdeV = erdeV + Fgrav

PyDSTool step of integration

I have an ODE system. I'm looking for a solution of the system using PyDSTool. I try to put the integration step, but I get an error.
import PyDSTool as ds
from PyDSTool import Par, Var
import time
from PyDSTool import *
# Declare names and initial values for (symbolic) parameters
varepsilon = pow(10, -2)
j = 2.5*pow(10, -5)
e = 3.0
y8 = lambda y1,y5,y7: 1 / (1 - 2 / y1) * math.sqrt(y5 ** 2 + (1 - 2 / y1) * (1 + y1 ** 2 * y7 ** 2))
E0 = lambda y1,y8: (1 - 2 / y1) * y8
Phi0 = lambda y1,y7: y1 ** 2 * y7
# Compute nontrivial boundary equilibrium initial condition from parameters (see reference for derivation)
u0 = -math.sqrt(-1 + math.sqrt(varepsilon ** 2 + 12) / varepsilon) * math.sqrt(2) / 6
v0 = 1 / (1 - 2 / e) * math.sqrt(j ** 2 + (1 - 2 / e) * (e ** 2 * u0 ** 2 + 1))
y08 = y8(y1=e, y5=j, y7=u0);
E = E0(y1=e, y8=y08); Phi = Phi0(y1=e, y7=u0)
z01, z03, z04, z05, z07, z08 = e, 0.0, 0.0, j, u0, v0
# Declare symbolic variables
z1, z3, z4, z5, z7, z8 = Var('z1'), Var('z3'), Var('z4'), Var('z5'), Var('z7'), Var('z8')
# Create Symbolic Quantity objects for definitions
p1 = -z1*z5/(z1 - 2);
p3 = -z1**2 *z7;
p4 = z8*(1 - 2/z1);
Q1 = -z5**2/(z1*(z1 - 2)) + (z8**2/z1**3 - z7**2)*(z1 - 2);
Q3 = 2*z5*z7/z1;
Q4 = 2*z5*z8/(z1*(z1 - 2));
c1 = z1*z7*varepsilon;
c3 = -z1*z5*varepsilon;
C = z7*varepsilon/z1 - z8*(1 - 2/z1);
d1 = -z1*z8*varepsilon;
d3 = z1*z5*varepsilon;
B = z1**2*z7 - z8*varepsilon*(1 - 2/z1);
Omega = 1/(c1*d3*p3+c3*d1*p4-c3*d3*p1);
# differential equations
z1dot = z5;
z3dot = z7;
z4dot = z8;
z5dot = Omega*(-Q1*c1*d3*p3 - Q1*c3*d1*p4 + Q1*c3*d3*p1 + B*c3*p4 + C*d3*p3 + E*d3*p3 - Phi*c3*p4);
z7dot = -Omega*(Q3*c1*d3*p3 + Q3*c3*d1*p4 - Q3*c3*d3*p1 + B*c1*p4 - C*d1*p4 + C*d3*p1 - E*d1*p4 + E*d3*p1 - Phi*c1*p4);
z8dot = Omega*(-Q4*c1*d3*p3 - Q4*c3*d1*p4 + Q4*c3*d3*p1 + B*c1*p3 - B*c3*p1 - C*d1*p3 - E*d1*p3 - Phi*c1*p3 + Phi*c3*p1);
# Build Generator
DSargs = args(name='Sining particle')
#print(dir(DSargs))
#DSargs.pars = [varepsilon, j, e]
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
DSargs.tdata = [0.0, 0.1]
DSargs.varspecs = args(z1=z1dot, z3=z3dot, z4=z4dot, z5=z5dot, z7=z7dot, z8=z8dot)
# Use eval method to get a float value from the symbolic definitions given in
# terms of parameter values
DSargs.ics = args(z1=z01, z3=z03, z4=z04, z5=z05, z7=z07, z8=z08)
ode = Generator.Vode_ODEsystem(DSargs)
t = time.time()
result = ode.compute('test')
print("time for integration: %f" %(time.time() - t))
pts = result.sample()
plt.plot(pts['t'], pts['z7'], label='x')
plt.legend()
plt.xlabel('t')
plt.show()
Through the next lines I get an the error:
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
Traceback (most recent call last):
File "C:\Users\mykola\Downloads\pydstool.py", line 65, in <module>
ode = Generator.Vode_ODEsystem(DSargs)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\Vode_ODEsystem.py", line 47, in __init__
ODEsystem.__init__(self, kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\ODEsystem.py", line 61, in __init__
self.checkArgs(kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\baseclasses.py", line 1069, in checkArgs
raise PyDSTool_KeyError('Invalid keyword arguments for this class')
PyDSTool.errors.PyDSTool_KeyError: 'Invalid keyword arguments for this class'
The library PyDSTool has very little training information in internet.
What I do wrong?. And how to correctly determine the step of integration?

Global variables aren't working

My global variables are not working in my code. I'm fairly new to this and I can't seem to figure this out: I have set variables (only showing gna for this), which can be manipulated by an entry field, triggered by a corresponding button. For some reason, it's not taking the changes within the loop. I'm trying to make it to where the changed variable can be graphed as well, but it gives me the following error:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args) File "G:/PYTHON/Eulers.py", line 64, in graph
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('< U32') dtype('< U32') dtype('< U32')
Here is the code:
gna = 0.9
gnalabel = Label(topFrame, text="gna = %s" % gna)
gnalabel.pack()
gnaEntry = Entry(topFrame, justify=CENTER)
gnaEntry.pack()
def gnacallback():
global gna
gna = gnaEntry.get()
gnalabel.config(text="C = %s" % gna)
gnaButton = Button(topFrame, text="Change", width=10, command=gnacallback)
gnaButton.pack()
def graph():
global c, gna, gk, beta, gamma
for i in range(0, len(t)-1):
stinum = np.floor(i / 3000)
stimt = 3000 + 3000 * (stinum - 1)
f[i] = v[i] * (1 - (((v[i]) ** 2) / 3))
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
if(i == stimt):
v[i + 1] = v[i + 1] + v_stim
u[i + 1] = (v[i] + beta - gamma * u[i]) * del_t + u[i]
plt.plot(v)
plt.show()
gna = gnaEntry.get()
Entry.get returns a string, which is probably an unsuitable type for the arithmetic you're doing in graph. Try converting to a number first.
gna = float(gnaEntry.get()) #or perhaps `int` if it's always an integer

Im having an issue when running a class design, need help figuring out where is the issue

# Classy Mandelbrot Patterns.
import turtle;
import colorsys;
# A Mandelbrot patterns class:
class MandelbrotPatterns:
# Initialize the pen, and determine the window width and height:
def __init__(self):
self.pen = turtle.Pen();
self.width = self.pen.window_width();
self.height = self.pen.window_height();
# Given numbers self, u0, v0, and side, design a pattern:
def mandelbrot(self, u0, v0, side):
self.pen.tracer(False);
for x in range(-self.width/2, +self.width/2):
for y in range (-self.height/2, +self.height/2):
draw(self.pen, side, u0, v0, x, y);
if (x % 20 == 0):
self.pen.tracer(True); self.pen.tracer(False);
self.pen.tracer(True);
# Draw in color a pattern element at point (x, y):
def selfdraw(self, side, u0, v0, x, y):
maxCount = 25;
u = u0 + x * (side / 100.0);
v = v0 - y * (side / 100.0);
a = 0 ; b = 0; count = 0;
while (count < maxCount and a * a + b * b <= 4):
count = count + 1;
a1 = a * a - b * b + u;
b1 = 2 * a * b + v;
a = a1; b = b1;
ez = float(count) / maxCount;
color = colorsys.hsv_to_rgb(ez, ez, ez);
self.pen.color(color);
self.pen.up(); self.pen.goto(x, y); self.pen.down();
self.pen.forward(1);
when I run the module Im testing this information to make sure it works:
>>> mb = MandelbrotPatterns();
>>> mb.mandelbrot(u0= -0.5, v0 = 0, side = 1);
This is the response I'am getting back from Idle:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
mb.mandelbrot(-0.5, 0, 1)
AttributeError: MandelbrotPatterns instance has no attribute 'mandelbrot'
I was thinking where I define mandelbrot is the problem but I don't see where there could be an error. If someone could give me an idea or solution that would be great. Thanks
Your methods need to be indented one level further. As it is, they're functions defined at the same level as the class.

Categories

Resources