/[escript]/trunk/doc/examples/cookbook/example02.py
ViewVC logotype

Diff of /trunk/doc/examples/cookbook/example02.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 5287 by jfenwick, Wed Apr 9 05:41:57 2014 UTC revision 5288 by sshaw, Tue Dec 2 23:18:40 2014 UTC
# Line 1  Line 1 
1  from __future__ import division  from __future__ import division, print_function
 from __future__ import print_function  
2  ##############################################################################  ##############################################################################
3  #  #
4  # Copyright (c) 2009-2014 by University of Queensland  # Copyright (c) 2009-2014 by University of Queensland
# Line 39  matplotlib.use('agg') #It's just here fo Line 38  matplotlib.use('agg') #It's just here fo
38  from esys.escript import * # This imports everything from the escript library  from esys.escript import * # This imports everything from the escript library
39  from esys.escript.unitsSI import *  from esys.escript.unitsSI import *
40  from esys.escript.linearPDEs import LinearPDE # This defines LinearPDE as LinearPDE  from esys.escript.linearPDEs import LinearPDE # This defines LinearPDE as LinearPDE
 from esys.finley import Rectangle # This imports the rectangle domain function  
41  import pylab as pl #Plotting package.  import pylab as pl #Plotting package.
42  import numpy as np #Array package.  import numpy as np #Array package.
43  import os, sys #This package is necessary to handle saving our data.  import os, sys #This package is necessary to handle saving our data.
44    try:
45        from esys.finley import Rectangle
46        HAVE_FINLEY = True
47    except ImportError:
48        print("Finley module not available")
49        HAVE_FINLEY = False
50    
51  ########################################################MPI WORLD CHECK  ########################################################MPI WORLD CHECK
52  if getMPISizeWorld() > 1:  if getMPISizeWorld() > 1:
# Line 50  if getMPISizeWorld() > 1: Line 54  if getMPISizeWorld() > 1:
54      print("This example will not run in an MPI world.")      print("This example will not run in an MPI world.")
55      sys.exit(0)      sys.exit(0)
56    
57  #################################################ESTABLISHING VARIABLES  if HAVE_FINLEY:
58  #Domain related.      #################################################ESTABLISHING VARIABLES
59  mx = 1*m #meters - model length      #Domain related.
60  my = .1*m #meters - model width      mx = 1*m #meters - model length
61  ndx = 100 # mesh steps in x direction      my = .1*m #meters - model width
62  ndy = 1 # mesh steps in y direction - one dimension means one element      ndx = 100 # mesh steps in x direction
63  #PDE related      ndy = 1 # mesh steps in y direction - one dimension means one element
64  rho = 7874. *kg/m**3 #kg/m^{3} density of iron      #PDE related
65  cp = 449.*J/(kg*K) # J/Kg.K thermal capacity      rho = 7874. *kg/m**3 #kg/m^{3} density of iron
66  rhocp = rho*cp      cp = 449.*J/(kg*K) # J/Kg.K thermal capacity
67  kappa = 80.*W/m/K   # watts/m.Kthermal conductivity      rhocp = rho*cp
68  qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source      kappa = 80.*W/m/K   # watts/m.Kthermal conductivity
69  Tref = 20 * Celsius  # base temperature of the rod      qH=0 * J/(sec*m**3) # J/(sec.m^{3}) no heat source
70  T0 = 100 * Celsius # temperature at heating element      Tref = 20 * Celsius  # base temperature of the rod
71        T0 = 100 * Celsius # temperature at heating element
72  ################################################ESTABLISHING PARAMETERS  
73  t=0 * day  # our start time, usually zero      ################################################ESTABLISHING PARAMETERS
74  tend= 0.5 *day  # - time to end simulation      t=0 * day  # our start time, usually zero
75  outputs = 200 # number of time steps required.      tend= 0.5 *day  # - time to end simulation
76  h=(tend-t)/outputs #size of time step      outputs = 200 # number of time steps required.
77  #user warning statement      h=(tend-t)/outputs #size of time step
78  print("Expected Number of time outputs is: ", (tend-t)/h)      #user warning statement
79  i=0 #loop counter      print("Expected Number of time outputs is: ", (tend-t)/h)
80  #the folder to put our outputs in, leave blank "" for script path      i=0 #loop counter
81  save_path= os.path.join("data","example02")      #the folder to put our outputs in, leave blank "" for script path
82  #ensure the dir exists      save_path= os.path.join("data","example02")
83  mkDir(save_path, os.path.join(save_path,"tempT"))      #ensure the dir exists
84        mkDir(save_path, os.path.join(save_path,"tempT"))
85  ####################################################DOMAIN CONSTRUCTION  
86  rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)      ####################################################DOMAIN CONSTRUCTION
87  x=Solution(rod).getX()      rod = Rectangle(l0=mx,l1=my,n0=ndx, n1=ndy)
88  ###############################################ESCRIPT PDE CONSTRUCTION      x=Solution(rod).getX()
89  mypde=LinearPDE(rod)      ###############################################ESCRIPT PDE CONSTRUCTION
90  A=zeros((2,2))      mypde=LinearPDE(rod)
91  A[0,0]=kappa      A=zeros((2,2))
92  q=whereZero(x[0])      A[0,0]=kappa
93  mypde.setValue(A=A, D=rhocp/h, q=q, r=T0)      q=whereZero(x[0])
94  # ... set initial temperature ....      mypde.setValue(A=A, D=rhocp/h, q=q, r=T0)
95  T= T0*whereZero(x[0])+Tref*(1-whereZero(x[0]))      # ... set initial temperature ....
96        T= T0*whereZero(x[0])+Tref*(1-whereZero(x[0]))
97  # ... open a collector for the time marks and corresponding total energy  
98  t_list=[]      # ... open a collector for the time marks and corresponding total energy
99  E_list=[]      t_list=[]
100  # ... convert solution points for plotting      E_list=[]
101  plx = x.toListOfTuples()      # ... convert solution points for plotting
102  plx = np.array(plx) #convert to tuple to numpy array      plx = x.toListOfTuples()
103  plx = plx[:,0] #extract x locations      plx = np.array(plx) #convert to tuple to numpy array
104  ########################################################START ITERATION      plx = plx[:,0] #extract x locations
105  while t<tend:      ########################################################START ITERATION
106        i+=1      while t<tend:
107        t+=h            i+=1
108        mypde.setValue(Y=qH+rhocp/h*T)            t+=h
109        T=mypde.getSolution()            mypde.setValue(Y=qH+rhocp/h*T)
110        totE=integrate(rhocp*T)            T=mypde.getSolution()
111        print("time step %s at t=%e minutes completed. total energy = %e."%(i,t/minute,totE))            totE=integrate(rhocp*T)
112        t_list.append(t)            print("time step %s at t=%e minutes completed. total energy = %e."%(i,t/minute,totE))
113        E_list.append(totE)            t_list.append(t)
114              E_list.append(totE)
115        #establish figure 1 for temperature vs x plots  
116        tempT = T.toListOfTuples()            #establish figure 1 for temperature vs x plots
117        pl.figure(1) #current figure            tempT = T.toListOfTuples()
118        pl.plot(plx,tempT) #plot solution            pl.figure(1) #current figure
119        # add title            pl.plot(plx,tempT) #plot solution
120        pl.axis([0,mx,Tref*.9,T0*1.1])            # add title
121        pl.ylabel('Temperature (K)')            pl.axis([0,mx,Tref*.9,T0*1.1])
122        pl.xlabel("Length (m)")            pl.ylabel('Temperature (K)')
123        pl.title("Temperature across rod at time %e hours"%(t/hour))            pl.xlabel("Length (m)")
124        #save figure to file            pl.title("Temperature across rod at time %e hours"%(t/hour))
125        pl.savefig(os.path.join(save_path,"tempT", "rodpyplot%03d.png"%i))            #save figure to file
126        pl.clf() #clear figure            pl.savefig(os.path.join(save_path,"tempT", "rodpyplot%03d.png"%i))
127                    pl.clf() #clear figure
128  ###############################################################PLOTTING            
129  # plot the total energy over time:      ###############################################################PLOTTING
130  pl.figure(2)      # plot the total energy over time:
131  pl.plot(t_list,E_list)      pl.figure(2)
132  pl.title("Total Energy")      pl.plot(t_list,E_list)
133  pl.ylabel('Energy (W)')      pl.title("Total Energy")
134  pl.xlabel('Time (s)')      pl.ylabel('Energy (W)')
135  # pl.axis([0,max(t_list),0,max(E_list)*1.1])      pl.xlabel('Time (s)')
136  pl.savefig(os.path.join(save_path,"totE.png"))      # pl.axis([0,max(t_list),0,max(E_list)*1.1])
137  pl.clf()      pl.savefig(os.path.join(save_path,"totE.png"))
138        pl.clf()
139  #########################################################CREATE A MOVIE  
140  # compile the *.png files to create a*.avi video that show T change      #########################################################CREATE A MOVIE
141  # with time. This opperation uses linux mencoder. For other operating      # compile the *.png files to create a*.avi video that show T change
142  # systems it may be possible to use your favourite video compiler to      # with time. This opperation uses linux mencoder. For other operating
143  # convert image files to videos. To enable this step uncomment the      # systems it may be possible to use your favourite video compiler to
144  # following lines.      # convert image files to videos. To enable this step uncomment the
145        # following lines.
146  #os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\  
147  #w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \      #os.system("mencoder mf://"+save_path+"/tempT"+"/*.png -mf type=png:\
148  #example02tempT.avi")      #w=800:h=600:fps=25 -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o \
149        #example02tempT.avi")

Legend:
Removed from v.5287  
changed lines
  Added in v.5288

  ViewVC Help
Powered by ViewVC 1.1.26