Nätgenerering
Nätgenerering För större problem måste topologin skapas med hjälp av algoritmer Utgår ofta från en geometrisk beskrivning Kriterier kan sättas som anger hur tätt elemennätet skall genereras Area/Volymskriterier Explicit angivelse av antal element på ränder Resultat från tidigare beräkning kan ligga till grund för hur ett nät skall förbättras, adaptivt nät.
Nätgenering Strukturerad nätgenerering Regel finns för strukturen på nätet Koordinatsystem anger element position Ostrukturerad nätgenerering Algoritm fyller volym ytor med element Ofta begränsade till triangel eller tetraederelement
Ostrukturerat nät
Strukturerade nät
Strukturerade nät
Triangle 2 dimensionell nätgenererare för triangel element Skriven av Jonathan Shewchuck Kan generera nät från Punkter Geometri beskriven med linjer och punkter Kvalitetskriterier kan definieras: Max area Minsta vinkel
Triangle Geometri definition 0 0 1 5 5 4 1 4 3 3 2 2
Triangle Geometri definition l = 0.2 w = 0.05 h = 0.1 Index börjar på 0 vertices = array([ [0.0, h], [l, h], [l, 0.0], [l w, 0.0], [l w, h w], [0.0, h w] ]) segments = array([ [0,1,1], [1,2,1], [2,3,3], [3,4,1], [4,5,1], [5,0,2] ]) Kantmarkörer 1 anger inget randvillkor.
trimesh2d Nodkoordinater Elementtopologi Nodfrihetsgrader Randfrihetsgrader coords, edof, dofs, bdofs = trimesh2d(vertices, segments, maxarea=0.0001, dofspernode=2) Nodkoordinater Max area tillåten för triangelelement
trimesh2d maxarea= 0.0001 0 0 1 5 5 4 1 4 3 3 2 2
trimesh2d maxarea= 0.0005 0 0 1 5 5 4 1 4 3 3 2 2
trimesh2d maxarea= 0.00005 0 0 1 5 5 4 1 4 3 3 2 2
Randvillkor def applybc(boundarydofs, bcpresc, bcval, marker, value=0.0, dimension=0): """ Apply boundary condition to bcpresc and bcval matrices. Parameters: """ boundarydofs Dictionary with boundary dofs. bcpresc 1 dim integer array containing prescribed dofs. bcval 1 dim float array containing prescribed values. marker Boundary marker to assign boundary condition. value Value to assign boundary condition. If not giben 0.0 is assigned. dimension dimension to apply bc. 0 all, 1 x, 2 y bc, bcval = applybc(bdofs,bc,bcval,2,0.0)
Randvillkor def applyforce(boundarydofs, f, marker, value=0.0, dimension=0): """ Apply boundary condition to bcpresc and bcval matrices. Parameters: """ boundarydofs Dictionary with boundary dofs. f force matrix. marker Boundary marker to assign boundary condition. value Value to assign boundary condition. If not giben 0.0 is assigned. dimension dimension to apply force. 0 all, 1 x, 2 y applyforce(bdofs,f,3,10e3,2)
Uppritning av elementnät def eldraw2(ex, ey): """ Draw elements in 2d. Parameters: ex, ey plotpar Element coordinates (not implemented yet) """
Uppritning av elementvariabler def eliso2(ex, ey, showmesh=false): """ Draw elements in 2d. Parameters: ex, ey showmesh Element coordinates Display element mesh """
Uppritning av elementförskjutning def eldisp2(ex, ey, ed, magnfac=0.1, showmesh=false)
Objektorientering
Klasser Grupperar data och funktioner till en enhet Funktioner i klassen opererar på data i klassen Möjligör enklare och mer lättförstådd kod Kan utökas i framtiden utan att existerande kod behöver ändras Alla datatyper i python är klasser
Exempel på klass Konstruktor. Anropas när klassen instantieras (skapas) Alla klassfunktioner har self som första parameter, vilken är en variabel som pekar på den egna instansen. Skickas automatiskt till funktionerna. class Point: def init (self, x, y): self._x = x self._y = y def show(self): print "x =", self._x, ", y =", self._y def setposition(self, x, y): self._x = x self._y = y def getposition(self): return self._x, self._y p1 = Point(0.0, 0.0) p1.show() p1.setposition(2.0, 3.0) p1.show() x = 0.0, y = 0.0 x = 2.0, y = 3.0 x = 1.0, y = 2.0 1.0 2.0 p2 = Point(1.0, 2.0) p2.show() x, y = p2.getposition() print x, y
Arv Nya klasser kan ärva funktionalitet från andra klasser Funktionalitet kan läggas till utan att påverka existerande x = kod 0.0, y = 0.0x = 2.0, y = 3.0x = 1.0, y = 2.01.0 2.0
Exempel på arv class Circle(Point): def init (self, x, y, radius): Point. init (self, x, y) self._radius = radius Anropa Points konstruktor def show(self): x, y = self.getposition() print "x =", self._x, ", y =", self._y, ", radius =", self._radius def setradius(self, radius): self._radius = radius def getradius(self): return self._radius def getarea(self): return pi*self._radius**2 if name == " main ": c1 = Circle(0.0, 0.0, 1.0) c1.setposition(1.0, 2.0) c1.show() print "area =", c1.getarea() setposition från Point
Visualisation in Python
Outline 2D Tkinter Canvas widget Python Gnuplot matplotlib 3D PyOpenGL vpython Visualisation Toolkit VTK
Python Gnuplot Python interface to Gnuplot Allows direct plotting of Python and Numeric data types in Gnuplot Depends on an external application Does not integrate with GUI toolkits
Examples
Code import Gnuplot from Numeric import * points1 = [[0,1.2],[1.1,5.2],[2, 0.3]] x = arrayrange(0.0, 1.8, 0.1) y = 3 2*x + 2*sin(4*x) points2 = transpose(array([x,y])) gnuplot = Gnuplot.Gnuplot() d1 = Gnuplot.Data(points1, with='lines', title='points1') d2 = Gnuplot.Data(points2, with='linespoints', title='points2') d3 = Gnuplot.Data(x, y, with='linespoints', title='x and y') gnuplot.title('simple Python Gnuplot demo') gnuplot.xlabel('t') gnuplot.plot(d1, d2) gnuplot.hardcopy(filename='tmp.ps', enhanced=1, mode='eps', color=0, fontname='times Roman', fontsize=28) gnuplot('set term png small') gnuplot('set output "tmp.png"') gnuplot.plot(d1, d2, d3)
matplotlib Python module for 2D plotting No dependencies on external applications Close to MATLAB syntax Many backends for export Integrates into wxwindows, Tkinter etc. Supports Numeric
Examples
Simple from pylab import * plot([1,2,3,4]) show()
x and y series from pylab import * plot([1,2,3,4],[1,4,9,16]) show()
axis and saving from pylab import * plot([1,2,3,4], [1,4,9,16], 'ro') axis([0, 6, 0, 20]) savefig('secondfig.png') show()
Setting properties from pylab import * from Numeric import * x = arange(0.0, 2*pi, 0.1) y = sin(x) x1 = arange(0.0, 2*pi, 0.1) y1 = cos(x1) x2 = arange(0.0, 2*pi, 0.1) y2 = sin(2*x2) plot(x, y, linewidth=2.0) line, = plot(x, y, 'o') line.set_antialiased(false) # turn off antialising lines = plot(x1, y1, x2, y2) set(lines, color='r', linewidth=2.0) set(lines, 'color', 'r', 'linewidth', 2.0) show()
Setting properties
Subplots from pylab import * def f(t): s1 = cos(2*pi*t) e1 = exp( t) return multiply(s1,e1) t1 = arange(0.0, 5.0, 0.1) t2 = arange(0.0, 5.0, 0.02) figure(1) subplot(211) plot(t1, f(t1), 'bo', t2, f(t2), 'k') subplot(212) plot(t2, cos(2*pi*t2), 'r ') show()
Subplots
Multiple figures from pylab import * figure(1) # the first figure plot([1,2,3]) figure(2) # a second figure plot([4,5,6]) figure(1) # figure 1 current title('easy as 1,2,3') # figure 1 title show()
Multiple figures
Fonts from pylab import * font = {'fontname' : 'Courier', 'color' : 'r', 'fontweight' : 'bold', 'fontsize' : 11} plot([1,2,3]) title('a title', font, fontsize=12) text(0.5, 2.5, 'a line', font, color='k') xlabel('time (s)', font) ylabel('voltage (mv)', font) show()
Fonts
Mathematical text from pylab import * t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plot(t,s) title(r'$\alpha_i > \beta_i$', fontsize=20) text(1, 0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20) text(0.6, 0.6, r'$\cal{a}\rm{sin}(2 \omega t)$', fontsize=20) xlabel('time (s)') ylabel('volts (mv)') savefig('mathtext_tut', dpi=50) show()
Mathematical text
Plot window controls
vpython 3D graphics module for Python Easy to use Real time visualisation Not for everything, but a good start
A simple program from visual import * redbox = box(pos=vector(4,2,3), size=(8.,4.,6.), color=color.red) greenball = sphere(pos=vector(4,7,3), radius=2, color=color.green)
Viewing the scene Right button
Viewing the scene Right button
Viewing the scene left and right button
Animation from visual import * ball = sphere(pos=( 5,0,0), radius=0.5, color=color.red) wallr = box(pos=(6,0,0),size=(0.2,4,4),color=color.green) walll = box(pos=( 6,0,0),size=(0.2,4,4),color=color.green) dt = 0.05 ball.velocity = vector(2., 0., 0.) while True: rate(100) # Not more than 100 times/s ball.pos = ball.pos + ball.velocity*dt if ball.x>wallr.x: ball.velocity.x = ball.velocity.x if ball.x<walll.x: ball.velocity.x = ball.velocity.x
Animation
Visualising velocity direction from visual import * ball = sphere(pos=( 5,0,0), radius=0.5, color=color.red) wallr = box(pos=(6,0,0),size=(0.2,4,4),color=color.green) walll = box(pos=( 6,0,0),size=(0.2,4,4),color=color.green) dt = 0.05 ball.velocity = vector(2., 1.5, 0.) ballvel = arrow(pos=ball.pos, axis=ball.velocity, color=color.yellow) while True: rate(100) # Not more than 100 times/s ball.pos = ball.pos + ball.velocity*dt if ball.x>wallr.x: ball.velocity.x = ball.velocity.x if ball.x<walll.x: ball.velocity.x = ball.velocity.x ballvel.pos = ball.pos ballvel.axis = ball.velocity
Visualising velocity direction
Adding a trail from visual import * ball = sphere(pos=( 5,0,0), radius=0.5, color=color.red) wallr = box(pos=(6,0,0),size=(0.2,4,4),color=color.green) walll = box(pos=( 6,0,0),size=(0.2,4,4),color=color.green) dt = 0.05 ball.velocity = vector(2., 1.5, 0.) ball.trail = curve(color=ball.color) ballvel = arrow(pos=ball.pos, axis=ball.velocity, color=color.yellow) while True: rate(100) # Not more than 100 times/s ball.pos = ball.pos + ball.velocity*dt if ball.x>wallr.x: ball.velocity.x = ball.velocity.x if ball.x<walll.x: ball.velocity.x = ball.velocity.x ballvel.pos = ball.pos ballvel.axis = ball.velocity ball.trail.append(pos=ball.pos)
Adding a trail
A complete example from visual import * ball = sphere(pos=( 5,0,0), radius=0.5, color=color.red) wallr = box(pos=(6,0,0),size=(0.2,12,12),color=color.green) walll = box(pos=( 6,0,0),size=(0.2,12,12),color=color.green) wallt = box(pos=(0,6,0),size=(12,0.2,12),color=color.green) wallb = box(pos=(0, 6,0),size=(12,0.2,12),color=color.green) dt = 0.05 ball.velocity = vector(2., 1.5, 1.5) ball.trail = curve(color=ball.color) ballvel = arrow(pos=ball.pos, axis=ball.velocity, color=color.yellow) while True: rate(100) # Not more than 100 times/s ball.pos = ball.pos + ball.velocity*dt if ball.x>wallr.x: ball.velocity.x = ball.velocity.x if ball.x<walll.x: ball.velocity.x = ball.velocity.x if ball.y>wallt.y: ball.velocity.y = ball.velocity.y if ball.y<wallb.y: ball.velocity.y = ball.velocity.y if ball.z>6: ball.velocity.z = ball.velocity.z if ball.z< 6: ball.velocity.z = ball.velocity.z ballvel.pos = ball.pos ballvel.axis = ball.velocity ball.trail.append(pos=ball.pos)
A complete example
Other examples
Visualisation Toolkit Open Source 3d graphics toolkit Language bindings to C++, Java, Python, Tcl Implements most visualisation algorithms available Uses a the Visualisation network concept Large and complex to use Easier in Python : )
Simple example # load VTK extensions from vtkpython import * # create a rendering window and renderer ren = vtkrenderer() renwin = vtkrenderwindow() renwin.addrenderer(ren) renwin.setsize(300,300) iren = vtkrenderwindowinteractor() iren.setrenderwindow(renwin) # create an actor and give it cone geometry cone = vtkconesource() cone.setresolution(8) conemapper = vtkpolydatamapper() conemapper.setinput(cone.getoutput()) coneactor = vtkactor() coneactor.setmapper(conemapper) # assign our actor to the renderer ren.addactor(coneactor) # enable user interface interactor iren.initialize() iren.start()
Simple example
More advanced examples
2D Graphics using OpenGL
OpenGL Programmeringsgränssnitt (API) för hårdvarustödd 2D/3D grafik Plattformsoberoende Generellt Flexibelt Låg nivå...
Uppritning Uppritning sker med 10 grafiska primitiver Alla skapas på samma sätt # Draw 4 points glbegin(gl_points) glvertex2i( 50, 50) glvertex2i( 50, 50) glvertex2i( 50, 50) glvertex2i( 50, 50) glend()
GL_POINTS v1 v0 v2 v3 v4
GL_LINES v6 v3 v0 v2 v4 v1 v5 v7
GL_LINE_STRIP v1 v2 v0 v3 v6 v5 v4
GL_LINE_LOOP v1 v2 v0 v3 v6 v5 v4
GL_TRIANGLES v1 v3 v4 v0 v2 v5
GL_TRIANGLE_STRIP v0 v2 v3 v1 v4
GL_TRIANGLE_FAN v1 v2 v3 v0 v4
GL_QUADS v1 v2 v5 v6 v0 v3 v4 v7
GL_QUAD_STRIP v1 v3 v5 v7 v0 v2 v4 v6
GL_POLYGON v5 v4 v0 v3 v1 v2
Egenskaper för primitiver Linjer och Punkter Utanför glbegin()/glend() Linjetjocklek, gllinewidth(2.0) Punktstorlek Färg Ges på vertex nivå Innanför glbegin()/glend() Ges i RGB, där 1.0 är max intensitet och 0.0 är min intensitet Interpolering mellan vertex
Egenskaper för primitiver # Sätt linjebredden gllinewidth(2.0) glbegin(gl_lines) glvertex2i( 1000,0); glvertex2i(1000,0); glvertex2i(0, 1000); glvertex2i(0, 1000); glend() # Sätt punktstorleken glpointsize(5) glbegin(gl_points) glvertex2i( 50, 50) glvertex2i( 50, 50) glvertex2i( 50, 50) glvertex2i( 50, 50) glend()
Egenskaper för primitiver
Egenskaper för primitiver glbegin(gl_quads) glcolor3f(1.0, 0.0, 0.0) # Röd färg glvertex2i(-50, -50) glcolor3f(0.0, 1.0, 0.0) # Grön färg glvertex2i( 50, -50) glcolor3f(0.0, 0.0, 1.0) # Blå färg glvertex2i( 50, 50) glcolor3f(1.0, 1.0, 0.0) # Gul färg glvertex2i(-50, 50) glend()
Egenskaper för primitiver
Geometriska transformationer Transformationer viktiga i datorgrafik Translation Rotation Skalning OpenGL Transformationsmatriser i hårdvara Modell glmatrixmode(gl_modelview) Projektion glmatrixmode(gl_projection)
Initiering av matriser # Initiera modelview matrisen till enhetsmatrisen glmatrixmode(gl_modelview) glloadidentity()
Translation Translaterar koordinatsystem gltranslatef(x, y, z) Aktuell matris multipliceras med en translationsmatris
Translation gltranslatef(40.0, 40.0, 0.0) glbegin(gl_quads) glcolor3f(1.0, 1.0, 1.0) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glend()
Translation
Rotation Rotation av koordinatsystem glrotatef(angle, axis_x, axis_y, axis_z) Högerhandsregel Positiv Z axel ut ur skärm
Rotation gltranslatef(40.0, 40.0, 0.0) glrotatef(30.0, 0.0, 0.0, 1.0) glbegin(gl_quads) glcolor3f(1.0, 1.0, 1.0) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glend()
Rotation
Skalning Skalar aktuell koordinatsystem glscalef(scale_x, scale_y, scale_z)
Skalning gltranslatef(40.0, 40.0, 0.0) glrotatef(30.0, 0.0, 0.0, 1.0) glscalef(2.0, 2.0, 0.0) glbegin(gl_quads) glcolor3f(1.0, 1.0, 1.0) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glvertex2i( 20, 20) glend()
Skalning
Problem med aktuell metod Matriser måste hela tiden initieras Svårt att implementera hierarkiska transformationer Många och upprepade matrismultiplikationer
OpenGL Matrisstack Stapel av matriser Översta matrisen är den aktuella Läggs en matris till stapeln tilldelas den den aktuella matrisen glpushmatrix() Matris kan förkastas med glpopmatrix() Reducerar matrismultiplikationerna Snabbar upp koden Implementerad i hårdvara
glpushmatrix()/glpopmatrix() glpushmatrix() gltranslatef(40.0, 40.0, 0.0) glrotatef(30.0, 0.0, 0.0, 1.0) glbegin(gl_quads) glcolor3f(1.0, 1.0, 1.0) glvertex2i(-20, -20) glvertex2i( 20, -20) glvertex2i( 20, 20) glvertex2i(-20, 20) glend() glpopmatrix() glpushmatrix() gltranslatef(-40.0, -40.0, 0.0) glrotatef(-30.0, 0.0, 0.0, 1.0) glbegin(gl_quads) glcolor3f(1.0, 1.0, 1.0) glvertex2i(-20, -20) glvertex2i( 20, -20) glvertex2i( 20, 20) glvertex2i(-20, 20) glend() glpopmatrix()
glpushmatrix()/glpopmatrix()
Uppritning i skärmbuffert Måste rensas för varje uppritning glclear(gl_color_buffer_bit) Bakgrundsfärg glclearcolor(red, green, blue) Dubbelbuffring Minskar flimmer Uppritning i dold buffer Växling mellan synlig/dold
Projektion och skärmvy Projektion mappar modellkoordinater till skärmen glmatrixmode(gl_projection) 2D = Ortografisk projektion gluortho2d(left, right, top, bottom)
Initiering av projektionsmatris # Initiera projektionsmatris glmatrixmode(gl_projection) glloadidentity() # Skapa en projektion som mappar koordinater # direkt mot skärmkoordinater. gluortho2d(0,width, 0, height) # Initiera modelview matrisen till enhetsmatrisen glmatrixmode(gl_modelview) glloadidentity()
Skärmvy Anger var i fönstret uppritningen skall ske glviewport(x,y,width,height) Medger uppritning i flera vyer för samma fönster Måste uppdateras då fönstret ändrar storlek
OpenGL i Python PyOpenGL Bindningar för OpenGL och relaterade projekt GLU, GLUT, GLE etc # * coding: cp1252 * from OpenGL.GL import * from OpenGL.GLU import * import sys, time