Skip to content

Commit b618927

Browse files
authored
Merge pull request #53 from Gromwud/main
Cumulitive update
2 parents 5580906 + 49fae96 commit b618927

10 files changed

Lines changed: 74 additions & 67 deletions

File tree

epde/operators/common/fitness.py

Lines changed: 37 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -65,22 +65,20 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
6565
"""
6666
self_args, subop_args = self.parse_suboperator_args(arguments = arguments)
6767

68-
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
68+
if force_out_of_place:
69+
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
6970
self.suboperators['coeff_calc'].apply(objective, subop_args['coeff_calc'])
7071

7172
_, target, features = objective.evaluate(normalize = False, return_val = False)
72-
try:
73-
if features is None:
74-
discr_feats = 0
75-
else:
76-
discr_feats = np.dot(features, objective.weights_final[:-1][objective.weights_internal != 0])
73+
if features is None:
74+
discr_feats = 0
75+
else:
76+
discr_feats = np.dot(features, objective.weights_final[:-1][objective.weights_internal != 0])
7777

78-
discr = (discr_feats + np.full(target.shape, objective.weights_final[-1]) - target)
79-
self.g_fun_vals = global_var.grid_cache.g_func.reshape(-1)
80-
discr = np.multiply(discr, self.g_fun_vals)
81-
rl_error = np.linalg.norm(discr, ord = 2)
82-
except ValueError:
83-
raise ValueError('An error in getting weights ')
78+
discr = (discr_feats + np.full(target.shape, objective.weights_final[-1]) - target)
79+
self.g_fun_vals = global_var.grid_cache.g_func.reshape(-1)
80+
discr = np.multiply(discr, self.g_fun_vals)
81+
rl_error = np.linalg.norm(discr, ord = 2)
8482

8583
if not (self.params['penalty_coeff'] > 0. and self.params['penalty_coeff'] < 1.):
8684
raise ValueError('Incorrect penalty coefficient set, value shall be in (0, 1).')
@@ -124,20 +122,17 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
124122
_, target, features = objective.evaluate(normalize=False, return_val=False)
125123

126124
self.get_g_fun_vals()
125+
data_shape = global_var.grid_cache.g_func.shape
127126

128-
try:
129-
if features is None:
130-
discr = target - objective.weights_final[-1]
131-
else:
132-
discr_feats = np.dot(features, objective.weights_final[:-1][objective.weights_internal != 0])
133-
discr_feats = discr_feats + objective.weights_final[-1]
134-
discr = discr_feats - target
127+
if features is None:
128+
discr = target - objective.weights_final[-1]
129+
else:
130+
discr_feats = np.dot(features, objective.weights_final[:-1][objective.weights_internal != 0])
131+
discr_feats = discr_feats + objective.weights_final[-1]
132+
discr = discr_feats - target
135133

136-
discr = np.multiply(discr, self.g_fun_vals) / np.std(target)
137-
# discr = np.multiply(discr, self.g_fun_vals) / np.linalg.norm(target, 2)
138-
rl_error = np.linalg.norm(discr, 2)
139-
except ValueError:
140-
raise ValueError('An error in getting weights ')
134+
discr = np.multiply(discr, self.g_fun_vals) / np.std(target)
135+
rl_error = np.sqrt(np.mean(discr ** 2))
141136

142137
if not (self.params['penalty_coeff'] > 0. and self.params['penalty_coeff'] < 1.):
143138
raise ValueError('Incorrect penalty coefficient set, value shall be in (0, 1).')
@@ -153,17 +148,17 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
153148
# assert objective.simplified, 'Trying to evaluate not simplified equation.'
154149

155150
# Calculate r-loss
156-
data_shape = global_var.grid_cache.g_func.shape
157151
target_vals = target.reshape(*data_shape)
158152
features_vals = []
159153

160154
if target_vals.ndim == 1:
155+
horizons_default = 30
161156
window_size = len(target_vals) // 2
162157
num_horizons = len(target_vals) - window_size + 1
163-
if num_horizons < 30:
158+
if num_horizons < horizons_default:
164159
step_size = 1
165160
else:
166-
step_size = num_horizons // 30
161+
step_size = num_horizons // horizons_default
167162
eq_window_weights = []
168163
# Compute coefficients and collect statistics over horizons
169164
if features is None:
@@ -187,21 +182,23 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
187182
eq_window_weights.append(valuable_weights)
188183
eq_cv = np.array([
189184
np.abs(np.std(_)) if np.isclose(np.mean(_), 0)
185+
# else np.abs(np.std(_) / np.sqrt(np.mean(np.pow(_, 2))))
190186
else np.abs(np.std(_) / np.mean(_))
191187
for _ in zip(*eq_window_weights)
192188
])
193-
lr = eq_cv.mean()
189+
lr = eq_cv.sum()
194190

195191
elif target_vals.ndim == 2:
196192
lr = 0
197193
for dim in range(target_vals.ndim):
194+
horizons_default = 30
198195
eq_window_weights = []
199196
window_size = target_vals.shape[dim] // 2
200197
num_horizons = target_vals.shape[dim] - window_size + 1
201-
if num_horizons < 30:
198+
if num_horizons < horizons_default:
202199
step_size = 1
203200
else:
204-
step_size = num_horizons // 30
201+
step_size = num_horizons // horizons_default
205202
# Compute coefficients and collect statistics over horizons
206203
if features is None:
207204
for start_idx in range(0, num_horizons, step_size):
@@ -235,7 +232,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
235232
else np.abs(np.std(_) / np.mean(_))
236233
for _ in zip(*eq_window_weights)
237234
])
238-
lr += eq_cv.mean()
235+
lr += eq_cv.sum()
239236

240237
elif target_vals.ndim == 3:
241238
lr = 0
@@ -282,7 +279,7 @@ def apply(self, objective: Equation, arguments: dict, force_out_of_place: bool =
282279
else np.abs(np.std(_) / np.mean(_))
283280
for _ in zip(*eq_window_weights)
284281
])
285-
lr += eq_cv.mean()
282+
lr += eq_cv.sum()
286283

287284
objective.fitness_calculated = True
288285
objective.fitness_value = fitness_value
@@ -334,8 +331,8 @@ def apply(self, objective : SoEq, arguments : dict, force_out_of_place: bool = F
334331
net = None
335332

336333
self.set_adapter(net=net)
337-
338-
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
334+
if force_out_of_place:
335+
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
339336
self.suboperators['coeff_calc'].apply(objective, subop_args['coeff_calc'])
340337

341338
print('solving equation:')
@@ -415,7 +412,8 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
415412

416413
self.set_adapter(net=net)
417414

418-
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
415+
if force_out_of_place:
416+
self.suboperators['sparsity'].apply(objective, subop_args['sparsity'])
419417
self.suboperators['coeff_calc'].apply(objective, subop_args['coeff_calc'])
420418

421419
print('solving equation:')
@@ -443,7 +441,7 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
443441
referential_data = global_var.tensor_cache.get((eq.main_var_to_explain, (1.0,)))
444442
discr = solution[..., eq_idx] - referential_data.reshape(solution[..., eq_idx].shape)
445443
discr = np.multiply(discr, self.g_fun_vals.reshape(discr.shape)) / np.std(discr)
446-
rl_error = np.linalg.norm(discr, ord=2)
444+
rl_error = np.sqrt(np.mean(discr ** 2))
447445

448446
print(f'fitness error is {rl_error}, while loss addition is {float(loss_add)}')
449447
lp = rl_error + self.params['pinn_loss_mult'] * float(
@@ -493,7 +491,7 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
493491
else np.abs(np.std(_) / np.mean(_))
494492
for _ in zip(*eq_window_weights)
495493
])
496-
lr = eq_cv.mean()
494+
lr = eq_cv.sum()
497495

498496
elif target_vals.ndim == 2:
499497
lr = 0
@@ -540,7 +538,7 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
540538
else np.abs(np.std(_) / np.mean(_))
541539
for _ in zip(*eq_window_weights)
542540
])
543-
lr += eq_cv.mean()
541+
lr += eq_cv.sum()
544542

545543
elif target_vals.ndim == 3:
546544
lr = 0
@@ -590,7 +588,7 @@ def apply(self, objective: SoEq, arguments: dict, force_out_of_place: bool = Fal
590588
else np.abs(np.std(_) / np.mean(_))
591589
for _ in zip(*eq_window_weights)
592590
])
593-
lr += eq_cv.mean()
591+
lr += eq_cv.sum()
594592

595593
eq.fitness_calculated = True
596594
eq.fitness_value = lp

epde/operators/multiobjective/moeadd_specific.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -366,12 +366,14 @@ def apply(self, objective: ParetoLevels, arguments: dict):
366366

367367
while objective.unplaced_candidates:
368368
offspring = objective.unplaced_candidates.pop()
369-
attempt = 0
369+
attempt = 1
370370
mutation_attempt_limit = self.params['mutation_attempt_limit']
371371
offspring_attempt_limit = self.params['offspring_attempt_limit']
372372
temp_offspring = deepcopy(offspring)
373373
replaced = 0
374374
while True:
375+
temp_offspring = self.suboperators['chromosome_mutation'].apply(objective=temp_offspring,
376+
arguments=subop_args['chromosome_mutation'])
375377
self.suboperators['right_part_selector'].apply(objective=temp_offspring,
376378
arguments=subop_args['right_part_selector'])
377379
temp_offspring.reset_state()
@@ -382,7 +384,7 @@ def apply(self, objective: ParetoLevels, arguments: dict):
382384
self.suboperators['pareto_level_updater'].apply(objective=(temp_offspring, objective),
383385
arguments=subop_args['pareto_level_updater'])
384386
objective.history.add(system)
385-
# print(temp_offspring.obj_fun)
387+
print(temp_offspring.obj_fun)
386388
break
387389
elif replaced == offspring_attempt_limit:
388390
print("Could not generate unique offspring")
@@ -391,8 +393,6 @@ def apply(self, objective: ParetoLevels, arguments: dict):
391393
temp_offspring = deepcopy(offspring)
392394
replaced += 1
393395
attempt = 0
394-
temp_offspring = self.suboperators['chromosome_mutation'].apply(objective=temp_offspring,
395-
arguments=subop_args['chromosome_mutation'])
396396
attempt += 1
397397
return objective
398398

@@ -447,7 +447,7 @@ def apply(self, objective : ParetoLevels, arguments : dict):
447447
self.suboperators['chromosome_fitness'].apply(objective=candidate,
448448
arguments=subop_args['chromosome_fitness'])
449449
objective.history.add(system)
450-
# print(candidate.obj_fun)
450+
print(candidate.obj_fun)
451451
objective.initial_placing()
452452

453453
# TODO: consider carefully, where normalizer init shall be held. If here, only the initial values are employed

epde/operators/multiobjective/mutations.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,22 @@ class EquationMutation(CompoundOperator):
5757
def apply(self, objective : Equation, arguments : dict):
5858
self_args, subop_args = self.parse_suboperator_args(arguments = arguments)
5959

60-
for term_idx in range(objective.n_immutable, len(objective.structure)):
61-
if np.random.uniform(0, 1) <= self.params['r_mutation']:
62-
objective.structure[term_idx] = self.suboperators['mutation'].apply(objective = (term_idx, objective),
63-
arguments = subop_args['mutation'])
64-
# term_idx = np.random.choice(len(objective.structure))
65-
# objective.structure[term_idx] = self.suboperators['mutation'].apply(objective=(term_idx, objective),
66-
# arguments=subop_args['mutation'])
60+
# for term_idx in range(objective.n_immutable, len(objective.structure)):
61+
# if np.random.uniform(0, 1) <= self.params['r_mutation']:
62+
# objective.structure[term_idx] = self.suboperators['mutation'].apply(objective = (term_idx, objective),
63+
# arguments = subop_args['mutation'])
64+
nonzero_terms_mask = np.array([False if weight == 0 else True for weight in objective.weights_internal],
65+
dtype=np.integer)
66+
nonrs_terms_idx = [i for i, term in enumerate(objective.structure) if i != objective.target_idx]
67+
nonzero_terms_idx = [item for item, keep in zip(nonrs_terms_idx, nonzero_terms_mask) if keep]
68+
nonzero_terms_idx.append(objective.target_idx)
69+
# term_idx = np.random.choice(nonzero_terms_idx)
70+
if len(nonzero_terms_idx) > 0:
71+
term_idx = np.random.choice(nonzero_terms_idx)
72+
else:
73+
term_idx = objective.target_idx
74+
objective.structure[term_idx] = self.suboperators['mutation'].apply(objective=(term_idx, objective),
75+
arguments=subop_args['mutation'])
6776
return objective
6877

6978
def use_default_tags(self):

epde/operators/utils/parameters/default_parameters_multi_objective.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
"number_of_neighbors" : 4
1111
},
1212
"ParetoLevelUpdater" : {
13-
"mutation_attempt_limit" : 5,
14-
"offspring_attempt_limit" : 5
13+
"mutation_attempt_limit" : 3,
14+
"offspring_attempt_limit" : 10
1515
},
1616
"InitialParetoLevelSorting" : {
1717

projects/pic/data/ac/ac.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,10 @@ def ac_discovery(foldername, noise_level):
132132
# preprocessor_kwargs={'epochs_max' : 1e3})
133133
epde_search_obj.set_preprocessor(default_preprocessor_type='FD',
134134
preprocessor_kwargs={})
135-
popsize = 8
135+
popsize = 16
136136

137137
epde_search_obj.set_moeadd_params(population_size=popsize,
138-
training_epochs=10)
138+
training_epochs=5)
139139

140140
custom_grid_tokens = CacheStoredTokens(token_type='grid',
141141
token_labels=['t', 'x'],
@@ -150,7 +150,7 @@ def ac_discovery(foldername, noise_level):
150150

151151
factors_max_number = {'factors_num': [1, 2], 'probas': [0.65, 0.35]}
152152

153-
bounds = (1e-8, 1e-0)
153+
bounds = (1e-12, 1e-0)
154154
epde_search_obj.fit(data=noised_data, variable_names=['u', ], max_deriv_order=(2, 3), derivs=None,
155155
equation_terms_max_number=5, data_fun_pow=3,
156156
additional_tokens=[],

projects/pic/data/kdv/kdv.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ def kdv_sindy_discovery(foldername, noise_level):
430430
popsize = 8
431431

432432
epde_search_obj.set_moeadd_params(population_size=popsize,
433-
training_epochs=5)
433+
training_epochs=10)
434434

435435
custom_trigonometric_eval_fun = {
436436
'cos(t)sin(x)': lambda *grids, **kwargs: (np.cos(grids[0]) * np.sin(grids[1])) ** kwargs['power']}
@@ -451,7 +451,7 @@ def kdv_sindy_discovery(foldername, noise_level):
451451

452452
factors_max_number = {'factors_num': [1, 2], 'probas': [0.65, 0.35]}
453453

454-
bounds = (1e-8, 1e-0)
454+
bounds = (1e-12, 1e-0)
455455
epde_search_obj.fit(data=noised_data, variable_names=['u', ], max_deriv_order=(2, 3), derivs=None,
456456
equation_terms_max_number=5, data_fun_pow=3,
457457
additional_tokens=[],

projects/pic/data/ode/ode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ def ODE_discovery(foldername, noise_level):
145145
epde_search_obj.set_preprocessor(default_preprocessor_type='FD',
146146
preprocessor_kwargs={})
147147

148-
popsize = 12
149-
epde_search_obj.set_moeadd_params(population_size=popsize, training_epochs=10)
148+
popsize = 16
149+
epde_search_obj.set_moeadd_params(population_size=popsize, training_epochs=15)
150150

151151
factors_max_number = {'factors_num': [1, 2], 'probas': [0.65, 0.35]}
152152

projects/pic/data/pde_compound/pde_compound.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def run_test(self, noise_level: int = 0) -> bool:
170170
search_obj = EpdeSearch(
171171
use_solver=False,
172172
use_pic=True,
173-
boundary=10,
173+
boundary=(10, 25),
174174
coordinate_tensors=[grid[0], grid[1]],
175175
verbose_params={'show_iter_idx': True},
176176
device='cuda'
@@ -209,10 +209,10 @@ def run_discovery(self, noise_level: int = 0) -> EpdeSearch:
209209
preprocessor_kwargs={}
210210
)
211211

212-
popsize = 12
212+
popsize = 8
213213
search_obj.set_moeadd_params(
214214
population_size=popsize,
215-
training_epochs=2
215+
training_epochs=5
216216
)
217217

218218
# Prepare custom tokens
@@ -245,7 +245,7 @@ def run_discovery(self, noise_level: int = 0) -> EpdeSearch:
245245
)
246246

247247
factors_max_number = {'factors_num': [1, 2], 'probas': [0.65, 0.35]}
248-
bounds = (1e-4, 1e-3)
248+
bounds = (1e-8, 1e-0)
249249

250250
search_obj.fit(
251251
data=noised_data,

projects/pic/data/pde_divide/pde_divide.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,10 @@ def run_discovery(self, noise_level: int = 0) -> EpdeSearch:
132132
preprocessor_kwargs={}
133133
)
134134

135-
popsize = 8
135+
popsize = 16
136136
search_obj.set_moeadd_params(
137137
population_size=popsize,
138-
training_epochs=50
138+
training_epochs=20
139139
)
140140

141141
grid_tokens, custom_trig_tokens = self.create_custom_tokens(grid)

projects/pic/data/vdp/vdp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def vdp_discovery(foldername, noise_level):
140140
epde_search_obj.set_preprocessor(default_preprocessor_type='FD',
141141
preprocessor_kwargs={})
142142

143-
popsize = 8
143+
popsize = 16
144144
epde_search_obj.set_moeadd_params(population_size=popsize, training_epochs=10)
145145

146146
factors_max_number = {'factors_num': [1, 2], 'probas': [0.65, 0.35]}

0 commit comments

Comments
 (0)