Skip to content

Commit bf4460e

Browse files
authored
Merge pull request #65 from Gromwud/main
Cumulitive update
2 parents 073aae2 + 37e4f45 commit bf4460e

13 files changed

Lines changed: 287 additions & 172 deletions

File tree

epde/cache/cache.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,8 @@ class Cache(object):
150150
def __init__(self, device = 'cpu'):
151151
self._device = device
152152
self.max_allowed_tensors = None
153+
self._g_func_flat_cache = None
154+
self._g_func_mask_cache = None
153155

154156
self.memory_default = {'torch' : dict(), 'numpy' : dict()} # TODO: add separate cache for torch tensors and numpy
155157
self.memory_normalized = {'torch' : dict(), 'numpy' : dict()}
@@ -226,6 +228,20 @@ def g_func(self): # , g_func: Union[Callable, type(None)] = None
226228
@g_func.setter
227229
def g_func(self, function: Union[Callable, np.ndarray, list]):
228230
self._g_func = function
231+
self._g_func_flat_cache = None
232+
self._g_func_mask_cache = None
233+
234+
@property
235+
def g_func_flat(self):
236+
if self._g_func_flat_cache is None:
237+
self._g_func_flat_cache = self.g_func.reshape(-1)
238+
return self._g_func_flat_cache
239+
240+
@property
241+
def g_func_mask(self):
242+
if self._g_func_mask_cache is None:
243+
self._g_func_mask_cache = self.g_func != 0
244+
return self._g_func_mask_cache
229245

230246
def add_base_matrix(self, label):
231247
assert label in self.memory_default['numpy'].keys()

epde/globals.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,14 @@ class VerboseManager:
9797
show_iter_idx : bool
9898
iter_fitness : bool
9999
iter_stats : bool
100-
show_ann_loss : bool
100+
show_ann_loss : bool
101101
show_warnings : bool
102+
candidate_objectives : bool
102103

103-
def init_verbose(plot_DE_solutions : bool = False, show_iter_idx : bool = True,
104-
show_iter_fitness : bool = False, show_iter_stats : bool = False,
105-
show_ann_loss : bool = False, show_warnings : bool = False):
104+
def init_verbose(plot_DE_solutions : bool = False, show_iter_idx : bool = True,
105+
show_iter_fitness : bool = False, show_iter_stats : bool = False,
106+
show_ann_loss : bool = False, show_warnings : bool = False,
107+
candidate_objectives : bool = False):
106108
"""
107109
Method for initialized of manager for output in text form
108110
@@ -121,8 +123,9 @@ def init_verbose(plot_DE_solutions : bool = False, show_iter_idx : bool = True,
121123
global verbose
122124
if not show_warnings:
123125
warnings.filterwarnings("ignore")
124-
verbose = VerboseManager(plot_DE_solutions, show_iter_idx, show_iter_fitness,
125-
show_iter_stats, show_ann_loss, show_warnings)
126+
verbose = VerboseManager(plot_DE_solutions, show_iter_idx, show_iter_fitness,
127+
show_iter_stats, show_ann_loss, show_warnings,
128+
candidate_objectives)
126129

127130
def reset_control_nn(n_control: int = 1, ann: torch.nn.Sequential = None,
128131
ctrl_args: list = [(0, [None,]),], device: str = 'cpu'):

epde/operators/common/fitness.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
7878
discr_feats = np.dot(features, objective.weights_final[:-1][objective.weights_internal != 0])
7979

8080
discr = (discr_feats + np.full(target.shape, objective.weights_final[-1]) - target)
81-
self.g_fun_vals = global_var.grid_cache.g_func.reshape(-1)
81+
self.g_fun_vals = global_var.grid_cache.g_func_flat
8282
discr = np.multiply(discr, self.g_fun_vals)
8383
rl_error = np.linalg.norm(discr, ord = 2)
8484

@@ -153,7 +153,10 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
153153
objective.aic_calculated = True
154154

155155
data_shape = global_var.grid_cache.inner_shape
156-
weights = calculate_weights(features, target, self.g_fun_vals, data_shape)
156+
if hasattr(objective, '_cached_sw_weights') and objective._cached_sw_weights is not None:
157+
weights = objective._cached_sw_weights
158+
else:
159+
weights = calculate_weights(features, target, self.g_fun_vals, data_shape)
157160
weights_arr = np.array(weights)
158161
std = weights_arr.std(axis=0, ddof=1)
159162
mu = weights_arr.mean(axis=0)
@@ -164,7 +167,6 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
164167
cv[mu == 0] = 0.0 # Handle zero mean
165168

166169
total_lr = sum(cv[:-1]) / len(data_shape)
167-
# total_lr = sum(dim_results) / target_vals.ndim
168170

169171
objective.fitness_calculated = True
170172
objective.fitness_value = fitness_value
@@ -173,7 +175,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
173175

174176
def get_g_fun_vals(self):
175177
try:
176-
self.g_fun_vals = global_var.grid_cache.g_func[global_var.grid_cache.g_func != 0].reshape(-1)
178+
self.g_fun_vals = global_var.grid_cache.g_func[global_var.grid_cache.g_func_mask].reshape(-1)
177179
except AttributeError:
178180
self.g_fun_vals = None
179181

@@ -230,7 +232,7 @@ def apply(self, objective : SoEq, arguments : dict, force_out_of_place: bool = F
230232
grids = torch.stack([grid.reshape(-1) for grid in grids], dim = 1).float()
231233
solution = solution_nn(grids).detach().cpu().numpy()
232234
self.g_fun_vals = global_var.grid_cache.g_func
233-
235+
234236
if force_out_of_place:
235237
sum_err = 0
236238

@@ -306,10 +308,11 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
306308
boundary_conditions=None, use_fourier=True)
307309

308310
_, grids = global_var.grid_cache.get_all(mode='torch')
309-
grids = [grid[global_var.grid_cache.g_func != 0] for grid in grids]
311+
g_mask = global_var.grid_cache.g_func_mask
312+
grids = [grid[g_mask] for grid in grids]
310313
grids = torch.stack([grid.reshape(-1) for grid in grids], dim=1).float()
311314
solution = solution_nn(grids).detach().cpu().numpy()
312-
self.g_fun_vals = global_var.grid_cache.g_func[global_var.grid_cache.g_func != 0]
315+
self.g_fun_vals = global_var.grid_cache.g_func[g_mask]
313316

314317
if force_out_of_place:
315318
sum_err = 0
@@ -339,7 +342,10 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
339342
# Calculate r-loss
340343
data_shape = global_var.grid_cache.inner_shape
341344
_, target, features = eq.evaluate(normalize=True, return_val=False)
342-
weights = calculate_weights(features, target, self.g_fun_vals, data_shape)
345+
if hasattr(eq, '_cached_sw_weights') and eq._cached_sw_weights is not None:
346+
weights = eq._cached_sw_weights
347+
else:
348+
weights = calculate_weights(features, target, self.g_fun_vals, data_shape)
343349
weights_arr = np.array(weights)
344350
std = weights_arr.std(axis=0, ddof=1)
345351
mu = weights_arr.mean(axis=0)
@@ -369,7 +375,7 @@ def feature_reshape(self, features_vals):
369375

370376
def get_g_fun_vals(self):
371377
try:
372-
self.g_fun_vals = global_var.grid_cache.g_func.reshape(-1)
378+
self.g_fun_vals = global_var.grid_cache.g_func_flat
373379
except AttributeError:
374380
self.g_fun_vals = None
375381

epde/operators/common/right_part_selection.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ def apply(self, objective : Equation, arguments : dict):
6868
min_idx = target_idx
6969
weights_internal = objective.weights_internal
7070
weights_final = [weight for weight in objective.weights_final if weight != 0]
71+
sw_weights = objective._cached_sw_weights
7172

7273
objective.weights_internal_evald = False
7374
objective.weights_final_evald = False
@@ -78,6 +79,7 @@ def apply(self, objective : Equation, arguments : dict):
7879

7980
objective.weights_internal = weights_internal
8081
objective.weights_final = weights_final
82+
objective._cached_sw_weights = sw_weights
8183
objective.weights_internal_evald = True
8284
objective.weights_final_evald = True
8385
objective.target_idx = min_idx

epde/operators/common/sparsity.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@ def get_cv(self, weights):
4141

4242
def fit(self, X, y, sample_weights):
4343
self.n_samples, self.n_features = X.shape
44+
self.cached_weights_ = None
4445

4546
# 1. Initial Weights
4647
weights = calculate_weights(X, y, sample_weights=sample_weights, grid_shape=self.grid_shape)
48+
self.cached_weights_ = weights
4749
cv = self.get_cv(weights[:, :-1])
4850

4951
self.coef_ = weights.mean(axis=0)[:-1]
@@ -80,6 +82,7 @@ def fit(self, X, y, sample_weights):
8082

8183
if new_coef == 0:
8284
weights = calculate_weights(X[:, self.coef_ != 0], y, sample_weights=sample_weights, grid_shape=self.grid_shape)
85+
self.cached_weights_ = weights
8386
new_cv = iter(self.get_cv(weights[:, :-1]))
8487
cv = np.array([next(new_cv) if _ else 0 for _ in self.coef_ != 0])
8588

@@ -151,14 +154,16 @@ def apply(self, objective : Equation, arguments : dict):
151154

152155
_, target, features = objective.evaluate(normalize = True, return_val = False)
153156

154-
self.g_fun_vals = global_var.grid_cache.g_func[global_var.grid_cache.g_func != 0]
157+
self.g_fun_vals = global_var.grid_cache.g_func[global_var.grid_cache.g_func_mask]
155158

156159
estimator.fit(features, target, self.g_fun_vals)
157160
objective.weights_internal = estimator.coef_
158161
objective.weights_internal_evald = True
159162
objective.weights_final = np.append(objective.weights_internal, estimator.intercept_)
160163
objective.weights_final_evald = True
161164
objective.weights_final = [weight for weight in objective.weights_final if weight != 0]
165+
objective._cached_sw_weights = estimator.cached_weights_
166+
objective._eval_cache = {}
162167

163168

164169
def use_default_tags(self):

0 commit comments

Comments
 (0)