Skip to content

Commit 4ad939f

Browse files
fix connection issue
1 parent 09596a9 commit 4ad939f

File tree

7 files changed

+78
-61
lines changed

7 files changed

+78
-61
lines changed

pina/problem/zoo/inverse_poisson_2d_square.py

Lines changed: 58 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,19 @@
44
import requests
55
import torch
66
from io import BytesIO
7-
from requests.exceptions import RequestException
87
from ... import Condition
98
from ... import LabelTensor
109
from ...operator import laplacian
1110
from ...domain import CartesianDomain
1211
from ...equation import Equation, FixedValue
1312
from ...problem import SpatialProblem, InverseProblem
14-
from ...utils import custom_warning_format
13+
from ...utils import custom_warning_format, check_consistency
1514

1615
warnings.formatwarning = custom_warning_format
1716
warnings.filterwarnings("always", category=ResourceWarning)
1817

1918

20-
def _load_tensor_from_url(url, labels):
19+
def _load_tensor_from_url(url, labels, timeout=10):
2120
"""
2221
Downloads a tensor file from a URL and wraps it in a LabelTensor.
2322
@@ -28,21 +27,24 @@ def _load_tensor_from_url(url, labels):
2827
2928
:param str url: URL to the remote `.pth` tensor file.
3029
:param list[str] | tuple[str] labels: Labels for the resulting LabelTensor.
30+
:param int timeout: Timeout for the request in seconds.
3131
:return: A LabelTensor object if successful, otherwise None.
3232
:rtype: LabelTensor | None
3333
"""
34+
# Try to download the tensor file from the given URL
3435
try:
35-
response = requests.get(url)
36+
response = requests.get(url, timeout=timeout)
3637
response.raise_for_status()
3738
tensor = torch.load(
3839
BytesIO(response.content), weights_only=False
3940
).tensor.detach()
4041
return LabelTensor(tensor, labels)
41-
except RequestException as e:
42-
print(
43-
"Could not download data for 'InversePoisson2DSquareProblem' "
44-
f"from '{url}'. "
45-
f"Reason: {e}. Skipping data loading.",
42+
43+
# If the request fails, issue a warning and return None
44+
except requests.exceptions.RequestException as e:
45+
warnings.warn(
46+
f"Could not download data for 'InversePoisson2DSquareProblem' "
47+
f"from '{url}'. Reason: {e}. Skipping data loading.",
4648
ResourceWarning,
4749
)
4850
return None
@@ -66,19 +68,6 @@ def laplace_equation(input_, output_, params_):
6668
return delta_u - force_term
6769

6870

69-
# loading data
70-
input_url = (
71-
"https://github.com/mathLab/PINA/raw/refs/heads/master"
72-
"/tutorials/tutorial7/data/pts_0.5_0.5"
73-
)
74-
output_url = (
75-
"https://github.com/mathLab/PINA/raw/refs/heads/master"
76-
"/tutorials/tutorial7/data/pinn_solution_0.5_0.5"
77-
)
78-
input_data = _load_tensor_from_url(input_url, ["x", "y", "mu1", "mu2"])
79-
output_data = _load_tensor_from_url(output_url, ["u"])
80-
81-
8271
class InversePoisson2DSquareProblem(SpatialProblem, InverseProblem):
8372
r"""
8473
Implementation of the inverse 2-dimensional Poisson problem in the square
@@ -113,5 +102,50 @@ class InversePoisson2DSquareProblem(SpatialProblem, InverseProblem):
113102
"D": Condition(domain="D", equation=Equation(laplace_equation)),
114103
}
115104

116-
if input_data is not None and input_data is not None:
117-
conditions["data"] = Condition(input=input_data, target=output_data)
105+
def __init__(self, load=True, data_size=1.0):
106+
"""
107+
Initialization of the :class:`InversePoisson2DSquareProblem`.
108+
109+
:param bool load: If True, it attempts to load data from remote URLs.
110+
Set to False to skip data loading (e.g., if no internet connection).
111+
:param float data_size: The fraction of the total data to use for the
112+
"data" condition. If set to 1.0, all available data is used.
113+
If set to 0.0, no data is used. Default is 1.0.
114+
:raises ValueError: If `data_size` is not in the range [0.0, 1.0].
115+
:raises ValueError: If `data_size` is not a float.
116+
"""
117+
super().__init__()
118+
119+
# Check consistency
120+
check_consistency(load, bool)
121+
check_consistency(data_size, float)
122+
if not 0.0 <= data_size <= 1.0:
123+
raise ValueError(
124+
f"data_size must be in the range [0.0, 1.0], got {data_size}."
125+
)
126+
127+
# Load data if requested
128+
if load:
129+
130+
# Define URLs for input and output data
131+
input_url = (
132+
"https://github.com/mathLab/PINA/raw/refs/heads/master"
133+
"/tutorials/tutorial7/data/pts_0.5_0.5"
134+
)
135+
output_url = (
136+
"https://github.com/mathLab/PINA/raw/refs/heads/master"
137+
"/tutorials/tutorial7/data/pinn_solution_0.5_0.5"
138+
)
139+
140+
# Define input and output data
141+
input_data = _load_tensor_from_url(
142+
input_url, ["x", "y", "mu1", "mu2"]
143+
)
144+
output_data = _load_tensor_from_url(output_url, ["u"])
145+
146+
# Add the "data" condition
147+
if input_data is not None and output_data is not None:
148+
n_data = int(input_data.shape[0] * data_size)
149+
self.conditions["data"] = Condition(
150+
input=input_data[:n_data], target=output_data[:n_data]
151+
)
Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
from pina.problem.zoo import InversePoisson2DSquareProblem
22
from pina.problem import InverseProblem, SpatialProblem
3+
import pytest
34

45

5-
def test_constructor():
6-
problem = InversePoisson2DSquareProblem()
6+
@pytest.mark.parametrize("load", [True, False])
7+
@pytest.mark.parametrize("data_size", [0.01, 0.05])
8+
def test_constructor(load, data_size):
9+
10+
# Define the problem with or without loading data
11+
problem = InversePoisson2DSquareProblem(load=load, data_size=data_size)
12+
13+
# Discretise the domain
714
problem.discretise_domain(n=10, mode="random", domains="all")
15+
16+
# Check if the problem is correctly set up
817
assert problem.are_all_domains_discretised
918
assert isinstance(problem, InverseProblem)
1019
assert isinstance(problem, SpatialProblem)
1120
assert hasattr(problem, "conditions")
1221
assert isinstance(problem.conditions, dict)
22+
23+
# Should fail if data_size is not in the range [0.0, 1.0]
24+
with pytest.raises(ValueError):
25+
problem = InversePoisson2DSquareProblem(load=load, data_size=3.0)

tests/test_solver/test_competitive_pinn.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,9 @@
2020
# define problems
2121
problem = Poisson()
2222
problem.discretise_domain(10)
23-
inverse_problem = InversePoisson()
23+
inverse_problem = InversePoisson(load=True, data_size=0.01)
2424
inverse_problem.discretise_domain(10)
2525

26-
# reduce the number of data points to speed up testing
27-
if hasattr(inverse_problem.conditions, "data"):
28-
data_condition = inverse_problem.conditions["data"]
29-
data_condition.input = data_condition.input[:10]
30-
data_condition.target = data_condition.target[:10]
31-
3226
# add input-output condition to test supervised learning
3327
input_pts = torch.rand(10, len(problem.input_variables))
3428
input_pts = LabelTensor(input_pts, problem.input_variables)

tests/test_solver/test_gradient_pinn.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,9 @@ class DummyTimeProblem(TimeDependentProblem):
3131
# define problems
3232
problem = Poisson()
3333
problem.discretise_domain(10)
34-
inverse_problem = InversePoisson()
34+
inverse_problem = InversePoisson(load=True, data_size=0.01)
3535
inverse_problem.discretise_domain(10)
3636

37-
# reduce the number of data points to speed up testing
38-
if hasattr(inverse_problem.conditions, "data"):
39-
data_condition = inverse_problem.conditions["data"]
40-
data_condition.input = data_condition.input[:10]
41-
data_condition.target = data_condition.target[:10]
42-
4337
# add input-output condition to test supervised learning
4438
input_pts = torch.rand(10, len(problem.input_variables))
4539
input_pts = LabelTensor(input_pts, problem.input_variables)

tests/test_solver/test_pinn.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,9 @@
2020
# define problems
2121
problem = Poisson()
2222
problem.discretise_domain(10)
23-
inverse_problem = InversePoisson()
23+
inverse_problem = InversePoisson(load=True, data_size=0.01)
2424
inverse_problem.discretise_domain(10)
2525

26-
# reduce the number of data points to speed up testing
27-
if hasattr(inverse_problem.conditions, "data"):
28-
data_condition = inverse_problem.conditions["data"]
29-
data_condition.input = data_condition.input[:10]
30-
data_condition.target = data_condition.target[:10]
31-
3226
# add input-output condition to test supervised learning
3327
input_pts = torch.rand(10, len(problem.input_variables))
3428
input_pts = LabelTensor(input_pts, problem.input_variables)

tests/test_solver/test_rba_pinn.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,9 @@
1919
# define problems
2020
problem = Poisson()
2121
problem.discretise_domain(10)
22-
inverse_problem = InversePoisson()
22+
inverse_problem = InversePoisson(load=True, data_size=0.01)
2323
inverse_problem.discretise_domain(10)
2424

25-
# reduce the number of data points to speed up testing
26-
if hasattr(inverse_problem.conditions, "data"):
27-
data_condition = inverse_problem.conditions["data"]
28-
data_condition.input = data_condition.input[:10]
29-
data_condition.target = data_condition.target[:10]
30-
3125
# add input-output condition to test supervised learning
3226
input_pts = torch.rand(10, len(problem.input_variables))
3327
input_pts = LabelTensor(input_pts, problem.input_variables)

tests/test_solver/test_self_adaptive_pinn.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,9 @@
2020
# define problems
2121
problem = Poisson()
2222
problem.discretise_domain(10)
23-
inverse_problem = InversePoisson()
23+
inverse_problem = InversePoisson(load=True, data_size=0.01)
2424
inverse_problem.discretise_domain(10)
2525

26-
# reduce the number of data points to speed up testing
27-
if hasattr(inverse_problem.conditions, "data"):
28-
data_condition = inverse_problem.conditions["data"]
29-
data_condition.input = data_condition.input[:10]
30-
data_condition.target = data_condition.target[:10]
31-
3226
# add input-output condition to test supervised learning
3327
input_pts = torch.rand(10, len(problem.input_variables))
3428
input_pts = LabelTensor(input_pts, problem.input_variables)

0 commit comments

Comments
 (0)