Skip to content
Closed
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
/neopdf_capi/docs/xml/
/neopdf_capi/docs/html/
/neopdf_capi/docs/latex/
/neopdf_capi/tests/*.txt
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions neopdf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ itertools.workspace = true
regex.workspace = true
git-version.workspace = true
indicatif.workspace = true
once_cell = "1.19.0"

[dev-dependencies]
criterion.workspace = true
Expand Down
52 changes: 52 additions & 0 deletions neopdf/src/caching.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::env;

/// A caching mechanism to store results of previously interpolated computations.
///
/// The cache is enabled by setting the `NEOPDF_ENABLE_CACHE` environment variable.
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Mutex;

type CacheKey = (String, Vec<u64>);
type Cache = Mutex<HashMap<CacheKey, f64>>;

static PDF_CACHE: Lazy<Cache> = Lazy::new(|| Mutex::new(HashMap::new()));

/// Checks if the cache is enabled via the `NEOPDF_ENABLE_CACHE` environment variable.
fn is_cache_enabled() -> bool {
env::var("NEOPDF_ENABLE_CACHE").is_ok()
}

/// Caches and retrieves interpolated PDF values.
///
/// If caching is enabled, this function first checks the cache for a pre-computed
/// result. If found, it returns the cached value. Otherwise, it computes the value
/// using the provided function, stores the result in the cache, and then returns it.
///
/// # Arguments
///
/// * `key` - A unique key to identify the cached value.
/// * `f` - A function that computes the value if it's not in the cache.
///
/// # Returns
///
/// The computed or cached value.
pub fn with_cache<F, E>(key: CacheKey, f: F) -> Result<f64, E>
where
F: FnOnce() -> Result<f64, E>,
{
if !is_cache_enabled() {
return f();
}

let mut cache = PDF_CACHE.lock().unwrap();
if let Some(&value) = cache.get(&key) {
return Ok(value);
}

let result = f();
if let Ok(value) = result {
cache.insert(key, value);
}
result
}
26 changes: 17 additions & 9 deletions neopdf/src/gridpdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::alphas::AlphaS;
use super::caching;
use super::interpolator::{DynInterpolator, InterpolatorFactory};
use super::metadata::{InterpolatorType, MetaData};
use super::parser::SubgridData;
Expand Down Expand Up @@ -300,15 +301,22 @@ impl GridPDF {
| InterpolatorType::LogChebyshev
);

self.interpolators[subgrid_idx][pid_idx]
.interpolate_point(
&points
.iter()
.map(|&p| if use_log { p.ln() } else { p })
.collect::<Vec<_>>(),
)
.map_err(|e| Error::InterpolationError(e.to_string()))
.map(|result| self.apply_force_positive(result))
let key = (
format!("-{}-{}", self.info.set_index, flavor_id),
points.iter().map(|&p| p.to_bits()).collect(),
);

caching::with_cache(key, || {
self.interpolators[subgrid_idx][pid_idx]
.interpolate_point(
&points
.iter()
.map(|&p| if use_log { p.ln() } else { p })
.collect::<Vec<_>>(),
)
.map_err(|e| Error::InterpolationError(e.to_string()))
.map(|result| self.apply_force_positive(result))
})
}

/// Interpolates PDF values for multiple points in parallel.
Expand Down
1 change: 1 addition & 0 deletions neopdf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
//! See module-level documentation for more details and advanced usage.

pub mod alphas;
pub mod caching;
pub mod converter;
pub mod gridpdf;
pub mod interpolator;
Expand Down
2 changes: 1 addition & 1 deletion neopdf_cli/tests/pdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,5 +171,5 @@ fn xfxq2_kt_tmdlib() {
])
.assert()
.success()
.stdout("0.0655544\n");
.stdout("0.07892252798564643\n");
}