Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended Amici history #1263

Merged
merged 26 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
2528989
add extended history for AmiciObjective
plakrisenko Dec 20, 2023
293f8b7
test amici history
plakrisenko Dec 20, 2023
50f582b
add _simulation_to_values method
plakrisenko Dec 22, 2023
29e5f7e
add CsvAmiciHistory
plakrisenko Dec 22, 2023
4d8d34f
docstrings
plakrisenko Dec 22, 2023
079dbd6
fix typo
plakrisenko Dec 22, 2023
6606558
spell out Backward
plakrisenko Dec 22, 2023
ec77861
import order
plakrisenko Dec 22, 2023
3ac4073
Merge branch 'develop' into amici_history
m-philipps Jan 5, 2024
1bd4fc7
black
m-philipps Jan 5, 2024
92b8c5e
convert ms to s
plakrisenko Jan 5, 2024
ed63dfe
no amici in pypesto.optimize
plakrisenko Jan 8, 2024
8c0fdfb
Update test/base/test_history.py
plakrisenko Jan 8, 2024
26059db
Update pypesto/optimize/optimizer.py
plakrisenko Jan 8, 2024
926620b
delete files in the test
plakrisenko Jan 8, 2024
1388693
style
plakrisenko Jan 8, 2024
b6a750e
Merge branch 'develop' into amici_history
plakrisenko Jan 8, 2024
f543041
isort
plakrisenko Jan 8, 2024
ddeee94
black
plakrisenko Jan 8, 2024
994900c
Update pypesto/history/amici.py
plakrisenko Jan 9, 2024
fce0037
more compact code
plakrisenko Jan 9, 2024
996b21e
Merge branch 'develop' into amici_history
plakrisenko Jan 9, 2024
dcc8cd7
Merge branch 'develop' into amici_history
plakrisenko Jan 10, 2024
1d96334
Merge branch 'develop' into amici_history
plakrisenko Jan 12, 2024
7822cab
Merge branch 'develop' into amici_history
plakrisenko Jan 15, 2024
9c9a229
Merge branch 'develop' into amici_history
plakrisenko Jan 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pypesto/C.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,12 @@ class InnerParameterType(str, Enum):
SUFFIXES_HDF5 = ["hdf5", "h5"]
SUFFIXES = SUFFIXES_CSV + SUFFIXES_HDF5

CPU_TIME_TOTAL = 'cpu_time_total'
PREEQ_CPU_TIME = 'preeq_cpu_time'
PREEQ_CPU_TIME_B = 'preeq_cpu_timeB'
POSTEQ_CPU_TIME = 'posteq_cpu_time'
POSTEQ_CPU_TIME_B = 'posteq_cpu_timeB'
plakrisenko marked this conversation as resolved.
Show resolved Hide resolved


###############################################################################
# PRIOR
Expand Down
1 change: 1 addition & 0 deletions pypesto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
CountHistoryBase,
CsvHistory,
Hdf5History,
Hdf5AmiciHistory,
NoHistory,
HistoryBase,
HistoryOptions,
Expand Down
1 change: 1 addition & 0 deletions pypesto/history/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
and evaluate performance.
"""

from .amici import Hdf5AmiciHistory
from .base import CountHistory, CountHistoryBase, HistoryBase, NoHistory
from .csv import CsvHistory
from .generate import create_history
Expand Down
160 changes: 160 additions & 0 deletions pypesto/history/amici.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import time
from pathlib import Path
from typing import Sequence, Union

import numpy as np

from ..C import (
FVAL,
GRAD,
HESS,
N_ITERATIONS,
RES,
SRES,
RDATAS,
TIME,
ModeType,
X,
CPU_TIME_TOTAL,
PREEQ_CPU_TIME,
POSTEQ_CPU_TIME_B,
POSTEQ_CPU_TIME,
PREEQ_CPU_TIME_B
)
from .base import add_fun_from_res, reduce_result_via_options
from .hdf5 import Hdf5History, with_h5_file
from .options import HistoryOptions
from .util import ResultDict, trace_wrap


class Hdf5AmiciHistory(Hdf5History):
"""
Stores a representation of the history in an HDF5 file, extended with
AMICI-specific traces of total simulation time, pre-equilibration time and
post-equilibration time

Parameters
----------
id:
Id of the history
file:
HDF5 file name.
options:
History options. Defaults to ``None``.
"""

def __init__(
self,
id: str,
file: Union[str, Path],
options: Union[HistoryOptions, dict, None] = None,
):
super().__init__(id, file, options=options)

@with_h5_file("a")
def _update_trace(
self,
x: np.ndarray,
sensi_orders: tuple[int],
mode: ModeType,
result: ResultDict,
) -> None:
"""Update and possibly store the trace."""
if not self.options.trace_record:
return

# calculating function values from residuals
# and reduce via requested history options
result = reduce_result_via_options(
add_fun_from_res(result), self.options
)

used_time = time.time() - self.start_time

values = {
X: x,
FVAL: result[FVAL],
GRAD: result[GRAD],
RES: result[RES],
SRES: result[SRES],
HESS: result[HESS],
TIME: used_time,
CPU_TIME_TOTAL: sum([rdata[CPU_TIME_TOTAL] for rdata in
result[RDATAS]]),
PREEQ_CPU_TIME: sum([rdata[PREEQ_CPU_TIME] for rdata in
result[RDATAS]]),
PREEQ_CPU_TIME_B: sum([rdata[PREEQ_CPU_TIME_B] for rdata in
result[RDATAS]]),
POSTEQ_CPU_TIME: sum([rdata[POSTEQ_CPU_TIME] for rdata in
result[RDATAS]]),
POSTEQ_CPU_TIME_B: sum([rdata[POSTEQ_CPU_TIME_B] for rdata in
result[RDATAS]])
}

iteration = self._require_group().attrs[N_ITERATIONS]

for key in values.keys():
if values[key] is not None:
self._require_group()[f'{iteration}/{key}'] = values[key]

self._require_group().attrs[N_ITERATIONS] += 1

@trace_wrap
def get_cpu_time_total_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative simulation CPU time [ms].
Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
"""
return self._get_hdf5_entries(CPU_TIME_TOTAL, ix)

@trace_wrap
def get_preeq_time_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative computation time of the steady state solver [ms].
(preequilibration)
Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
"""
return self._get_hdf5_entries(PREEQ_CPU_TIME, ix)

@trace_wrap
def get_preeq_timeB_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative computation time of the steady state solver of the backward
problem [ms] (preequilibration).
Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
"""
return self._get_hdf5_entries(PREEQ_CPU_TIME_B, ix)

@trace_wrap
def get_posteq_time_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative computation time of the steady state solver [ms]
(postequilibration).
Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
"""
return self._get_hdf5_entries(POSTEQ_CPU_TIME, ix)

@trace_wrap
def get_posteq_timeB_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative computation time of the steady state solver of the backward
problem [ms] (postequilibration).
Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
"""
return self._get_hdf5_entries(POSTEQ_CPU_TIME_B, ix)

2 changes: 1 addition & 1 deletion pypesto/history/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def get_time_trace(
trim: bool = False,
) -> Union[Sequence[float], float]:
"""
Cumulative execution times.
Cumulative execution times [s].
dweindl marked this conversation as resolved.
Show resolved Hide resolved

Takes as parameter an index or indices and returns corresponding trace
values. If only a single value is requested, the list is flattened.
Expand Down
9 changes: 8 additions & 1 deletion pypesto/history/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from .base import CountHistory, HistoryBase
from .csv import CsvHistory
from .hdf5 import Hdf5History
from .amici import Hdf5AmiciHistory
from .memory import MemoryHistory
from .options import HistoryOptions
from .util import HistoryTypeError
Expand All @@ -16,6 +17,7 @@ def create_history(
id: str,
x_names: Sequence[str],
options: HistoryOptions,
amici_objective: bool
) -> HistoryBase:
"""Create a :class:`HistoryBase` object; Factory method.

Expand All @@ -27,6 +29,8 @@ def create_history(
Parameter names.
options:
History options.
amici_objective:
Indicates if AmiciObjective was used

Returns
-------
Expand All @@ -49,6 +53,9 @@ def create_history(
if suffix in SUFFIXES_CSV:
return CsvHistory(x_names=x_names, file=storage_file, options=options)
elif suffix in SUFFIXES_HDF5:
return Hdf5History(id=id, file=storage_file, options=options)
if amici_objective:
return Hdf5AmiciHistory(id=id, file=storage_file, options=options)
else:
return Hdf5History(id=id, file=storage_file, options=options)
else:
raise HistoryTypeError(suffix)
3 changes: 2 additions & 1 deletion pypesto/optimize/optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
OptimizerHistory,
create_history,
)
from ..objective import Objective
from ..objective import AmiciObjective, Objective
plakrisenko marked this conversation as resolved.
Show resolved Hide resolved
from ..problem import Problem
from ..result import OptimizerResult
from .load import fill_result_from_history
Expand Down Expand Up @@ -106,6 +106,7 @@ def wrapped_minimize(
id=id,
x_names=[problem.x_names[ix] for ix in problem.x_free_indices],
options=history_options,
amici_objective=isinstance(objective, AmiciObjective)
dweindl marked this conversation as resolved.
Show resolved Hide resolved
)
optimizer_history = OptimizerHistory(
history=history,
Expand Down
51 changes: 51 additions & 0 deletions test/base/test_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from pypesto import (
CsvHistory,
Hdf5History,
Hdf5AmiciHistory,
HistoryOptions,
MemoryHistory,
ObjectiveBase,
Expand Down Expand Up @@ -689,6 +690,56 @@ def test_hdf5_history_mp():
)


def test_hdf5_amici_history():
objective1 = pypesto.Objective(
fun=so.rosen, grad=so.rosen_der, hess=so.rosen_hess
)
objective2 = load_amici_objective('conversion_reaction')[0]
lb = -2 * np.ones((1, 2))
ub = 2 * np.ones((1, 2))
problem1 = pypesto.Problem(
objective=objective1, lb=lb, ub=ub
)
problem2 = pypesto.Problem(
objective=objective2, lb=lb, ub=ub
)

optimizer = pypesto.optimize.ScipyOptimizer(options={'maxiter': 10})

with tempfile.TemporaryDirectory(dir=".") as tmpdirname:
_, fn = tempfile.mkstemp(".hdf5", dir=f"{tmpdirname}")

history_options_mp = pypesto.HistoryOptions(
trace_record=True, storage_file=fn
)

result1 = pypesto.optimize.minimize(
problem=problem1,
optimizer=optimizer,
n_starts=1,
history_options=history_options_mp,
progress_bar=False,
)
assert not isinstance(result1.optimize_result.list[0].history,
Hdf5AmiciHistory)

# optimizing with amici history saved in hdf5
result2 = pypesto.optimize.minimize(
problem=problem2,
optimizer=optimizer,
n_starts=1,
history_options=history_options_mp,
progress_bar=False,
)
assert isinstance(result2.optimize_result.list[0].history,
Hdf5AmiciHistory)
result2.optimize_result.list[0].history.get_cpu_time_total_trace()
result2.optimize_result.list[0].history.get_preeq_time_trace()
result2.optimize_result.list[0].history.get_preeq_timeB_trace()
result2.optimize_result.list[0].history.get_posteq_time_trace()
result2.optimize_result.list[0].history.get_posteq_timeB_trace()


def test_trim_history():
"""
Test whether the history gets correctly trimmed to be monotonically
Expand Down
Loading