Esempio n. 1
0
def superspud(filename, cmd):
  libspud.load_options(filename)
  r = None
  if hasattr(cmd, '__iter__'):
    for c in cmd:
      exec("try: r = " + c + "\nexcept libspud.SpudNewKeyWarning: pass")
  else:
    exec("try: r = " + cmd + "\nexcept libspud.SpudNewKeyWarning: pass")
  libspud.clear_options()
  return r
Esempio n. 2
0
def superspud(filename, cmd):
    libspud.load_options(filename)
    r = None
    if hasattr(cmd, '__iter__'):
        for c in cmd:
            exec "try: r = " + c + "\nexcept libspud.SpudNewKeyWarning: pass"
    else:
        exec "try: r = " + cmd + "\nexcept libspud.SpudNewKeyWarning: pass"
    libspud.clear_options()
    return r
Esempio n. 3
0
def Main():
	#Import the command line arguments and return them
	parser = argparse.ArgumentParser(description='input a file name')
	parser.add_argument('--v','--verbose', action='store_true', help="Verbose output: mainly graphics at each time step", default=False)
	parser.add_argument('file_name', help='Insert the file name of the simulation you wish to run. It should end with.osml')
	args = parser.parse_args()
	libspud.clear_options()
	file_name = args.file_name
	Verbose = args.v

	return file_name, Verbose
	def test17(self):
		with self.assertRaises(SystemExit):
			#should be an osml file
			libspud.clear_options()
			try: 
				libspud.load_options('test17.osml')
			except:
				print "This file doesn't exist or is the wrong file type. It should be a .osml file"
				sys.exit()

			try:
				start = float(libspud.get_option('/diffusion_model/timestepping/start_time',))
			
				end = float(libspud.get_option('/diffusion_model/timestepping/end_time'))

				time_step = float(libspud.get_option('/diffusion_model/timestepping/timestep'))

				mesh_int = int(libspud.get_option('/diffusion_model/mesh/initial_mesh_size'))

				alpha = float(libspud.get_option('/diffusion_model/model_parameters/diffusion_coefficient'))

				initial_conditions = str(libspud.get_option('/diffusion_model/model_parameters/initial_conditions'))
			except: 
				print 'The information provided was incomplete, please recreate the file'
				sys.exit()
			print start
			print end
			print time_step
			print mesh_int
			print alpha
			print initial_conditions

			
			#create a simple testcase
			model = SedimentModel()
			mesh = UnitSquareMesh(mesh_int,mesh_int)
			model.set_mesh(mesh)
			init_cond = Expression(initial_conditions) # simple slope
			init_sed = Expression('x[0]') # this gives
			# total of above gives a slope of 0 to 2 (over the unit square)
			model.set_initial_conditions(init_cond,init_sed)
			model.set_end_time(end)
			model.set_diffusion_coeff(alpha)
			model.init()
			model.solve()
			# answer should be 1 everywhere
			plot(model.get_total_height(),interactive=True)
			answer = model.get_total_height_array()
Esempio n. 5
0
    def geterrors(self, checkpoint_file):
        """
        reads checkpoint file and accompanying .xml solution file and
        extracts the time, and calculates shape and phase errors for the solitary waves
        """
        # this seems to be a dangerous thing but I'm going to clear
        # the option then load the new ones from the checkpoint file
        libspud.clear_options()
        libspud.load_options(checkpoint_file)
        time = libspud.get_option("/timestepping/current_time")
        dt = libspud.get_option(
            "/timestepping/timestep/coefficient/type/rank/value/constant")
        print "t=", time, " dt=", dt

        #load xml file
        xml_file = checkpoint_file.replace("checkpoint", self.system_name)
        xml_file = xml_file.replace("tfml", "xml")

        # load function and extract porosity
        u = df.Function(self.functionspace, xml_file)
        fields = u.split(deepcopy=True)
        f = fields[self.f_index]

        #initialize Error Object
        err = WaveError(f, self.swave, self.x0, self.h)

        #minimize error using fsolve
        #out = err.min_grad(delta_0)
        delta_0 = np.zeros(self.dim)
        out = err.min_grad_z(delta_0[-1])

        delta = out[0]
        err_min = out[1]
        elapsed_time = out[2]

        L2_f = err.L2_f
        rel_error = err_min / L2_f
        c_rel_error = np.sign(delta) * np.sqrt(np.dot(
            delta, delta)) / (self.swave.c * time)

        #print "delta=",delta, " err =",err_min, " elapsed_time=",elapsed_time
        #print "L2_f=",L2_f, "rel_err =",rel_error, " c_rel_error=",c_rel_error
        #print "L2_error=",err_min," delta=",delta," rel_error=",rel_error," c_rel_error=",c_rel_error
        return [time, dt, err_min, delta, rel_error, c_rel_error, elapsed_time]
Esempio n. 6
0
    def geterrors(self,checkpoint_file):
        """
        reads checkpoint file and accompanying .xml solution file and
        extracts the time, and calculates shape and phase errors for the solitary waves
        """
        # this seems to be a dangerous thing but I'm going to clear
        # the option then load the new ones from the checkpoint file
        libspud.clear_options()
        libspud.load_options(checkpoint_file)
        time = libspud.get_option("/timestepping/current_time")
        dt = libspud.get_option("/timestepping/timestep/coefficient/type/rank/value/constant")
        print "t=",time," dt=", dt
        
        #load xml file
        xml_file = checkpoint_file.replace("checkpoint",self.system_name)
        xml_file = xml_file.replace("tfml","xml")
        
        
        # load function and extract porosity
        u = df.Function(self.functionspace,xml_file)
        fields = u.split(deepcopy = True)
        f = fields[self.f_index]
        
        
        #initialize Error Object
        err = WaveError(f,self.swave,self.x0,self.h)
        
        #minimize error using fsolve
        #out = err.min_grad(delta_0)
        delta_0=np.zeros(self.dim)
        out = err.min_grad_z(delta_0[-1])
        
        delta = out[0]
        err_min = out[1]
        elapsed_time = out[2]
        
        L2_f= err.L2_f
        rel_error = err_min/L2_f
        c_rel_error = np.sign(delta)*np.sqrt(np.dot(delta,delta))/(self.swave.c*time)

        #print "delta=",delta, " err =",err_min, " elapsed_time=",elapsed_time
        #print "L2_f=",L2_f, "rel_err =",rel_error, " c_rel_error=",c_rel_error
        #print "L2_error=",err_min," delta=",delta," rel_error=",rel_error," c_rel_error=",c_rel_error
        return [time,dt,err_min,delta,rel_error,c_rel_error,elapsed_time]
Esempio n. 7
0
def prepare_inputs_for_forward_model(k):
    ''' make directory to run the fowrard model in, copy across the input files and
        modify the time step in flml so the forward model will run just for one time step'''             
    # make a directory to run the code in and copy across input files
    cwd = os.getcwd()
    input_file_name = "fwd_model.flml" 
#             print "files in cwd"
#             for files in os.listdir(cwd):
#                print files
    if not os.path.isdir( str(k) ):
        print "attempting to mkdir" 
        os.mkdir(str(k))
        os.system('cp *.msh ' + str(k))
        os.system('cp *_' +str(k)+ '_checkpoint* ' + str(k))

        os.chdir(str(k))

        # modify the checkpoint file times
        for files in os.listdir('./'):
            # get the name of the checkpoint flml     
            if files.endswith(str(k)+"_checkpoint.flml"):
#               pos = files.rfind('.')
                checkpoint_file_name = files
#               print "checkpoint fname", checkpoint_file_name

                # load options from checkpoint file
                libspud.load_options(checkpoint_file_name)

                # change the name of the output 
                libspud.set_option('/simulation_name','2d_canyon')

                # change the final time so it runs from t_k to t_k+1 only
                t0 = libspud.get_option('/timestepping/current_time')
                dt = libspud.get_option('/timestepping/timestep')
                libspud.set_option('/timestepping/finish_time',t0+dt)
                # could check with vtu's that these are the correct times

                # rename input file
                libspud.write_options(input_file_name)
                libspud.clear_options()

    os.chdir(cwd)

    return input_file_name
Esempio n. 8
0
def Main():
    #Import the command line arguments and return them
    parser = argparse.ArgumentParser(description='input a file name')
    parser.add_argument(
        '--v',
        '--verbose',
        action='store_true',
        help="Verbose output: mainly graphics at each time step",
        default=False)
    parser.add_argument(
        'file_name',
        help=
        'Insert the file name of the simulation you wish to run. It should end with.osml'
    )
    args = parser.parse_args()
    libspud.clear_options()
    file_name = args.file_name
    Verbose = args.v

    return file_name, Verbose
Esempio n. 9
0
    def __init__(self,
                 tfml_file,
                 system_name='magma',
                 p_name='Pressure',
                 f_name='Porosity',
                 c_name='c',
                 n_name='n',
                 m_name='m',
                 d_name='d',
                 N_name='N',
                 h_squared_name='h_squared',
                 x0_name='x0'):
        """read the tfml_file and use libspud to populate the internal parameters

        c: wavespeed
        n: permeability exponent
        m: bulk viscosity exponent
        d: wave dimension
        N: number of collocation points
        x0: coordinate wave peak
        h_squared:  the size of the system in compaction lengths
                    squared (h/delta)**2
        """
        # initialize libspud and extract parameters
        libspud.clear_options()
        libspud.load_options(tfml_file)
        # get model dimension
        self.dim = libspud.get_option("/geometry/dimension")
        self.system_name = system_name
        # get solitary wave parameters
        path = "/system::" + system_name + "/coefficient::"
        scalar_value = "/type::Constant/rank::Scalar/value::WholeMesh/constant"
        vector_value = "/type::Constant/rank::Vector/value::WholeMesh/constant::dim"
        c = libspud.get_option(path + c_name + scalar_value)
        n = int(libspud.get_option(path + n_name + scalar_value))
        m = int(libspud.get_option(path + m_name + scalar_value))
        d = float(libspud.get_option(path + d_name + scalar_value))
        N = int(libspud.get_option(path + N_name + scalar_value))
        self.h = np.sqrt(
            libspud.get_option(path + h_squared_name + scalar_value))
        self.x0 = np.array(libspud.get_option(path + x0_name + vector_value))
        self.swave = SolitaryWave(c, n, m, d, N)
        self.rmax = self.swave.r[-1]
        self.tfml_file = tfml_file

        # check that d <= dim
        assert (d <= self.dim)

        # sort out appropriate index for calculating distance r
        if d == 1:
            self.index = [self.dim - 1]
        else:
            self.index = range(0, int(d))

        # check that the origin point is the correct dimension
        assert (len(self.x0) == self.dim)

        #read in information for constructing Function space and dolfin objects
        # get the mesh parameters and reconstruct the mesh
        meshtype = libspud.get_option("/geometry/mesh/source[0]/name")
        if meshtype == 'UnitSquare':
            number_cells = libspud.get_option(
                "/geometry/mesh[0]/source[0]/number_cells")
            diagonal = libspud.get_option(
                "/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.UnitSquareMesh(number_cells[0], number_cells[1],
                                     diagonal)
        elif meshtype == 'Rectangle':
            x0 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/lower_left")
            x1 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/upper_right")
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/number_cells")
            diagonal = libspud.get_option(
                "/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.RectangleMesh(x0[0], x0[1], x1[0], x1[1],
                                    number_cells[0], number_cells[1], diagonal)
        elif meshtype == 'UnitCube':
            number_cells = libspud.get_option(
                "/geometry/mesh[0]/source[0]/number_cells")
            mesh = df.UnitCubeMesh(number_cells[0], number_cells[1],
                                   number_cells[2])
        elif meshtype == 'Box':
            x0 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/lower_back_left")
            x1 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/upper_front_right")
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/number_cells")
            mesh = df.BoxMesh(x0[0], x0[1], x0[2], x1[0], x1[1], x1[2],
                              number_cells[0], number_cells[1],
                              number_cells[2])
        elif meshtype == 'UnitInterval':
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::UnitInterval/number_cells")
            mesh = df.UnitIntervalMesh(number_cells)
        elif meshtype == 'Interval':
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/number_cells")
            left = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/left")
            right = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/right")
            mesh = df.IntervalMesh(number_cells, left, right)
        elif meshtype == 'File':
            mesh_filename = libspud.get_option(
                "/geometry/mesh::Mesh/source::File/file")
            print "tfml_file  = ", self.tfml_file, "mesh_filename=", mesh_filename
            mesh = df.Mesh(mesh_filename)
        else:
            df.error("Error: unknown mesh type " + meshtype)

        #set the functionspace for n-d solitary waves
        path = "/system::" + system_name + "/field::"
        p_family = libspud.get_option(path + p_name +
                                      "/type/rank/element/family")
        p_degree = libspud.get_option(path + p_name +
                                      "/type/rank/element/degree")
        f_family = libspud.get_option(path + f_name +
                                      "/type/rank/element/family")
        f_degree = libspud.get_option(path + f_name +
                                      "/type/rank/element/degree")
        pe = df.FiniteElement(p_family, mesh.ufl_cell(), p_degree)
        ve = df.FiniteElement(f_family, mesh.ufl_cell(), f_degree)
        e = pe * ve
        self.functionspace = df.FunctionSpace(mesh, e)

        #work out the order of the fields
        for i in xrange(
                libspud.option_count("/system::" + system_name + "/field")):
            name = libspud.get_option("/system::" + system_name + "/field[" +
                                      ` i ` + "]/name")
            if name == f_name:
                self.f_index = i
            if name == p_name:
                self.p_index = i
Esempio n. 10
0
def data_assimilation(opal_options):

   global Model_updated, iter_count

   # functions used within data_assimilation: J() and gradJ()
   def J(v):
	global Model_updated, iter_count

        iter_count = iter_count + 1

        vT = np.transpose(v)
        vTv = np.dot(vT,v)
        Vv = np.dot(V,v)
        HVv = np.dot(H,Vv)

        # we need the model results - check if these are already available, if not, run the forward model with Vv as the input
        if Model_updated:
             print "in J(): using pre-exiting forward model model solution"
             Model_updated = False
        else:
             print "in J(): updating the forward model solution"

             # prepare directory and input files for forward model
             input_file_name = prepare_inputs_for_forward_model(k)

             # modify initial condition of tracer
             field = modify_initial_conditions_at_tk(k,Vv)

             # run forward model
             run_forward_model_tk(k,opal_options.executable,input_file_name)

             Model_updated = True

        # retrieve the forward model results, MVv
        path_to_vtu_file = str(k) + '/2d_canyon_1.vtu'
        vtu_data = vtktools.vtu(path_to_vtu_file)
        MVv = vtu_data.GetScalarField(field)
#        print "J(): MVv[0:10]", MVv[0:10]

        ##MVv = np.dot(M,Vv)
        HMVv = np.dot(H,MVv)
        Jmis = np.subtract(HVv,d)
        JmisM = np.subtract(HMVv,d)
        invR = np.linalg.inv(R)
        JmisT = np.transpose(Jmis)
        JmisMT = np.transpose(JmisM)
        RJmis = np.dot(invR,JmisT)
        RJmisM = np.dot(invR,JmisMT)
        J1 = np.dot(Jmis,RJmis)
        JM1 = np.dot(JmisM,RJmisM)

        Jv = (vTv + J1 + JM1) / 2

        return Jv    
    
###############################################
#######         GRADIENT OF J          ########
###############################################


   def gradJ(v):
        global Model_updated

        Vv = np.dot(V,v)
        HVv = np.dot(H,Vv)

        # CODE COPIED FROM J() ###########################################
        # we need the model results - check if these are already available, 
        # if not, run the forward model with Vv as the input
        if Model_updated:
             print "in gradJ(): using pre-exiting forward model model solution"
             Model_updated = False
        else:
             print "in gradJ(): updating the forward model solution"

             # prepare directory and input files for forward model
             input_file_name = prepare_inputs_for_forward_model(k)

             # modify initial condition of tracer
             field = modify_initial_conditions_at_tk(k,Vv)

             # run forward model
             run_forward_model_tk(k,opal_options.executable,input_file_name)

             Model_updated = True

        # END OF CODE COPIED FROM J() ###########################################

        # MVv = np.dot(M,Vv)
        # retrieve the forward model results, MVv
        path_to_vtu_file = str(k) + '/2d_canyon_1.vtu'
        vtu_data = vtktools.vtu(path_to_vtu_file)
        MVv = vtu_data.GetScalarField('Tracer') #vtu_data.GetScalarField(field)
#        print "gradJ: MVv[0:10]", MVv[0:10]

        HMVv = np.dot(H,MVv)
        Jmis = np.subtract(HVv,d)
        JmisM = np.subtract(HMVv,d)
        invR = np.linalg.inv(R)
        RJmis = np.dot(invR,Jmis)
        RJmisM = np.dot(invR,JmisM)
        HT = np.transpose(H)
        g1 = np.dot(HT,RJmis)
        g1M = np.dot(HT,RJmisM)
        ##MT = ... MT(g1M) = from importance map t_k+1 , map at t_k
        VT = np.transpose(V)
        ##VTMT = np.dot(VT,MT)
        g2 = np.dot(VT,g1)


        ggJ = v + g2 ##+ VTMT

        return ggJ

    #print "exectuable which has been selected:", opal_options.executable
    
    # ......... read the input .........
    
###############################################
## TRUNCATION AND REGULARIZATION PARAMETERS ###
###############################################
   # inputs
   n = 852
   lam = 1  #REGULARIZATION PARAMETER
   m = 45  #TRUNCATION PARAMETER FROM buildV.py
   xB = np.ones(n)
   y = np.ones(n)

   k = 8 # time at which observation is known

###############################################
########  INTIAL RUN OF FLUIDITY #############
###############################################
   # put checkpointing on for file k
   print "name of fwd_input_file", opal_options.data_assimilation.fwd_input_file
   libspud.load_options('2d_canyon.flml')#(opal_options.data_assimilation.fwd_input_file)

   # don't need these currently
   if libspud.have_option('io/checkpointing/checkpoint_at_start'):
       libspud.delete_option('io/checkpointing/checkpoint_at_start')
   if libspud.have_option('io/checkpointing/checkpoint_at_end'):
       libspud.delete_option('io/checkpointing/checkpoint_at_end')
   if libspud.have_option('io/checkpointing/checkpoint_period_in_dumps'):
       libspud.set_option('io/checkpointing/checkpoint_period_in_dumps',k)
   else:
      print "checkpoint_period_in_dumps option missing from xml file"
      sys.exit(0)

   libspud.write_options(opal_options.data_assimilation.fwd_input_file)
   libspud.clear_options() 

   string = opal_options.executable + " " + opal_options.data_assimilation.fwd_input_file


   # run code which will checkpoint every "k" dumps at the moment....
   print string
   os.system(string)


###############################################
########  COVARIANCE MATRICES     #############
###############################################


   V = np.loadtxt('matrixVprec'+str(m)+'.txt', usecols=range(m))

   R = lam * 0.5 * np.identity(n)

   H = np.identity(n)


###############################################
####### FROM PHYSICAL TO CONTROL SPACE ########
###############################################

   x0 = np.ones(n)
   Vin = np.linalg.pinv(V)
   v0 = np.dot(Vin,x0)


###############################################
#######       COMPUTE THE MISFIT       ########
###############################################


   VT = np.transpose(V)
   HxB = np.dot(H,xB)
   # consider multiple observations later - just one for now
   d = np.subtract(y,HxB)


###############################################
#######    COMPUTE THE MINIMUM OF J    ########
###############################################

   t = time.time()
   iter_count = 0
   Model_updated = False

   res = minimize(J, v0, method='L-BFGS-B', jac=gradJ,
                options={'disp': True})

###############################################
####### FROM CONTROL TO PHYSICAL SPACE ########
###############################################


   vDA = np.array([])
   vDA = res.x
   deltaxDA = np.dot(V,vDA)
   xDA = xB + deltaxDA

   elapsed = time.time() - t

   print " iter_count", iter_count

   #return 

###############################################
####### PRECONDITIONED COST FUNCTION J ########
###############################################



   return
Esempio n. 11
0
def convert(fluidity_options_file_path, ff_options_file_path):

    # Read in Fluidity simulation options

    libspud.clear_options()
    libspud.load_options(fluidity_options_file_path)

    # Simulation name
    simulation_name = libspud.get_option("/simulation_name")

    # Geometry
    base = "/geometry"
    dimension = libspud.get_option(base + "/dimension")
    mesh_path = libspud.get_option(
        base + "/mesh::CoordinateMesh/from_file/file_name"
    ) + ".msh"  # FIXME: Always assumes gmsh format.

    # Function spaces
    velocity_function_space = FunctionSpace("/geometry", 1)
    freesurface_function_space = FunctionSpace("/geometry", 2)

    # Timestepping
    base = "/timestepping"
    current_time = libspud.get_option(base + "/current_time")
    timestep = libspud.get_option(base + "/timestep")
    finish_time = libspud.get_option(base + "/finish_time")

    ## Steady-state
    if (libspud.have_option(base + "/steady_state")):
        if (libspud.have_option(base + "/steady_state/tolerance")):
            steady_state = libspud.get_option(base + "/steady_state/tolerance")
        else:
            steady_state = 1e-7
    else:
        steady_state = None

    # I/O
    base = "/io"
    dump_format = libspud.get_option(base + "/dump_format")
    if (libspud.have_option(base + "/dump_period")):
        dump_period = libspud.get_option(base + "/dump_period/constant")
    elif (libspud.have_option(base + "/dump_period_in_timesteps")):
        dump_period = libspud.get_option(
            base + "/dump_period_in_timesteps/constant") * timestep
    else:
        print "Unable to obtain dump_period."
        sys.exit()

    # Gravity
    g_magnitude = libspud.get_option("/physical_parameters/gravity/magnitude")

    # Velocity field (momentum equation)
    base = "/material_phase[0]/vector_field::Velocity"

    ## Depth (free surface mean height)
    c = libspud.get_child_name(
        base +
        "/prognostic/equation::ShallowWater/scalar_field::BottomDepth/prescribed/value::WholeMesh/",
        1)
    depth = libspud.get_option(
        base +
        "/prognostic/equation::ShallowWater/scalar_field::BottomDepth/prescribed/value::WholeMesh/%s"
        % c)

    ## Bottom drag coefficient
    if (libspud.have_option(base +
                            "/prognostic/equation::ShallowWater/bottom_drag")):
        c = libspud.get_child_name(
            base +
            "/prognostic/equation::ShallowWater/bottom_drag/scalar_field::BottomDragCoefficient/prescribed/value::WholeMesh/",
            1)
        bottom_drag = libspud.get_option(
            base +
            "/prognostic/equation::ShallowWater/bottom_drag/scalar_field::BottomDragCoefficient/prescribed/value::WholeMesh/%s"
            % c)
    else:
        bottom_drag = None

    ## Viscosity
    if (libspud.have_option(base + "/prognostic/tensor_field::Viscosity")):
        viscosity = libspud.get_option(
            base +
            "/prognostic/tensor_field::Viscosity/prescribed/value::WholeMesh/anisotropic_symmetric/constant"
        )[0][0]
    else:
        viscosity = None

    ## Momentum source
    if (libspud.have_option(base + "/prognostic/vector_field::Source")):
        c = libspud.get_child_name(
            base +
            "/prognostic/vector_field::Source/prescribed/value::WholeMesh/", 1)
        momentum_source = libspud.get_option(
            base +
            "/prognostic/vector_field::Source/prescribed/value::WholeMesh/%s" %
            c)
    else:
        momentum_source = None

    ## Initial condition
    if (libspud.have_option(base +
                            "/prognostic/initial_condition::WholeMesh")):
        c = libspud.get_child_name(
            base + "/prognostic/initial_condition::WholeMesh/", 1)
        velocity_initial_condition = libspud.get_option(
            base + "/prognostic/initial_condition::WholeMesh/%s" % c)
    else:
        velocity_initial_condition = 0.0

    ## Boundary conditions
    number_of_bcs = libspud.option_count(base +
                                         "/prognostic/boundary_conditions")
    velocity_bcs = []
    for i in range(number_of_bcs):
        velocity_bcs.append(
            VelocityBoundaryCondition(base +
                                      "/prognostic/boundary_conditions[%d]" %
                                      i))

    # Pressure field (continuity equation)
    base = "/material_phase[0]/scalar_field::Pressure"
    integrate_by_parts = libspud.have_option(
        base +
        "/prognostic/spatial_discretisation/continuous_galerkin/integrate_continuity_by_parts"
    )

    ## Initial condition
    if (libspud.have_option(base +
                            "/prognostic/initial_condition::WholeMesh")):
        c = libspud.get_child_name(
            base + "/prognostic/initial_condition::WholeMesh/", 1)
        pressure_initial_condition = libspud.get_option(
            base + "/prognostic/initial_condition::WholeMesh/%s" % c)
    else:
        pressure_initial_condition = 0.0

    ## Boundary conditions
    number_of_bcs = libspud.option_count(base +
                                         "/prognostic/boundary_conditions")
    pressure_bcs = []
    for i in range(number_of_bcs):
        pressure_bcs.append(
            PressureBoundaryCondition(base +
                                      "/prognostic/boundary_conditions[%d]" %
                                      i))

    ## Continuity source
    if (libspud.have_option(base + "/prognostic/scalar_field::Source")):
        c = libspud.get_child_name(
            base +
            "/prognostic/scalar_field::Source/prescribed/value::WholeMesh/", 1)
        continuity_source = libspud.get_option(
            base +
            "/prognostic/scalar_field::Source/prescribed/value::WholeMesh/%s" %
            c)
    else:
        continuity_source = None

    # Write out to a Firedrake-Fluids simulation configuration file
    libspud.clear_options()

    # Create a bare-bones .swml file to add to.
    f = open(ff_options_file_path, "w")
    f.write("<?xml version='1.0' encoding='utf-8'?>\n")
    f.write("<shallow_water_options>\n")
    f.write("</shallow_water_options>\n")
    f.close()

    libspud.load_options(ff_options_file_path)

    # Simulation name
    libspud.set_option("/simulation_name", simulation_name)

    # Geometry
    base = "/geometry"
    libspud.set_option(base + "/dimension", dimension)
    libspud.set_option(base + "/mesh/from_file/relative_path", mesh_path)

    # Function spaces
    base = "/function_spaces"
    libspud.set_option(base + "/function_space::VelocityFunctionSpace/degree",
                       velocity_function_space.degree)
    libspud.set_option(base + "/function_space::VelocityFunctionSpace/family",
                       velocity_function_space.family)
    libspud.set_option(
        base + "/function_space::FreeSurfaceFunctionSpace/degree",
        freesurface_function_space.degree)
    libspud.set_option(
        base + "/function_space::FreeSurfaceFunctionSpace/family",
        freesurface_function_space.family)

    # I/O
    base = "/io"
    libspud.set_option(base + "/dump_format", dump_format)
    libspud.set_option(base + "/dump_period", dump_period)

    # Timestepping
    base = "/timestepping"
    print timestep
    libspud.set_option(base + "/current_time", current_time)
    try:
        libspud.set_option(base + "/timestep", timestep)
    except:
        pass
    libspud.set_option(base + "/finish_time", finish_time)

    ## Steady-state
    if (steady_state):
        libspud.set_option(base + "/steady_state/tolerance", steady_state)

    # Gravity
    libspud.set_option("/physical_parameters/gravity/magnitude", g_magnitude)

    # System/Core Fields: Velocity
    base = "/system/core_fields/vector_field::Velocity"

    ## Initial condition
    if (isinstance(velocity_initial_condition, str)):
        libspud.set_option(base + "/initial_condition/python",
                           velocity_initial_condition)
    else:
        libspud.set_option(base + "/initial_condition/constant",
                           velocity_initial_condition)

    ## Boundary conditions
    try:
        for i in range(len(velocity_bcs)):
            libspud.set_option(
                base +
                "/boundary_condition::%s/surface_ids" % velocity_bcs[i].name,
                velocity_bcs[i].surface_ids)
            libspud.set_option_attribute(
                base +
                "/boundary_condition::%s/type/name" % velocity_bcs[i].name,
                velocity_bcs[i].type)

            if (velocity_bcs[i].type == "dirichlet"):
                if (isinstance(velocity_bcs[i].value, str)):
                    libspud.set_option(
                        base +
                        "/boundary_condition::%s/type::dirichlet/value/python"
                        % velocity_bcs[i].name, velocity_bcs[i].value)
                else:
                    libspud.set_option(
                        base +
                        "/boundary_condition::%s/type::dirichlet/value/constant"
                        % velocity_bcs[i].name, velocity_bcs[i].value)
    except:
        pass

    # System/Core Fields: FreeSurfacePerturbation
    base = "/system/core_fields/scalar_field::FreeSurfacePerturbation"

    #FIXME: Pressure initial and boundary conditions are multiplied by 'g' in Fluidity, but not in Firedrake-Fluids.
    ## Initial condition
    if (isinstance(pressure_initial_condition, str)):
        libspud.set_option(base + "/initial_condition/python",
                           pressure_initial_condition)
    else:
        libspud.set_option(base + "/initial_condition/constant",
                           pressure_initial_condition)

    ## Boundary conditions
    try:
        for i in range(len(pressure_bcs)):
            libspud.set_option(
                base +
                "/boundary_condition::%s/surface_ids" % pressure_bcs[i].name,
                pressure_bcs[i].surface_ids)
            libspud.set_option(
                base +
                "/boundary_condition::%s/type/name" % pressure_bcs[i].name,
                pressure_bcs[i].type)

            if (pressure_bcs[i].type == "dirichlet"):
                if (isinstance(pressure_bcs[i].value, str)):
                    libspud.set_option(
                        base +
                        "/boundary_condition::%s/type::dirichlet/value/python"
                        % pressure_bcs[i].name, pressure_bcs[i].value)
                else:
                    libspud.set_option(
                        base +
                        "/boundary_condition::%s/type::dirichlet/value/constant"
                        % pressure_bcs[i].name, pressure_bcs[i].value)
    except:
        pass

    # System/Core Fields: FreeSurfaceMean
    base = "/system/core_fields/scalar_field::FreeSurfaceMean"
    if (isinstance(depth, str)):
        libspud.set_option(base + "/value/python", depth)
    else:
        libspud.set_option(base + "/value/constant", depth)

    # Equations: Continuity equation
    base = "/system/equations/continuity_equation"
    libspud.set_option(base + "/integrate_by_parts", integrate_by_parts)

    ## Source term
    if (continuity_source is not None):
        if (isinstance(continuity_source, str)):
            libspud.set_option(
                base + "/source_term/scalar_field::Source/value/python",
                continuity_source)
        else:
            libspud.set_option(
                base + "/source_term/scalar_field::Source/value/constant",
                continuity_source)

    # Equations: Momentum equation
    base = "/system/equations/momentum_equation"

    ## Viscosity
    if (viscosity is not None):
        if (isinstance(viscosity, str)):
            libspud.set_option(
                base + "/stress_term/scalar_field::Viscosity/value/python",
                viscosity)
        else:
            libspud.set_option(
                base + "/stress_term/scalar_field::Viscosity/value/constant",
                viscosity)

    ## Bottom drag
    if (bottom_drag is not None):
        if (isinstance(bottom_drag, str)):
            libspud.set_option(
                base +
                "/drag_term/scalar_field::BottomDragCoefficient/value/python",
                bottom_drag)
        else:
            libspud.set_option(
                base +
                "/drag_term/scalar_field::BottomDragCoefficient/value/constant",
                bottom_drag)

    ## Source term
    if (momentum_source is not None):
        if (isinstance(momentum_source, str)):
            libspud.set_option(
                base + "/source_term/vector_field::Source/value/python",
                momentum_source)
        else:
            libspud.set_option(
                base + "/source_term/vector_field::Source/value/constant",
                momentum_source)

    # Write all the applied options to file.
    libspud.write_options(ff_options_file_path)

    return
Esempio n. 12
0
def generate():
    libspud.load_options(name + ".tfml")
    meshbasename = libspud.get_option("/geometry/mesh::Mesh/source::File/file")
    libspud.clear_options()

    for n in ncells:
        dir_name = "run_" + ` n `
        try:
            os.mkdir(dir_name)
        except OSError:
            pass
        chdir(dir_name)

        tempgeo = file("../../../../../src/transfinite_square_template.geo",
                       'r')
        templines = tempgeo.readlines()
        tempgeo.close()

        lines = []
        for templine in templines:
            line = template(templine).substitute({'ncells': n, 'factor': 0.01})
            lines.append(line)

        geo = file(meshbasename + "_temp.geo", 'w')
        geo.writelines(lines)
        geo.close()

        try:
            checksum = hashlib.md5(open(meshbasename +
                                        ".geo").read()).hexdigest()
        except:
            checksum = None

        if checksum != hashlib.md5(
                open(meshbasename + "_temp.geo").read()).hexdigest():
            # file has changed
            shutil.copy(meshbasename + "_temp.geo", meshbasename + ".geo")
            try:
                subprocess.check_call(
                    ["gmsh", "-2", "-algo", "del2d", meshbasename + ".geo"])
            except:
                print "ERROR while calling gmsh in directory ", dir_name
                os.chdir("../")
                sys.exit(1)

            try:
                subprocess.check_call([
                    "dolfin-convert", meshbasename + ".msh",
                    meshbasename + ".xml"
                ])
            except:
                print "ERROR while calling dolfin-convert in directory ", dir_name
                os.chdir("../")
                sys.exit(1)

            extensions = [".xml", "_facet_region.xml"]
            for ext in extensions:
                try:
                    subprocess.check_call(["gzip", "-f", meshbasename + ext])
                except:
                    print "ERROR while calling gzip in directory ", dir_name, " on extension ", ext
                    os.chdir("../")
                    sys.exit(1)

        os.chdir("../")
Esempio n. 13
0
def extract():
    table0 = []
    table0.append("\\begin{tabular}{c|ccccccc}\n")
    table0.append(
        "    & $\Nu$ & $v_{rms}$ & $\max(u|_{z=1})$ & $<u|_{z=1}>$ & $<T + \\bar{T}>$ & $<\phi>$ & $<W>$ \\\\\n"
    )
    table0.append("\hline\n")

    libspud.load_options(name + ".tfml")
    ioname = libspud.get_option("/io/output_base_name")
    Ra = libspud.get_option(
        "/system::Stokes/coefficient::RayleighNumber/type::Constant/rank::Scalar/value::WholeMesh/constant"
    )
    Di = libspud.get_option(
        "/system::Stokes/coefficient::DissipationNumber/type::Constant/rank::Scalar/value::WholeMesh/constant"
    )

    for n in ncells:
        dir_name = "run_" + ` n `
        chdir(dir_name)

        try:
            stat = parser(ioname + ".stat")
        except IOError:
            os.chdir("../")
            continue
        try:
            det = parser(ioname + ".det")
        except IOError:
            os.chdir("../")
            continue

        nu = -1.0 * (
            stat["Stokes"]["Temperature"]["FullTopSurfaceIntegral"][-1])
        v_rms = sqrt(stat["Stokes"]["Velocity"]["L2NormSquared"][-1]) * Ra
        v_surf_max = abs(det["Stokes"]["Velocity_0"]["Array"][:,
                                                              -1]).max() * Ra
        v_surf_int = stat["Stokes"]["Velocity"]["TopSurfaceIntegral"][-1] * Ra
        T_int = stat["Stokes"]["Temperature"]["FullIntegral"][-1]
        phi_int = stat["ViscousDissipation"]["ViscousDissipation"]["Integral"][
            -1] * Ra * Di
        W_int = stat["WorkDone"]["WorkDone"]["Integral"][-1] * Ra

        table0.append(
            "{0:2d}$\\times${0:2d} & {1:.3f} & {2:.3f} & {3:.3f} & {4:.3f} & {5:.3f} & {6:.3f} & {7:.3f} \\\\\n"
            .format(n, nu, v_rms, v_surf_max, v_surf_int, T_int, phi_int,
                    W_int))

        os.chdir("../")

    libspud.clear_options()

    Raind = int(round(Ra))
    Diind = '%d' % Di if Di == int(Di) else '%s' % Di
    f = file("../../../tables.dict", 'r')
    tables = pickle.load(f)
    f.close()

    table0.append("\hline\n")
    for code, values in tables[approx][Raind][Diind].iteritems():
        if len(values) > 0 and code in comparisoncodes:
            line = "Benchmark (" + code + ") & "
            for v in range(len(values) - 1):
                line += '%.3f' % values[v] + " & "
            line += '%.3f' % values[-1] + " \\\\\n"
            table0.append(line)
    table0.append("\\end{tabular}\n")

    for line in table0:
        print line[0:-1]

    filename = "table0.tex"
    filehandle = file(filename, 'w')
    filehandle.writelines(table0)
    filehandle.close()
 def __del__(self):
     libspud.clear_options()
   def __init__(self, path):
      """ Initialise a new shallow water simulation, using an options file.
      
      :param str path: The path to the simulation's configuration/options file.
      :returns: None
      """
   
      LOG.info("Initialising simulation...")
      
      # Remove any stored options.
      libspud.clear_options()

      # Load the options from the options tree.
      libspud.load_options(path)
     
      # Populate the options dictionary
      self.populate_options()
        
      # Read in the input mesh (or construct one)
      self.mesh = self.get_mesh(path)

      # Create a dictionary containing all the function spaces
      LOG.info("Creating function spaces...")
      self.function_spaces = {}
                      
      # The Velocity field's function space
      name = "VelocityFunctionSpace"
      path = "/function_spaces/function_space::%s" % name
      family = libspud.get_option(path+"/family")
      degree = libspud.get_option(path+"/degree")
      try:
         if(family == "Continuous Lagrange"):
            self.function_spaces[name] = VectorFunctionSpace(self.mesh, "CG", degree)
         elif(family == "Discontinuous Lagrange"):
            self.function_spaces[name] = VectorFunctionSpace(self.mesh, "DG", degree)
         else:
            raise ValueError("Unknown element family: %s." % family)
      except ValueError as e:      
         LOG.exception(e)
         sys.exit()
      LOG.debug("Created a new %s function space of degree %d for Velocity" % (family, degree))
      
      # The FreeSurfacePerturbation field's function space
      name = "FreeSurfaceFunctionSpace"
      path = "/function_spaces/function_space::%s" % name
      family = libspud.get_option(path+"/family")
      degree = libspud.get_option(path+"/degree")
      try:
         if(family == "Continuous Lagrange"):
            self.function_spaces[name] = FunctionSpace(self.mesh, "CG", degree)
         elif(family == "Discontinuous Lagrange"):
            self.function_spaces[name] = FunctionSpace(self.mesh, "DG", degree)
         else:
            raise ValueError("Unknown element family: %s." % family)
      except ValueError as e:
         LOG.exception(e)
         sys.exit()
      LOG.debug("Created a new %s function space of degree %d for FreeSurfacePerturbation" % (family, degree))
      
      # Define the mixed function space
      U = self.function_spaces["VelocityFunctionSpace"]
      H = self.function_spaces["FreeSurfaceFunctionSpace"]
      self.W = MixedFunctionSpace([U, H])

      # Set up the output streams
      self.create_output_streams()
      
      return
Esempio n. 16
0
def convert(fluidity_options_file_path, ff_options_file_path):
   
   # Read in Fluidity simulation options
   
   libspud.clear_options()
   libspud.load_options(fluidity_options_file_path)
   
   # Simulation name
   simulation_name = libspud.get_option("/simulation_name")
   
   # Geometry
   base = "/geometry"
   dimension = libspud.get_option(base + "/dimension")
   mesh_path = libspud.get_option(base + "/mesh::CoordinateMesh/from_file/file_name") + ".msh" # FIXME: Always assumes gmsh format.
  
   # Function spaces
   velocity_function_space = FunctionSpace("/geometry", 1)
   freesurface_function_space = FunctionSpace("/geometry", 2)
    
   # Timestepping
   base = "/timestepping"
   current_time = libspud.get_option(base + "/current_time")
   timestep = libspud.get_option(base + "/timestep")
   finish_time = libspud.get_option(base + "/finish_time")

   ## Steady-state
   if(libspud.have_option(base + "/steady_state")):
      if(libspud.have_option(base + "/steady_state/tolerance")):
         steady_state = libspud.get_option(base + "/steady_state/tolerance")
      else:
         steady_state = 1e-7
   else:
      steady_state = None   

   # I/O
   base = "/io"
   dump_format = libspud.get_option(base + "/dump_format")
   if(libspud.have_option(base + "/dump_period")):
      dump_period = libspud.get_option(base + "/dump_period/constant")
   elif(libspud.have_option(base + "/dump_period_in_timesteps")):
      dump_period = libspud.get_option(base + "/dump_period_in_timesteps/constant")*timestep
   else:
      print "Unable to obtain dump_period."
      sys.exit()
      
   # Gravity
   g_magnitude = libspud.get_option("/physical_parameters/gravity/magnitude")
   
   # Velocity field (momentum equation)
   base = "/material_phase[0]/vector_field::Velocity"
   
   ## Depth (free surface mean height)
   c = libspud.get_child_name(base + "/prognostic/equation::ShallowWater/scalar_field::BottomDepth/prescribed/value::WholeMesh/", 1)
   depth = libspud.get_option(base + "/prognostic/equation::ShallowWater/scalar_field::BottomDepth/prescribed/value::WholeMesh/%s" % c)
   
   ## Bottom drag coefficient
   if(libspud.have_option(base + "/prognostic/equation::ShallowWater/bottom_drag")):
      c = libspud.get_child_name(base + "/prognostic/equation::ShallowWater/bottom_drag/scalar_field::BottomDragCoefficient/prescribed/value::WholeMesh/", 1)
      bottom_drag = libspud.get_option(base + "/prognostic/equation::ShallowWater/bottom_drag/scalar_field::BottomDragCoefficient/prescribed/value::WholeMesh/%s" % c)
   else:
      bottom_drag = None
      
   ## Viscosity
   if(libspud.have_option(base + "/prognostic/tensor_field::Viscosity")):
      viscosity = libspud.get_option(base + "/prognostic/tensor_field::Viscosity/prescribed/value::WholeMesh/anisotropic_symmetric/constant")[0][0]
   else:
      viscosity = None

   ## Momentum source
   if(libspud.have_option(base + "/prognostic/vector_field::Source")):
      c = libspud.get_child_name(base + "/prognostic/vector_field::Source/prescribed/value::WholeMesh/", 1)
      momentum_source = libspud.get_option(base + "/prognostic/vector_field::Source/prescribed/value::WholeMesh/%s" % c)
   else:
      momentum_source = None
      
   ## Initial condition
   if(libspud.have_option(base + "/prognostic/initial_condition::WholeMesh")):
      c = libspud.get_child_name(base + "/prognostic/initial_condition::WholeMesh/", 1)
      velocity_initial_condition = libspud.get_option(base + "/prognostic/initial_condition::WholeMesh/%s" % c)
   else:
      velocity_initial_condition = 0.0
      
   ## Boundary conditions
   number_of_bcs = libspud.option_count(base + "/prognostic/boundary_conditions")
   velocity_bcs = []
   for i in range(number_of_bcs):
      velocity_bcs.append(VelocityBoundaryCondition(base + "/prognostic/boundary_conditions[%d]" % i))
   
   
   # Pressure field (continuity equation)
   base = "/material_phase[0]/scalar_field::Pressure"
   integrate_by_parts = libspud.have_option(base + "/prognostic/spatial_discretisation/continuous_galerkin/integrate_continuity_by_parts")
   
   ## Initial condition
   if(libspud.have_option(base + "/prognostic/initial_condition::WholeMesh")):
      c = libspud.get_child_name(base + "/prognostic/initial_condition::WholeMesh/", 1)
      pressure_initial_condition = libspud.get_option(base + "/prognostic/initial_condition::WholeMesh/%s" % c)
   else:
      pressure_initial_condition = 0.0
      
   ## Boundary conditions
   number_of_bcs = libspud.option_count(base + "/prognostic/boundary_conditions")
   pressure_bcs = []
   for i in range(number_of_bcs):
      pressure_bcs.append(PressureBoundaryCondition(base + "/prognostic/boundary_conditions[%d]" % i))
   
   ## Continuity source
   if(libspud.have_option(base + "/prognostic/scalar_field::Source")):
      c = libspud.get_child_name(base + "/prognostic/scalar_field::Source/prescribed/value::WholeMesh/", 1)
      continuity_source = libspud.get_option(base + "/prognostic/scalar_field::Source/prescribed/value::WholeMesh/%s" % c)
   else:
      continuity_source = None
   





   
   
   # Write out to a Firedrake-Fluids simulation configuration file
   libspud.clear_options()
   
   # Create a bare-bones .swml file to add to.
   f = open(ff_options_file_path, "w")
   f.write("<?xml version='1.0' encoding='utf-8'?>\n")
   f.write("<shallow_water_options>\n")
   f.write("</shallow_water_options>\n")
   f.close()
   
   libspud.load_options(ff_options_file_path)

   # Simulation name
   libspud.set_option("/simulation_name", simulation_name)
   
   # Geometry
   base = "/geometry"
   libspud.set_option(base + "/dimension", dimension)
   libspud.set_option(base + "/mesh/from_file/relative_path", mesh_path)
   
   # Function spaces
   base = "/function_spaces"
   libspud.set_option(base + "/function_space::VelocityFunctionSpace/degree", velocity_function_space.degree)
   libspud.set_option(base + "/function_space::VelocityFunctionSpace/family", velocity_function_space.family)
   libspud.set_option(base + "/function_space::FreeSurfaceFunctionSpace/degree", freesurface_function_space.degree)
   libspud.set_option(base + "/function_space::FreeSurfaceFunctionSpace/family", freesurface_function_space.family)
   
   # I/O
   base = "/io"
   libspud.set_option(base + "/dump_format", dump_format)
   libspud.set_option(base + "/dump_period", dump_period)
   
   # Timestepping
   base = "/timestepping"
   print timestep
   libspud.set_option(base + "/current_time", current_time)
   try:
      libspud.set_option(base + "/timestep", timestep)
   except:
      pass
   libspud.set_option(base + "/finish_time", finish_time)
   
   ## Steady-state
   if(steady_state):
      libspud.set_option(base + "/steady_state/tolerance", steady_state)
      
   # Gravity
   libspud.set_option("/physical_parameters/gravity/magnitude", g_magnitude)
   
   # System/Core Fields: Velocity
   base = "/system/core_fields/vector_field::Velocity"
   
   ## Initial condition
   if(isinstance(velocity_initial_condition, str)):
      libspud.set_option(base + "/initial_condition/python", velocity_initial_condition)
   else:
      libspud.set_option(base + "/initial_condition/constant", velocity_initial_condition)
   
   ## Boundary conditions
   try:
      for i in range(len(velocity_bcs)):
         libspud.set_option(base + "/boundary_condition::%s/surface_ids" % velocity_bcs[i].name, velocity_bcs[i].surface_ids)
         libspud.set_option_attribute(base + "/boundary_condition::%s/type/name" % velocity_bcs[i].name, velocity_bcs[i].type)
         
         if(velocity_bcs[i].type == "dirichlet"):
            if(isinstance(velocity_bcs[i].value, str)):
               libspud.set_option(base + "/boundary_condition::%s/type::dirichlet/value/python" % velocity_bcs[i].name, velocity_bcs[i].value)
            else:
               libspud.set_option(base + "/boundary_condition::%s/type::dirichlet/value/constant" % velocity_bcs[i].name, velocity_bcs[i].value)
   except:
      pass

   # System/Core Fields: FreeSurfacePerturbation
   base = "/system/core_fields/scalar_field::FreeSurfacePerturbation"
   
   #FIXME: Pressure initial and boundary conditions are multiplied by 'g' in Fluidity, but not in Firedrake-Fluids.
   ## Initial condition
   if(isinstance(pressure_initial_condition, str)):
      libspud.set_option(base + "/initial_condition/python", pressure_initial_condition)
   else:
      libspud.set_option(base + "/initial_condition/constant", pressure_initial_condition)
   
   ## Boundary conditions
   try:
      for i in range(len(pressure_bcs)):
         libspud.set_option(base + "/boundary_condition::%s/surface_ids" % pressure_bcs[i].name, pressure_bcs[i].surface_ids)
         libspud.set_option(base + "/boundary_condition::%s/type/name" % pressure_bcs[i].name, pressure_bcs[i].type)
         
         if(pressure_bcs[i].type == "dirichlet"):
            if(isinstance(pressure_bcs[i].value, str)):
               libspud.set_option(base + "/boundary_condition::%s/type::dirichlet/value/python" % pressure_bcs[i].name, pressure_bcs[i].value)
            else:
               libspud.set_option(base + "/boundary_condition::%s/type::dirichlet/value/constant" % pressure_bcs[i].name, pressure_bcs[i].value)
   except:
      pass

   # System/Core Fields: FreeSurfaceMean
   base = "/system/core_fields/scalar_field::FreeSurfaceMean"
   if(isinstance(depth, str)):
      libspud.set_option(base + "/value/python", depth)
   else:
      libspud.set_option(base + "/value/constant", depth)
      
   
   # Equations: Continuity equation
   base = "/system/equations/continuity_equation"
   libspud.set_option(base + "/integrate_by_parts", integrate_by_parts)

   ## Source term
   if(continuity_source is not None):
      if(isinstance(continuity_source, str)):
         libspud.set_option(base + "/source_term/scalar_field::Source/value/python", continuity_source)
      else:
         libspud.set_option(base + "/source_term/scalar_field::Source/value/constant", continuity_source)
         
   # Equations: Momentum equation
   base = "/system/equations/momentum_equation"
   
   ## Viscosity
   if(viscosity is not None):
      if(isinstance(viscosity, str)):
         libspud.set_option(base + "/stress_term/scalar_field::Viscosity/value/python", viscosity)
      else:
         libspud.set_option(base + "/stress_term/scalar_field::Viscosity/value/constant", viscosity)

   ## Bottom drag
   if(bottom_drag is not None):
      if(isinstance(bottom_drag, str)):
         libspud.set_option(base + "/drag_term/scalar_field::BottomDragCoefficient/value/python", bottom_drag)
      else:
         libspud.set_option(base + "/drag_term/scalar_field::BottomDragCoefficient/value/constant", bottom_drag)
   
   ## Source term
   if(momentum_source is not None):
      if(isinstance(momentum_source, str)):
         libspud.set_option(base + "/source_term/vector_field::Source/value/python", momentum_source)
      else:
         libspud.set_option(base + "/source_term/vector_field::Source/value/constant", momentum_source)
   
   
   # Write all the applied options to file.
   libspud.write_options(ff_options_file_path)
   
   return
Esempio n. 17
0
 def clear_options(self):
   libspud.clear_options()
   if self.lock.locked(): self.lock.release()
def get_opal_options():
    "Initialises the structure for the options."
    opal_options = Opal_input()
    nirom_options = Nirom_input()
    fwd_options = Forward_model_options()

    #Read the input data from the user
    opal_input_file = str(sys.argv[1])
    #Load the .opal file
    libspud.load_options(opal_input_file)
    ##Create Opal Variable
    #    opal_options = Opal_input()
    ##Start reading options
    print "reading opal input file", opal_input_file
    if libspud.have_option('/avoid_perturbing_near_wells'):
        opal_options.avoid_perturbing_near_wells = True

    if (libspud.have_option('/opal_operation/importance_map')):

        opal_options.opal_operation = 'importance_map'
        im_path = '/opal_operation/importance_map/'
        opal_options = read_in_importance_map_options(im_path, opal_options)

    elif (libspud.have_option('/opal_operation/data_assimilation')):

        opal_options.opal_operation = 'da'
        opal_options.data_assimilation.fwd_input_file = libspud.get_option(
            '/opal_operation/data_assimilation/fwd_input_file')
        #print "opal_options.data_assimilation.fwd_input_file", opal_options.data_assimilation.fwd_input_file

    elif (libspud.have_option('/opal_operation/nirom')):

        opal_options.opal_operation = 'nirom'
        nirom_path = 'opal_operation/nirom/'
        opal_options, nirom_options, fwd_options = read_in_nirom_options(
            nirom_path, opal_options, nirom_options, fwd_options)

    elif (libspud.have_option('/opal_operation/second_order_da')):

        opal_options.opal_operation = 'second_order_da'
        da_path = '/opal_operation/second_order_da/'
        opal_options = read_in_soda_options(da_path, opal_options)

    elif (libspud.have_option('/opal_operation/ga_optimisation')):
        opal_options.opal_operation = 'ga_optimisation'
        path = '/opal_operation/ga_optimisation'

        # previously these three options were at the top level
        opal_options.output_filename = libspud.get_option(path +
                                                          '/Output_filename')
        opal_options.executable = libspud.get_option(path + '/Executable')
        opal_options.input_file = libspud.get_option(path + '/Input_file')

        opal_options.ga_max_generations = libspud.get_option(
            path + '/convergence_settings/Maximum_generations')

        opal_options.ga_locations_to_study = libspud.get_option(
            path + '/Locations_to_study/value')
        if libspud.have_option(path + '/Locations_to_study/Initial_guess'):
            opal_options.ga_initial_guess = libspud.get_option(
                path + '/Locations_to_study/Initial_guess')
        if libspud.have_option(path + '/Locations_to_study/Mind_the_gap'):
            opal_options.mind_the_gap = libspud.get_option(
                path + '/Locations_to_study/Mind_the_gap')
        if libspud.have_option(path + '/Trelis_integration'):
            opal_options.trelis_path = libspud.get_option(
                path + '/Trelis_integration/trelis_path')
            opal_options.trelis_input_file = libspud.get_option(
                path + '/Trelis_integration/trelis_input_file')
        opal_options.optimise_input = libspud.have_option(path +
                                                          '/optimise_input')
        if libspud.have_option(path +
                               '/convergence_settings/Gradient_convergence'):
            opal_options.ga_gradient_convergence = libspud.get_option(
                path + '/convergence_settings/Gradient_convergence')
        if libspud.have_option(path +
                               '/convergence_settings/Absolute_convergence'):
            opal_options.ga_absolute_convergence = libspud.get_option(
                path + '/convergence_settings/Absolute_convergence')
        if libspud.have_option(path + '/Number_processors'):
            opal_options.number_processors = libspud.get_option(
                path + '/Number_processors')
            if libspud.have_option(path + '/Number_processors/MPI_runs'):
                opal_options.MPI_runs = libspud.get_option(
                    path + '/Number_processors/MPI_runs')
                opal_options.number_processors /= opal_options.MPI_runs
        opal_options.ga_population_generation = libspud.get_option(
            path + '/Population_generation')
        opal_options.ga_breeding_prob = libspud.get_option(
            path + '/Breeding_probability/value')
        if libspud.have_option(path +
                               '/Breeding_probability/Generation_method'):
            opal_options.generation_method = libspud.get_option(
                path + '/Breeding_probability/Generation_method')
        opal_options.ga_mutation_prob = libspud.get_option(
            path + '/Mutation_probability/value')
        if libspud.have_option(path + '/Mutation_probability/Mutation_method'):
            opal_options.mutation_method = libspud.get_option(
                path + '/Mutation_probability/Mutation_method')
        opal_options.precision = libspud.get_option(path + '/Precision')
        if libspud.have_option(path + '/Fitness/python_function'):
            opal_options.ga_fitness_functional = libspud.get_option(
                path + '/Fitness/python_function')
        opal_options.ga_Minimise = libspud.have_option(
            path + '/Fitness/Optimisation/Minimise')
        opal_options.producer_ids = libspud.get_option(path +
                                                       '/Fitness/producer_ids')
        opal_options.injector_ids = libspud.get_option(path +
                                                       '/Fitness/injector_ids')
        if libspud.have_option(path +
                               '/GA_methods/Evolutionary_algorithm/eaSimple'):
            opal_options.ga_evol_algorithm = 1
        elif libspud.have_option(
                path + '/GA_methods/Evolutionary_algorithm/eaMuCommaLambda'):
            opal_options.ga_evol_algorithm = 2
            opal_options.ga_mu = libspud.get_option(
                path + '/GA_methods/Evolutionary_algorithm/eaMuCommaLambda/Mu')
            opal_options.ga_lambda = libspud.get_option(
                path +
                '/GA_methods/Evolutionary_algorithm/eaMuCommaLambda/Lambda')
        elif libspud.have_option(
                path + '/GA_methods/Evolutionary_algorithm/eaMuPlusLambda'):
            opal_options.ga_evol_algorithm = 3
            opal_options.ga_mu = libspud.get_option(
                path + '/GA_methods/Evolutionary_algorithm/eaMuPlusLambda/Mu')
            opal_options.ga_lambda = libspud.get_option(
                path +
                '/GA_methods/Evolutionary_algorithm/eaMuPlusLambda/Lambda')
        if libspud.have_option(path + '/GA_methods/Selection_method/selBest'):
            opal_options.ga_selection_method = 1
        elif libspud.have_option(path +
                                 '/GA_methods/Selection_method/selNSGA2'):
            opal_options.ga_selection_method = 2
        elif libspud.have_option(path +
                                 '/GA_methods/Selection_method/selSPEA2'):
            opal_options.ga_selection_method = 3

        opal_options.ga_CMA = False
        if libspud.have_option(path + '/GA_methods/Use_CMA'):
            opal_options.ga_CMA = True
            opal_options.ga_centroid = libspud.get_option(
                path + '/GA_methods/Use_CMA/centroid')
            opal_options.ga_sigma = libspud.get_option(
                path + '/GA_methods/Use_CMA/sigma')
        if libspud.have_option(path + 'Hall_of_fame'):
            opal_options.ga_hall_of_fame = libspud.get_option(path +
                                                              'Hall_of_fame')
        nfields = libspud.option_count(path + '/Variables')
        for i in range(nfields):
            temp_field = ga_variable()
            fieldpath = path + '/Variables[' + str(i) + ']'
            temp_field.name = libspud.get_option(fieldpath + '/name')
            temp_field.min_limit = libspud.get_option(fieldpath + '/Min_limit')
            temp_field.max_limit = libspud.get_option(fieldpath + '/Max_limit')
            temp_field.variable_pattern = libspud.get_option(
                fieldpath + '/Variable_pattern')
            temp_field.normaliser = 1.0
            if libspud.have_option(fieldpath + '/normaliser'):
                temp_field.normaliser = libspud.get_option(fieldpath +
                                                           '/normaliser')
            ##Now append to the variables list
            opal_options.ga_variables.append(temp_field)

    libspud.clear_options()

    return opal_options, fwd_options, nirom_options
   def __init__(self, path, checkpoint=None):
      """ Initialise a new shallow water simulation, using an options file.
      
      :param str path: The path to the simulation's configuration/options file.
      :param str checkpoint: The path to a checkpoint file.
      :returns: None
      """
   
      LOG.info("Initialising simulation...")
      
      # Remove any stored options.
      libspud.clear_options()

      # Load the options from the options tree.
      libspud.load_options(path)
     
      # Populate the options dictionary
      self.populate_options()
        
      # Read in the input mesh (or construct one)
      self.mesh = self.get_mesh(path)

      # Create a dictionary containing all the function spaces
      LOG.info("Creating function spaces...")
      self.function_spaces = {}
                      
      # The Velocity field's function space
      name = "VelocityFunctionSpace"
      path = "/function_spaces/function_space::%s" % name
      family = libspud.get_option(path+"/family")
      degree = libspud.get_option(path+"/degree")
      try:
         if(family == "Continuous Lagrange"):
            self.function_spaces[name] = VectorFunctionSpace(self.mesh, "CG", degree)
         elif(family == "Discontinuous Lagrange"):
            self.function_spaces[name] = VectorFunctionSpace(self.mesh, "DG", degree)
         else:
            raise ValueError("Unknown element family: %s." % family)
      except ValueError as e:      
         LOG.exception(e)
         sys.exit()
      LOG.debug("Created a new %s function space of degree %d for Velocity" % (family, degree))
      
      # The FreeSurfacePerturbation field's function space
      name = "FreeSurfaceFunctionSpace"
      path = "/function_spaces/function_space::%s" % name
      family = libspud.get_option(path+"/family")
      degree = libspud.get_option(path+"/degree")
      try:
         if(family == "Continuous Lagrange"):
            self.function_spaces[name] = FunctionSpace(self.mesh, "CG", degree)
         elif(family == "Discontinuous Lagrange"):
            self.function_spaces[name] = FunctionSpace(self.mesh, "DG", degree)
         else:
            raise ValueError("Unknown element family: %s." % family)
      except ValueError as e:
         LOG.exception(e)
         sys.exit()
      LOG.debug("Created a new %s function space of degree %d for FreeSurfacePerturbation" % (family, degree))
      
      # Get the function spaces
      U = self.function_spaces["VelocityFunctionSpace"]
      H = self.function_spaces["FreeSurfaceFunctionSpace"]

      # Test functions
      self.w = TestFunction(U)
      self.v = TestFunction(H)
      LOG.info("Test functions created.")
      
      # Trial functions (i.e. the solutions for time n+1)
      self.u = TrialFunction(U)
      self.h = TrialFunction(H)
      LOG.info("Trial functions created.")

      # Normal vector to each element facet
      self.n = FacetNormal(self.mesh)

      # Set up initial conditions
      LOG.info("Setting initial conditions...")
      h_initial = ExpressionFromOptions(path = "/system/core_fields/scalar_field::FreeSurfacePerturbation/initial_condition").get_expression()
      u_initial = ExpressionFromOptions(path = "/system/core_fields/vector_field::Velocity/initial_condition").get_expression()
      
      # The solution at time n.
      self.u0 = Function(U).interpolate(u_initial)
      self.h0 = Function(H).interpolate(h_initial)
      
      # The solution at time n-1.
      self.u00 = Function(U)
      self.u00.assign(self.u0)
      
      # Load initial conditions from the specified checkpoint file if desired.
      if(checkpoint is not None):
         self.solution_old.dat.load(checkpoint)
         LOG.debug("Loaded initial condition from checkpoint file.")
      
      # Mean free surface height
      self.h_mean = Function(H)
      self.h_mean.interpolate(ExpressionFromOptions(path = "/system/core_fields/scalar_field::FreeSurfaceMean/value").get_expression())

      # Set up the functions used to write fields to file.
      self.output_functions = {}
      self.output_functions["Velocity"] = Function(U, name="Velocity")
      self.output_functions["FreeSurfacePerturbation"] = Function(H, name="FreeSurfacePerturbation")
      
      # Set up the output stream
      LOG.info("Initialising output file streams...")
      self.output_files = {}
      for field in self.output_functions.keys():
         self.output_files[field] = File("%s_%s.pvd" % (self.options["simulation_name"], field))
      
      # Write initial conditions to file
      LOG.info("Writing initial conditions to file...")
      self.output_functions["Velocity"].assign(self.u0)
      self.output_files["Velocity"] << self.output_functions["Velocity"]
      self.output_functions["FreeSurfacePerturbation"].assign(self.h0)
      self.output_files["FreeSurfacePerturbation"] << self.output_functions["FreeSurfacePerturbation"]
      
      return
    def test17(self):
        with self.assertRaises(SystemExit):
            #should be an osml file
            libspud.clear_options()
            try:
                libspud.load_options('test17.osml')
            except:
                print "This file doesn't exist or is the wrong file type. It should be a .osml file"
                sys.exit()

            try:
                start = float(
                    libspud.get_option(
                        '/diffusion_model/timestepping/start_time', ))

                end = float(
                    libspud.get_option(
                        '/diffusion_model/timestepping/end_time'))

                time_step = float(
                    libspud.get_option(
                        '/diffusion_model/timestepping/timestep'))

                mesh_int = int(
                    libspud.get_option(
                        '/diffusion_model/mesh/initial_mesh_size'))

                alpha = float(
                    libspud.get_option(
                        '/diffusion_model/model_parameters/diffusion_coefficient'
                    ))

                initial_conditions = str(
                    libspud.get_option(
                        '/diffusion_model/model_parameters/initial_conditions')
                )
            except:
                print 'The information provided was incomplete, please recreate the file'
                sys.exit()
            print start
            print end
            print time_step
            print mesh_int
            print alpha
            print initial_conditions

            #create a simple testcase
            model = SedimentModel()
            mesh = UnitSquareMesh(mesh_int, mesh_int)
            model.set_mesh(mesh)
            init_cond = Expression(initial_conditions)  # simple slope
            init_sed = Expression('x[0]')  # this gives
            # total of above gives a slope of 0 to 2 (over the unit square)
            model.set_initial_conditions(init_cond, init_sed)
            model.set_end_time(end)
            model.set_diffusion_coeff(alpha)
            model.init()
            model.solve()
            # answer should be 1 everywhere
            plot(model.get_total_height(), interactive=True)
            answer = model.get_total_height_array()
Esempio n. 21
0
#To get the mpml file
path = os.getcwd()
mpmlfile = get_mpml_filename(path)

libspud.load_options(mpmlfile + '.mpml')
meshname_base = libspud.get_option('/geometry[0]/mesh[0]/from_file/file_name')
NDIM = libspud.get_option('/geometry/dimension')
Dt_n = libspud.get_option('/timestepping/timestep')  #timestep
tlevel_begin = libspud.get_option('/timestepping/current_time')  #start time
tlevel_end = libspud.get_option('/timestepping/finish_time')  #end time
NSCALAR = libspud.option_count('/Field_to_study')
DELTA_T = libspud.get_option(
    '/io/dump_period_in_timesteps/constant'
)  ###change to point to checkpint file in unperturbed
libspud.clear_options()

DT = tlevel_end - tlevel_begin  #total simulation period
NTIME = int(DT / Dt_n) + 1  # number of timelevels


def get_coordinates(vtu_filename):
    vtu_data = vtktools.vtu(vtu_filename)
    coordinates = vtu_data.GetLocations()
    return vtu_data, coordinates


#def map_matrix(coordinates, NONODS):
def map_matrix(vtu_data, coordinates, NONODS):
    #This is the matrix for the compressed row storage (CSR) format
    #NCOLM0 gives the number of number of non-zero elements
Esempio n. 22
0
    def __init__(self, tfml_file,system_name='magma',p_name='Pressure',f_name='Porosity',c_name='c',n_name='n',m_name='m',d_name='d',N_name='N',h_squared_name='h_squared',x0_name='x0'):
        """read the tfml_file and use libspud to populate the internal parameters

        c: wavespeed
        n: permeability exponent
        m: bulk viscosity exponent
        d: wave dimension
        N: number of collocation points
        x0: coordinate wave peak
        h_squared:  the size of the system in compaction lengths
                    squared (h/delta)**2
        """
        # initialize libspud and extract parameters
        libspud.clear_options()
        libspud.load_options(tfml_file)
        # get model dimension
        self.dim = libspud.get_option("/geometry/dimension")
        self.system_name = system_name
        # get solitary wave parameters
        path="/system::"+system_name+"/coefficient::"
        scalar_value="/type::Constant/rank::Scalar/value::WholeMesh/constant"
        vector_value="/type::Constant/rank::Vector/value::WholeMesh/constant::dim"
        c = libspud.get_option(path+c_name+scalar_value)
        n = int(libspud.get_option(path+n_name+scalar_value))
        m = int(libspud.get_option(path+m_name+scalar_value))
        d = float(libspud.get_option(path+d_name+scalar_value))
        N = int(libspud.get_option(path+N_name+scalar_value))
        self.h = np.sqrt(libspud.get_option(path+h_squared_name+scalar_value))
        self.x0 = np.array(libspud.get_option(path+x0_name+vector_value))
        self.swave = SolitaryWave(c,n,m,d,N)
        self.rmax = self.swave.r[-1]
        self.tfml_file = tfml_file
  
        # check that d <= dim
        assert (d <= self.dim)   
        
        # sort out appropriate index for calculating distance r
        if d == 1:
            self.index = [self.dim - 1]
        else: 
            self.index = range(0,int(d))  
            
        # check that the origin point is the correct dimension
        assert (len(self.x0) == self.dim)
        
        
        #read in information for constructing Function space and dolfin objects
        # get the mesh parameters and reconstruct the mesh
        meshtype = libspud.get_option("/geometry/mesh/source[0]/name")
        if meshtype == 'UnitSquare':
            number_cells = libspud.get_option("/geometry/mesh[0]/source[0]/number_cells")
            diagonal = libspud.get_option("/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.UnitSquareMesh(number_cells[0],number_cells[1],diagonal)
        elif meshtype == 'Rectangle':
            x0 = libspud.get_option("/geometry/mesh::Mesh/source::Rectangle/lower_left")
            x1 = libspud.get_option("/geometry/mesh::Mesh/source::Rectangle/upper_right")
            number_cells = libspud.get_option("/geometry/mesh::Mesh/source::Rectangle/number_cells")
            diagonal = libspud.get_option("/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.RectangleMesh(x0[0],x0[1],x1[0],x1[1],number_cells[0],number_cells[1],diagonal)
        elif meshtype == 'UnitCube':
            number_cells = libspud.get_option("/geometry/mesh[0]/source[0]/number_cells")
            mesh = df.UnitCubeMesh(number_cells[0],number_cells[1],number_cells[2])
        elif meshtype == 'Box':
            x0 = libspud.get_option("/geometry/mesh::Mesh/source::Box/lower_back_left")
            x1 = libspud.get_option("/geometry/mesh::Mesh/source::Box/upper_front_right")
            number_cells = libspud.get_option("/geometry/mesh::Mesh/source::Box/number_cells")
            mesh = df.BoxMesh(x0[0],x0[1],x0[2],x1[0],x1[1],x1[2],number_cells[0],number_cells[1],number_cells[2])
        elif meshtype == 'UnitInterval':
            number_cells = libspud.get_option("/geometry/mesh::Mesh/source::UnitInterval/number_cells")
            mesh = df.UnitIntervalMesh(number_cells)
        elif meshtype == 'Interval':
            number_cells = libspud.get_option("/geometry/mesh::Mesh/source::Interval/number_cells")
            left = libspud.get_option("/geometry/mesh::Mesh/source::Interval/left")
            right = libspud.get_option("/geometry/mesh::Mesh/source::Interval/right")
            mesh = df.IntervalMesh(number_cells,left,right)
        elif meshtype == 'File':
            mesh_filename = libspud.get_option("/geometry/mesh::Mesh/source::File/file")
            print "tfml_file  = ",self.tfml_file, "mesh_filename=",mesh_filename
            mesh = df.Mesh(mesh_filename)
        else:
            df.error("Error: unknown mesh type "+meshtype)
           
        #set the functionspace for n-d solitary waves
        path="/system::"+system_name+"/field::"
        p_family = libspud.get_option(path+p_name+"/type/rank/element/family")
        p_degree = libspud.get_option(path+p_name+"/type/rank/element/degree")
        f_family = libspud.get_option(path+f_name+"/type/rank/element/family")
        f_degree = libspud.get_option(path+f_name+"/type/rank/element/degree")        
        pe = df.FiniteElement(p_family, mesh.ufl_cell(), p_degree)
        ve = df.FiniteElement(f_family, mesh.ufl_cell(), f_degree)
        e = pe*ve
        self.functionspace = df.FunctionSpace(mesh, e)

        #work out the order of the fields
        for i in xrange(libspud.option_count("/system::"+system_name+"/field")):
          name = libspud.get_option("/system::"+system_name+"/field["+`i`+"]/name")
          if name == f_name:
            self.f_index = i
          if name == p_name:
            self.p_index = i
    def __init__(self, path, checkpoint=None):
        """ Initialise a new shallow water simulation, using an options file.
      
      :param str path: The path to the simulation's configuration/options file.
      :param str checkpoint: The path to a checkpoint file.
      :returns: None
      """

        LOG.info("Initialising simulation...")

        # Remove any stored options.
        libspud.clear_options()

        # Load the options from the options tree.
        libspud.load_options(path)

        # Populate the options dictionary
        self.populate_options()

        # Read in the input mesh (or construct one)
        self.mesh = self.get_mesh(path)

        # Create a dictionary containing all the function spaces
        LOG.info("Creating function spaces...")
        self.function_spaces = {}

        # The Velocity field's function space
        name = "VelocityFunctionSpace"
        path = "/function_spaces/function_space::%s" % name
        family = libspud.get_option(path + "/family")
        degree = libspud.get_option(path + "/degree")
        try:
            if (family == "Continuous Lagrange"):
                self.function_spaces[name] = VectorFunctionSpace(
                    self.mesh, "CG", degree)
            elif (family == "Discontinuous Lagrange"):
                self.function_spaces[name] = VectorFunctionSpace(
                    self.mesh, "DG", degree)
            else:
                raise ValueError("Unknown element family: %s." % family)
        except ValueError as e:
            LOG.exception(e)
            sys.exit()
        LOG.debug("Created a new %s function space of degree %d for Velocity" %
                  (family, degree))

        # The FreeSurfacePerturbation field's function space
        name = "FreeSurfaceFunctionSpace"
        path = "/function_spaces/function_space::%s" % name
        family = libspud.get_option(path + "/family")
        degree = libspud.get_option(path + "/degree")
        try:
            if (family == "Continuous Lagrange"):
                self.function_spaces[name] = FunctionSpace(
                    self.mesh, "CG", degree)
            elif (family == "Discontinuous Lagrange"):
                self.function_spaces[name] = FunctionSpace(
                    self.mesh, "DG", degree)
            else:
                raise ValueError("Unknown element family: %s." % family)
        except ValueError as e:
            LOG.exception(e)
            sys.exit()
        LOG.debug(
            "Created a new %s function space of degree %d for FreeSurfacePerturbation"
            % (family, degree))

        # Get the function spaces
        U = self.function_spaces["VelocityFunctionSpace"]
        H = self.function_spaces["FreeSurfaceFunctionSpace"]

        # Test functions
        self.w = TestFunction(U)
        self.v = TestFunction(H)
        LOG.info("Test functions created.")

        # Trial functions (i.e. the solutions for time n+1)
        self.u = TrialFunction(U)
        self.h = TrialFunction(H)
        LOG.info("Trial functions created.")

        # Normal vector to each element facet
        self.n = FacetNormal(self.mesh)

        # Set up initial conditions
        LOG.info("Setting initial conditions...")
        h_initial = ExpressionFromOptions(
            path=
            "/system/core_fields/scalar_field::FreeSurfacePerturbation/initial_condition"
        ).get_expression()
        u_initial = ExpressionFromOptions(
            path="/system/core_fields/vector_field::Velocity/initial_condition"
        ).get_expression()

        # The solution at time n.
        self.u0 = Function(U).interpolate(u_initial)
        self.h0 = Function(H).interpolate(h_initial)

        # The solution at time n-1.
        self.u00 = Function(U)
        self.u00.assign(self.u0)

        # Load initial conditions from the specified checkpoint file if desired.
        if (checkpoint is not None):
            self.solution_old.dat.load(checkpoint)
            LOG.debug("Loaded initial condition from checkpoint file.")

        # Mean free surface height
        self.h_mean = Function(H)
        self.h_mean.interpolate(
            ExpressionFromOptions(
                path="/system/core_fields/scalar_field::FreeSurfaceMean/value"
            ).get_expression())

        # Set up the functions used to write fields to file.
        self.output_functions = {}
        self.output_functions["Velocity"] = Function(U, name="Velocity")
        self.output_functions["FreeSurfacePerturbation"] = Function(
            H, name="FreeSurfacePerturbation")

        # Set up the output stream
        LOG.info("Initialising output file streams...")
        self.output_files = {}
        for field in self.output_functions.keys():
            self.output_files[field] = File(
                "%s_%s.pvd" % (self.options["simulation_name"], field))

        # Write initial conditions to file
        LOG.info("Writing initial conditions to file...")
        self.output_functions["Velocity"].assign(self.u0)
        self.output_files["Velocity"] << self.output_functions["Velocity"]
        self.output_functions["FreeSurfacePerturbation"].assign(self.h0)
        self.output_files["FreeSurfacePerturbation"] << self.output_functions[
            "FreeSurfacePerturbation"]

        return