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 8 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_BACKWARD = 'preeq_cpu_timeB'
POSTEQ_CPU_TIME = 'posteq_cpu_time'
POSTEQ_CPU_TIME_BACKWARD = 'posteq_cpu_timeB'


###############################################################################
# PRIOR
Expand Down
2 changes: 2 additions & 0 deletions pypesto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
CountHistory,
CountHistoryBase,
CsvHistory,
CsvAmiciHistory,
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 CsvAmiciHistory, Hdf5AmiciHistory
from .base import CountHistory, CountHistoryBase, HistoryBase, NoHistory
from .csv import CsvHistory
from .generate import create_history
Expand Down
236 changes: 236 additions & 0 deletions pypesto/history/amici.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
from pathlib import Path
from typing import Sequence, Union

import numpy as np

from ..C import (
CPU_TIME_TOTAL,
POSTEQ_CPU_TIME,
POSTEQ_CPU_TIME_BACKWARD,
PREEQ_CPU_TIME,
PREEQ_CPU_TIME_BACKWARD,
RDATAS,
)
from .csv import CsvHistory
from .hdf5 import Hdf5History
from .options import HistoryOptions
from .util import trace_wrap


class Hdf5AmiciHistory(Hdf5History):
"""
Stores history extended by AMICI-specific time traces in an HDF5 file.

Stores 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)

@staticmethod
def _simulation_to_values(x, result, used_time):
values = Hdf5History._simulation_to_values(x, result, used_time)
Comment on lines +45 to +47
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here it's @staticmethod, but n CsvAmiciHistory it's super().... Just curious, why?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In CsvHistory it's not static as it uses dynamically updated attributes (e.g. _n_fval), in Hdf5History it's not the case, so I made the methods static both in Hdf5History and Hdf5AmiciHistory.

values |= {
plakrisenko marked this conversation as resolved.
Show resolved Hide resolved
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_BACKWARD: sum([rdata[PREEQ_CPU_TIME_BACKWARD] for
rdata in result[RDATAS]]),
POSTEQ_CPU_TIME: sum([rdata[POSTEQ_CPU_TIME] for rdata in
result[RDATAS]]),
POSTEQ_CPU_TIME_BACKWARD: sum([rdata[POSTEQ_CPU_TIME_BACKWARD] for
rdata in result[RDATAS]])}
return values

@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 pre-equilibration 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(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 pre-equilibration time of the backward problem, [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(PREEQ_CPU_TIME_BACKWARD, ix)

@trace_wrap
def get_posteq_time_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative post-equilibration 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(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 post-equilibration time of the backward problem [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(POSTEQ_CPU_TIME_BACKWARD, ix)


class CsvAmiciHistory(CsvHistory):
"""
Stores history extended by AMICI-specific time traces in a CSV file.

Stores AMICI-specific traces of total simulation time, pre-equilibration
time and post-equilibration time.

Parameters
----------
file:
CSV file name.
x_names:
Parameter names.
options:
History options.
load_from_file:
If True, history will be initialized from data in the specified file.
"""

def __init__(
self,
file: str,
x_names: Sequence[str] = None,
options: Union[HistoryOptions, dict] = None,
load_from_file: bool = False,
):
super().__init__(file, x_names, options, load_from_file=load_from_file)

def _trace_columns(self) -> list[tuple]:
columns = super()._trace_columns()
return columns + [
(c, np.nan)
for c in [
CPU_TIME_TOTAL,
PREEQ_CPU_TIME,
PREEQ_CPU_TIME_BACKWARD,
POSTEQ_CPU_TIME,
POSTEQ_CPU_TIME_BACKWARD
]
]

def _simulation_to_values(self, result, used_time):
values = super()._simulation_to_values(result, used_time)
values |= {
plakrisenko marked this conversation as resolved.
Show resolved Hide resolved
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_BACKWARD: sum([rdata[PREEQ_CPU_TIME_BACKWARD] for rdata in
result[RDATAS]]),
POSTEQ_CPU_TIME: sum([rdata[POSTEQ_CPU_TIME] for rdata in
result[RDATAS]]),
POSTEQ_CPU_TIME_BACKWARD: sum([rdata[POSTEQ_CPU_TIME_BACKWARD] for rdata in
result[RDATAS]])}
return values

@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 list(self._trace[(CPU_TIME_TOTAL, np.nan)].values[ix])

@trace_wrap
def get_preeq_time_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative pre-equilibration 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 list(self._trace[(PREEQ_CPU_TIME, np.nan)].values[ix])

@trace_wrap
def get_preeq_timeB_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative pre-equilibration time of the backward problem [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 list(self._trace[(PREEQ_CPU_TIME_BACKWARD, np.nan)].values[ix])

@trace_wrap
def get_posteq_time_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative post-equilibration 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 list(self._trace[(POSTEQ_CPU_TIME, np.nan)].values[ix])

@trace_wrap
def get_posteq_timeB_trace(
self, ix: Union[int, Sequence[int], None] = None, trim: bool = False
) -> Union[Sequence[float], float]:
"""
Cumulative post-equilibration time of the backward problem [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 list(self._trace[(POSTEQ_CPU_TIME_BACKWARD, np.nan)].values[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
41 changes: 24 additions & 17 deletions pypesto/history/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,20 @@ def finalize(self, message: str = None, exitflag: str = None):
super().finalize(message=message, exitflag=exitflag)
self._save_trace(finalize=True)

def _simulation_to_values(self, result, used_time):
values = {
TIME: used_time,
N_FVAL: self._n_fval,
N_GRAD: self._n_grad,
N_HESS: self._n_hess,
N_RES: self._n_res,
N_SRES: self._n_sres,
FVAL: result[FVAL],
RES: result[RES],
HESS: result[HESS],
}
return values

def _update_trace(
self,
x: np.ndarray,
Expand Down Expand Up @@ -127,17 +141,7 @@ def _update_trace(
name=len(self._trace), index=self._trace.columns, dtype='object'
)

values = {
TIME: used_time,
N_FVAL: self._n_fval,
N_GRAD: self._n_grad,
N_HESS: self._n_hess,
N_RES: self._n_res,
N_SRES: self._n_sres,
FVAL: result[FVAL],
RES: result[RES],
HESS: result[HESS],
}
values = self._simulation_to_values(result, used_time)

for var, val in values.items():
row[(var, np.nan)] = val
Expand All @@ -162,12 +166,8 @@ def _update_trace(
# save trace to file
self._save_trace()

def _init_trace(self, x: np.ndarray):
"""Initialize the trace."""
if self.x_names is None:
self.x_names = [f'x{i}' for i, _ in enumerate(x)]

columns: list[tuple] = [
def _trace_columns(self) -> list[tuple]:
return [
(c, np.nan)
for c in [
TIME,
Expand All @@ -183,6 +183,13 @@ def _init_trace(self, x: np.ndarray):
]
]

def _init_trace(self, x: np.ndarray):
"""Initialize the trace."""
if self.x_names is None:
self.x_names = [f'x{i}' for i, _ in enumerate(x)]

columns = self._trace_columns()

for var in [X, GRAD]:
if var == X or self.options[f'trace_record_{var}']:
columns.extend([(var, x_name) for x_name in self.x_names])
Expand Down
16 changes: 14 additions & 2 deletions pypesto/history/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import Sequence

from ..C import SUFFIXES_CSV, SUFFIXES_HDF5
from .amici import CsvAmiciHistory, Hdf5AmiciHistory
from .base import CountHistory, HistoryBase
from .csv import CsvHistory
from .hdf5 import Hdf5History
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 @@ -47,8 +51,16 @@ def create_history(

# create history type based on storage type
if suffix in SUFFIXES_CSV:
return CsvHistory(x_names=x_names, file=storage_file, options=options)
if amici_objective:
return CsvAmiciHistory(x_names=x_names, file=storage_file,
options=options)
else:
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)
Loading
Loading