Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion examples/discrete_turbines/channel-optimisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import random
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
op2.init(log_level=INFO)

output_dir = 'outputs_optimisation'

Expand Down
1 change: 0 additions & 1 deletion examples/tidalfarm/tidalfarm.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

from thetis import *
from firedrake.adjoint import *
op2.init(log_level=INFO)

# start annotating all Firedrake opterations in the forward model
continue_annotation()
Expand Down
2 changes: 0 additions & 2 deletions test/firedrake/test_divergence_2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
import numpy
import os

op2.init(log_level=WARNING)


def compute(refinement=1, order=1, do_export=False):
print('--- soving refinement {:}'.format(refinement))
Expand Down
6 changes: 3 additions & 3 deletions test/firedrake/test_domain_constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ def test_domain_constant():
# create from float or (nested) list)
dc = domain_constant(value, mesh)
assert dc.ufl_shape == shape
np.testing.assert_equal(dc.dat.data, fl_arr)
np.testing.assert_equal(dc.dat.data.ravel(), fl_arr)

# create from Constant
dc = domain_constant(fd.Constant(value), mesh)
assert dc.ufl_shape == shape
np.testing.assert_equal(dc.dat.data, fl_arr)
np.testing.assert_equal(dc.dat.data.ravel(), fl_arr)

# create from domain_constant
dc = domain_constant(dc, mesh)
assert dc.ufl_shape == shape
np.testing.assert_equal(dc.dat.data, fl_arr)
np.testing.assert_equal(dc.dat.data.ravel(), fl_arr)
2 changes: 0 additions & 2 deletions test/firedrake/test_implicit_diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from thetis.utility import get_functionspace
import numpy

op2.init(log_level=WARNING)


def test_implicit_diffusion(do_export=False, do_assert=True):

Expand Down
2 changes: 0 additions & 2 deletions test/firedrake/test_implicit_friction.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import time as time_mod
import numpy

op2.init(log_level=WARNING)


def test_implicit_friction(do_export=False, do_assert=True):
# set mesh resolution
Expand Down
8 changes: 8 additions & 0 deletions test/operations/test_operations_2d-3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,14 @@ def test_anisotropic_cell_size(mesh2d):
assert numpy.allclose(cell_size.min(), (numpy.sqrt(5)-1)/10)


def test_extruded_function_shares_data(mesh2d, mesh):
V = FunctionSpace(mesh2d, "CG", 3)
extr_func = utility.ExtrudedFunction(V, mesh_3d=mesh)

extr_func.dat.data_wo[3] = 666
assert extr_func.view_3d.dat.data_ro[3] == 666


if __name__ == '__main__':
"""Run all tests"""
import os
Expand Down
2 changes: 1 addition & 1 deletion test/swe2d/test_rossby_wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def run(refinement_level, **model_options):
preproc_func=vorticity_calculator)

# Apply boundary conditions
for tag in mesh2d.exterior_facets.unique_markers:
for tag in mesh2d.facet_markers:
solver_obj.bnd_functions['shallow_water'][tag] = {'uv': Constant(as_vector([0., 0.]))}

# Apply initial conditions (asymptotic solution at initial time)
Expand Down
5 changes: 2 additions & 3 deletions test_adjoint/test_swe_adjoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from thetis import *
from firedrake.adjoint import *

op2.init(log_level=INFO)

continue_annotation()

Expand Down Expand Up @@ -119,7 +118,7 @@ def test_gradient_from_adjoint(setup):
c = Function(solver_obj.options.quadratic_drag_coefficient)
dc = Function(c)
from numpy.random import rand
c.dat.data_wo[...] = rand(*c.dat.shape)
dc.dat.data_wo[...] = rand(*dc.dat.shape)
c.dat.data_wo[...] = rand(*c.dat.data_wo.shape)
dc.dat.data_wo[...] = rand(*dc.dat.data_wo.shape)
minconv = taylor_test(Jhat, c, dc)
assert minconv > 1.90
4 changes: 2 additions & 2 deletions thetis/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,15 @@ def __init__(self, field_2d, hessian_2d, gradient_2d=None, **kwargs):
# Extract function spaces
if element_continuity(Sigma.ufl_element()).horizontal != 'cg':
raise ValueError('Hessians must be calculated in a continuous space')
if Sigma.dof_dset.dim != (2, 2):
if Sigma.shape != (2, 2):
raise ValueError('Expecting a square tensor function')
if gradient_2d is None:
V = get_functionspace(mesh, 'CG', 1, vector=True)
else:
V = gradient_2d.function_space()
if element_continuity(V.ufl_element()).horizontal != 'cg':
raise ValueError('Gradients must be calculated in a continuous space')
if V.dof_dset.dim != (2,):
if V.shape != (2,):
raise ValueError('Expecting a 2D vector function')

# Setup function spaces
Expand Down
2 changes: 1 addition & 1 deletion thetis/equation.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self, function_space, test_function=None, trial_function=None):
self.tri = trial_function or TrialFunction(self.function_space)
self.normal = FacetNormal(self.mesh)
# TODO construct them here from mesh ?
self.boundary_markers = sorted(function_space.mesh().exterior_facets.unique_markers)
self.boundary_markers = sorted(function_space.mesh().facet_markers)
self.boundary_len = function_space.mesh().boundary_len

def residual(self, solution, solution_old, fields, fields_old, bnd_conditions):
Expand Down
2 changes: 2 additions & 0 deletions thetis/exporter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Routines for handling file exports.
"""
import pyadjoint
from .utility import *
from firedrake.output.vtk_output import is_cg, VTKFile
from collections import OrderedDict
Expand Down Expand Up @@ -101,6 +102,7 @@ def set_next_export_ix(self, next_export_ix):
self.outfile.counter = itertools.count(start=self.next_export_ix)

@PETSc.Log.EventDecorator("thetis.VTKExporter.export")
@pyadjoint.stop_annotating()
def export(self, function):
"""Exports given function to disk"""
op = self.cast_operators.get(function)
Expand Down
4 changes: 2 additions & 2 deletions thetis/inversion_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ def construct_evaluator(self):
Builds evaluators needed to compute the error functional.
"""
# Create 0D mesh for station evaluation
xy = numpy.array((self.observation_x, self.observation_y)).T
xy = numpy.array((self.observation_x, self.observation_y)).T.copy()
mesh0d = fd.VertexOnlyMesh(self.mesh, xy)
self.fs_points_0d_scalar = fd.FunctionSpace(mesh0d, 'DG', 0)
if self.observed_quantity_is_scalar:
Expand All @@ -816,7 +816,7 @@ def construct_evaluator(self):
self.local_station_index = []

if len(mesh0d.coordinates.dat.data[:]) > 0:
for i in range(self.fs_points_0d_scalar.dof_dset.size):
for i in range(self.fs_points_0d_scalar.dof_count):
# loop over local DOFs and match coordinates to observations
# NOTE this must be done manually as VertexOnlyMesh reorders points
x_mesh, y_mesh = mesh0d.coordinates.dat.data[i, :]
Expand Down
101 changes: 66 additions & 35 deletions thetis/limiter.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""
Slope limiters for discontinuous fields
"""
from petsc4py import PETSc
import pyop3 as op3
from .utility import *
from firedrake import VertexBasedLimiter
from pyop2.profiling import timed_stage
import numpy


Expand Down Expand Up @@ -114,15 +115,17 @@ def compute_bounds(self, field):

if self.is_2d:
entity_dim = 1 # get 1D facets
iter_type = "exterior_facet"
facet_indices = self.P1DG.mesh().exterior_facet_local_facet_indices
else:
entity_dim = (1, 1) # get vertical facets
iter_type = "exterior_facet_vert"
facet_indices = self.P1DG.mesh().exterior_facet_vert_local_facet_indices
boundary_dofs = entity_support_dofs(self.P1DG.finat_element, entity_dim)
local_facet_nodes = numpy.array([boundary_dofs[e] for e in sorted(boundary_dofs.keys())])
n_bnd_nodes = local_facet_nodes.shape[1]
local_facet_idx = op2.Global(local_facet_nodes.shape, local_facet_nodes, dtype=numpy.int32, name='local_facet_idx')
local_facet_idx = op3.Dat.from_array(local_facet_nodes.ravel(), name='local_facet_idx', constant=True, rank_equal=True)
code = """
void my_kernel(double *qmax, double *qmin, double *field, unsigned int *facet, unsigned int *local_facet_idx)
{
double face_mean = 0.0;
for (int i = 0; i < %(nnodes)d; i++) {
unsigned int idx = local_facet_idx[facet[0]*%(nnodes)d + i];
Expand All @@ -133,25 +136,37 @@ def compute_bounds(self, field):
unsigned int idx = local_facet_idx[facet[0]*%(nnodes)d + i];
qmax[idx] = fmax(qmax[idx], face_mean);
qmin[idx] = fmin(qmin[idx], face_mean);
}
}"""
bnd_kernel = op2.Kernel(code % {'nnodes': n_bnd_nodes}, 'my_kernel')
op2.par_loop(bnd_kernel,
self.P1DG.mesh().exterior_facets.set,
self.max_field.dat(op2.MAX, self.max_field.exterior_facet_node_map()),
self.min_field.dat(op2.MIN, self.min_field.exterior_facet_node_map()),
field.dat(op2.READ, field.exterior_facet_node_map()),
self.P1DG.mesh().exterior_facets.local_facet_dat(op2.READ),
local_facet_idx(op2.READ))
}"""
bnd_kernel = op3.Function.from_c_string(
"my_kernel",
code % {'nnodes': n_bnd_nodes},
[
("qmax", op3.ScalarType, op3.MAX_RW),
("qmin", op3.ScalarType, op3.MIN_RW),
("field", op3.ScalarType, op3.READ),
("facet", field.dat.dtype, op3.READ),
("local_facet_idx", local_facet_idx.dtype, op3.READ),
],
)
op3.loop(
f := self.P1DG.mesh().iter(iter_type),
bnd_kernel(
pack(self.max_field, f),
pack(self.min_field, f),
pack(field, f),
facet_indices[f],
local_facet_idx,
),
eager=True,
)
if not self.is_2d:
# Add nodal values from surface/bottom boundaries
# NOTE calling firedrake par_loop with measure=ds_t raises an error
bottom_nodes = get_facet_mask(self.P1CG, 'bottom')
top_nodes = get_facet_mask(self.P1CG, 'top')
bottom_idx = op2.Global(len(bottom_nodes), bottom_nodes, dtype=numpy.int32, name='node_idx')
top_idx = op2.Global(len(top_nodes), top_nodes, dtype=numpy.int32, name='node_idx')
bottom_idx = op3.Dat.from_array(bottom_nodes, name='node_idx', constant=True, rank_equal=True)
top_idx = op3.Dat.from_array(top_nodes, name='node_idx', constant=True, rank_equal=True)
code = """
void my_kernel(double *qmax, double *qmin, double *field, int *idx) {
double face_mean = 0;
for (int i=0; i<%(nnodes)d; i++) {
face_mean += field[idx[i]];
Expand All @@ -160,23 +175,39 @@ def compute_bounds(self, field):
for (int i=0; i<%(nnodes)d; i++) {
qmax[idx[i]] = fmax(qmax[idx[i]], face_mean);
qmin[idx[i]] = fmin(qmin[idx[i]], face_mean);
}
}"""
kernel = op2.Kernel(code % {'nnodes': len(bottom_nodes)}, 'my_kernel')

op2.par_loop(kernel, self.mesh.cell_set,
self.max_field.dat(op2.MAX, self.max_field.function_space().cell_node_map()),
self.min_field.dat(op2.MIN, self.min_field.function_space().cell_node_map()),
field.dat(op2.READ, field.function_space().cell_node_map()),
bottom_idx(op2.READ),
iteration_region=op2.ON_BOTTOM)

op2.par_loop(kernel, self.mesh.cell_set,
self.max_field.dat(op2.MAX, self.max_field.function_space().cell_node_map()),
self.min_field.dat(op2.MIN, self.min_field.function_space().cell_node_map()),
field.dat(op2.READ, field.function_space().cell_node_map()),
top_idx(op2.READ),
iteration_region=op2.ON_TOP)
}"""
kernel = op3.Function.from_c_string(
"my_kernel",
code % {'nnodes': len(bottom_nodes)},
[
("qmax", op3.ScalarType, op3.MAX_RW),
("qmin", op3.ScalarType, op3.MIN_RW),
("field", op3.ScalarType, op3.READ),
("idx", "int", op3.READ),
],
)

op3.loop(
f := self.mesh.iter("exterior_facet_bottom"),
kernel(
pack(self.max_field, f),
pack(self.min_field, f),
pack(field, f),
bottom_idx,
),
eager=True,
)

op3.loop(
f := self.mesh.iter("exterior_facet_top"),
kernel(
pack(self.max_field, f),
pack(self.min_field, f),
pack(field, f),
top_idx,
),
eager=True,
)

@PETSc.Log.EventDecorator("thetis.VertexBasedP1DGLimiter.apply")
def apply(self, field):
Expand All @@ -185,7 +216,7 @@ def apply(self, field):

:arg field: :class:`Function` to limit
"""
with timed_stage('limiter'):
with PETSc.Log.Stage('limiter'):
if self.is_vector:
tmp_func = self.P1DG.get_work_function()
fs = field.function_space()
Expand Down
2 changes: 1 addition & 1 deletion thetis/optimisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def compute_values(self, *args):
derivatives = args[1]
if self.array_dim != len(derivatives):
raise ValueError("Need array_dim argument in ConstantControlOptimisationCallback set to the number of controls")
return [[float(d.dat.data[0]) for d in derivatives]]
return [[float(d) for d in derivatives]]

def message_str(self, *derivatives):
return 'Derivatives: {}'.format(derivatives)
Loading