Пример #1
0
def Parameters(file_name):
	
	try: 
		libspud.load_options(file_name)
	except:
		print "This file doesn't exist or is the wrong file type. It should be a .osml file. Use -h for help"
		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/topography_conditions'))
		sediment_conditions =str(libspud.get_option('/diffusion_model/model_parameters/sediment_conditions'))
	except: 
		print 'The information provided was incomplete, please recreate the file'
		sys.exit()
	
	if ((start-end) >= 0):
		print 'The start time is after the end time'
		sys.exit()
	elif (time_step == 0):
		print 'The time step cannot be 0'
		sys.exit()
	elif (mesh_int == 0):
		print 'The mesh has to have a size greater than 0'
		sys.exit()
	elif ((end - start) < time_step):
		print 'The time step is too large for the total time'
		sys.exit()
	return start, end, time_step, mesh_int, alpha, initial_conditions, sediment_conditions
Пример #2
0
def get_parameters_from_options(options_file=None,**kwargs):

    if options_file:
        libspud.load_options(options_file)

    parameters = []

    options_base = '/embedded_models/particle_model/particle_classes'

    def get_option(pclass,key,default=None):

        result = default
        if libspud.have_option('/'.join((options_base,pclass,key))):
            result = libspud.get_option('/'.join((options_base,pclass,key)))
        return result

    for i in range(libspud.get_number_of_children(options_base)):
        key = libspud.get_child_name(options_base,i)
        name = get_option(key,'name')

        diameter = get_option(key,'diameter')
        distribution = get_option(key,'distribution')
        density = get_option(key,'density',default=2.5e3)
        
        parameters.append(PhysicalParticle(diameter=diameter,
                                           rho=density,
                                           distribution=distribution,
                                           material_name=name,
                                           **kwargs))

    return parameters
	def test8(self):
		#should be an osml file
		libspud.load_options('test8.osml')

		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'))

		#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()
		for i in answer:
			self.assert_(-1e-8 < i - 1 < 1e-8)
	def test14(self):
		with self.assertRaises(SystemExit):
			#should be an osml file
			libspud.load_options('test14.osml')
	
			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'))
			if ((start-end) >= 0):
				print 'The start time is after the end time'
				sys.exit()
			elif (time_step == 0):
				print 'The time step cannot be 0'
				sys.exit()
		
	

			#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()
Пример #5
0
    def __init__(self, options_file=None):

        if options_file:
            libspud.load_options(options_file)

            self.simulation_name = libspud.get_option('/simulation_name')
            self.dimension = libspud.get_option('/geometry/dimension')
Пример #6
0
def get_parameters_from_options(options_file=None, **kwargs):
    """Read particle data from Fluidity options file."""

    if options_file:
        libspud.load_options(options_file)

    parameters = []

    options_base = '/embedded_models/particle_model/particle_classes'

    def get_option(pclass, key, default=None):
        """Get option from key."""

        result = default
        if libspud.have_option('/'.join((options_base, pclass, key))):
            result = libspud.get_option('/'.join((options_base, pclass, key)))
        return result

    for i in range(libspud.get_number_of_children(options_base)):
        key = libspud.get_child_name(options_base, i)
        name = get_option(key, 'name')

        diameter = get_option(key, 'diameter')
        distribution = get_option(key, 'distribution')
        density = get_option(key, 'density', default=2.5e3)

        parameters.append(
            PhysicalParticle(diameter=diameter,
                             rho=density,
                             distribution=distribution,
                             material_name=name,
                             **kwargs))

    return parameters
    def test11(self):
        #should be an osml file
        libspud.load_options('test11.osml')

        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'))

        #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()
Пример #8
0
def pre_init(model, xml_path):

    # load options file
    libspud.load_options(xml_path)

    # model name
    model.project_name = libspud.get_option('project_name')

    # mesh options
    model.ele_count = get_optional('mesh/element_count', default=20)

    # time options
    option_path = 'time_options/time_discretisation::'
    if libspud.have_option(option_path + 'runge_kutta'):
        model.time_discretise = time_discretisation.runge_kutta
    elif libspud.have_option(option_path + 'crank_nicholson'):
        model.time_discretise = time_discretisation.crank_nicholson
    elif libspud.have_option(option_path + 'explicit'):
        model.time_discretise = time_discretisation.explicit
    elif libspud.have_option(option_path + 'implicit'):
        model.time_discretise = time_discretisation.implicit
    else:
        raise Exception('unrecognised time discretisation in options file')

    if libspud.have_option('time_options/finish_time'):
        model.finish_time = libspud.get_option('time_options/finish_time')
        model.tol = None
    elif libspud.have_option('time_options/steady_state_tolerance'):
        model.tol = libspud.get_option('time_options/steady_state_tolerance')
        model.finish_time = None
    else:
        raise Exception('unrecognised finishing criteria')

    # spatial_discretisation
    if libspud.have_option('spatial_discretiation/discretisation::continuous'):
        model.disc = 'CG'
    elif libspud.have_option(
            'spatial_discretisation/discretisation::discontinuous'):
        model.disc = 'DG'
        model.slope_limit = libspud.have_option(
            'spatial_discretisation/discretisation/slope_limit')
    else:
        raise Exception('unrecognised spatial discretisation in options file')
    model.degree = get_optional('spatial_discretisation/polynomial_degree',
                                default=1)

    # tests
    if libspud.have_option('testing/test::mms'):
        option_path = 'testing/test::mms/source_terms/'
        model.mms = True
        model.S_e = (read_ic(option_path + 'momentum_source', default=None),
                     read_ic(option_path + 'height_source', default=None),
                     read_ic(option_path + 'volume_fraction_source',
                             default=None),
                     read_ic(option_path + 'deposit_depth_source',
                             default=None))
    else:
        model.mms = False
Пример #9
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
Пример #10
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
	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()
    def test15(self):
        with self.assertRaises(SystemExit):
            #should be an osml file
            libspud.load_options('test15.osml')

            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'))

            if ((start - end) >= 0):
                print 'The start time is after the end time'
                sys.exit()
            elif (time_step == 0):
                print 'The time step cannot be 0'
                sys.exit()
            elif ((end - start) <= time_step):
                print 'The time step is too large for the total time'
                sys.exit()

            #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()
Пример #13
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]
Пример #14
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]
Пример #15
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
Пример #16
0
def Parameters(file_name):

    try:
        libspud.load_options(file_name)
    except:
        print "This file doesn't exist or is the wrong file type. It should be a .osml file. Use -h for help"
        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()

    if ((start - end) >= 0):
        print 'The start time is after the end time'
        sys.exit()
    elif (time_step == 0):
        print 'The time step cannot be 0'
        sys.exit()
    elif (mesh_int == 0):
        print 'The mesh has to have a size greater than 0'
        sys.exit()
    elif ((end - start) < time_step):
        print 'The time step is too large for the total time'
        sys.exit()
    return start, end, time_step, mesh_int, alpha, initial_conditions
Пример #17
0
import libspud
import shutil

class flml_things:
    "list of things to change in an flml file"

    def __init__(self,name='',mesh='',dt=0.2):
        self.name = name
        self.dt = dt
        self.mesh = mesh

parent_file = 'diffusion_dg1'
diffusion_dg_A = flml_things(name='diffusion_dg_A',mesh='MMS_A',dt=0.2)
diffusion_dg_B = flml_things(name='diffusion_dg_B',mesh='MMS_B',dt=0.2)
diffusion_dg_C = flml_things(name='diffusion_dg_C',mesh='MMS_C',dt=0.2)
diffusion_dg_D = flml_things(name='diffusion_dg_D',mesh='MMS_D',dt=0.2)
diffusion_dg_E = flml_things(name='diffusion_dg_E',mesh='MMS_E',dt=0.2)
filelist = [diffusion_dg_A,diffusion_dg_B,diffusion_dg_C,diffusion_dg_D,diffusion_dg_E]

for file in filelist:
    shutil.copy(parent_file+'.flml',file.name+'.flml')
    libspud.load_options(file.name+'.flml')
    libspud.set_option('/simulation_name', file.name)
    libspud.set_option('/geometry/mesh[@name="CoordinateMesh"]/from_file/file_name', file.mesh)
    libspud.set_option('/timestepping/timestep', file.dt)

    libspud.write_options(file.name+'.flml')
   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
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
Пример #20
0
#Authors: P. Salinas
import operator

from opal_classes import *
from deap import tools, base, creator, cma
from importance_map_tools import *
import libspud
from exodus2gmsh import convertExodusII2MSH

#Read Opal options, for the time being just so we can call the same subroutines
# read in the opal options
opal_options, fwd_options, nirom_options = get_opal_options()
# get xml extension (mpml or flml)
xml_extension = get_xml_extension(opal_options.input_file)
# load the options for the forward model from xml file
libspud.load_options(opal_options.input_file)
# Production file
prod_file = libspud.get_option('/simulation_name') + "_outfluxes.csv"
# Final time to extract from the csv file
final_time = libspud.get_option('/timestepping/finish_time')
#Retrieve extra variables required to run the optimisation
MIN = opal_options.ga_variables[0].min_limit
MAX = opal_options.ga_variables[0].max_limit
spatial_precision = int((abs(MIN) + abs(MAX)) * opal_options.precision)
##Global variable to be used for gradient convergence
previous_convergence = [0.0, 0.0]
##Geothermal if we have temperature field
geothermal = libspud.have_option('material_phase[' + str(0) +
                                 ']/scalar_field::Temperature')
##Already visited studied
explored_locations = []
Пример #21
0
def tfmlgeterrors(name):
    # get arguments from .tfml file
    tfmlfile = name+'.tfml'
    libspud.load_options(tfmlfile)
    
    
    # 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 = UnitSquare(number_cells[0],number_cells[1],diagonal)
    elif meshtype == 'UnitCube':
        number_cells = libspud.get_option("/geometry/mesh[0]/source[0]/number_cells")
        mesh = UnitCube(number_cells[0],number_cells[1],number_cells[2])
    else:
       error("Error: unknown mesh type "+meshtype)

    # get the mesh dimension 
    dim = mesh.topology().dim()
    
    # get and set  the mixed function space
    p_family = libspud.get_option("/system[0]/field[0]/type/rank/element/family")
    p_degree = libspud.get_option("/system[0]/field[0]/type/rank/element/degree")
    f_family = libspud.get_option("/system[0]/field[1]/type/rank/element/family")
    f_degree = libspud.get_option("/system[0]/field[1]/type/rank/element/degree")
    Vp = FunctionSpace(mesh,p_family,p_degree)
    Vf = FunctionSpace(mesh,f_family,f_degree)
    ME = Vp*Vf
    
    # get the solitarywave profile
    solwave_code = libspud.get_option("/system::magma/field::Porosity/type::Function/rank::Scalar/initial_condition/python")
    exec(solwave_code)
    # print wave parameters
    print 'Solitary Wave parameters: c =',swave.c,', n = ',swave.n,', m = ',swave.m,', d = ',swave.d
    print 'h_on_delta =', h_on_delta
   
    # calculate dh_nodes_per_compaction length
    dh = mesh.hmin() # cell diameter (circum-circle)
    dh_node = dh/sqrt(dim)/2.
    dh_node_delta = dh_node*h_on_delta

    # cd to build directory to loop over checkpoint files
    # os.chdir('build')

    # get and sort xml files by time
    tfml_files = glob(name+'*checkpoint*.tfml')
    xml_files = glob(name+'*.xml')
    dtype = [ ('time', float), ('name','S28')]
    values = []
    for i in range(len(tfml_files)):
        libspud.load_options(tfml_files[i])
        time = libspud.get_option("/timestepping/current_time")
        dt = libspud.get_option("/timestepping/timestep/coefficient/type/rank/value/constant")
        values = values + [(time, xml_files[i])]

    a = array(values,dtype)
    t_file=sort(a,order='time')
         
    
    set_log_active(False) # turn off dolfin messages

    # initialize output arrays
    t = []
    delta = []
    err_min = []
    L2_f = []
    rel_error = []
    c_rel_error = []
    elapsed_time = []
    
    # loop over files and check errors for each one

    delta_0 = zeros(dim)
    for i in range(len(t_file)):
        
        # get time and filename
        t.append(t_file[i][0])
        name = t_file[i][1]
        
        # load function and extract porosity
        u = Function(ME,name)
        p, f = u.split(deepcopy = True)
        
        
        #initialize Error Object
        err = WaveError(f,swave,x0,h_on_delta)
        
        #minimize error using fsolve
        #out = err.min_grad(delta_0)
        out = err.min_grad_z(delta_0[-1])

        # collect output variables
        delta_i = out[0]
        delta.append(delta_i)
        err_min.append(out[1])
        elapsed_time = out[2]
        #print "delta= ", delta_i

        L2_f.append(err.L2_f)
        rel_error.append(err_min[-1]/L2_f[-1])
        c_rel_error.append(sign(delta_i[-1])*sqrt(dot(delta_i,delta_i))/(c*t[-1]))

        #create string and dump to screen and file
        if dim == 2:
            str = "%g\t [ %g %g ] \t %g\t %g\t %g\t %g\t%g" % (t[-1],delta_i[0],delta_i[1],err_min[-1],L2_f[-1],rel_error[-1],c_rel_error[-1],elapsed_time)
        elif dim == 3:
            str = "%g\t [ %g %g %g ] \t %g\t %g\t %g\t %g\t%g" % (t[-1],delta_i[0],delta_i[1],delta_i[2],err_min[-1],L2_f[-1],rel_error[-1],c_rel_error[-1],elapsed_time)

                
        disp(str)
        delta_0 = delta_i

    # set up dictionary and pickle
    list = [['c', swave.c],['d', swave.d],['n',swave.n],['m',swave.m],
            ['h_on_delta',h_on_delta],['dh_on_delta', dh_node_delta],['dt',dt],
            [ 'time', t], ['delta', delta], ['min_err', err_min], ['L2_f', L2_f], ['rel_error', rel_error], ['c_rel_error',c_rel_error]]
    d = dict(list)
    f = file('ErrorFile.pkl','w+')
    dump(d,f)
Пример #22
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
Пример #23
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()
Пример #24
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
   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
Пример #26
0
def exception_test(test_str, exception):
    """Test should throw exception."""
    try:
        suite.test_cases.append(TestCase("%s fails" % test_str))
        eval(test_str)
        suite.test_cases[-1].add_failure_info('No exception')
    except exception as e:
        return
    # reach here on test failure
    suite.test_cases[-1].add_failure_info('Exception', str(e))


try:
    suite.test_cases.append(TestCase('libspud for python.load_options'))
    libspud.load_options(dirpath + '/test.flml')
except:
    suite.test_cases[-1].add_failure_info('Exception')
    with open('test_results.xml', 'w') as handle:
        suite.to_file(handle, [suite])
    raise ValueError

test("libspud.get_option('/timestepping/timestep') == 0.025")
test("libspud.get_number_of_children('/geometry') == 5")
test("libspud.get_child_name('geometry', 0) == 'dimension'")

test("libspud.option_count('/problem_type') == 1")
test("libspud.have_option('/problem_type')")

test("libspud.get_option_type('/geometry/dimension') is int")
test("libspud.get_option_type('/problem_type') is str")
Пример #27
0
 def __init__(self, filename):
     libspud.load_options(filename)
Пример #28
0
 def load_options(self, filename):
   self.lock.acquire()
   try:
     libspud.load_options(filename)
   except:
     self.lock.release()
Пример #29
0
def gen_flmls(params, template_dir, output_dir, paths, names, verbose):

    import types

    # get flml file from template_dir - first one we come across
    # If you have more in there, tough.
    full_flml = glob.glob(os.path.join(template_dir, '*.flml'))[0]
    # strip to the filename only
    flml = os.path.basename(full_flml)

    f = open(os.path.join(output_dir, 'runs', "directory_listing.csv"), "w")
    # append data to directory listing file
    line = "Directory number"
    for n in names:
        line = line + "," + n

    line = line + "\n"
    f.write(line)

    # loop over paramas
    # create a new directory, with a unqiue number, starting from 1
    # This makes it easier to use in an array job on CX1
    dir_num = 1
    for p_set in params:
        if (verbose):
            print "Processing " + str(dir_num)

        # copy contents from template folder to directory number
        dirname = os.path.join(output_dir, 'runs', str(dir_num))
        if (os.path.exists(os.path.join(dirname))):
            shutil.rmtree(dirname)
        shutil.copytree(template_dir, dirname)

        # open FLML file
        output_file = os.path.join(dirname, flml)
        # This load the data into the memory of the libspud library
        libspud.load_options(output_file)

        i = 0
        for path in paths:
            path = path.strip()
            # get type
            path_type = libspud.get_option_type(path)
            path_rank = libspud.get_option_rank(path)
            path_shape = libspud.get_option_shape(path)
            if (path_type is float and path_rank == 0):
                libspud.set_option(path, float(p_set[i]))
            elif (path_rank == 1 and path_type is float):
                value = eval(p_set[i])
                val = list(map(float, value))
                libspud.set_option(path, val)
            elif (path_rank == 2 and path_type is float):
                value = eval(p_set[i])
                val = []
                for row in value:
                    val.append(list(map(float, row)))
                libspud.set_option(path, val)

            i = i + 1

        # save file
        libspud.write_options(output_file)

        # append data to directory listing file
        line = str(dir_num)
        for p in p_set:
            # quoting the params so csv parsers can get the columns right
            line = line + "," + '"' + str(p) + '"'
        line = line + "\n"
        f.write(line)

        dir_num += 1

    f.close()
    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()
Пример #31
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("../")
Пример #32
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
Пример #33
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
Пример #34
0
from importance_map_tools import *
from importance_map import *
import time
import random
#sys.path.insert(1, '/home/zdt16/MultiFluids_Dev/libspud/')
import libspud

#To load the vtu files and read the coordinates of the nodes
#vtu_data = vtktools.vtu("Input_Importance_map_1.vtu") ###Hardcoded
#coordinates = vtu_data.GetLocations()

#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

Пример #35
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
Пример #36
0
def gen_flmls(params, template_dir, output_dir, paths, names, verbose):

    import types

    # get flml file from template_dir - first one we come across
    # If you have more in there, tough.
    full_flml = glob.glob(os.path.join(template_dir,'*.flml'))[0]
    # strip to the filename only
    flml = os.path.basename(full_flml)

    f = open(os.path.join(output_dir,'runs',"directory_listing.csv"),"w")
    # append data to directory listing file
    line = "Directory number"
    for n in names:
        line = line+","+n

    line = line + "\n"
    f.write(line)

    # loop over paramas
    # create a new directory, with a unqiue number, starting from 1
    # This makes it easier to use in an array job on CX1
    dir_num = 1
    for p_set in params:
        if (verbose):
            print "Processing "+str(dir_num)

        # copy contents from template folder to directory number
        dirname = os.path.join(output_dir,'runs',str(dir_num))
        if (os.path.exists(os.path.join(dirname))):
            shutil.rmtree(dirname)
        shutil.copytree(template_dir,dirname)

        # open FLML file
        output_file = os.path.join(dirname,flml)
        # This load the data into the memory of the libspud library
        libspud.load_options(output_file)

        i = 0
        for path in paths:
            path = path.strip()
            # get type
            path_type = libspud.get_option_type(path)
            path_rank = libspud.get_option_rank(path)
            path_shape = libspud.get_option_shape(path)
            if (path_type is float and path_rank == 0):
                libspud.set_option(path,float(p_set[i]))
            elif (path_rank == 1 and path_type is float):
                value = eval(p_set[i])
                val = list(map(float, value))
                libspud.set_option(path,val)
            elif (path_rank == 2 and path_type is float):
                value = eval(p_set[i])
                val = []
                for row in value:
                    val.append(list(map(float, row)))
                libspud.set_option(path,val)

            i = i+1

        # save file
        libspud.write_options(output_file)
            
        # append data to directory listing file
        line = str(dir_num)
        for p in p_set:
            # quoting the params so csv parsers can get the columns right
            line = line+","+'"'+str(p)+'"'
        line = line +"\n"
        f.write(line)

        dir_num += 1


    f.close()
Пример #37
0
import libspud
print libspud.__file__

libspud.load_options('test.flml')

libspud.print_options()

print libspud.number_of_children('/geometry')
print libspud.get_child_name('geometry', 0)

print libspud.option_count('/problem_type')
print libspud.have_option('/problem_type')

print libspud.get_option_type('/geometry/dimension')
print libspud.get_option_type('/problem_type')

print libspud.get_option_rank('/geometry/dimension')
print libspud.get_option_rank(
    '/physical_parameters/gravity/vector_field::GravityDirection/prescribed/value/constant'
)

print libspud.get_option_shape('/geometry/dimension')
print libspud.get_option_shape('/problem_type')

print libspud.get_option('/problem_type')
print libspud.get_option('/geometry/dimension')
libspud.set_option('/geometry/dimension', 3)
print libspud.get_option('/geometry/dimension')

list_path = '/material_phase::Material1/scalar_field::MaterialVolumeFraction/prognostic/boundary_conditions::LetNoOneLeave/surface_ids'
print libspud.get_option_shape(list_path)
Пример #38
0
import libspud

libspud.load_options('test.flml')

#libspud.print_options()

assert libspud.get_option('/timestepping/timestep') == 0.025

assert libspud.get_number_of_children('/geometry') == 5
assert libspud.get_child_name('geometry', 0) == "dimension"

assert libspud.option_count('/problem_type') == 1
assert libspud.have_option('/problem_type')

assert libspud.get_option_type('/geometry/dimension') is int
assert libspud.get_option_type('/problem_type') is str

assert libspud.get_option_rank('/geometry/dimension') == 0
assert libspud.get_option_rank('/physical_parameters/gravity/vector_field::GravityDirection/prescribed/value/constant') == 1

assert libspud.get_option_shape('/geometry/dimension') == (-1, -1)
assert libspud.get_option_shape('/problem_type')[0] > 1
assert libspud.get_option_shape('/problem_type')[1] == -1

assert libspud.get_option('/problem_type') == "multimaterial"
assert libspud.get_option('/geometry/dimension') == 2
libspud.set_option('/geometry/dimension', 3)


assert libspud.get_option('/geometry/dimension') == 3
Пример #39
0
def main():

    parser = argparse.ArgumentParser(
         prog="plot 2D",
         description="""Plot a 2D (time vs depth) of a variable"""
                     )
    parser.add_argument(
            '-v', 
            '--verbose', 
            action='store_true', 
            help="Verbose output: mainly progress reports.",
            default=False
            )
    parser.add_argument(
            '-s', 
            '--station', 
            choices=['papa', 'india', 'bermuda'],
            help="Choose a station: india, papa or bermuda",
            required=True
            )
    parser.add_argument(
            '--var', 
            choices=['dz', 'chlor', 'det', 'nit', 'zoo', 'phyto', 'pp', 'temp', 'sal', 'rho', 'tke','vertdiff'],
            help="Choose a variable to plot",
            required=True
            )
    parser.add_argument(
            '-m', 
            '--no_mld', 
            help="Do not plot the MLD",
            required=False,
            action="store_true",
            default=False
            )
    parser.add_argument(
            '--tke',
            help="Plot MLD based on TKE, not density",
            action='store_true',
            default=False
            )
    parser.add_argument(
            '-z', 
            type=float,
            help="Maximum depth to plot",
            default=500,
            required=False,
            )
    parser.add_argument(
            '-n',
            '--nyears',
            type=int,
            default=None,
            help="Number of years to plot. Default is longest time from Fluidity data",
            required=False,
            )
    parser.add_argument(
            '--minvalue',
            default=None,
            type=float,
            help="Set a minimum value to use in the plot",
            required=False,
            )
    parser.add_argument(
            '--maxvalue',
            default=None,
	        type=float,
            help="Set a maximum value to use in the plot",
            required=False,
            )
    parser.add_argument(
            '--logscale',
            help="Use a log colour scale",
            action='store_true',
            default=False
            )
    parser.add_argument(
            'input', 
            metavar='input',
            help="Fluidity results directory",
            )
    parser.add_argument(
            'output_file', 
            metavar='output_file',
            help='The output filename'
            )

    args = parser.parse_args()
    verbose = args.verbose
    adaptive = False
    output_file = args.output_file
    max_depth = args.z
    plot_tke = args.tke
    var = args.var
    minvalue = args.minvalue
    maxvalue = args.maxvalue
    logscale = args.logscale
    if (args.nyears == None):
        nDays = None
    else:
        nDays = args.nyears*365
    # actually irrelavent as we do it by day of year...
    start = datetime.strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")

    variable = None
    long_name = None
    # work out which variable to pull out
    # 'dz', 'chlor', 'det', 'nit', 'zoo', 'phyto', 'pp', 'temp', 'sal', 'rho', 'tke'
    if (var == 'dz'):
        variable = None # don't need one - special case
        long_name = r'$\delta z$'
    elif (var == 'chlor'):
        variable = 'Chlorophyll'
        long_name = 'Chlorophyll-a ($mmol/m^3$)'
    elif (var == 'det'):
        variable = 'Detritus'
        long_name = 'Detritus ($mmol/m^3$)'
    elif (var == 'nit'):
        variable = 'Nutrient'
        long_name = 'Nitrate ($mmol/m^3$)'
    elif (var == 'zoo'):
        variable = 'Zooplankton'
        long_name = 'Zooplankton ($mmol/m^3$)'
    elif (var == 'phyto'):
        variable = 'Phytoplankton'
        long_name = 'Phytoplankton ($mmol/m^3$)'
    elif (var == 'pp'):
        variable = 'DailyAveragedPrimaryProduction'
        long_name = 'Primary Production ($mmol/m^3$)'
    elif (var == 'temp'):
        variable = 'Temperature'
        long_name = 'Temperature ($^/circ C$)'
    elif (var == 'sal'):
        variable = 'Salinity'
        long_name = 'Salinity ($PSU$)'
    elif (var == 'rho'):
        variable = 'Density'
        long_name = 'Density ($kg/m^3$)'
    elif (var == 'tke'):
        variable = 'GLSTurbulentKineticEnergy'
        long_name = 'Turbulent Kinetic Energy ($m^2s^{-2}$)'
    elif (var == 'vertdiff'):
        variable = 'GLSVerticalDiffusivity'
        long_name = 'Vertical Diffusivity ($m^2s^{-1}$)'
    else:
        print "Unknown variable"
        sys.exit(-1)

    if (verbose):
        print "Plot 2D plot of : "

    files = get_vtus(args.input)

    if (not verbose):
        # print progress bar
        total_vtus = len(files)
        percentPerVtu = 100.0/float(total_vtus)

    if (args.station == 'bermuda'):
        pp_averaged = True
    else:
        pp_averaged = False

    # Are we adaptive - if so, set up some variables
    # We need maxdepth, min edge length, max edge length, etc
    # I think the easiest is to parse the flml...glob flml files
    # that don't have checkpoint in their name...
    flmls = (glob.glob(os.path.join(args.input, "*.flml")))
    flmls.sort()
    
    # grab bits of the flml we want
    if flmls == None or len(flmls) == 0:
        print "No flml files available: can't check for adaptivity, this might fail..."
    elif len(flmls) > 1:
        print "Found multiple FLMLs, using the first one"
    else:
        flml = flmls[0]
        # grab min_edge_length, max_edge_length, bottom depth and starting resolution
        libspud.load_options(flml)
        if (libspud.have_option('mesh_adaptivity/')):
            adaptive = True
            minEdgeLength = libspud.get_option('/mesh_adaptivity/hr_adaptivity/tensor_field::MinimumEdgeLengths/anisotropic_symmetric/constant')[-1][-1]
            maxEdgeLength = libspud.get_option('/mesh_adaptivity/hr_adaptivity/tensor_field::MaximumEdgeLengths/anisotropic_symmetric/constant')[-1][-1]
            maxDepth = libspud.get_option('/geometry/mesh::CoordinateMesh/from_mesh/extrude/regions::WholeMesh/bottom_depth/constant')
            initial_spacing = min(minEdgeLength,libspud.get_option('/geometry/mesh::CoordinateMesh/from_mesh/extrude/regions::WholeMesh/sizing_function/constant'))
            nPoints = int(maxDepth/max(initial_spacing,minEdgeLength))+1 # maximum number of points will be at start with uniform resolution
            if (verbose):
                print minEdgeLength, maxEdgeLength, maxDepth, nPoints, initial_spacing
        else:
        # If not found, it's not adaptive...
            adaptive = False

    if (verbose):
        print "Adaptive run: ", adaptive

    current_file = 1
    # set up our master variables
    mld = []
    data = []
    dates = []
    depths = []
    for vtu in files:
        if (not verbose):
            progress(50,current_file*percentPerVtu)
        # obtain surface values from each dataset
        try:
            #if (verbose):
            #    print vtu
            os.stat(vtu)
        except:
            print "No such file: %s" % file
            sys.exit(1)

        # open vtu and derive the field indices of the edge at (x=0,y=0) ordered by depth
        u=vtktools.vtu(vtu)
        pos = u.GetLocations()
        ind = get_1d_indices(pos)

        # deal with depths
        depth = [-pos[i,2] for i in ind]
        if (adaptive):
            depth.extend([maxDepth+1 for i in range(len(ind),nPoints)])
        depths.append(depth)

        # handle time and convert to calendar time
        time = u.GetScalarField('Time')
        tt = [time[i] for i in ind]
        cur_dt = start + timedelta(seconds=time[0])
        days = (cur_dt - start).days
        tt = [days for i in ind]
        if (adaptive):
            tt.extend([days for i in range(len(ind),nPoints)])
        dates.append( tt )
        
        if plot_tke:
             d = u.GetScalarField('GLSTurbulentKineticEnergy')
             den = [d[i] for i in ind]
             if (adaptive):
                 den.extend([1e-10 for i in range(len(ind),nPoints)])
             mld.append(calc_mld_tke(den, depth))
        else:
            # grab density profile and calculate MLD_den
            d = u.GetScalarField('Density')
            den = [d[i] * 1000 for i in ind]
            if (adaptive):
                den.extend([d[-1]*1000. for i in range(len(ind),nPoints)])
            mld.append(calc_mld_den(den, depth, den0=0.125) )


        if (var == 'dz'):
            z = []
            for i in range(1,len(depth)):
                if (depth[i] - depth[i-1] < minEdgeLength): # we're in the region where we've made up the edges...
                    z.append(minEdgeLength)
                else:
                    z.append(depth[i] - depth[i-1])
            z.append(100) # to make sure shape(dz) == shape(depths)
            data.append(vtktools.arr(z))
        else:
            # primprod is depth integrated or averaged, so we need the whole field
            t = u.GetScalarField(variable)
            if (var == 'pp'):
                temp = [6.7*12*8.64e4*t[i] for i in ind]
            elif (var == 'density'):
                temp = [1024.0*t[i] for i in ind]
            else:
                temp = [t[i] for i in ind]
            if (adaptive):
                temp.extend([t[-1] for i in range(len(ind),nPoints)])
            data.append(temp)

        current_file = current_file + 1

    if (not nDays):
        nDays = dates[-1][0]

    filename = output_file
    data = numpy.array(data)

    if (var == 'dz'):
        # Add or subtract a bit more than edgelength as DZ might be a bit more or less than this
        min_data = minEdgeLength - (0.1*minEdgeLength)
        max_data = maxEdgeLength + (0.1*maxEdgeLength)
    else:
        if (minvalue == None):
            min_data = data.min()
        else:
            min_data = minvalue
        if (maxvalue == None):
            max_data = data.max()
        else:
            max_data = maxvalue
    plot_2d_data(data, depths, dates, filename, long_name, finish_day=nDays,mld_data=mld,max_depth=max_depth,minimum=min_data,maximum=max_data,logscale=logscale)
Пример #40
0
    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