Skip to content

Commit

Permalink
ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
ksagiyam committed Aug 21, 2024
1 parent a0a5fd4 commit 3da43d0
Show file tree
Hide file tree
Showing 12 changed files with 77 additions and 39 deletions.
12 changes: 8 additions & 4 deletions test/test_external_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,14 +236,16 @@ def test_extractions(domain_2d, V1):

assert extract_coefficients(e) == [u]
assert extract_arguments(e) == [vstar_e, u_hat]
assert extract_arguments_and_coefficients_and_geometric_quantities(e) == ([vstar_e, u_hat], [u], [])
assert extract_arguments_and_coefficients_and_geometric_quantities(e) == \
([vstar_e, u_hat], [u], [])
assert extract_base_form_operators(e) == [e]

F = e * dx

assert extract_coefficients(F) == [u]
assert extract_arguments(e) == [vstar_e, u_hat]
assert extract_arguments_and_coefficients_and_geometric_quantities(e) == ([vstar_e, u_hat], [u], [])
assert extract_arguments_and_coefficients_and_geometric_quantities(e) == \
([vstar_e, u_hat], [u], [])
assert F.base_form_operators() == (e,)

w = Coefficient(V1)
Expand All @@ -252,14 +254,16 @@ def test_extractions(domain_2d, V1):

assert extract_coefficients(e2) == [u, w]
assert extract_arguments(e2) == [vstar_e2, u_hat]
assert extract_arguments_and_coefficients_and_geometric_quantities(e2) == ([vstar_e2, u_hat], [u, w], [])
assert extract_arguments_and_coefficients_and_geometric_quantities(e2) == \
([vstar_e2, u_hat], [u, w], [])
assert extract_base_form_operators(e2) == [e, e2]

F = e2 * dx

assert extract_coefficients(e2) == [u, w]
assert extract_arguments(e2) == [vstar_e2, u_hat]
assert extract_arguments_and_coefficients_and_geometric_quantities(e2) == ([vstar_e2, u_hat], [u, w], [])
assert extract_arguments_and_coefficients_and_geometric_quantities(e2) == \
([vstar_e2, u_hat], [u, w], [])
assert F.base_form_operators() == (e, e2)


Expand Down
3 changes: 2 additions & 1 deletion test/test_interpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,8 @@ def test_extract_base_form_operators(V1, V2):
# -- Interpolate(u, V2) -- #
Iv = Interpolate(uhat, V2)
assert extract_arguments(Iv) == [vstar, uhat]
assert extract_arguments_and_coefficients_and_geometric_quantities(Iv) == ([vstar, uhat], [], [])
assert extract_arguments_and_coefficients_and_geometric_quantities(Iv) == \
([vstar, uhat], [], [])
assert extract_coefficients(Iv) == []
assert extract_base_form_operators(Iv) == [Iv]

Expand Down
25 changes: 20 additions & 5 deletions test/test_mixed_function_space_with_mixed_mesh.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,25 @@
from ufl import (triangle, Mesh, MixedMesh, FunctionSpace, TestFunction, TrialFunction, Coefficient,
Measure, SpatialCoordinate, FacetNormal, CellVolume, FacetArea, inner, grad, split, )
from ufl import (
CellVolume,
Coefficient,
FacetArea,
FacetNormal,
FunctionSpace,
Measure,
Mesh,
MixedMesh,
SpatialCoordinate,
TestFunction,
TrialFunction,
grad,
inner,
split,
triangle,
)
from ufl.algorithms import compute_form_data
from ufl.finiteelement import FiniteElement, MixedElement
from ufl.pullback import identity_pullback, contravariant_piola
from ufl.sobolevspace import H1, HDiv, L2
from ufl.domain import extract_domains
from ufl.finiteelement import FiniteElement, MixedElement
from ufl.pullback import contravariant_piola, identity_pullback
from ufl.sobolevspace import H1, L2, HDiv


def test_mixed_function_space_with_mixed_mesh_basic():
Expand Down
2 changes: 1 addition & 1 deletion ufl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@
from ufl.core.external_operator import ExternalOperator
from ufl.core.interpolate import Interpolate, interpolate
from ufl.core.multiindex import Index, indices
from ufl.domain import AbstractDomain, Mesh, MixedMesh, MeshView
from ufl.domain import AbstractDomain, Mesh, MeshView, MixedMesh
from ufl.finiteelement import AbstractFiniteElement
from ufl.form import BaseForm, Form, FormSum, ZeroBaseForm
from ufl.formoperators import (
Expand Down
7 changes: 5 additions & 2 deletions ufl/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,12 @@ def _get_action_form_arguments(left, right):
elif isinstance(right, CoefficientDerivative):
# Action differentiation pushes differentiation through
# right as a consequence of Leibniz formula.
from ufl.algorithms.analysis import extract_arguments_and_coefficients_and_geometric_quantities
from ufl.algorithms.analysis import (
extract_arguments_and_coefficients_and_geometric_quantities,
)

right_args, right_coeffs, _ = extract_arguments_and_coefficients_and_geometric_quantities(right)
right_args, right_coeffs, _ = \
extract_arguments_and_coefficients_and_geometric_quantities(right)
arguments = left_args + tuple(right_args)
coefficients += tuple(right_coeffs)
elif isinstance(right, (BaseCoefficient, Zero)):
Expand Down
18 changes: 12 additions & 6 deletions ufl/algorithms/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
from itertools import chain

from ufl.algorithms.traversal import iter_expressions
from ufl.domain import Mesh
from ufl.argument import BaseArgument, Coargument
from ufl.coefficient import BaseCoefficient
from ufl.constant import Constant
from ufl.geometry import GeometricQuantity
from ufl.core.base_form_operator import BaseFormOperator
from ufl.core.terminal import Terminal
from ufl.corealg.traversal import traverse_unique_terminals, unique_pre_traversal
from ufl.domain import Mesh
from ufl.form import BaseForm, Form
from ufl.geometry import GeometricQuantity
from ufl.utils.sorting import sorted_by_count, topological_sorting

# TODO: Some of these can possibly be optimised by implementing
Expand Down Expand Up @@ -203,7 +203,8 @@ def extract_base_form_operators(a):
def extract_arguments_and_coefficients_and_geometric_quantities(a):
"""Build three sorted lists of all arguments, coefficients, and geometric quantities in a.
This function is faster than extract_arguments + extract_coefficients + extract_geometric_quantities
This function is faster than
extract_arguments + extract_coefficients + extract_geometric_quantities
for large forms, and has more validation built in.
Args:
Expand All @@ -213,7 +214,9 @@ def extract_arguments_and_coefficients_and_geometric_quantities(a):
base_coeff_and_args_and_gq = extract_type(a, (BaseArgument, BaseCoefficient, GeometricQuantity))
arguments = [f for f in base_coeff_and_args_and_gq if isinstance(f, BaseArgument)]
coefficients = [f for f in base_coeff_and_args_and_gq if isinstance(f, BaseCoefficient)]
geometric_quantities = [f for f in base_coeff_and_args_and_gq if isinstance(f, GeometricQuantity)]
geometric_quantities = [f
for f in base_coeff_and_args_and_gq
if isinstance(f, GeometricQuantity)]

# Build number,part: instance mappings, should be one to one
bfnp = dict((f, (f.number(), f.part())) for f in arguments)
Expand Down Expand Up @@ -241,13 +244,16 @@ def extract_arguments_and_coefficients_and_geometric_quantities(a):
if len(gqcounts) != len(set(gqcounts.values())):
raise ValueError(
"Found different geometric quantities with same (geometric_quantity_type, domain).\n"
"The GeometricQuantities found are:\n" + "\n".join(f" {gq}" for gq in geometric_quantities)
"The GeometricQuantities found are:\n"
"\n".join(f" {gq}" for gq in geometric_quantities)
)

# Passed checks, so we can safely sort the instances by count
arguments = _sorted_by_number_and_part(arguments)
coefficients = sorted_by_count(coefficients)
geometric_quantities = list(sorted(geometric_quantities, key=lambda gq: (type(gq).name, gq._domain._ufl_id)))
geometric_quantities = list(
sorted(geometric_quantities, key=lambda gq: (type(gq).name, gq._domain._ufl_id))
)

return arguments, coefficients, geometric_quantities

Expand Down
24 changes: 13 additions & 11 deletions ufl/algorithms/apply_derivatives.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import warnings
from collections import defaultdict
from math import pi
import numpy

import numpy as np

from ufl.action import Action
from ufl.algorithms.analysis import extract_arguments
Expand Down Expand Up @@ -54,7 +55,7 @@
BaseFormOperatorDerivative,
CoordinateDerivative,
)
from ufl.domain import extract_unique_domain, MixedMesh
from ufl.domain import MixedMesh, extract_unique_domain
from ufl.form import Form, ZeroBaseForm
from ufl.operators import (
bessel_I,
Expand Down Expand Up @@ -685,9 +686,10 @@ def reference_value(self, o):
esh = (1, )
if isinstance(e.pullback, PhysicalPullback):
if ref_dim != self._var_shape[0]:
raise NotImplementedError("""PhysicalPullback not handled for immersed domain :
raise NotImplementedError("""
PhysicalPullback not handled for immersed domain :
reference dim ({ref_dim}) != physical dim (self._var_shape[0])""")
for idx in range(int(numpy.prod(esh))):
for idx in range(int(np.prod(esh))):
for i in range(ref_dim):
components.append(g[(dofoffset + idx, ) + (i, )])
else:
Expand All @@ -697,14 +699,14 @@ def reference_value(self, o):
raise RuntimeError(f"{rdim} != {ref_dim}")
if gdim != self._var_shape[0]:
raise RuntimeError(f"{gdim} != {self._var_shape[0]}")
for idx in range(int(numpy.prod(esh))):
for idx in range(int(np.prod(esh))):
for i in range(gdim):
temp = Zero()
for j in range(rdim):
temp += g[(dofoffset + idx, ) + (j, )] * K[j, i]
components.append(temp)
dofoffset += int(numpy.prod(esh))
return as_tensor(numpy.asarray(components).reshape(vsh + self._var_shape))
dofoffset += int(np.prod(esh))
return as_tensor(np.asarray(components).reshape(vsh + self._var_shape))
else:
if isinstance(f.ufl_element().pullback, PhysicalPullback):
# TODO: Do we need to be more careful for immersed things?
Expand Down Expand Up @@ -747,17 +749,17 @@ def reference_grad(self, o):
raise RuntimeError(f"{rdim} != {ref_dim}")
if gdim != self._var_shape[0]:
raise RuntimeError(f"{gdim} != {self._var_shape[0]}")
for idx in range(int(numpy.prod(esh))):
for midx in numpy.ndindex(g.ufl_shape[1:-1]):
for idx in range(int(np.prod(esh))):
for midx in np.ndindex(g.ufl_shape[1:-1]):
for i in range(gdim):
temp = Zero()
for j in range(rdim):
temp += g[(dofoffset + idx, ) + midx + (j, )] * K[j, i]
components.append(temp)
dofoffset += int(numpy.prod(esh))
dofoffset += int(np.prod(esh))
if g.ufl_shape[0] != dofoffset:
raise RuntimeError(f"{g.ufl_shape[0]} != {dofoffset}")
return as_tensor(numpy.asarray(components).reshape(vsh + self._var_shape))
return as_tensor(np.asarray(components).reshape(vsh + self._var_shape))
else:
K = JacobianInverse(domain)
return grad_to_reference_grad(o, K)
Expand Down
2 changes: 1 addition & 1 deletion ufl/algorithms/estimate_degrees.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from ufl.constantvalue import IntValue
from ufl.corealg.map_dag import map_expr_dags
from ufl.corealg.multifunction import MultiFunction
from ufl.domain import extract_unique_domain, extract_domains
from ufl.domain import extract_domains, extract_unique_domain
from ufl.form import Form
from ufl.integral import Integral

Expand Down
5 changes: 4 additions & 1 deletion ufl/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,13 @@ def __len__(self):
return len(self.meshes)

def __getitem__(self, i):
"""Return i-th component mesh."""
if i >= len(self):
raise ValueError(f"index ({i}) >= num. component meshes ({len(self)})")
return self.meshes[i]

def __iter__(self):
"""Return iterable component meshes."""
return iter(self.meshes)


Expand Down Expand Up @@ -161,7 +163,8 @@ def __init__(self, *meshes, ufl_id=None, cargo=None):
if cargo is not None and cargo.ufl_id() != self._ufl_id:
raise ValueError("Expecting cargo object (e.g. dolfin.Mesh) to have the same ufl_id.")
if any(isinstance(m, MixedMesh) for m in meshes):
raise NotImplementedError("Currently component meshes can not include MixedMesh instances")
raise NotImplementedError("""
Currently component meshes can not include MixedMesh instances""")
# currently only support single cell type.
self._ufl_cell, = set(m.ufl_cell() for m in meshes)
gdim, = set(m.geometric_dimension() for m in meshes)
Expand Down
10 changes: 7 additions & 3 deletions ufl/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,8 @@ def _analyze_domains(self):
from ufl.domain import join_domains, sort_domains

# Collect integration domains.
self._integration_domains = sort_domains(join_domains([itg.ufl_domain() for itg in self._integrals]))
self._integration_domains = \
sort_domains(join_domains([itg.ufl_domain() for itg in self._integrals]))
# Collect domains in integrands.
domains_in_integrands = set()
for o in chain(self.arguments(),
Expand Down Expand Up @@ -647,9 +648,12 @@ def _analyze_subdomain_data(self):

def _analyze_form_arguments(self):
"""Analyze which Argument and Coefficient objects can be found in the form."""
from ufl.algorithms.analysis import extract_arguments_and_coefficients_and_geometric_quantities
from ufl.algorithms.analysis import (
extract_arguments_and_coefficients_and_geometric_quantities,
)

arguments, coefficients, geometric_quantities = extract_arguments_and_coefficients_and_geometric_quantities(self)
arguments, coefficients, geometric_quantities = \
extract_arguments_and_coefficients_and_geometric_quantities(self)

# Define canonical numbering of arguments and coefficients
self._arguments = tuple(sorted(set(arguments), key=lambda x: x.number()))
Expand Down
2 changes: 1 addition & 1 deletion ufl/pullback.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from ufl.core.expr import Expr
from ufl.core.multiindex import indices
from ufl.domain import extract_unique_domain, AbstractDomain, MixedMesh
from ufl.domain import AbstractDomain, MixedMesh, extract_unique_domain
from ufl.functionspace import FunctionSpace
from ufl.tensors import as_tensor

Expand Down
6 changes: 3 additions & 3 deletions ufl/split_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Modified by Anders Logg, 2008

from ufl.domain import extract_unique_domain, MixedMesh
from ufl.domain import MixedMesh, extract_unique_domain
from ufl.functionspace import FunctionSpace
from ufl.indexed import Indexed
from ufl.permutation import compute_indices
Expand All @@ -22,7 +22,6 @@ def split(v):
If v is a Coefficient or Argument in a mixed space, returns a tuple
with the function components corresponding to the subelements.
"""

# Default range is all of v
begin = 0
end = None
Expand Down Expand Up @@ -64,7 +63,8 @@ def split(v):
def _make_domains(_domain, _element):
if isinstance(_domain, MixedMesh):
if len(_domain) != _element.num_sub_elements:
raise RuntimeError(f"len(domain) ({len(_domain)}) != element.num_sub_elements ({_element.num_sub_elements})")
raise RuntimeError(f"""len(domain) ({len(_domain)}) !=
element.num_sub_elements ({_element.num_sub_elements})""")
return _domain
else:
return tuple(_domain for _ in _element.sub_elements)
Expand Down

0 comments on commit 3da43d0

Please sign in to comment.