Skip to content

Commit 3c9add8

Browse files
authored
Merge pull request #37 from Gromwud/main
Cumulitive EPDE updates
2 parents e59d45e + e88c2f2 commit 3c9add8

3 files changed

Lines changed: 48 additions & 58 deletions

File tree

epde/operators/common/fitness.py

Lines changed: 31 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
170170
# print(aic)
171171
# print(len([_ for _ in objective.weights_final if _ !=0]))
172172
# print(objective.aic)
173+
assert objective.simplified, 'Trying to evaluate not simplified equation.'
173174

174175
# Calculate r-loss
175176
data_shape = global_var.grid_cache.g_func.shape
@@ -189,17 +190,21 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
189190
if target_vals.ndim == 1:
190191
window_size = len(target_vals) // 2
191192
num_horizons = len(target_vals) - window_size + 1
193+
if window_size < 15:
194+
step_size = 1
195+
else:
196+
step_size = num_horizons // 30
192197
eq_window_weights = []
193198
# Compute coefficients and collect statistics over horizons
194199
if len(features_vals) == 0:
195-
for start_idx in range(num_horizons):
200+
for start_idx in range(0, num_horizons, step_size):
196201
end_idx = start_idx + window_size
197202
target_window = target_vals[start_idx:end_idx]
198203
eq_window_weights.append(np.abs(np.std(target_window) / np.mean(target_window)))
199204
lr = np.mean(eq_window_weights)
200205
else:
201206
features = self.feature_reshape(features_vals)
202-
for start_idx in range(num_horizons):
207+
for start_idx in range(0, num_horizons, step_size):
203208
end_idx = start_idx + window_size
204209
target_window = target_vals[start_idx:end_idx]
205210
feature_window = features[start_idx:end_idx, :]
@@ -216,9 +221,13 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
216221
eq_window_weights = []
217222
window_size = target_vals.shape[dim] // 2
218223
num_horizons = target_vals.shape[dim] - window_size + 1
224+
if window_size < 15:
225+
step_size = 1
226+
else:
227+
step_size = num_horizons // 30
219228
# Compute coefficients and collect statistics over horizons
220229
if len(features_vals) == 0:
221-
for start_idx in range(num_horizons):
230+
for start_idx in range(0, num_horizons, step_size):
222231
end_idx = start_idx + window_size
223232
if dim == 0:
224233
target_window = target_vals[start_idx:end_idx, :].reshape(-1)
@@ -228,7 +237,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
228237
lr += np.mean(eq_window_weights)
229238
else:
230239
features = self.feature_reshape(features_vals)
231-
for start_idx in range(num_horizons):
240+
for start_idx in range(0, num_horizons, step_size):
232241
end_idx = start_idx + window_size
233242
estimator = LinearRegression(fit_intercept=False)
234243
if dim == 0:
@@ -454,23 +463,18 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
454463
print(f'solution shape {solution.shape}')
455464
print(f'solution[..., eq_idx] {solution[..., eq_idx].shape}, eq_idx {eq_idx}')
456465
referential_data = global_var.tensor_cache.get((eq.main_var_to_explain, (1.0,)))
457-
# initial_data = global_var.tensor_cache.get(('u', (1.0,))).reshape(solution[..., eq_idx].shape)
458-
#
459-
# sol_pinn = solution[..., eq_idx]
460-
# sol_ann = referential_data.reshape(solution[..., eq_idx].shape)
461-
# sol_pinn_normalized = (sol_pinn - min(initial_data)) / (max(initial_data) - min(initial_data))
462-
# sol_ann_normalized = (sol_ann - min(initial_data)) / (max(initial_data) - min(initial_data))
463-
#
464-
# discr = sol_pinn_normalized - sol_ann_normalized
465-
discr = (solution[..., eq_idx] - referential_data.reshape(solution[..., eq_idx].shape)) # Default
466+
maximum = np.max([referential_data.max(axis=0), solution[..., eq_idx].max(axis=0)])
467+
minimum = np.min([referential_data.min(axis=0), solution[..., eq_idx].min(axis=0)])
468+
discr = ((solution[..., eq_idx] - minimum) - (referential_data - minimum)) / (maximum - minimum) # Normalized
469+
# discr = (solution[..., eq_idx] - referential_data.reshape(solution[..., eq_idx].shape)) # Default
466470
discr = np.multiply(discr, self.g_fun_vals.reshape(discr.shape))
467471
rl_error = np.linalg.norm(discr, ord=2)
468472

469473
print(f'fitness error is {rl_error}, while loss addition is {float(loss_add)}')
470474
lp = rl_error + self.params['pinn_loss_mult'] * float(
471-
loss_add) # TODO: make pinn_loss_mult case dependent
472-
if np.sum(eq.weights_final) == 0:
473-
lp /= self.params['penalty_coeff']
475+
loss_add) * 0 # TODO: make pinn_loss_mult case dependent
476+
# if np.sum(eq.weights_final) == 0:
477+
# lp /= self.params['penalty_coeff']
474478

475479
ssr = np.sum(discr ** 2)
476480
n = len(discr)
@@ -488,6 +492,7 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
488492
eq.aic_calculated = True
489493

490494
# Calculate r-loss
495+
data_shape = global_var.grid_cache.g_func.shape
491496
target = eq.structure[eq.target_idx]
492497
target_vals = target.evaluate(False).reshape(*data_shape)
493498
features_vals = []
@@ -548,20 +553,12 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
548553
estimator = LinearRegression(fit_intercept=False)
549554
if dim == 0:
550555
target_window = target_vals[start_idx:end_idx, :].reshape(-1)
551-
feature_window = features.reshape(*data_shape, -1)[start_idx:end_idx, :].reshape(-1,
552-
features.shape[
553-
-1])
554-
estimator.fit(feature_window, target_window,
555-
sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[start_idx:end_idx,
556-
:].reshape(-1))
556+
feature_window = features.reshape(*data_shape, -1)[start_idx:end_idx, :].reshape(-1, features.shape[-1])
557+
estimator.fit(feature_window, target_window, sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[start_idx:end_idx, :].reshape(-1))
557558
else:
558559
target_window = target_vals[:, start_idx:end_idx].reshape(-1)
559-
feature_window = features.reshape(*data_shape, -1)[:, start_idx:end_idx].reshape(-1,
560-
features.shape[
561-
-1])
562-
estimator.fit(feature_window, target_window,
563-
sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:,
564-
start_idx:end_idx].reshape(-1))
560+
feature_window = features.reshape(*data_shape, -1)[:, start_idx:end_idx].reshape(-1, features.shape[-1])
561+
estimator.fit(feature_window, target_window, sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:, start_idx:end_idx].reshape(-1))
565562
valuable_weights = estimator.coef_[:-1]
566563
eq_window_weights.append(valuable_weights)
567564
eq_cv = np.array([np.abs(np.std(_) / np.mean(_)) for _ in zip(*eq_window_weights)])
@@ -592,28 +589,16 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
592589
estimator = LinearRegression(fit_intercept=False)
593590
if dim == 0:
594591
target_window = target_vals[start_idx:end_idx, :, :].reshape(-1)
595-
feature_window = features.reshape(*data_shape, -1)[start_idx:end_idx, :, :].reshape(-1,
596-
features.shape[
597-
-1])
598-
estimator.fit(feature_window, target_window,
599-
sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[start_idx:end_idx, :,
600-
:].reshape(-1))
592+
feature_window = features.reshape(*data_shape, -1)[start_idx:end_idx, :, :].reshape(-1, features.shape[-1])
593+
estimator.fit(feature_window, target_window, sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[start_idx:end_idx, :, :].reshape(-1))
601594
elif dim == 1:
602595
target_window = target_vals[:, start_idx:end_idx, :].reshape(-1)
603-
feature_window = features.reshape(*data_shape, -1)[:, start_idx:end_idx, :].reshape(-1,
604-
features.shape[
605-
-1])
606-
estimator.fit(feature_window, target_window,
607-
sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:, start_idx:end_idx,
608-
:].reshape(-1))
596+
feature_window = features.reshape(*data_shape, -1)[:, start_idx:end_idx, :].reshape(-1, features.shape[-1])
597+
estimator.fit(feature_window, target_window, sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:, start_idx:end_idx, :].reshape(-1))
609598
elif dim == 2:
610599
target_window = target_vals[:, :, start_idx:end_idx].reshape(-1)
611-
feature_window = features.reshape(*data_shape, -1)[:, :, start_idx:end_idx].reshape(-1,
612-
features.shape[
613-
-1])
614-
estimator.fit(feature_window, target_window,
615-
sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:, :,
616-
start_idx:end_idx].reshape(-1))
600+
feature_window = features.reshape(*data_shape, -1)[:, :, start_idx:end_idx].reshape(-1, features.shape[-1])
601+
estimator.fit(feature_window, target_window, sample_weight=self.g_fun_vals.reshape(*data_shape, -1)[:, :, start_idx:end_idx].reshape(-1))
617602
valuable_weights = estimator.coef_[:-1]
618603
eq_window_weights.append(valuable_weights)
619604
eq_cv = np.array([np.abs(np.std(_) / np.mean(_)) for _ in zip(*eq_window_weights)])

epde/operators/common/right_part_selection.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,11 @@ def apply(self, objective : Equation, arguments : dict):
5252
min_fitness = np.inf
5353
weights_internal = np.zeros_like(objective.structure)
5454
min_idx = 0
55-
if not objective.contains_deriv(objective.main_var_to_explain):
56-
objective.restore_property(deriv = True)
57-
if not objective.contains_variable(objective.main_var_to_explain):
58-
objective.restore_property(mandatory_family = objective.main_var_to_explain)
55+
if not any(term.contains_variable(objective.main_var_to_explain) and term.contains_deriv(objective.main_var_to_explain) for term in objective.structure):
56+
objective.restore_property(mandatory_family=objective.main_var_to_explain, deriv=True)
5957

6058
for target_idx, target_term in enumerate(objective.structure):
61-
if not objective.structure[target_idx].contains_deriv(objective.main_var_to_explain):
59+
if not (objective.structure[target_idx].contains_variable(objective.main_var_to_explain) and objective.structure[target_idx].contains_deriv(objective.main_var_to_explain)):
6260
continue
6361
objective.target_idx = target_idx
6462
fitness = self.suboperators['fitness_calculation'].apply(objective,

epde/structure/main_structures.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,8 @@ def evaluate(self, structural, grids=None):
215215
self.prev_normalized = normalize
216216
value = super().evaluate(structural)
217217
if normalize:
218+
value = np.ones_like(value)
218219
if np.ndim(value) != 1:
219-
value = np.ones_like(value)
220220
for factor in self.structure:
221221
temp = factor.evaluate()
222222
# value *= normalize_ts(temp)
@@ -226,10 +226,14 @@ def evaluate(self, structural, grids=None):
226226
# # value = normalize_ts(value)
227227
# value = minmax_normalize(value)
228228
else:
229-
if np.std(value) != 0:
230-
value = (value - np.mean(value)) / np.std(value)
231-
else:
232-
value = (value - np.mean(value))
229+
# if np.std(value) != 0:
230+
# value = (value - np.mean(value)) / np.std(value)
231+
# else:
232+
# value = (value - np.mean(value))
233+
for factor in self.structure:
234+
temp = factor.evaluate()
235+
# value *= normalize_ts(temp)
236+
value *= (temp - np.mean(temp) - np.min(temp)) / (np.max(temp) - np.min(temp))
233237
if np.all([len(factor.params) == 1 for factor in self.structure]) and grids is None:
234238
# Место возможных проблем: сохранение/загрузка нормализованных данных
235239
self.saved[normalize] = global_var.tensor_cache.add(self.cache_label, value, normalized=normalize)
@@ -508,10 +512,13 @@ def restore_property(self, deriv: bool = False, mandatory_family: bool = False):
508512
mf_marker = mandatory_family if mandatory_family else None
509513
temp = Term(self.pool, mandatory_family=mf_marker,
510514
max_factors_in_term=self.metaparameters['max_factors_in_term']['value'])
511-
if deriv and temp.contains_deriv():
515+
if deriv and mandatory_family and temp.contains_deriv() and temp.contains_variable(self.main_var_to_explain):
516+
self.structure[replacement_idx] = temp
517+
break
518+
elif deriv and temp.contains_deriv() and not mandatory_family:
512519
self.structure[replacement_idx] = temp
513520
break
514-
elif mandatory_family and temp.contains_variable(self.main_var_to_explain):
521+
elif mandatory_family and temp.contains_variable(self.main_var_to_explain) and not deriv:
515522
self.structure[replacement_idx] = temp
516523
break
517524
else:

0 commit comments

Comments
 (0)