Skip to content

Commit 3af8d6e

Browse files
FilippoOlivondem0
authored andcommitted
Introduce add_points method in AbstractProblem, removed unused comments in Collector class and add the test for add_points and codacy corrections
1 parent 710c777 commit 3af8d6e

File tree

4 files changed

+57
-110
lines changed

4 files changed

+57
-110
lines changed

pina/collector.py

Lines changed: 1 addition & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -62,72 +62,18 @@ def store_fixed_data(self):
6262
# condition now is ready
6363
self._is_conditions_ready[condition_name] = True
6464

65-
6665
def store_sample_domains(self):
6766
"""
6867
# TODO: Add docstring
6968
"""
7069
for condition_name in self.problem.conditions:
7170
condition = self.problem.conditions[condition_name]
7271
if not hasattr(condition, "domain"):
73-
continue
72+
continue
7473

7574
samples = self.problem.discretised_domains[condition.domain]
7675

7776
self.data_collections[condition_name] = {
7877
'input_points': samples,
7978
'equation': condition.equation
8079
}
81-
82-
# # get condition
83-
# condition = self.problem.conditions[loc]
84-
# condition_domain = condition.domain
85-
# if isinstance(condition_domain, str):
86-
# condition_domain = self.problem.domains[condition_domain]
87-
# keys = ["input_points", "equation"]
88-
# # if the condition is not ready, we get and store the data
89-
# if not self._is_conditions_ready[loc]:
90-
# # if it is the first time we sample
91-
# if not self.data_collections[loc]:
92-
# already_sampled = []
93-
# # if we have sampled the condition but not all variables
94-
# else:
95-
# already_sampled = [
96-
# self.data_collections[loc]['input_points']
97-
# ]
98-
# # if the condition is ready but we want to sample again
99-
# else:
100-
# self._is_conditions_ready[loc] = False
101-
# already_sampled = []
102-
# # get the samples
103-
# samples = [
104-
# condition_domain.sample(n=n, mode=mode,
105-
# variables=variables)
106-
# ] + already_sampled
107-
# pts = merge_tensors(samples)
108-
# if set(pts.labels).issubset(sorted(self.problem.input_variables)):
109-
# pts = pts.sort_labels()
110-
# if sorted(pts.labels) == sorted(self.problem.input_variables):
111-
# self._is_conditions_ready[loc] = True
112-
# values = [pts, condition.equation]
113-
# self.data_collections[loc] = dict(zip(keys, values))
114-
# else:
115-
# raise RuntimeError(
116-
# 'Try to sample variables which are not in problem defined '
117-
# 'in the problem')
118-
119-
def add_points(self, new_points_dict):
120-
"""
121-
Add input points to a sampled condition
122-
123-
:param new_points_dict: Dictonary of input points (condition_name:
124-
LabelTensor)
125-
:raises RuntimeError: if at least one condition is not already sampled
126-
"""
127-
for k, v in new_points_dict.items():
128-
if not self._is_conditions_ready[k]:
129-
raise RuntimeError(
130-
'Cannot add points on a non sampled condition')
131-
self.data_collections[k]['input_points'] = LabelTensor.vstack(
132-
[self.data_collections[k][
133-
'input_points'], v])

pina/problem/abstract_problem.py

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from ..condition.domain_equation_condition import DomainEquationCondition
77
from ..condition import InputPointsEquationCondition
88
from copy import deepcopy
9+
from pina import LabelTensor
910

1011

1112
class AbstractProblem(metaclass=ABCMeta):
@@ -135,12 +136,11 @@ def conditions(self):
135136
"""
136137
The conditions of the problem.
137138
"""
138-
return self._conditions
139+
return self.conditions
139140

140141
def discretise_domain(self,
141142
n,
142143
mode="random",
143-
variables="all",
144144
domains="all"):
145145
"""
146146
Generate a set of points to span the `Location` of all the conditions of
@@ -153,10 +153,8 @@ def discretise_domain(self,
153153
Available modes include: random sampling, ``random``;
154154
latin hypercube sampling, ``latin`` or ``lh``;
155155
chebyshev sampling, ``chebyshev``; grid sampling ``grid``.
156-
:param variables: problem's variables to be sampled, defaults to 'all'.
157-
:type variables: str | list[str]
158-
:param domain: problem's domain from where to sample, defaults to 'all'.
159-
:type locations: str
156+
:param domains: problem's domain from where to sample, defaults to 'all'.
157+
:type domains: str | list[str]
160158
161159
:Example:
162160
>>> pinn.discretise_domain(n=10, mode='grid')
@@ -174,22 +172,12 @@ def discretise_domain(self,
174172
# check consistecy n, mode, variables, locations
175173
check_consistency(n, int)
176174
check_consistency(mode, str)
177-
check_consistency(variables, str)
178175
check_consistency(domains, (list, str))
179176

180177
# check correct sampling mode
181178
# if mode not in DomainInterface.available_sampling_modes:
182179
# raise TypeError(f"mode {mode} not valid.")
183180

184-
# check correct variables
185-
if variables == "all":
186-
variables = self.input_variables
187-
for variable in variables:
188-
if variable not in self.input_variables:
189-
TypeError(
190-
f"Wrong variables for sampling. Variables ",
191-
f"should be in {self.input_variables}.",
192-
)
193181
# check correct location
194182
if domains == "all":
195183
domains = self.domains.keys()
@@ -198,14 +186,16 @@ def discretise_domain(self,
198186

199187
for domain in domains:
200188
self.discretised_domains[domain] = (
201-
self.domains[domain].sample(n, mode, variables)
189+
self.domains[domain].sample(n, mode)
202190
)
203-
# if not isinstance(self.conditions[loc], DomainEquationCondition):
204-
# raise TypeError(
205-
# f"Wrong locations passed, locations for sampling "
206-
# f"should be in {[loc for loc in locations if isinstance(self.conditions[loc], DomainEquationCondition)]}.",
207-
# )
208-
209-
# store data
210-
# self.collector.store_sample_domains()
211-
# self.collector.store_sample_domains(n, mode, variables, domain)
191+
192+
def add_points(self, new_points_dict):
193+
"""
194+
Add input points to a sampled condition
195+
:param new_points_dict: Dictionary of input points (condition_name:
196+
LabelTensor)
197+
:raises RuntimeError: if at least one condition is not already sampled
198+
"""
199+
for k, v in new_points_dict.items():
200+
self.discretised_domains[k] = LabelTensor.vstack(
201+
[self.discretised_domains[k], v])

tests/test_collector.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from pina.operators import laplacian
1111
from pina.collector import Collector
1212

13+
1314
# def test_supervised_tensor_collector():
1415
# class SupervisedProblem(AbstractProblem):
1516
# output_variables = None
@@ -37,6 +38,7 @@ def laplace_equation(input_, output_):
3738
my_laplace = Equation(laplace_equation)
3839
in_ = LabelTensor(torch.tensor([[0., 1.]], requires_grad=True), ['x', 'y'])
3940
out_ = LabelTensor(torch.tensor([[0.]], requires_grad=True), ['u'])
41+
4042
class Poisson(SpatialProblem):
4143
output_variables = ['u']
4244
spatial_domain = CartesianDomain({'x': [0, 1], 'y': [0, 1]})
@@ -78,7 +80,8 @@ class Poisson(SpatialProblem):
7880

7981
def poisson_sol(self, pts):
8082
return -(torch.sin(pts.extract(['x']) * torch.pi) *
81-
torch.sin(pts.extract(['y']) * torch.pi)) / (2 * torch.pi**2)
83+
torch.sin(pts.extract(['y']) * torch.pi)) / (
84+
2 * torch.pi ** 2)
8285

8386
truth_solution = poisson_sol
8487

@@ -91,30 +94,34 @@ def poisson_sol(self, pts):
9194
collector.store_fixed_data()
9295
collector.store_sample_domains()
9396

94-
for k,v in problem.conditions.items():
97+
for k, v in problem.conditions.items():
9598
if isinstance(v, InputOutputPointsCondition):
96-
assert list(collector.data_collections[k].keys()) == ['input_points', 'output_points']
99+
assert list(collector.data_collections[k].keys()) == [
100+
'input_points', 'output_points']
97101

98-
for k,v in problem.conditions.items():
102+
for k, v in problem.conditions.items():
99103
if isinstance(v, DomainEquationCondition):
100-
assert list(collector.data_collections[k].keys()) == ['input_points', 'equation']
104+
assert list(collector.data_collections[k].keys()) == [
105+
'input_points', 'equation']
106+
101107

102108
def test_supervised_graph_collector():
103-
pos = torch.rand((100,3))
104-
x = [torch.rand((100,3)) for _ in range(10)]
109+
pos = torch.rand((100, 3))
110+
x = [torch.rand((100, 3)) for _ in range(10)]
105111
graph_list_1 = RadiusGraph(pos=pos, x=x, build_edge_attr=True, r=.4)
106-
out_1 = torch.rand((10,100,3))
107-
pos = torch.rand((50,3))
108-
x = [torch.rand((50,3)) for _ in range(10)]
112+
out_1 = torch.rand((10, 100, 3))
113+
pos = torch.rand((50, 3))
114+
x = [torch.rand((50, 3)) for _ in range(10)]
109115
graph_list_2 = RadiusGraph(pos=pos, x=x, build_edge_attr=True, r=.4)
110-
out_2 = torch.rand((10,50,3))
116+
out_2 = torch.rand((10, 50, 3))
117+
111118
class SupervisedProblem(AbstractProblem):
112119
output_variables = None
113120
conditions = {
114-
'data1' : Condition(input_points=graph_list_1,
115-
output_points=out_1),
116-
'data2' : Condition(input_points=graph_list_2,
117-
output_points=out_2),
121+
'data1': Condition(input_points=graph_list_1,
122+
output_points=out_1),
123+
'data2': Condition(input_points=graph_list_2,
124+
output_points=out_2),
118125
}
119126

120127
problem = SupervisedProblem()

tests/test_problem.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import torch
22
import pytest
33
from pina.problem.zoo import Poisson2DSquareProblem as Poisson
4+
from pina import LabelTensor
5+
46

57
def test_discretise_domain():
68
n = 10
@@ -14,7 +16,7 @@ def test_discretise_domain():
1416
assert poisson_problem.discretised_domains[b].shape[0] == n
1517

1618
poisson_problem.discretise_domain(n, 'grid', domains=['D'])
17-
assert poisson_problem.discretised_domains['D'].shape[0] == n**2
19+
assert poisson_problem.discretised_domains['D'].shape[0] == n ** 2
1820
poisson_problem.discretise_domain(n, 'random', domains=['D'])
1921
assert poisson_problem.discretised_domains['D'].shape[0] == n
2022

@@ -25,6 +27,8 @@ def test_discretise_domain():
2527
assert poisson_problem.discretised_domains['D'].shape[0] == n
2628

2729
poisson_problem.discretise_domain(n)
30+
31+
2832
'''
2933
def test_sampling_few_variables():
3034
n = 10
@@ -36,8 +40,8 @@ def test_sampling_few_variables():
3640
assert poisson_problem.discretised_domains['D'].shape[1] == 1
3741
'''
3842

39-
def test_variables_correct_order_sampling():
4043

44+
def test_variables_correct_order_sampling():
4145
n = 10
4246
poisson_problem = Poisson()
4347
poisson_problem.discretise_domain(n,
@@ -50,15 +54,15 @@ def test_variables_correct_order_sampling():
5054
assert poisson_problem.discretised_domains['D'].labels == sorted(
5155
poisson_problem.input_variables)
5256

53-
# def test_add_points():
54-
# poisson_problem = Poisson()
55-
# poisson_problem.discretise_domain(0,
56-
# 'random',
57-
# domains=['D'],
58-
# variables=['x', 'y'])
59-
# new_pts = LabelTensor(torch.tensor([[0.5, -0.5]]), labels=['x', 'y'])
60-
# poisson_problem.add_points({'D': new_pts})
61-
# assert torch.isclose(poisson_problem.discretised_domain['D'].extract('x'),
62-
# new_pts.extract('x'))
63-
# assert torch.isclose(poisson_problem.discretised_domain['D'].extract('y'),
64-
# new_pts.extract('y'))
57+
58+
def test_add_points():
59+
poisson_problem = Poisson()
60+
poisson_problem.discretise_domain(0,
61+
'random',
62+
domains=['D'])
63+
new_pts = LabelTensor(torch.tensor([[0.5, -0.5]]), labels=['x', 'y'])
64+
poisson_problem.add_points({'D': new_pts})
65+
assert torch.isclose(poisson_problem.discretised_domains['D'].extract('x'),
66+
new_pts.extract('x'))
67+
assert torch.isclose(poisson_problem.discretised_domains['D'].extract('y'),
68+
new_pts.extract('y'))

0 commit comments

Comments
 (0)