Skip to content
Open
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
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# apply ruff formatting
3920071bac94e2c4b20bcf0ce9911a7b7656d0ac
9 changes: 6 additions & 3 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
with:
python-version: '3.13'
cache: 'pip'
- name: Install jupyter
run: |
python -m pip install jupyterlab
- uses: pre-commit/action@v3.0.1
- uses: pre-commit-ci/lite-action@v1.0.2
- uses: pre-commit-ci/lite-action@v1.1.0
if: always()
18 changes: 6 additions & 12 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,12 @@ repos:
rev: v2.3.0
hooks:
- id: check-merge-conflict # prevent committing files with merge conflicts
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies:
- Flake8-pyproject
- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
language_version: python3
files: '^(bilby/bilby_mcmc/|bilby/core/sampler/|examples/)'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.0 # Use the latest stable Ruff version
hooks:
- id: ruff-check # Runs the Ruff linter
args: [ --fix ] # Optionally enable automatic fixes
- id: ruff-format # Runs the Ruff formatter
- repo: https://github.com/codespell-project/codespell
rev: v2.1.0
hooks:
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The original MRs are only visible on the [LIGO GitLab repository](https://git.li

## [Unreleased]

* MAINT: switch to ruff for automated formatting

## [2.7.1]

### Fixes
Expand Down
28 changes: 18 additions & 10 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@ Code of Conduct](https://www.python.org/psf/codeofconduct/). Furthermore, member

## Code style

During a code review (when you want to contribute changes to the code base),
you may be asked to change your code to fit with the bilby style. This is based
on a few python conventions and is generally maintained to ensure the code base
remains consistent and readable to new users. Here we list some typical things
to keep in mind ensuring the code review is as smooth as possible

1. We follow the [standard python PEP8](https://www.python.org/dev/peps/pep-0008/) conventions for style. While the testing of this is largely automated (the C.I. pipeline tests check using [flake8](http://flake8.pycqa.org/en/latest/)), some more subjective things might slip the net.
2. New classes/functions/methods should have a docstring and following the [numpy docstring guide](https://numpydoc.readthedocs.io/en/latest/format.html), for example
We apply [ruff](https://docs.astral.sh/ruff/) automated formatting to the
entire codebase. This ensures that we have an objectively enforced and
consistent style across the project. In addition to the automated test below
are a few useful guidelines when writing code for Bilby.

1. New classes/functions/methods should have a docstring and following the [numpy docstring guide](https://numpydoc.readthedocs.io/en/latest/format.html), for example
```python
def my_new_function(x, y, print=False):
""" A function to calculate the sum of two numbers
Expand All @@ -47,15 +45,17 @@ def my_new_function(x, y, print=False):
print("Message!")
return x + y
```
2. Changes to existing functions and classes that change the functionality should generally be accompanied by a change in the docstring describing the change in behaviour and version the change was introduced.
3. Avoid inline comments unless necessary. Ideally, the code should make it obvious what is going on, if not the docstring, only in subtle cases use comments
4. Name variables sensibly. Avoid using single-letter variables, it is better to name something `power_spectral_density_array` than `psda`.
5. Don't repeat yourself. If code is repeated in multiple places, wrap it up into a function. This also helps with the writing of robust unit tests (see below).


## Automated code checking

In order to automate checking of the code quality, we use
[pre-commit](https://pre-commit.com/). For more details, see the documentation,
We use [pre-commit](https://pre-commit.com/) to apply the automated code checking.
To maximize smoothness of the contributing process, we recommend that you install
the pre-commit tests on your development machine. For more details, see the documentation,
here we will give a quick-start guide:
1. Install and configure:
```console
Expand All @@ -78,6 +78,14 @@ $ pre-commit install
If you experience any issues with pre-commit, please ask for support on the
usual help channels.

You can additionally run the individual checks manually, e.g.,

```console
$ pip install ruff
$ cd bilby
$ ruff format
$ ruff check --fix
```

## Unit Testing

Expand Down
48 changes: 19 additions & 29 deletions bilby/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,39 +15,29 @@

"""


import sys

from . import core, gw, hyper

from .core import utils, likelihood, prior, result, sampler
from .core.sampler import run_sampler
from .core import likelihood, prior, result, sampler, utils
from .core.likelihood import Likelihood
from .core.result import read_in_result, read_in_result_list
from .core.sampler import run_sampler

try:
from ._version import version as __version__
except ModuleNotFoundError: # development mode
__version__ = 'unknown'


if sys.version_info < (3,):
raise ImportError(
"""You are running bilby >= 0.6.4 on Python 2

Bilby 0.6.4 and above are no longer compatible with Python 2, and you still
ended up with this version installed. That's unfortunate; sorry about that.
It should not have happened. Make sure you have pip >= 9.0 to avoid this kind
of issue, as well as setuptools >= 24.2:

$ pip install pip setuptools --upgrade

Your choices:

- Upgrade to Python 3.

- Install an older version of bilby:

$ pip install 'bilby<0.6.4'

""")
__version__ = "unknown"

__all__ = [
core,
gw,
hyper,
likelihood,
prior,
result,
sampler,
utils,
Likelihood,
read_in_result,
read_in_result_list,
run_sampler,
__version__,
]
2 changes: 2 additions & 0 deletions bilby/bilby_mcmc/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from .sampler import Bilby_MCMC

__all__ = [Bilby_MCMC]
39 changes: 11 additions & 28 deletions bilby/bilby_mcmc/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .utils import LOGLKEY, LOGLLATEXKEY, LOGPKEY, LOGPLATEXKEY


class Chain(object):
class Chain:
def __init__(
self,
initial_sample,
Expand Down Expand Up @@ -84,9 +84,7 @@ def _get_zero_chain_array(self):
return np.zeros((self.block_length, self.ndim + 2), dtype=np.float64)

def _extend_chain_array(self):
self._chain_array = np.concatenate(
(self._chain_array, self._get_zero_chain_array()), axis=0
)
self._chain_array = np.concatenate((self._chain_array, self._get_zero_chain_array()), axis=0)
self._chain_array_length = len(self._chain_array)

@property
Expand Down Expand Up @@ -259,11 +257,7 @@ def tau(self):
if self.position in self.max_tau_dict:
# If we have the ACT at the current position, return it
return self.max_tau_dict[self.position]
elif (
self.tau_last < np.inf
and self.cached_tau_count < 50
and self.nsamples_last > 50
):
elif self.tau_last < np.inf and self.cached_tau_count < 50 and self.nsamples_last > 50:
# If we have a recent ACT return it
self.cached_tau_count += 1
return self.tau_last
Expand Down Expand Up @@ -312,9 +306,7 @@ def _calculate_tau_dict(self, minimum_index):
# Choose minimimum index for the ACT calculation
last_tau = self.tau_last
if self.tau_window is not None and last_tau < np.inf:
minimum_index_for_act = max(
minimum_index, int(self.position - self.tau_window * last_tau)
)
minimum_index_for_act = max(minimum_index, int(self.position - self.tau_window * last_tau))
else:
minimum_index_for_act = minimum_index

Expand Down Expand Up @@ -364,9 +356,7 @@ def samples(self):
def plot(self, outdir=".", label="label", priors=None, all_samples=None):
import matplotlib.pyplot as plt

fig, axes = plt.subplots(
nrows=self.ndim + 3, ncols=2, figsize=(8, 9 + 3 * (self.ndim))
)
fig, axes = plt.subplots(nrows=self.ndim + 3, ncols=2, figsize=(8, 9 + 3 * (self.ndim)))
scatter_kwargs = dict(
lw=0,
marker="o",
Expand All @@ -386,7 +376,7 @@ def plot(self, outdir=".", label="label", priors=None, all_samples=None):
position_indexes = np.arange(self.position + 1)

# Plot the traceplots
for (start, stop, thin, color, alpha, ms) in plot_setups:
for start, stop, thin, color, alpha, ms in plot_setups:
for ax, key in zip(axes[:, 0], self.keys):
xx = position_indexes[start:stop:thin] / K
yy = self.get_1d_array(key)[start:stop:thin]
Expand Down Expand Up @@ -415,16 +405,12 @@ def plot(self, outdir=".", label="label", priors=None, all_samples=None):
if all_samples is not None:
yy_all = all_samples[key]
if np.any(np.isinf(yy_all)):
logger.warning(
f"Could not plot histogram for parameter {key} due to infinite values"
)
logger.warning(f"Could not plot histogram for parameter {key} due to infinite values")
else:
ax.hist(yy_all, bins=50, alpha=0.6, density=True, color="k")
yy = self.get_1d_array(key)[nburn : self.position : self.thin]
if np.any(np.isinf(yy)):
logger.warning(
f"Could not plot histogram for parameter {key} due to infinite values"
)
logger.warning(f"Could not plot histogram for parameter {key} due to infinite values")
else:
ax.hist(yy, bins=50, alpha=0.8, density=True)
ax.set_xlabel(self._get_plot_label_by_key(key, priors))
Expand All @@ -441,16 +427,13 @@ def plot(self, outdir=".", label="label", priors=None, all_samples=None):

axes[-1, 1].set_axis_off()

filename = "{}/{}_checkpoint_trace.png".format(outdir, label)
filename = f"{outdir}/{label}_checkpoint_trace.png"
msg = [
r"Maximum $\tau$" + f"={self.tau:0.1f} ",
r"$n_{\rm samples}=$" + f"{self.nsamples} ",
]
if self.thin_by_nact != 1:
msg += [
r"$n_{\rm samples}^{\rm eff}=$"
+ f"{int(self.nsamples * self.thin_by_nact)} "
]
msg += [r"$n_{\rm samples}^{\rm eff}=$" + f"{int(self.nsamples * self.thin_by_nact)} "]
fig.suptitle(
"| ".join(msg),
y=1,
Expand All @@ -471,7 +454,7 @@ def _get_plot_label_by_key(key, priors=None):
return key


class Sample(object):
class Sample:
def __init__(self, sample_dict):
"""A single sample

Expand Down
9 changes: 2 additions & 7 deletions bilby/bilby_mcmc/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def __init__(
batch_norm_between_layers=False,
random_permutation=True,
):

if use_volume_preserving:
coupling_constructor = AdditiveCouplingTransform
else:
Expand All @@ -66,9 +65,7 @@ def create_resnet(in_features, out_features):

layers = []
for _ in range(num_layers):
transform = coupling_constructor(
mask=mask, transform_net_create_fn=create_resnet
)
transform = coupling_constructor(mask=mask, transform_net_create_fn=create_resnet)
layers.append(transform)
mask *= -1
if batch_norm_between_layers:
Expand All @@ -87,9 +84,7 @@ class BasicFlow(Flow):
def __init__(self, features):
transform = CompositeTransform(
[
MaskedAffineAutoregressiveTransform(
features=features, hidden_features=2 * features
),
MaskedAffineAutoregressiveTransform(features=features, hidden_features=2 * features),
RandomPermutation(features=features),
]
)
Expand Down
Loading