Nested for loop and 3D Plot within Class Object - python

i am sure this is an easy problem to deal with, but i cant figure it out. I created a Borehole Class and want to compute my pore pressure around each Borehole/Well. Along a single axis, my code looks like this:
from scipy.special import *
import matplotlib.pyplot as plt
import numpy as np
from math import *
## Globale Variablen ##
rhof = 1000 # Dichte Flüssigkeit [kg/m³]
lameu = 11.2*10**9 # Lamé-Parameter, undrained [GPa]
lame = 8.4*10**9 # Lamé-Parameter, drained [GPa]
pi # durch Pythonmodul "math" gegeben
alpha = 0.65 # Biot-Willis-Koeffizient
G = 8.4*10**9 # Schermodul [GPa]
k = 1.0e-15 # Permeabilität [m²] bzw. [Darcy]
eta = 0.001 # Viskosität des Fluids [Pa*s]
## Berechnung der Parameter ##
kappa = k/eta
c = ((kappa*(lameu-lame)*(lame+2*G))/((alpha**2)*(lameu+2*G)))
## Wertebereich ##
xmin = 0
xmax = 100
xsteps = 1.0
x = np.arange(xmin, xmax, xsteps)
## Class ##
class Bohrloch(object):
loch_zaehler = 0
def __init__(self, xlage, tstart, q): # Funktion, um BL zu erzeugen
self.xlage = xlage
#self.ylage = ylage # Lage der Bohrung
self.tstart = tstart # Start der Injektion/Produktion
self.q = q # Fluidmenge
## Druck ##
def getPressure(self, t): # gibt nach Zeit t die zugehörigen Druckwerte aus
if (t-self.tstart<0): # Fehlermeldung, falls Startpunkt nach t liegt
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
self.r = np.sqrt((x-self.xlage)**2)
self.P = (self.q/(rhof*4*pi*kappa))*(expn(1,self.r**2/(4*c*(t-self.tstart))))
#self.P[self.xlage] = 0 # gibt Bohrlochlage wieder
self.z = self.P/1e6
return self.z # Druckwerte in [MPa]
def pressureTable (self, t, xschritt): # erstellt Wertetabelle
self.getPressure(t)
for i in range (xmin, xmax, xschritt):
print i, " ", self.z[i]
t = 1000*24*3600
b1 = Bohrloch(50,0*24*3600,6.0/1000)
b1.pressureTable(t,1)
With this method i get my desired pressure table. Now i want to have a pressure table for x and y values, including an 3D Plot. This is my code so far:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy.special import *
import matplotlib.pyplot as plt
import numpy as np
from math import *
## Globale Variablen ##
rhof = 1000 # Dichte Flüssigkeit [kg/m³]
lameu = 11.2*10**9 # Lamé-Parameter, undrained [GPa]
lame = 8.4*10**9 # Lamé-Parameter, drained [GPa]
pi # durch Pythonmodul "math" gegeben
alpha = 0.65 # Biot-Willis-Koeffizient
G = 8.4*10**9 # Schermodul [GPa]
k = 1.0e-15 # Permeabilität [m²] bzw. [Darcy]
eta = 0.001 # Viskosität des Fluids [Pa*s]
## Berechnung der Parameter ##
kappa = k/eta
c = ((kappa*(lameu-lame)*(lame+2*G))/((alpha**2)*(lameu+2*G)))
## Wertebereich ##
xmin = 0
xmax = 100
xsteps = 1.0
x = np.arange(xmin,xmax,xsteps)
ymin = 0
ymax = 100
ysteps = 1.0
y = np.arange(ymin,ymax,ysteps)
## Klassendefinition ##
class Bohrloch(object):
loch_zaehler = 0
def __init__(self, xlage, ylage, tstart, q): # Funktion, um BL zu erzeugen
self.xlage = xlage # x-Lage der Bohrung
self.ylage = ylage # y-Lage der Bohrung
self.tstart = tstart # Start der Injektion/Produktion
self.q = q # Fluidmenge
## Druck ##
def getPressure(self, t):
if (t-self.tstart<0):
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
self.r = np.sqrt((x-self.xlage)**2+(y-self.ylage)**2)
self.P = (self.q/(rhof*4*pi*kappa))*(expn(1,self.r**2/(4*c*(t-self.tstart))))
self.P[self.xlage] = np.nan
self.P[self.ylage] = np.nan
self.z = self.P/1e6
return self.z # Druckwerte in [MPa]
def pressureTable (self, t, xschritt, yschritt):
self.getPressure(t)
for k in range (xmin, xmax, xschritt):
for l in range (ymin, ymax, yschritt):
# my mistake should be here?
print k, " ", l, " ", self.z[k][l]
def pressurePlot3D (self, t):
self.getPressure(t)
Z = self.z
X, Y = np.meshgrid(x,y)
Z[Z == np.inf] = np.nan
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, linewidth=0,
antialiased=False, vmin=np.nanmin(Z), vmax=np.nanmax(Z))
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlim(xmin,xmax) # x-Achsenskala vorgeben
ax.set_ylim(ymin,ymax) # y-Achsenskala vorgeben
ax.set_title('Druckverteilung')
ax.set_xlabel('x-Richtung [m]')
ax.set_ylabel('y-Richtung Well [m]')
ax.set_zlabel('Druck in [MPa]')
plt.show()
t = 1000*24*3600
b1 = Bohrloch(50,50,0*24*3600,6.0/1000)
b1.pressureTable(t,1)
b1.pressurePlot3D(t)
Unfortunately, my table doesnt work and the desired 3D Plot looks strange. I am still a total beginner in Python and need some advices.
Can anyone help?

The problem is that self.z is not a two-dimensional array/list. Therefore, trying to access self.z[k][l] results in IndexError: invalid index to scalar variable.
I do not quite understand how you want to implement the second dimension. You introduce the y-position, but then, you just calculate a 1D radius array by using both the x- and y-location in
self.r = np.sqrt((x-self.xlage)**2+(y-self.ylage)**2)
The next question is, what do you intend with:
self.P[self.xlage] = np.nan
self.P[self.ylage] = np.nan
If you change xsteps and ysteps to 10, and call:
b1 = Bohrloch(2,3,0*24*3600,6.0/1000)
print b1.getPressure(t)
Your output will be:
[ 5.44152501 4.40905986 nan nan 2.87481753 2.64950827
2.46756653 2.31503845 2.18379093 2.06866598]
Why would you want to replace the 3rd and 4th elements with nan?
These issues are also at the basis of your plotting routine. Because you now have np.nan values in your array, these won't show in the plot. Because self.z is not two-dimensional, you are probably not getting the surface you may be expecting:
Here's a simple way of coming up with a 2D implementation. I am not familiar enough with what you are trying to do, but it gets the idea across:
def getPressure(self, t):
if (t-self.tstart<0):
return ()
print "Startpunkt liegt außerhalb des Förderzeitraumes!"
else:
# you need to initialize r, P and z as list of lists
# make this dependent on your x coordinates
# the second dimension will grow dynamically
self.r = [[] for ri in range(len(x))]
self.P = [[] for ri in range(len(x))]
self.z = [[] for ri in range(len(x))]
# iterate through both x and y independently
for ii in range(len(x)):
for jj in range(len(y)):
# append to the list that corresponds to the current x -value
# also, use x[ii] and y[jj] to call one x-, y-value at a time
self.r[ii].append(np.sqrt((x[ii]-self.xlage)**2+(y[jj]-self.ylage)**2))
# calling r[ii][-1] ensures you are using the value that was last added to the list:
self.P[ii].append((self.q/(rhof*4*pi*kappa))*(expn(1,self.r[ii][-1]**2/(4*c*(t-self.tstart)))))
self.z[ii].append(self.P[ii][-1]/1e6)
# now, you can use xlage and ylage to blank one value
# do this for both P and z, because z is now calculated inside the loop
self.P[self.xlage][self.ylage] = np.nan
self.z[self.xlage][self.ylage] = np.nan
return self.z
From your plotting routine, remove this line: Z[Z == np.inf] = np.nan, use your original command:
b1 = Bohrloch(50,50,0*24*3600,6.0/1000)
b1.pressurePlot3D(t)
and you will now get this plot:

Related

Why will 'odeint' not let me unpack float object here?

I am testing some equations of motion with odeint. I am trying to integrate and test these while saying my control (us) is 0 the whole time. However, I get the above-mentioned error, and I do not understand why. Any advice is much appreciated!
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from scipy.interpolate import interp1d
import pickle
Ro = 6371000 #m
hs = -7254.24 #m scale height
rhosl = 1.225 #kg^3
Aref = 250 #m^2
m = 92079 #kg mass of vehicle
#cl and cd spline
dat = pickle.load(open('clp.pkl','rb'))
AOA =dat[0]
cl = dat[1]
cd = dat[2]
AOAnew = AOA.tolist()
cl1 = cl.tolist()
cd1 = cd.tolist()
clnew = interp1d(AOAnew,cl1,kind='linear')
cdnew = interp1d(AOAnew,cd1,kind='linear')
def rhos(h):
rho = rhosl*np.exp((hs)/h)
return rho
def f(t,xs):
r,theta,phi,V,gamma,psi = xs
L = Ro*(rhos(r))*V**2*Aref*(clnew(gamma))/(2*m)
D = Ro*(rhos(r))*V**2*Aref*(cdnew(gamma))/(2*m)
us = 0
drdot = V*np.sin(gamma)
dthetadot = (V*np.cos(gamma)*np.sin(gamma))/(r*np.cos(phi))
dphidot = (V*np.cos(gamma)*np.cos(psi))/r
dVdot = -D - np.sin(gamma/r**2)
dgammadot = (L*np.cos(us)/V) + (V**2 - (1/r))*np.cos(gamma/(V*r))
dpsidot = L*np.sin(us)/(V*np.cos(gamma)) + V*np.cos(gamma)*np.sin(psi)*np.tan(phi/r)
return [drdot,dthetadot,dphidot,dVdot,dgammadot,dpsidot]
#initial/terminal conditiions
h0 = 79248
theta0 = 0
phi0 = 0
V0 = 7802.88
gamma0 = -1/np.pi
psi0 = 90/np.pi
y0 = [h0,theta0,phi0,V0,gamma0,psi0]
t = np.linspace(0,20)
y = odeint(f,y0,t)
plt.plot(t,y)
plt.show()
You need to pass tfirst=True to odeint, as it expects f(y, t) by default.

Error on creating spiral arms for galaxy formation on python

i have writing this code but in my code there is error, how can i make spiral arms from this code by used profile used below i want to create surface density profile using spiral arms of the galaxy
import numpy as np
import matplotlib.pyplot as plt
from math import*
#r,theta = meshgrid(np.arange(0,200,1), np.arange(0,360,1))
t = 1
c = 100
alpha = 12 #degree
m = 2
rd = 5
sigd = 35
omegap = 8.4
r,theta = np.meshgrid(np.arange(1,200,1), np.arange(1,360,1))
def k(m,r):
k1 = (m/r)*(1/0.212)
#print(k1)
return k1
def sig0(sigd,r,rd):
sig_0 = sigd*np.exp(-r/rd)
return sig_0
def phi (m,r):
phi_1 = m*(1/0.212)*np.log(r)
return phi_1
def omega (r):
omega_1 = (200/r)+1.37
return omega_1
def kappa (r):
kppa= (400*sqrt(0.5))/r
return kppa
def xt(c,m,r):
x_t = ((k(m,r)**2)*(c**2))/((kappa(r))**2)
return x_t
def v(m,omegap,r):
v_1 = (m/kappa(r))*(omegap-omega(r))
return v_1
def del_12 (c,r,m,omegap):
de1 = (1-((4*xt(c,m,r))*((1-v(m,omegap,r)**2))))**(1/2)
return de1
def sig(r,m,t,theta,c,sigd,rd,omegap):
r,theta = np.meshgrid(np.arange(1,200,1), np.arange(1,360,1))
sig1 = sig0(sigd,r,rd)+(((abs(k(m,r)))/r**(1/2))*(1/(abs(del_12(c,m,r,omegap))**(1/2)))*(np.cos(omegap*m*t-m*theta+phi(m,r))))
#+ ((abs(k(m,r)))/r**(1/2))*(1/abs(del_12(c,r,m,omegap))**(1/2))*np.cos(omegap*m*t-m*theta+phi)
return sig1
model = sig(r,m,t,theta,c,sigd,rd,omegap)
print(model)
fig=plt.figure()
ax1=fig.add_subplot(121)
ax1.imshow(model)
#plt.contour(x,y,galaxy_model_1)
#pf.writeto('gal_1.fits', galaxy_model_1, clobber=1)
#ax2=fig.add_subplot(122, axisbg='white')
#ax2.imshow((abs(galaxy_model_2))**0.2)
plt.show()
more information about this code is given by this reference
Contribution of spiral arms to the surface brightness distribution
of disk galaxies
http://articles.adsabs.harvard.edu/pdf/1997A%26A...318..741S

ACO algorithm on python machine learning

I am trying to understand the code below where it shows the default TSP path on a picture. I understand most of the part except for the polyfit_plot() function. I understand the function in it separately but when combine together I just don't get what it contributes to. I have even tried to delete the function and the result is actually the same, and I don't see where the function is implemented in. Can someone explain it to me?
import numpy as np
import math
import random
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
united_states_map = mpimg.imread(r"C:\Users\user\Downloads\archive\united_states_map.png")
def show_cities(path, w=12, h=8):
if isinstance(path, dict): path = list(path.values())
if isinstance(path[0][0], str): path = [ item[1] for item in path ]
plt.imshow(united_states_map)
for x0, y0 in path:
plt.plot(x0, y0, 'y*', markersize=15) # y* = yellow star for starting point
plt.axis("off")
fig = plt.gcf()
fig.set_size_inches([w, h])
def show_path(path, starting_city=None, w=12, h=8):
if isinstance(path, dict): path = list(path.values())
if isinstance(path[0][0], str): path = [ item[1] for item in path ]
starting_city = starting_city or path[0]
x, y = list(zip(*path))
#_, (x0, y0) = starting_city
(x0, y0) = starting_city
plt.imshow(united_states_map)
#plt.plot(x0, y0, 'y*', markersize=15) # y* = yellow star for starting point
plt.plot(x + x[:1], y + y[:1]) # include the starting point at the end of path
plt.axis("off")
fig = plt.gcf()
fig.set_size_inches([w, h])
def polyfit_plot(x,y,deg, **kwargs):
coefficients = np.polyfit(x,y,deg,**kwargs)
poly = np.poly1d(coefficients)
new_x = np.linspace(x[0], x[-1])
new_y = poly(new_x)
plt.plot(x, y, "o", new_x, new_y)
plt.xlim([x[0]-1, x[-1] + 1 ])
terms = []
for p, c in enumerate(reversed(coefficients)):
term = str(round(c,1))
if p == 1: term += 'x'
if p >= 2: term += 'x^'+str(p)
terms.append(term)
plt.title(" + ".join(reversed(terms)))
cities = { "Oklahoma City": (392.8, 356.4), "Montgomery": (559.6, 404.8), "Saint Paul": (451.6, 186.0), "Trenton": (698.8, 239.6), "Salt Lake City": (204.0, 243.2), "Columbus": (590.8, 263.2), "Austin": (389.2, 448.4), "Phoenix": (179.6, 371.2), "Hartford": (719.6, 205.2), "Baton Rouge": (489.6, 442.0), "Salem": (80.0, 139.2), "Little Rock": (469.2, 367.2), "Richmond": (673.2, 293.6), "Jackson": (501.6, 409.6), "Des Moines": (447.6, 246.0), "Lansing": (563.6, 216.4), "Denver": (293.6, 274.0), "Boise": (159.6, 182.8), "Raleigh": (662.0, 328.8), "Atlanta": (585.6, 376.8), "Madison": (500.8, 217.6), "Indianapolis": (548.0, 272.8), "Nashville": (546.4, 336.8), "Columbia": (632.4, 364.8), "Providence": (735.2, 201.2), "Boston": (738.4, 190.8), "Tallahassee": (594.8, 434.8), "Sacramento": (68.4, 254.0), "Albany": (702.0, 193.6), "Harrisburg": (670.8, 244.0) }
cities = list(sorted(cities.items()))
print(len(cities))
show_cities(cities)
show_path(cities)
It seems that the function polyfit_plot is unused in the code, so it is never run and as you say it does not affect the outcome.

How can I speed up solving after a variable?

I would like to put different equations into each other and then solve after d. Unfortunately, it takes forever and at some point he tells me that the memory is full. Can I speed this up somehow? Am I doing something wrong?
The command should be correct, because with a simpler formula I have already done the same without inserting into each other.
Here is my module with the equations:
## Parameter in SI-Einheiten
p = 103000 # Pa
M_Ar = 0.039948 # kg/mol
R = 8.314 # J/(mol*K)
A_N = 0.0123
gamma = 3*10**(-4)
g = 9.81 # m/s^2
cw2 = 0.45
cw1 = 0.18
# --------
## Eingabe der Temperatur
choice = 1
if choice == 1:
temp = 298.15
roh_titan = 4505 # kg/m^3
eta = 0.0000225
elif choice == 2:
temp = 2000
roh_titan = 4000 # kg/m^3
eta = 0.00012217
# --------
## Berechnung Geschwindigkeit u für allgemein cw
def u_cw(du, u3):
return (sigma_p()*4/3*du/cw(du, u3)*g)-(u3*10**(-3))**2
# ------
# Berechnung cw-Wert
def cw(d4, u4):
return 24/re(d4, u4)*(1+0.15*re(d4, u4)**0.687)+0.44
# Berechnung Reynoldszahl
def re(d2, u2):
return roh_ar()*u2*d2/eta
## Berechnung Dichte Argon
def roh_ar():
return p*M_Ar/(R*temp)
def sigma_p():
return roh_titan/roh_ar()
And here's my script:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import pandas as pd
import fw_istgleich_fg_NurEinCw
from sympy import *
print('Datei einlesen')
## Aus Datei lesen mit genfromtxt und ausgeben
data = np.genfromtxt(dateiname3, skip_header=1, usecols=(0,1,4), delimiter='\t', invalid_raise=False, filling_values=0)
print('Datei eingelesen')
xx = data[0::,0]
yy = data[0::,1]
velocity_1d = data[0::,2]
# definiere Dataframe
vel_Coord = {'x':xx,
'y':yy,
'velocity': velocity_1d} # in mm/s, muss im Modul umgerechnet werden!
df = pd.DataFrame(vel_Coord)
print('Dataframe wurde erzeugt')
# Geschwindigkeit in Durchmesser umrechnen
diameter1 = []
diameter2 = []
This command should call the equations and then solve them after d:
d, geschw = symbols('d, geschw')
result = solve(fw_istgleich_fg_NurEinCw.u_cw(d, geschw), d)
print(result)
It seems you are solving essentially the same equation many times, just with different coefficients. It would be more efficient to introduce symbols
p, M_Ar, ..., eta = symbols('p, M_Ar, ... , eta', positive=True)
and solve the equation once. Then substitute the floating point constants into the solution, with
values = {p: 103000, ..., eta: 0.00012217}
result_numeric = result.subs(values)

FEniCS: UMFPACK reports that the matrix being solved is singular

I created a divided domain with the stokes-equation in the first subdomain and the mixed-poisson-equation (darcy) in the second subdomain. I work with the UnitSquare and the subdomain 1 should be the interval from 0 to 0,5 and the subdomain 2 from 0,5 to 1.
But now i get the following error:
Solving linear variational problem.
UMFPACK problem related to call to numeric
* Warning: UMFPACK reports that the matrix being solved is singular.
UMFPACK problem related to call to solve
* Warning: UMFPACK reports that the matrix being solved is singular.
assert vmax>=vmin, "empty range, please specify vmin and/or vmax"
Assertion error: empty range, please specify vmin and/or vmax
Can anyone help?
Thanks!
Here is the code:
enter code here
#-*- coding: utf-8 -*-
from dolfin import *
import numpy as np
# Define mesh
mesh = UnitSquare(32,32)
#Subdomain 1
# Gitter übergeben
subdomains = CellFunction("uint", mesh)
# Klasse des Teilgebiets
class Domain_1(SubDomain):
def inside(self, x, on_boundary):
return between(x[0], (0, 0.5)) # Koordinatenangabe des Teilgebiets
# Objekt der Klasse erstellen
sub_domain1 = Domain_1()
sub_domain1.mark(subdomains,0)
# Definition Funktionenräume
U = FunctionSpace(mesh, "CG", 2)
V = FunctionSpace(mesh, "CG", 1)
W = U*V
# Definition Trial- und Testfunktion
(u, p) = TrialFunctions(W)
(v, q) = TestFunctions(W)
# boundary condition
p_in = 1
p_out = 0
noslip = DirichletBC(W.sub(0), (0),
"on_boundary && \
(x[1] <= DOLFIN_EPS | x[1] >= 0.5-DOLFIN_EPS)")
inflow = DirichletBC(W.sub(1), p_in, "x[0] <= 0.0 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(1), p_out, "x[0] >= 0.5 - DOLFIN_EPS*1000")
bcp = [noslip,inflow, outflow]
# Definition f
f = Expression("0")
# Variationsformulierung
a = inner(grad(u), grad(v))*dx + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
# Lösung berechnen
w = Function(W)
problem = LinearVariationalProblem(a, L, w, bcp)
solver = LinearVariationalSolver(problem)
solver.solve()
(u, p) = w.split()
# Subdomain 2
# Gitter übergeben
subdomains = CellFunction("uint", mesh)
# Klasse des Teilgebiets
class Domain_2(SubDomain):
def inside(self,x,on_boundary):
return between(x[0], (0.5,1.0)) # Koordinatenangabe des Teilgebiets
# Objekt der Klasse erstellen
sub_domain2 = Domain_2()
sub_domain2.mark(subdomains,1)
# Define function spaces and mixed (product) space
BDM = FunctionSpace(mesh, "BDM", 1)
DG = FunctionSpace(mesh, "DG", 0)
CG = FunctionSpace(mesh, "CG", 1)
W = MixedFunctionSpace([BDM, DG, CG])
# Define trial and test functions
(sigma, u, p) = TrialFunctions(W)
(tau, v, q) = TestFunctions(W)
#Define pressure boundary condition
p_in = 1
p_out = 0
noslip = DirichletBC(W.sub(1), (0),
"on_boundary && \
(x[1] <= 0.5 + DOLFIN_EPS | x[1] >= 1.0-DOLFIN_EPS)")
inflow = DirichletBC(W.sub(2), p_in, "x[0] <= 0.5 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(2), p_out, "x[0] >= 1.0 - DOLFIN_EPS*1000")
bcp = [noslip,inflow, outflow]
# Define f
#f = Expression("0")
f = Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)")
# Define variational form
a = (dot(sigma, tau) + div(tau)*u + div(sigma)*v)*dx(1) + inner(p,q)*dx(1) + u*q*dx(1)
L = f*v*dx(1)
# Compute solution
w = Function(W)
problem = LinearVariationalProblem(a, L, w, bcp)
solver = LinearVariationalSolver(problem)
solver.solve()
(sigma, u, p) = w.split()
# plot
plot(u, axes = True, interactive=True, title = "u")
plot(p, axes = True, interactive=True, title = "p")
I forgot the dx(0) in this term. But this was not the problem.
In the first part of the code (Stokes) I tried to write the no slip condition in the following way:
# Randbedingungen
def top_bottom(x, on_boundary):
return x[1] > 1.0 - DOLFIN_EPS or x[1] < DOLFIN_EPS
noslip = Constant((0.0,0.0))
bc0 = DirichletBC(W.sub(0), noslip, top_bottom)
p_in = 1
p_out = 0
inflow = DirichletBC(W.sub(1), p_in, "x[0] <= 0.0 + DOLFIN_EPS*1000")
outflow = DirichletBC(W.sub(1), p_out, "x[0] >= 0.5 - DOLFIN_EPS*1000")
bcp = [bc0, inflow, outflow]
# Definition f
f = Expression("(0.0, 0.0)")
# Variationsformulierung Stokes
a = inner(grad(u), grad(v))*dx(0) + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
But now I get the following error:
Shape mismatch: line 56, in <module> L = inner(f,v)*dx(0
Can anyone help? Thanks!
I think there are several mistakes here. In the first part of the code I think you are using Taylor-Hood elements to solve Stokes equation. If this us the case, then U should be:
U = VectorFunctionSpace(mesh, "CG", 2)
Also in this part of the code:
a = inner(grad(u), grad(v))*dx + div(v)*p*dx(0) + q*div(u)*dx(0)
L = inner(f,v)*dx(0)
I don't know why you are not using dx(0) for the first term. I encourage you to look at the demos at: http://fenicsproject.org/documentation/dolfin/dev/python/demo/index.html
You might get some more tips.

Categories