opencmp.helpers package

Submodules

opencmp.helpers.dg module

opencmp.helpers.dg.avg(q)[source]

Returns the average of a scalar field.

Parameters

q (CoefficientFunction) – The scalar field.

Return type

CoefficientFunction

Returns

The average of q at every facet of the mesh.

opencmp.helpers.dg.grad_avg(q)[source]

Returns the average of the gradient of a field.

Parameters

q (CoefficientFunction) – The field.

Return type

CoefficientFunction

Returns

The average of the gradient of q at every facet of the mesh.

opencmp.helpers.dg.grad_jump(q)[source]

Returns the jump of the gradient of a field.

Parameters

q (CoefficientFunction) – The field.

Return type

CoefficientFunction

Returns

The jump of the gradient of q at every facet of the mesh.

opencmp.helpers.dg.jump(q)[source]

Returns the jump of a field.

Parameters

q (CoefficientFunction) – The field.

Return type

CoefficientFunction

Returns

The jump of q at every facet of the mesh.

opencmp.helpers.error module

opencmp.helpers.error._divergence(sol, mesh)[source]

Function to calculate the divergence of a variable over the domain.

Use with velocity to confirm that conservation of mass is being satisfied.

Parameters
  • sol (GridFunction) – The solution GridFunction.

  • mesh (Mesh) – The mesh that was solved on.

Return type

float

Returns

The L2 norm of the divergence of the field.

opencmp.helpers.error._facet_jumps(sol, mesh)[source]

Function to check how continuous the solution is across mesh facets.

This is mainly of interest when DG is used. Continuous Galerkin FEM solutions will always be perfectly continuous across facets.

Parameters
  • sol (GridFunction) – The solution GridFunction.

  • mesh (Mesh) – The mesh that was solved on.

Return type

float

Returns

The L2 norm of the facet jumps.

opencmp.helpers.error._l_1(sol, ref_sol, mesh)[source]

L1 norm

Return type

float

opencmp.helpers.error._l_2(sol, ref_sol, mesh)[source]

L2 norm

Return type

float

opencmp.helpers.error._l_inf(sol, ref_sol, mesh, fes)[source]

L-infinity norm

Return type

float

opencmp.helpers.error._surface_traction(sol, model, marker)[source]

Function to calculate the surface traction on an object described by a given mesh surface.

Parameters
  • sol (GridFunction) – The solution gridfunction.

  • model (None) – The solved model to calculate the error for.

  • marker (Optional[str, None]) – The mesh marker for the surface of the object. If the diffuse interface method is being used this is not needed since the phase field will be used to locate the object.

Return type

CoefficientFunction

Returns

The surface traction on the object due to the flow field.

opencmp.helpers.error.calc_error(config, model, sol)[source]

Function to calculate L2 error and other error metrics and print them.

Parameters
  • config (ConfigParser) – Config file from which to grab.

  • model (None) – The solved model to calculate the error for.

  • sol (GridFunction) – Gridfunction that contains the current solution.

Return type

List

Returns

A list of all of the calculated error metrics ordered by the order of the model.ref_sol[‘metrics’] dictionary.

opencmp.helpers.error.mean(gfu, mesh)[source]

Function to calculate the mean value of a gridfunction.

Parameters
  • gfu (Union[GridFunction, CoefficientFunction]) – The gridfunction of interest.

  • mesh (Mesh) – The mesh the gridfunction is defined on.

Return type

float

Returns

The mean value of the gridfunction.

opencmp.helpers.error.mean_to_zero(gfu, fes, mesh)[source]

Function to bias a gridfunction so its mean is zero.

Parameters
  • gfu (GridFunction) – The gridfunction to modify (or a component of a gridfunction).

  • fes (FESpace) – The finite element space the gridfunction is defined on.

  • mesh (Mesh) – The mesh the gridfunction is defined on.

Return type

GridFunction

Returns

The modified gridfunction.

opencmp.helpers.error.norm(norm_type, sol, ref_sol, mesh, fes, average)[source]

Function to calculate some norm between a solution and an “exact” solution.

Uses NGSolve’s Integrate function. The “exact” solution can be a known exact solution or a reference solution previously loaded from file.

Parameters
  • norm_type (str) – Which norm to calculate.

  • sol (GridFunction) – The solution GridFunction.

  • ref_sol (Union[GridFunction, CoefficientFunction]) – The “exact” solution to compare against.

  • mesh (Mesh) – The mesh to compare the solutions on.

  • fes (FESpace) – The finite element space that the solutions come from (or a component of it).

  • average (bool) – If true offset each solution by its average (use for variables like pressure that are only solved up to a constant).

Return type

float

Returns

The calculated error using the specified norm.

opencmp.helpers.error_analysis module

opencmp.helpers.error_analysis.h_convergence(config, solver, sol, var)[source]

Function to check h (mesh element size) convergence and print results.

Parameters
  • config (ConfigParser) – Config file from which to grab.

  • solver (Solver) – The solver used.

  • sol (GridFunction) – Gridfunction that contains the current solution.

  • var (str) – The variable of interest.

Return type

None

opencmp.helpers.error_analysis.p_convergence(config, solver, sol, var)[source]

Function to check p (interpolat polynomial order) convergence and print results.

Parameters
  • config (ConfigParser) – Config file from which to grab.

  • solver (Solver) – The solver used.

  • sol (GridFunction) – Gridfunction that contains the current solution.

  • var (str) – The variable of interest.

Return type

None

opencmp.helpers.io module

opencmp.helpers.io.create_and_load_gridfunction_from_file(filename, fes, current_dir=None)[source]

Function to create a gridfunction and load the contents of a file into it.

The gridfunction will be constructed from the same finite element space that the file data is assumed to come from. The file data must also fit the exact same dimensions and number of components as the given finite element space. NOTE: It is assumed that the gridfunction in the file is from the same FES and mesh as the one passed in, there is no way for the code to check. SECOND NOTE: If the FES and mesh are not the same, NGSolve will not necessarily crash, it will instead silently return garbage.

Parameters
  • filename (str) – Path to the file to load.

  • fes (FESpace) – The finite element space the file data was created for.

  • current_dir (Optional[List[str], None]) – The directory this command is being called from (ex: dim_dir if being called by DIM). Allows for file paths to be given relative to the specific config file’s directory instead of the main OpenCMP directory only.

Return type

GridFunction

Returns

A gridfunction containing the values from the file.

opencmp.helpers.io.load_mesh(config)[source]

Loads an NGSolve mesh from a .sol file whose file path is specified in the given config file.

Parameters

config (ConfigParser) – A ConfigParser object containing the information from the config file.

Return type

Mesh

Returns

The NGSolve mesh pointed to in the config file.

opencmp.helpers.io.update_gridfunction_from_files(gfu, file_dict)[source]

Function to take an existing gridfunction and load data into it from one or more files.

NOTE: It is assumed that the save data in the files is from the same FES and mesh as the existing grid function. There is no way to check this in code. SECOND NOTE: If the FES and mesh are not the same, NGSolve will not necessarily crash, it will instead silently return garbage.

Parameters
  • file_dict (Dict[Optional[int, None], str]) – Dict containing the paths to the files

  • gfu (GridFunction) – The gridfunction to load the values into

Return type

None

opencmp.helpers.math module

opencmp.helpers.math.H_s(t, w=0.1)[source]

Function to approximate the Heaviside function (step function) using a sigmoid.

Parameters
  • t (Union[int, float, Parameter, CoefficientFunction]) – Parameter representing time (or another value)

  • w (float) – Length of time over which to go from 0.0001 to 0.9999

Return type

Union[float, CoefficientFunction]

Returns

The evaluated value of the approximated Heaviside function

opencmp.helpers.math.H_t(t, w=0.1)[source]

Function to approximate the Heaviside function (step function) using a hyperbolic tangent (tanh).

Parameters
  • t (Union[int, float, Parameter, CoefficientFunction]) – Parameter reprenting time (or another value)

  • w (float) – Length of time over which to go from 0.0001 to 0.9999

Return type

Union[float, CoefficientFunction]

Returns

The evaluated value of the approximated Heaviside function

opencmp.helpers.math.ramp_cos(t, p1=0.0, p2=1.0, tr=1.0)[source]

Function to ramp from one specified value to another in a specified amount of time using the cosine function.

Parameters
  • t (Union[int, float, Parameter]) – Parameter representing time (or another value).

  • p1 (float) – The value to start the ramp at.

  • p2 (float) – The value to end the ramp at.

  • tr (float) – How quickly to ramp.

Return type

float

Returns

The evaluated value of the ramp function.

opencmp.helpers.math.sig(x)[source]

Function that implements the sigmoid function in a way that’s compatible with NGSolve Parameter and Coefficient objects.

Parameters

x (Union[int, float, Parameter, CoefficientFunction]) – The value to evaluate the sigmoid at

Return type

Union[float, CoefficientFunction]

Returns

sig(x)

opencmp.helpers.math.tanh(x)[source]

Function that implements the hyperbolic tangent in a way that’s compatible with NGSolve Parameter and Coefficient objects.

Parameters

x (Union[int, float, Parameter, CoefficientFunction]) – The value to evaluate tanh at.

Return type

Union[float, CoefficientFunction]

Returns

tanh(x)

opencmp.helpers.mesh module

opencmp.helpers.mesh.nondimensionalize_mesh_file(filename, char_length)[source]

Function to nondimensionalize a mesh file.

Given the path to a .vol or .msh file, a new file is created containing the exact same mesh but now nondimensionlized by the given characteristic length scale.

Parameters
  • filename (str) – The path to the mesh file.

  • char_length (List[float]) – The characteristic length scale. Can be different for each dimension (ex: char_length = [x_scale, y_scale, z_scale]) or if a single value is given it is used for every dimension (ex: char_length = [scale] -> char_length = [scale, scale, scale]).

Return type

None

opencmp.helpers.mesh.nondimensionlize_loaded_mesh(mesh, char_length)[source]

Function to nondimensionalize an NGSolve mesh.

Given an NGSolve mesh, the mesh nodes are modified to nondimensionlize it by the given characteristic length scale.

Parameters
  • mesh (Mesh) – The mesh to nondimensionalize.

  • char_length (List[float]) – The characteristic length scale. Can be different for each dimension (ex: char_length = [x_scale, y_scale, z_scale]) or if a single value is given it is used for every dimension (ex: char_length = [scale] -> char_length = [scale, scale, scale]).

Return type

Mesh

Returns

The original mesh now nondimensionalized.

opencmp.helpers.misc module

opencmp.helpers.misc.can_import_module(module_name)[source]

This function checks if a module can be imported. From: https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported

Parameters

module_name (str) – The name of the module to be imported

Return type

bool

Returns

True if the module can be imported, False otherwise

opencmp.helpers.misc.merge_bc_dict(dict_add_to, dict_add_from)[source]

This function merges two boundary condition dictionaries recursively.

The value of each dictionary is either another dictionary or a list.

The merging will be done semi shallowly, so not

If dict_add_from contains a key which is not present in dict_add_to, dict_add_from[key] is copied, shallowly. If the key is present in both dictionary, then the type of value associated with it must be the same. I.e. type(dict_add_to[i]) == type(dict_add_from[i])

If it is a dictionary, the function is called recursively to merge the dictionaries and store them in dict_add_to.

If the entries are lists, then the entries will merged according to the following rules. Let: list_add_to come from dict_add_to and list_add_from come from dict_add_from. 1. list_add_from[i] is None: leave list_add_to[i] alone 2. Otherwise, override list_add_to[i] with list_add_from[i]

The two lists must be of the same length

Parameters
  • dict_add_to (Dict) – The main dictionary into which things are added

  • dict_add_from (Dict) – The dictionary from which things are added

Return type

Dict

Returns

The dict_add_to dictionary with the new pieces added to it.

opencmp.helpers.ngsolve_ module

opencmp.helpers.ngsolve_.construct_identity_mat(dim)[source]

Constructs an identity matrix of the given dimension.

This expects

Parameters

dim (int) – The dimension of the matrix.

Return type

CoefficientFunction

Returns

An identity matrix of the desired dimension.

opencmp.helpers.ngsolve_.get_special_functions(mesh, nu)[source]

Generates a set of special functions needed for DG so they don’t need to be rewritten multiple times.

Parameters
  • mesh (Mesh) – The mesh used for the simulation.

  • nu (float) – The penalty parameter for interior penalty method DG.

Returns

  • n: The unit normal for every facet of the mesh.

  • h: The “size” of every mesh element.

  • alpha: The penalty coefficient.

  • I_mat: An identity matrix that matches the mesh dimension.

Return type

Tuple[CoefficientFunction, CoefficientFunction, CoefficientFunction, CoefficientFunction]

opencmp.helpers.ngsolve_.gridfunction_rigid_body_motion(t, orig_gfu, gfu, inv_R, mesh, N, scale, offset)[source]

Construct a gridfunction following rigid body motion of an original field.

This function currently only handles rigid body rotation as the only application of the diffuse interface method to moving domains is currently simulation of impeller motion in a stirred-tank reactor.

Parameters
  • t (Parameter) – Parameter containing the current time.

  • orig_gfu (GridFunction) – Gridfunction containing the initial field.

  • gfu (GridFunction) – The gridfunction whose values should be updated.

  • inv_R (Callable) – The inverse of the rotation matrix.

  • mesh (Mesh) – Structured quadrilateral/hexahedral NGSolve mesh.

  • N (List[int]) – Number of mesh elements in each direction (N+1 nodes).

  • scale (List[float]) – Extent of the meshed domain in each direction ([-2,2] square -> scale=[4,4]).

  • offset (List[float]) – Centers the meshed domain in each direction ([-2,2] square -> offset=[2,2]).

Return type

GridFunction

Returns

Gridfunction containing the field at the current time.

opencmp.helpers.ngsolve_.inverse_rigid_body_motion(new_coords, inv_R, b, c)[source]

Based on future coordinates new_coords, find the previous coordinates if rigid body motion occurred.

Parameters
  • new_coords (ndarray) – The coordinates at the future time.

  • inv_R (ndarray) – The inverse of the rotation matrix.

  • b (ndarray) – The vector to the center of rotation.

  • c (ndarray) – The translation vector.

Return type

ndarray

Returns

The coordinates at the previous time.

opencmp.helpers.ngsolve_.ngsolve_to_numpy(mesh, gfu, N, scale, offset, dim=2, binary=None)[source]

Assign the values in gfu to a numpy array whose elements correspond to the nodes of mesh while preserving spatial ordering.

The output array only contains node values, never the values of higher order dofs.

Parameters
  • mesh (Mesh) – Structured quadrilateral/hexahedral NGSolve mesh.

  • gfu (GridFunction) – NGSolve GridFunction containing the values to assign.

  • N (List[int]) – Number of mesh elements in each direction (N+1 nodes).

  • scale (List[float]) – Extent of the meshed domain in each direction ([-2,2] square -> scale=[4,4]).

  • offset (List[float]) – Centers the meshed domain in each direction ([-2,2] square -> offset=[2,2]).

  • dim (int) – Dimension of the domain (must be 2 or 3).

  • binary (Optional[ndarray, None]) – If exists, arr is multiplied by binary to zero out any array elements outside of the approximated complex geometry.

Return type

List[ndarray]

Returns

List of arrays containing the values in gfu. Since gfu may be vector-valued, the arrays in arr_vec correspond to the various components of gfu.

opencmp.helpers.ngsolve_.numpy_to_ngsolve(mesh, interp_ord, arr, scale, offset, dim=2)[source]

Assign the values in arr to a NGSolve GridFunction defined over the given NGSolve mesh while preserving spatial ordering.

Parameters
  • mesh (Mesh) – Mesh used by the problem the GridFunction will be needed to solve.

  • interp_ord (int) – Interpolant order of the finite element space for the problem.

  • arr (ndarray) – Array containing the values to assign.

  • scale (List[float]) – Extent of the meshed domain in each direction ([-2,2] square -> scale=[4,4]).

  • offset (List[float]) – Centers the meshed domain in each direction ([-2,2] square -> offset=[2,2]).

  • dim (int) – Dimension of the domain (must be 2 or 3).

Return type

GridFunction

Returns

Gridfunction containing the values in arr.

opencmp.helpers.post_processing module

class opencmp.helpers.post_processing.PhaseFieldModelMimic(model_to_copy)[source]

Bases: object

Helper class that mimics the attributes of the Model class that are used during saving and post-processing in order to be able to post-process saved phase field .sol files to .vtu.

construct_gfu()[source]

Function to construct a phase field gridfunction.

Return type

GridFunction

opencmp.helpers.post_processing._sol_to_vtu(gfu, sol_path_str, output_dir_path, save_names, delete_sol_file, subdivision, mesh)[source]

Function that gets parallelized and does the actual sol-to-vtu conversion.

Parameters
  • gfu (GridFunction) – The grid function into which to load the .sol file

  • sol_path_str (str) – The path to the solve file to load

  • output_dir_path (str) – The path to the directory to save the .vtu into

  • save_names (str) – The names of the variables to save

  • delete_sol_file (bool) – Whether or not to delete the sol file after

  • subdivision (int) – Number of subdivisions on each mesh element

  • mesh (Mesh) – The mesh on which the gfu was solved.

Return type

str

Returns

A string containing the entry for the .pvd file for this .vtu file.

opencmp.helpers.post_processing.sol_to_vtu(config, output_dir_path, model=None, delete_sol_file=False, allow_all_threads=False)[source]

Function to take the output .sol files and convert them into .vtu for visualization.

Parameters
  • config (ConfigParser) – The loaded config parser used by the model

  • output_dir_path (str) – The path to the folder in which the .sol files are, and where the .vtu files will be saved.

  • model (Union[Model, PhaseFieldModelMimic, None]) – The model that generated the .sol files.

  • delete_sol_file (bool) – Bool to indicate if to delete the original .sol files after converting to .vtu, Default is False.

  • allow_all_threads (bool) – Bool to indicate if to use all available threads (if there are enough files), Default is False.

Return type

None

opencmp.helpers.saving module

class opencmp.helpers.saving.SolutionFileSaver(model, quiet=False)[source]

Bases: object

Class to handle the saving of GridFunctions and CoefficientFunctions to file

save(gfu, timestep, DIM=False)[source]

Function to save the provided GridFunction or CoefficientFunction to file.

Parameters
  • gfu (Union[GridFunction, CoefficientFunction]) – GridFunction or CoefficientFunction to save

  • timestep (float) – The current time step, used for naming the file

  • DIM – If True, a phase field is being saved so should be saved to the phi_sol directory.

Return type

None

Module contents