Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
196 changes: 111 additions & 85 deletions docs/dev/Issues/issues_open.md

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions docs/docs/quick-reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,18 @@ project.display.fit.correlations()
project.display.pattern(expt_name='hrpt')
```

After a Bayesian fit, inspect posterior displays:

```python
project.display.posterior.distribution(param)
project.display.posterior.distribution()
project.display.posterior.pairs()
project.display.posterior.predictive(expt_name='hrpt')
```

Call `project.display.posterior.distribution()` without `param` to plot
the marginal distribution for each free parameter one by one.

## Add Simple Constraints

Create aliases from parameter objects, then define a constraint
Expand Down
3 changes: 1 addition & 2 deletions docs/docs/tutorials/ed-21.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -692,8 +692,7 @@
"metadata": {},
"outputs": [],
"source": [
"for param in project.free_parameters:\n",
" project.display.posterior.distribution(param)"
"project.display.posterior.distribution()"
]
},
{
Expand Down
3 changes: 1 addition & 2 deletions docs/docs/tutorials/ed-21.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,7 @@
# multimodality.

# %%
for param in project.free_parameters:
project.display.posterior.distribution(param)
project.display.posterior.distribution()

# %% [markdown]
# Finally, the posterior predictive plot propagates the sampled parameter
Expand Down
3 changes: 1 addition & 2 deletions docs/docs/tutorials/ed-22.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -570,8 +570,7 @@
"metadata": {},
"outputs": [],
"source": [
"for param in project.free_parameters:\n",
" project.display.posterior.distribution(param)"
"project.display.posterior.distribution()"
]
},
{
Expand Down
3 changes: 1 addition & 2 deletions docs/docs/tutorials/ed-22.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,7 @@
# multimodality.

# %%
for param in project.free_parameters:
project.display.posterior.distribution(param)
project.display.posterior.distribution()

# %% [markdown]
# Finally, the posterior predictive plot propagates the sampled
Expand Down
2 changes: 0 additions & 2 deletions pixi.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ classifiers = [
requires-python = '>=3.12'
dependencies = [
'numpy', # Numerical computing library
'colorama', # Color terminal output
'tabulate', # Pretty-print tabular data for terminal output
'asciichartpy', # ASCII charts for terminal output
'pooch', # Data downloader
'typer', # Command-line interface creation
Expand Down
3 changes: 2 additions & 1 deletion src/easydiffraction/analysis/fit_helpers/tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from easydiffraction.analysis.fit_helpers.metrics import calculate_reduced_chi_square
from easydiffraction.display.progress import ACTIVITY_LABEL_BURN_IN
from easydiffraction.display.progress import ACTIVITY_LABEL_FITTING
from easydiffraction.display.progress import ACTIVITY_LABEL_PROCESSING
from easydiffraction.display.progress import ACTIVITY_LABEL_SAMPLING
from easydiffraction.display.progress import ActivityIndicator
from easydiffraction.display.progress import _TerminalLiveHandle as _SharedTerminalLiveHandle
Expand Down Expand Up @@ -595,7 +596,7 @@ def _replace_last_tracking_row(self, row: list[str]) -> None:

def _default_activity_label(self) -> str:
if self._tracking_mode == TRACKING_MODE_SAMPLER:
return ACTIVITY_LABEL_SAMPLING
return ACTIVITY_LABEL_PROCESSING
return ACTIVITY_LABEL_FITTING

@staticmethod
Expand Down
61 changes: 57 additions & 4 deletions src/easydiffraction/analysis/minimizers/bumps_dream.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

from __future__ import annotations

import multiprocessing
import random
import sys
from dataclasses import dataclass

import numpy as np
Expand Down Expand Up @@ -726,14 +728,65 @@
if self.parallel == 1:
return None

if not can_pickle(problem):
if self._requires_serial_mapper_for_spawn_main_module():
log.warning(
'DREAM parallel evaluation requires a picklable '
'problem; falling back to serial execution.'
'DREAM parallel evaluation requires an import-safe main '
'module on spawn-based multiprocessing; falling back to '
'serial execution.'
)
return None

return MPMapper.start_mapper(problem, [], cpus=self.parallel)
shared_display_handle = getattr(self.tracker, '_shared_display_handle', None)
activity_indicator = getattr(self.tracker, '_activity_indicator', None)
if shared_display_handle is not None:
self.tracker._set_shared_display_handle(None)
if activity_indicator is not None:
self.tracker._activity_indicator = None

try:
if not can_pickle(problem):
log.warning(
'DREAM parallel evaluation requires a picklable '
'problem; falling back to serial execution.'
)
return None

return MPMapper.start_mapper(problem, [], cpus=self.parallel)
except RuntimeError as error:
message = str(error)
if 'bootstrapping phase' not in message:
raise

Check warning on line 758 in src/easydiffraction/analysis/minimizers/bumps_dream.py

View check run for this annotation

Codecov / codecov/patch

src/easydiffraction/analysis/minimizers/bumps_dream.py#L758

Added line #L758 was not covered by tests
log.warning(
'DREAM parallel evaluation requires an import-safe main '
'module on spawn-based multiprocessing; falling back to '
'serial execution.'
)
return None
finally:
if activity_indicator is not None:
self.tracker._activity_indicator = activity_indicator
if shared_display_handle is not None:
self.tracker._set_shared_display_handle(shared_display_handle)

@staticmethod
def _requires_serial_mapper_for_spawn_main_module() -> bool:
"""
Return whether direct-script spawn startup should stay serial.
"""
start_method = multiprocessing.get_start_method(allow_none=True)
if start_method is None:
start_method = multiprocessing.get_start_method()
if start_method != 'spawn':
return False

main_module = sys.modules.get('__main__')
if main_module is None:
return False

Check warning on line 784 in src/easydiffraction/analysis/minimizers/bumps_dream.py

View check run for this annotation

Codecov / codecov/patch

src/easydiffraction/analysis/minimizers/bumps_dream.py#L784

Added line #L784 was not covered by tests

return (
getattr(main_module, '__file__', None) is not None
and getattr(main_module, '__spec__', None) is None
)

@staticmethod
def _execute_driver(*, driver: FitDriver, random_seed: int) -> _DreamDriverResult:
Expand Down
52 changes: 50 additions & 2 deletions src/easydiffraction/display/plotters/ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

from __future__ import annotations

import shutil

import asciichartpy
import numpy as np

Expand All @@ -22,13 +24,55 @@
DEFAULT_COLORS = {
'meas': asciichartpy.blue,
'calc': asciichartpy.red,
'posterior': asciichartpy.red,
'density': asciichartpy.green,
'resid': asciichartpy.green,
}
ASCII_CHART_OFFSET = 3
ASCII_CHART_LEFT_PADDING = 15
ASCII_CHART_FALLBACK_POINT_COUNT = 80
ASCII_CHART_MIN_POINT_COUNT = 2


class AsciiPlotter(PlotterBase):
"""Terminal-based plotter using ASCII art."""

@staticmethod
def _chart_point_count() -> int:
"""Return the number of points that fit the current terminal."""
fallback_columns = (
ASCII_CHART_FALLBACK_POINT_COUNT + ASCII_CHART_OFFSET + ASCII_CHART_LEFT_PADDING
)
columns = shutil.get_terminal_size(fallback=(fallback_columns, DEFAULT_HEIGHT)).columns
return max(
ASCII_CHART_MIN_POINT_COUNT,
columns - ASCII_CHART_OFFSET - ASCII_CHART_LEFT_PADDING,
)

@classmethod
def _resample_series_for_chart(
cls,
y_series: object,
) -> list[list[float]]:
"""Return y-series resampled to the available chart width."""
target_point_count = cls._chart_point_count()
resampled_series: list[list[float]] = []
for series in y_series:
series_array = np.ravel(np.asarray(series, dtype=float))
if (
series_array.size <= target_point_count
or series_array.size < ASCII_CHART_MIN_POINT_COUNT
):
resampled_series.append(series_array.tolist())
continue

source_positions = np.linspace(0.0, 1.0, series_array.size)
target_positions = np.linspace(0.0, 1.0, target_point_count)
resampled_series.append(
np.interp(target_positions, source_positions, series_array).tolist()
)
return resampled_series

@staticmethod
def _get_legend_item(label: str) -> str:
"""
Expand Down Expand Up @@ -94,8 +138,12 @@ def plot_powder(
if height is None:
height = DEFAULT_HEIGHT
colors = [DEFAULT_COLORS[label] for label in labels]
config = {'height': height, 'colors': colors}
y_series = [y.tolist() for y in y_series]
config = {
'height': height,
'colors': colors,
'offset': ASCII_CHART_OFFSET,
}
y_series = self._resample_series_for_chart(y_series)

chart = asciichartpy.plot(y_series, config)

Expand Down
8 changes: 8 additions & 0 deletions src/easydiffraction/display/plotters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,14 @@ class XAxisType(StrEnum):
'mode': 'lines',
'name': 'Total calculated (Icalc)',
},
'posterior': {
'mode': 'lines',
'name': 'Max posterior',
},
'density': {
'mode': 'lines',
'name': 'Marginal density',
},
'bkg': {
'mode': 'lines',
'name': 'Background (Ibkg)',
Expand Down
1 change: 1 addition & 0 deletions src/easydiffraction/display/plotters/plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
'meas': 'rgb(31, 119, 180)',
'bkg': 'rgb(140, 140, 140)',
'calc': 'rgb(214, 39, 40)',
'posterior': 'rgb(214, 39, 40)',
'resid': 'rgb(44, 160, 44)',
}

Expand Down
Loading
Loading