Skip to content

Conversation

@RemiLehe
Copy link
Collaborator

@RemiLehe RemiLehe commented Jun 26, 2025

This adds a method to compute 1D histograms for ParticleBeam

TODO:

  • Discuss the interface/implementation:
    - should it be a method of ParticleBeam only? => yes, but open an issue to implement for both beams
    - what normalization to use by default? => Copy interface of numpy.historgram
    - should we reuse this function in plot_1d_distribution (with `method='histogram') => yes
    - check vectorization
    - check that it runs on GPU
  • Add an automated test

Here is a quick code snippet on how to use/test this on GPU:

import cheetah
import torch
import matplotlib.pyplot as plt

device = "mps"

# Initialize a particle beam
incoming = cheetah.ParticleBeam.from_parameters(
    num_particles=100_000,
    sigma_p = torch.tensor(1e-2, requires_grad=True),
    energy = torch.tensor(1e9)
).to(device)

# Check that both histogram methods give the same result
h1 = incoming.get_1d_histogram(
    dimension="p",
    bins=100,
    bin_range=(-3e-2, 3e-2),
    method="histogram",
    )

h2 = incoming.get_1d_histogram(
    dimension="p",
    bins=100,
    bin_range=(-3e-2, 3e-2),
    method="kde",
    )

plt.plot(h1.detach().cpu().numpy())
plt.plot(h2.detach().cpu().numpy())

# Check that the histogram obtained with KDE is differentiable
h2.sum().backward()

@RemiLehe RemiLehe marked this pull request as draft June 26, 2025 08:07

return xp_coords

def get_1d_histogram(
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This can be used in plot_1d_distribution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants