Fix Codacy Warnings (#477)
--------- Co-authored-by: Dario Coscia <dariocos99@gmail.com>
This commit is contained in:
committed by
Nicola Demo
parent
e3790e049a
commit
4177bfbb50
@@ -1,3 +1,7 @@
|
||||
"""
|
||||
This module contains the domain classes.
|
||||
"""
|
||||
|
||||
__all__ = [
|
||||
"DomainInterface",
|
||||
"CartesianDomain",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import torch
|
||||
"""Module for CartesianDomain class."""
|
||||
|
||||
import torch
|
||||
|
||||
from .domain_interface import DomainInterface
|
||||
@@ -46,7 +47,8 @@ class CartesianDomain(DomainInterface):
|
||||
def update(self, new_domain):
|
||||
"""Adding new dimensions on the ``CartesianDomain``
|
||||
|
||||
:param CartesianDomain new_domain: A new ``CartesianDomain`` object to merge
|
||||
:param CartesianDomain new_domain: A new ``CartesianDomain`` object
|
||||
to merge
|
||||
|
||||
:Example:
|
||||
>>> spatial_domain = CartesianDomain({'x': [0, 1], 'y': [0, 1]})
|
||||
@@ -78,7 +80,7 @@ class CartesianDomain(DomainInterface):
|
||||
"""
|
||||
dim = bounds.shape[0]
|
||||
if mode in ["chebyshev", "grid"] and dim != 1:
|
||||
raise RuntimeError("Something wrong in Span...")
|
||||
raise RuntimeError("Something wrong in Cartesian...")
|
||||
|
||||
if mode == "random":
|
||||
pts = torch.rand(size=(n, dim))
|
||||
@@ -89,11 +91,10 @@ class CartesianDomain(DomainInterface):
|
||||
# elif mode == 'lh' or mode == 'latin':
|
||||
elif mode in ["lh", "latin"]:
|
||||
pts = torch_lhs(n, dim)
|
||||
else:
|
||||
raise ValueError("Invalid mode")
|
||||
|
||||
pts *= bounds[:, 1] - bounds[:, 0]
|
||||
pts += bounds[:, 0]
|
||||
|
||||
return pts
|
||||
return pts * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0]
|
||||
|
||||
def sample(self, n, mode="random", variables="all"):
|
||||
"""Sample routine.
|
||||
@@ -121,7 +122,8 @@ class CartesianDomain(DomainInterface):
|
||||
are sampled all together, and the final number of points
|
||||
|
||||
.. warning::
|
||||
The extrema values of Span are always sampled only for ``grid`` mode.
|
||||
The extrema values of Span are always sampled only for ``grid``
|
||||
mode.
|
||||
|
||||
:Example:
|
||||
>>> spatial_domain = Span({'x': [0, 1], 'y': [0, 1]})
|
||||
@@ -153,7 +155,7 @@ class CartesianDomain(DomainInterface):
|
||||
"""Sample independentely the variables and cross the results"""
|
||||
tmp = []
|
||||
for variable in variables:
|
||||
if variable in self.range_.keys():
|
||||
if variable in self.range_:
|
||||
bound = torch.tensor([self.range_[variable]])
|
||||
pts_variable = self._sample_range(n, mode, bound)
|
||||
pts_variable = pts_variable.as_subclass(LabelTensor)
|
||||
@@ -166,7 +168,7 @@ class CartesianDomain(DomainInterface):
|
||||
result = result.append(i, mode="cross")
|
||||
|
||||
for variable in variables:
|
||||
if variable in self.fixed_.keys():
|
||||
if variable in self.fixed_:
|
||||
value = self.fixed_[variable]
|
||||
pts_variable = torch.tensor([[value]]).repeat(
|
||||
result.shape[0], 1
|
||||
@@ -201,7 +203,7 @@ class CartesianDomain(DomainInterface):
|
||||
result.labels = keys
|
||||
|
||||
for variable in variables:
|
||||
if variable in self.fixed_.keys():
|
||||
if variable in self.fixed_:
|
||||
value = self.fixed_[variable]
|
||||
pts_variable = torch.tensor([[value]]).repeat(
|
||||
result.shape[0], 1
|
||||
@@ -224,7 +226,7 @@ class CartesianDomain(DomainInterface):
|
||||
"""
|
||||
tmp = []
|
||||
for variable in variables:
|
||||
if variable in self.fixed_.keys():
|
||||
if variable in self.fixed_:
|
||||
value = self.fixed_[variable]
|
||||
pts_variable = torch.tensor([[value]]).repeat(n, 1)
|
||||
pts_variable = pts_variable.as_subclass(LabelTensor)
|
||||
@@ -244,15 +246,14 @@ class CartesianDomain(DomainInterface):
|
||||
|
||||
if self.fixed_ and (not self.range_):
|
||||
return _single_points_sample(n, variables)
|
||||
if isinstance(variables, str) and variables in self.fixed_.keys():
|
||||
if isinstance(variables, str) and variables in self.fixed_:
|
||||
return _single_points_sample(n, variables)
|
||||
|
||||
if mode in ["grid", "chebyshev"]:
|
||||
return _1d_sampler(n, mode, variables).extract(variables)
|
||||
elif mode in ["random", "lh", "latin"]:
|
||||
if mode in ["random", "lh", "latin"]:
|
||||
return _Nd_sampler(n, mode, variables).extract(variables)
|
||||
else:
|
||||
raise ValueError(f"mode={mode} is not valid.")
|
||||
raise ValueError(f"mode={mode} is not valid.")
|
||||
|
||||
def is_inside(self, point, check_border=False):
|
||||
"""Check if a point is inside the ellipsoid.
|
||||
|
||||
@@ -6,10 +6,12 @@ from ..label_tensor import LabelTensor
|
||||
|
||||
|
||||
class Difference(OperationInterface):
|
||||
"""
|
||||
PINA implementation of Difference of Domains.
|
||||
"""
|
||||
|
||||
def __init__(self, geometries):
|
||||
r"""
|
||||
PINA implementation of Difference of Domains.
|
||||
Given two sets :math:`A` and :math:`B` then the
|
||||
domain difference is defined as:
|
||||
|
||||
@@ -41,7 +43,8 @@ class Difference(OperationInterface):
|
||||
:param point: Point to be checked.
|
||||
:type point: torch.Tensor
|
||||
:param bool check_border: If ``True``, the border is considered inside.
|
||||
:return: ``True`` if the point is inside the Exclusion domain, ``False`` otherwise.
|
||||
:return: ``True`` if the point is inside the Exclusion domain,
|
||||
``False`` otherwise.
|
||||
:rtype: bool
|
||||
"""
|
||||
for geometry in self.geometries[1:]:
|
||||
@@ -54,7 +57,8 @@ class Difference(OperationInterface):
|
||||
Sample routine for ``Difference`` domain.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available
|
||||
modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
|
||||
@@ -17,7 +17,6 @@ class DomainInterface(metaclass=ABCMeta):
|
||||
"""
|
||||
Abstract method returing available samples modes for the Domain.
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
@@ -25,7 +24,6 @@ class DomainInterface(metaclass=ABCMeta):
|
||||
"""
|
||||
Abstract method returing Domain variables.
|
||||
"""
|
||||
pass
|
||||
|
||||
@sample_modes.setter
|
||||
def sample_modes(self, values):
|
||||
@@ -48,7 +46,6 @@ class DomainInterface(metaclass=ABCMeta):
|
||||
Abstract method for sampling a point from the location. To be
|
||||
implemented in the child class.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def is_inside(self, point, check_border=False):
|
||||
@@ -61,4 +58,3 @@ class DomainInterface(metaclass=ABCMeta):
|
||||
of the location is considered checked to be considered inside or
|
||||
not. Defaults to ``False``.
|
||||
"""
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import torch
|
||||
"""
|
||||
Module for the Ellipsoid domain.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from .domain_interface import DomainInterface
|
||||
from ..label_tensor import LabelTensor
|
||||
from ..utils import check_consistency
|
||||
@@ -113,7 +116,7 @@ class EllipsoidDomain(DomainInterface):
|
||||
tmp = torch.tensor(list_dict_vals, dtype=torch.float)
|
||||
centers = LabelTensor(tmp.reshape(1, -1), self.variables)
|
||||
|
||||
if not all([i in ax_sq.labels for i in point.labels]):
|
||||
if not all(i in ax_sq.labels for i in point.labels):
|
||||
raise ValueError(
|
||||
"point labels different from constructor"
|
||||
f" dictionary labels. Got {point.labels},"
|
||||
@@ -202,7 +205,8 @@ class EllipsoidDomain(DomainInterface):
|
||||
"""Sample routine.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``.
|
||||
Available modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
@@ -242,7 +246,7 @@ class EllipsoidDomain(DomainInterface):
|
||||
result.labels = keys
|
||||
|
||||
for variable in variables:
|
||||
if variable in self.fixed_.keys():
|
||||
if variable in self.fixed_:
|
||||
value = self.fixed_[variable]
|
||||
pts_variable = torch.tensor([[value]]).repeat(
|
||||
result.shape[0], 1
|
||||
@@ -265,7 +269,7 @@ class EllipsoidDomain(DomainInterface):
|
||||
"""
|
||||
tmp = []
|
||||
for variable in variables:
|
||||
if variable in self.fixed_.keys():
|
||||
if variable in self.fixed_:
|
||||
value = self.fixed_[variable]
|
||||
pts_variable = torch.tensor([[value]]).repeat(n, 1)
|
||||
pts_variable = pts_variable.as_subclass(LabelTensor)
|
||||
@@ -288,5 +292,5 @@ class EllipsoidDomain(DomainInterface):
|
||||
|
||||
if mode in self.sample_modes:
|
||||
return _Nd_sampler(n, mode, variables).extract(variables)
|
||||
else:
|
||||
raise NotImplementedError(f"mode={mode} is not implemented.")
|
||||
|
||||
raise NotImplementedError(f"mode={mode} is not implemented.")
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
"""Module for Exclusion class."""
|
||||
|
||||
import random
|
||||
import torch
|
||||
from ..label_tensor import LabelTensor
|
||||
import random
|
||||
from .operation_interface import OperationInterface
|
||||
|
||||
|
||||
class Exclusion(OperationInterface):
|
||||
"""
|
||||
PINA implementation of Exclusion of Domains.
|
||||
"""
|
||||
|
||||
def __init__(self, geometries):
|
||||
r"""
|
||||
PINA implementation of Exclusion of Domains.
|
||||
Given two sets :math:`A` and :math:`B` then the
|
||||
domain difference is defined as:
|
||||
|
||||
.. math::
|
||||
A \setminus B = \{x \mid x \in A \land x \in B \land x \not\in (A \lor B)\},
|
||||
A \setminus B = \{x \mid x \in A \land x \in B \land
|
||||
x \not\in(A \lor B)\},
|
||||
|
||||
with :math:`x` a point in :math:`\mathbb{R}^N` and :math:`N`
|
||||
the dimension of the geometry space.
|
||||
@@ -39,7 +42,8 @@ class Exclusion(OperationInterface):
|
||||
:param point: Point to be checked.
|
||||
:type point: torch.Tensor
|
||||
:param bool check_border: If ``True``, the border is considered inside.
|
||||
:return: ``True`` if the point is inside the Exclusion domain, ``False`` otherwise.
|
||||
:return: ``True`` if the point is inside the Exclusion domain,
|
||||
``False`` otherwise.
|
||||
:rtype: bool
|
||||
"""
|
||||
flag = 0
|
||||
@@ -53,7 +57,8 @@ class Exclusion(OperationInterface):
|
||||
Sample routine for ``Exclusion`` domain.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available
|
||||
modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
@@ -83,7 +88,8 @@ class Exclusion(OperationInterface):
|
||||
|
||||
sampled = []
|
||||
|
||||
# calculate the number of points to sample for each geometry and the remainder.
|
||||
# calculate the number of points to sample for each geometry and the
|
||||
# remainder.
|
||||
remainder = n % len(self.geometries)
|
||||
num_points = n // len(self.geometries)
|
||||
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
"""Module for Intersection class."""
|
||||
|
||||
import random
|
||||
import torch
|
||||
from ..label_tensor import LabelTensor
|
||||
from .operation_interface import OperationInterface
|
||||
import random
|
||||
|
||||
|
||||
class Intersection(OperationInterface):
|
||||
"""
|
||||
PINA implementation of Intersection of Domains.
|
||||
"""
|
||||
|
||||
def __init__(self, geometries):
|
||||
r"""
|
||||
PINA implementation of Intersection of Domains.
|
||||
Given two sets :math:`A` and :math:`B` then the
|
||||
domain difference is defined as:
|
||||
|
||||
@@ -41,7 +43,8 @@ class Intersection(OperationInterface):
|
||||
:param point: Point to be checked.
|
||||
:type point: torch.Tensor
|
||||
:param bool check_border: If ``True``, the border is considered inside.
|
||||
:return: ``True`` if the point is inside the Intersection domain, ``False`` otherwise.
|
||||
:return: ``True`` if the point is inside the Intersection domain,
|
||||
``False`` otherwise.
|
||||
:rtype: bool
|
||||
"""
|
||||
flag = 0
|
||||
@@ -55,7 +58,8 @@ class Intersection(OperationInterface):
|
||||
Sample routine for ``Intersection`` domain.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available
|
||||
modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
@@ -85,7 +89,8 @@ class Intersection(OperationInterface):
|
||||
|
||||
sampled = []
|
||||
|
||||
# calculate the number of points to sample for each geometry and the remainder.
|
||||
# calculate the number of points to sample for each geometry and the
|
||||
# remainder.
|
||||
remainder = n % len(self.geometries)
|
||||
num_points = n // len(self.geometries)
|
||||
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
"""Module for OperationInterface class."""
|
||||
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from .domain_interface import DomainInterface
|
||||
from ..utils import check_consistency
|
||||
from abc import ABCMeta, abstractmethod
|
||||
|
||||
|
||||
class OperationInterface(DomainInterface, metaclass=ABCMeta):
|
||||
"""
|
||||
Abstract class for set domains operations.
|
||||
"""
|
||||
|
||||
def __init__(self, geometries):
|
||||
"""
|
||||
Abstract set operation class. Any geometry operation entity must inherit from this class.
|
||||
Any geometry operation entity must inherit from this class.
|
||||
|
||||
:param list geometries: A list of geometries from ``pina.geometry``
|
||||
such as ``EllipsoidDomain`` or ``CartesianDomain``.
|
||||
@@ -57,10 +60,10 @@ class OperationInterface(DomainInterface, metaclass=ABCMeta):
|
||||
:param point: Point to be checked.
|
||||
:type point: torch.Tensor
|
||||
:param bool check_border: If ``True``, the border is considered inside.
|
||||
:return: ``True`` if the point is inside the Intersection domain, ``False`` otherwise.
|
||||
:return: ``True`` if the point is inside the Intersection domain,
|
||||
``False`` otherwise.
|
||||
:rtype: bool
|
||||
"""
|
||||
pass
|
||||
|
||||
def _check_dimensions(self, geometries):
|
||||
"""Check if the dimensions of the geometries are consistent.
|
||||
@@ -71,5 +74,5 @@ class OperationInterface(DomainInterface, metaclass=ABCMeta):
|
||||
for geometry in geometries:
|
||||
if geometry.variables != geometries[0].variables:
|
||||
raise NotImplementedError(
|
||||
f"The geometries need to have same dimensions and labels."
|
||||
"The geometries need to have same dimensions and labels."
|
||||
)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
"""
|
||||
Module for Simplex Domain.
|
||||
"""
|
||||
|
||||
import torch
|
||||
from .domain_interface import DomainInterface
|
||||
from pina.domain import CartesianDomain
|
||||
from .cartesian import CartesianDomain
|
||||
from ..label_tensor import LabelTensor
|
||||
from ..utils import check_consistency
|
||||
|
||||
@@ -51,23 +55,20 @@ class SimplexDomain(DomainInterface):
|
||||
# check consistency of labels
|
||||
matrix_labels = simplex_matrix[0].labels
|
||||
if not all(vertex.labels == matrix_labels for vertex in simplex_matrix):
|
||||
raise ValueError(f"Labels don't match.")
|
||||
raise ValueError("Labels don't match.")
|
||||
|
||||
# check consistency dimensions
|
||||
dim_simplex = len(matrix_labels)
|
||||
if len(simplex_matrix) != dim_simplex + 1:
|
||||
raise ValueError(
|
||||
"An n-dimensional simplex is composed by n + 1 tensors of dimension n."
|
||||
"An n-dimensional simplex is composed by n + 1 tensors of "
|
||||
"dimension n."
|
||||
)
|
||||
|
||||
# creating vertices matrix
|
||||
self._vertices_matrix = LabelTensor.vstack(simplex_matrix)
|
||||
|
||||
# creating basis vectors for simplex
|
||||
# self._vectors_shifted = (
|
||||
# (self._vertices_matrix.T)[:, :-1] - (self._vertices_matrix.T)[:, None, -1]
|
||||
# ) ### TODO: Remove after checking
|
||||
|
||||
vert = self._vertices_matrix
|
||||
self._vectors_shifted = (vert[:-1] - vert[-1]).T
|
||||
|
||||
@@ -92,7 +93,7 @@ class SimplexDomain(DomainInterface):
|
||||
"""
|
||||
|
||||
span_dict = {}
|
||||
for i, coord in enumerate(self.variables):
|
||||
for coord in self.variables:
|
||||
sorted_vertices = torch.sort(vertices[coord].tensor.squeeze())
|
||||
# respective coord bounded by the lowest and highest values
|
||||
span_dict[coord] = [
|
||||
@@ -133,6 +134,7 @@ class SimplexDomain(DomainInterface):
|
||||
point_shift = point_shift.tensor.reshape(-1, 1)
|
||||
|
||||
# compute barycentric coordinates
|
||||
|
||||
lambda_ = torch.linalg.solve(
|
||||
self._vectors_shifted * 1.0, point_shift * 1.0
|
||||
)
|
||||
@@ -222,7 +224,8 @@ class SimplexDomain(DomainInterface):
|
||||
Sample n points from Simplex domain.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available
|
||||
modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Module for Union class."""
|
||||
|
||||
import random
|
||||
import torch
|
||||
from .operation_interface import OperationInterface
|
||||
from ..label_tensor import LabelTensor
|
||||
import random
|
||||
|
||||
|
||||
class Union(OperationInterface):
|
||||
"""
|
||||
Union of Domains.
|
||||
"""
|
||||
|
||||
def __init__(self, geometries):
|
||||
r"""
|
||||
@@ -36,7 +39,7 @@ class Union(OperationInterface):
|
||||
@property
|
||||
def sample_modes(self):
|
||||
self.sample_modes = list(
|
||||
set([geom.sample_modes for geom in self.geometries])
|
||||
set(geom.sample_modes for geom in self.geometries)
|
||||
)
|
||||
|
||||
def is_inside(self, point, check_border=False):
|
||||
@@ -61,7 +64,8 @@ class Union(OperationInterface):
|
||||
Sample routine for ``Union`` domain.
|
||||
|
||||
:param int n: Number of points to sample in the shape.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available modes include: ``random``.
|
||||
:param str mode: Mode for sampling, defaults to ``random``. Available
|
||||
modes include: ``random``.
|
||||
:param variables: Variables to be sampled, defaults to ``all``.
|
||||
:type variables: str | list[str]
|
||||
:return: Returns ``LabelTensor`` of n sampled points.
|
||||
@@ -85,7 +89,8 @@ class Union(OperationInterface):
|
||||
"""
|
||||
sampled_points = []
|
||||
|
||||
# calculate the number of points to sample for each geometry and the remainder
|
||||
# calculate the number of points to sample for each geometry and the
|
||||
# remainder
|
||||
remainder = n % len(self.geometries)
|
||||
num_points = n // len(self.geometries)
|
||||
|
||||
@@ -103,7 +108,8 @@ class Union(OperationInterface):
|
||||
num_points + int(i < remainder), mode, variables
|
||||
)
|
||||
)
|
||||
# in case number of sampled points is smaller than the number of geometries
|
||||
# in case number of sampled points is smaller than the number of
|
||||
# geometries
|
||||
if len(sampled_points) >= n:
|
||||
break
|
||||
|
||||
|
||||
Reference in New Issue
Block a user