Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_profile_with_fixed_parameters():
"""Test using profiles with fixed parameters."""
obj = test_objective.rosen_for_sensi(max_sensi_order=1)['obj']
lb = -2 * np.ones(5)
ub = 2 * np.ones(5)
problem = pypesto.Problem(
objective=obj, lb=lb, ub=ub,
x_fixed_vals=[0.5, -1.8], x_fixed_indices=[0, 3])
optimizer = optimize.ScipyOptimizer(options={'maxiter': 50})
result = optimize.minimize(
problem=problem, optimizer=optimizer, n_starts=2)
for i_method, next_guess_method in enumerate([
'fixed_step', 'adaptive_step_order_0',
'adaptive_step_order_1', 'adaptive_step_regression']):
print(next_guess_method)
profile.parameter_profile(
problem=problem, result=result, optimizer=optimizer,
next_guess_method=next_guess_method)
# standard plotting
axes = visualize.profiles(result, profile_list_ids=i_method)
assert len(axes) == 3
visualize.profile_cis(result, profile_list=i_method)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.info("start test")
# problem definition
def fun(_):
raise Exception("This function cannot be called.")
objective = pypesto.Objective(fun=fun)
problem = pypesto.Problem(objective, -1, 1)
optimizer = pypesto.optimize.ScipyOptimizer()
options = {'allow_failed_starts': True}
# optimization
pypesto.optimize.minimize(problem, optimizer, 5, options=options)
# assert logging worked
assert os.path.exists(filename)
f = open(filename, 'rb')
content = str(f.read())
f.close()
# tidy up
os.remove(filename)
# check if error message got inserted
assert "fail" in content
def create_optimization_history():
# create the pypesto problem
problem = create_problem()
# create optimizer
optimizer_options = {'maxiter': 200}
optimizer = optimize.ScipyOptimizer(
method='TNC', options=optimizer_options)
history_options = pypesto.HistoryOptions(
trace_record=True, trace_save_iter=1)
# run optimization
optimize_options = optimize.OptimizeOptions(allow_failed_starts=True)
result_with_trace = optimize.minimize(
problem=problem,
optimizer=optimizer,
n_starts=5,
startpoint_method=pypesto.startpoint.uniform,
options=optimize_options,
history_options=history_options
)
return result_with_trace
def test_pipeline(sampler, problem):
"""Check that a typical pipeline runs through."""
# optimization
optimizer = optimize.ScipyOptimizer(options={'maxiter': 10})
result = optimize.minimize(
problem, n_starts=3, optimizer=optimizer)
# sample
result = sample.sample(
problem, sampler=sampler, n_samples=100, result=result)
# some plot
visualize.sampling_1d_marginals(result)
plt.close()
apply_sigma(x_val, _sigma, mask)
else:
raise ValueError("Can't handle parameter type.")
nllh = compute_nllh(data, _sim, _sigma)
return nllh
# TODO gradient
objective = Objective(fun)
# optimization problem
pypesto_problem = Problem(objective, lb=lb, ub=ub, x_names=x_names)
if self.x_guesses is not None:
pypesto_problem.x_guesses = self.x_guesses
# perform the actual optimization
result = minimize(pypesto_problem, n_starts=self.n_starts)
#print(result.optimize_result.get_for_key('fval'))
#print(result.optimize_result.get_for_key('id'))
best_par = result.optimize_result.list[0]['x']
x_opt = {x_name: val
for x_name, val in zip(pypesto_problem.x_names, best_par)}
# cache
self.x_guesses = np.array([
entry['x']
for entry in result.optimize_result.list[:self.n_records]])
# scale
if scaled:
x_opt = scale_value_dict(x_opt, problem)
# the PEtab parameter table. A warning is currently produced in
# `row2problem` above.
# Could move to a separate method that is only called when a
# criterion that requires the number of estimated parameters is
# called.
self.estimated = x_fixed_estimated | set(
self.petab_problem.parameter_df.query(f'{ESTIMATE} == 1').index
)
self.n_estimated = len(self.estimated)
# TODO for BIC. Could move to `calculate_BIC()` to save time.
self.n_edata = None
self.minimize_result = None
if autorun:
self.set_result(minimize(self.pypesto_problem))
self.n_measurements = len(petab_problem.measurement_df)
self.pypesto_problem = row2problem(row,
petab_problem,
x_guess=x_guess)
self.minimize_result = None
# TODO autorun may be unnecessary now that the `minimize_options`
# argument is implemented.
if autorun:
if minimize_options:
self.set_result(minimize(self.pypesto_problem,
**minimize_options))
else:
self.set_result(minimize(self.pypesto_problem))