-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlib.rs
More file actions
2502 lines (2271 loc) · 82.4 KB
/
lib.rs
File metadata and controls
2502 lines (2271 loc) · 82.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The C-language interface for `PineAPPL`.
//!
//! The `PineAPPL` Application Programming Interface for the C language (CAPI) defines types and
//! functions that allow `PineAPPL` to be used without having to write Rust code, and instead
//! offering
//!
//! * C or C++, or
//! * Fortran as programming languages. Fortran is supported using the `iso_c_binding` module to
//! wrap CAPI's functions (see the [Fortran example] in the repository).
//!
//! Note that the CAPI only defines a subset of functionality available in the Rust module, which
//! is extended on an as-needed basis. If you happen to miss a function please open a new [issue]
//! on the github page.
//!
//! [Fortran example]: https://github.com/NNPDF/pineappl/tree/master/examples/fortran
//! [issue]: https://github.com/NNPDF/pineappl/issues
//!
//! # Using and linking the CAPI
//!
//! To use `PineAPPL`'s CAPI you must include its header `pineappl_capi.h`. To successfully build
//! your program, you should rely on [`pkgconf`] or [`pkg-conf`], as follows:
//!
//! ```shell
//! pkg-config --cflags pineappl_capi
//! pkg-config --libs pineappl_capi
//! ```
//!
//! This will read `PineAPPL`'s `.pc` file and print the neccessary `CFLAGS` (`--cflags`) and
//! linker flags (`--libs`). This procedure is supported by many build systems, such as
//!
//! * [Autoconf]/[Automake], using the `PKG_CHECK_MODULES` macro, see the [Autotools mythbuster]
//! page for correct usage,
//! * [CMake], using [`FindPkgConfig`] and
//! * [meson], using [`dependency`]; it usually suffices to write `dependency('pineappl_capi')`.
//!
//! [Autoconf]: https://www.gnu.org/software/autoconf/
//! [Automake]: https://www.gnu.org/software/automake/
//! [Autotools mythbuster]: https://autotools.io/pkgconfig/pkg_check_modules.html
//! [CMake]: https://cmake.org/
//! [`dependency`]: https://mesonbuild.com/Reference-manual.html#dependency
//! [`FindPkgConfig`]: https://cmake.org/cmake/help/latest/module/FindPkgConfig.html
//! [meson]: https://mesonbuild.com/
//! [`pkgconf`]: https://github.com/pkgconf/pkgconf
//! [`pkg-conf`]: https://www.freedesktop.org/wiki/Software/pkg-config
//!
//! # Strings and other types
//!
//! Strings used in this library are have the Rust type `*const c_char` or `*mut c_char` and
//! correspond to the C types `const char*` and `char*`, respectively. The strings are assumed to
//! be encoded using UTF-8, which Rust uses internally.
//!
//! All other built-in types in Rust (`f64`, `usize`, `i32`, `u32`, ...) correspond to types in C
//! as defined by the [translation tables] of cbindgen. If in doubt, consult the generated header
//! `pineappl_capi.h`.
//!
//! [translation tables]: https://github.com/eqrion/cbindgen/blob/master/docs.md#std-types
use itertools::{izip, Itertools};
use ndarray::{Array4, CowArray};
use pineappl::boc::{Bin, BinsWithFillLimits, Channel, Kinematics, Order, ScaleFuncForm, Scales};
use pineappl::convolutions::{Conv, ConvType, ConvolutionCache};
use pineappl::evolution::{AlphasTable, OperatorSliceInfo};
use pineappl::fk_table::{FkAssumptions, FkTable};
use pineappl::grid::{Grid, GridOptFlags};
use pineappl::interpolation::{Interp as InterpMain, InterpMeth, Map, ReweightMeth};
use pineappl::packed_array::PackedArray;
use pineappl::packed_array::{ravel_multi_index, unravel_index};
use pineappl::pids::PidBasis;
use pineappl::subgrid::{ImportSubgridV1, Subgrid};
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::mem;
use std::os::raw::{c_char, c_void};
use std::path::Path;
use std::slice;
/// TODO
pub const PINEAPPL_GOF_OPTIMIZE_SUBGRID_TYPE: GridOptFlags = GridOptFlags::OPTIMIZE_SUBGRID_TYPE;
/// TODO
pub const PINEAPPL_GOF_OPTIMIZE_NODES: GridOptFlags = GridOptFlags::OPTIMIZE_NODES;
/// TODO
pub const PINEAPPL_GOF_SYMMETRIZE_CHANNELS: GridOptFlags = GridOptFlags::SYMMETRIZE_CHANNELS;
/// TODO
pub const PINEAPPL_GOF_STRIP_EMPTY_ORDERS: GridOptFlags = GridOptFlags::STRIP_EMPTY_ORDERS;
/// TODO
pub const PINEAPPL_GOF_MERGE_SAME_CHANNELS: GridOptFlags = GridOptFlags::MERGE_SAME_CHANNELS;
/// TODO
pub const PINEAPPL_GOF_STRIP_EMPTY_CHANNELS: GridOptFlags = GridOptFlags::STRIP_EMPTY_CHANNELS;
// TODO: make sure no `panic` calls leave functions marked as `extern "C"`
fn grid_interpolation_params(key_vals: Option<&KeyVal>) -> Vec<InterpMain> {
let mut q2_min = 1e2;
let mut q2_max = 1e8;
let mut q2_nodes = 40;
let mut q2_order = 3;
let mut x1_min = 2e-7;
let mut x1_max = 1.0;
let mut x1_nodes = 50;
let mut x1_order = 3;
let mut x2_min = 2e-7;
let mut x2_max = 1.0;
let mut x2_nodes = 50;
let mut x2_order = 3;
let mut reweight = ReweightMeth::ApplGridX;
if let Some(keyval) = key_vals {
if let Some(value) = keyval
.ints
.get("q2_bins")
.or_else(|| keyval.ints.get("nq2"))
{
q2_nodes = usize::try_from(*value).unwrap();
}
if let Some(value) = keyval
.doubles
.get("q2_max")
.or_else(|| keyval.doubles.get("q2max"))
{
q2_max = *value;
}
if let Some(value) = keyval
.doubles
.get("q2_min")
.or_else(|| keyval.doubles.get("q2min"))
{
q2_min = *value;
}
if let Some(value) = keyval
.ints
.get("q2_order")
.or_else(|| keyval.ints.get("q2order"))
{
q2_order = usize::try_from(*value).unwrap();
}
if let Some(value) = keyval.bools.get("reweight") {
if !value {
reweight = ReweightMeth::NoReweight;
}
}
if let Some(value) = keyval.ints.get("x_bins").or_else(|| keyval.ints.get("nx")) {
let value = usize::try_from(*value).unwrap();
x1_nodes = value;
x2_nodes = value;
}
if let Some(value) = keyval
.doubles
.get("x_max")
.or_else(|| keyval.doubles.get("xmax"))
{
x1_max = *value;
x2_max = *value;
}
if let Some(value) = keyval
.doubles
.get("x_min")
.or_else(|| keyval.doubles.get("xmin"))
{
x1_min = *value;
x2_min = *value;
}
if let Some(value) = keyval
.ints
.get("x_order")
.or_else(|| keyval.ints.get("xorder"))
{
let value = usize::try_from(*value).unwrap();
x1_order = value;
x2_order = value;
}
if let Some(value) = keyval.ints.get("x1_bins") {
x1_nodes = usize::try_from(*value).unwrap();
}
if let Some(value) = keyval.doubles.get("x1_max") {
x1_max = *value;
}
if let Some(value) = keyval.doubles.get("x1_min") {
x1_min = *value;
}
if let Some(value) = keyval.ints.get("x1_order") {
x1_order = usize::try_from(*value).unwrap();
}
if let Some(value) = keyval.ints.get("x2_bins") {
x2_nodes = usize::try_from(*value).unwrap();
}
if let Some(value) = keyval.doubles.get("x2_max") {
x2_max = *value;
}
if let Some(value) = keyval.doubles.get("x2_min") {
x2_min = *value;
}
if let Some(value) = keyval.ints.get("x2_order") {
x2_order = usize::try_from(*value).unwrap();
}
}
vec![
InterpMain::new(
q2_min,
q2_max,
q2_nodes,
q2_order,
ReweightMeth::NoReweight,
Map::ApplGridH0,
InterpMeth::Lagrange,
),
InterpMain::new(
x1_min,
x1_max,
x1_nodes,
x1_order,
reweight,
Map::ApplGridF2,
InterpMeth::Lagrange,
),
InterpMain::new(
x2_min,
x2_max,
x2_nodes,
x2_order,
reweight,
Map::ApplGridF2,
InterpMeth::Lagrange,
),
]
}
/// Type for defining a luminosity function.
#[derive(Default)]
pub struct Lumi(Vec<Channel>);
/// Returns the number of bins in `grid`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn pineappl_grid_bin_count(grid: *const Grid) -> usize {
let grid = unsafe { &*grid };
grid.bwfl().len()
}
/// Returns the number of dimensions of the bins this grid has.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_bin_dimensions(grid: *const Grid) -> usize {
let grid = unsafe { &*grid };
grid.bwfl().dimensions()
}
/// Stores the bin sizes of `grid` in `bin_sizes`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The parameter `bin_sizes` must point to an array that is as
/// long as `grid` has bins.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_bin_normalizations(grid: *const Grid, bin_sizes: *mut f64) {
let grid = unsafe { &*grid };
let bins = grid.bwfl().len();
let bin_sizes = unsafe { slice::from_raw_parts_mut(bin_sizes, bins) };
for (i, size) in grid.bwfl().normalizations().into_iter().enumerate() {
bin_sizes[i] = size;
}
}
/// Write the left limits for the specified dimension into `left`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The parameter `left` must point to an array that is as large
/// as `grid` has bins. If `dimension` is larger or equal the number of dimensions for this grid,
/// nothing is written into `left`, the result is undefined.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_bin_limits_left(
grid: *const Grid,
dimension: usize,
left: *mut f64,
) {
let grid = unsafe { &*grid };
let bins = grid.bwfl().len();
let result = unsafe { slice::from_raw_parts_mut(left, bins) };
for (lhs, rhs) in result.iter_mut().zip(
grid.bwfl()
.bins()
.iter()
.map(|bin| bin.limits()[dimension].0),
) {
*lhs = rhs;
}
}
/// Write the right limits for the specified dimension into `right`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The parameter `right` must point to an array that is as
/// large as `grid` has bins. If `dimension` is larger or equal the number of dimensions for this
/// grid, nothing is written into `right`, the result is undefined.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_bin_limits_right(
grid: *const Grid,
dimension: usize,
right: *mut f64,
) {
let grid = unsafe { &*grid };
let bins = grid.bwfl().len();
let result = unsafe { slice::from_raw_parts_mut(right, bins) };
for (lhs, rhs) in result.iter_mut().zip(
grid.bwfl()
.bins()
.iter()
.map(|bin| bin.limits()[dimension].1),
) {
*lhs = rhs;
}
}
/// Returns a cloned object of `grid`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_clone(grid: *const Grid) -> Box<Grid> {
let grid = unsafe { &*grid };
Box::new(grid.clone())
}
/// Wrapper for [`pineappl_grid_convolve_with_one`].
///
/// # Safety
///
/// See [`pineappl_grid_convolve_with_one`].
#[deprecated(
since = "0.8.0",
note = "use `pineappl_grid_convolve_with_one` instead"
)]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_convolute_with_one(
grid: *const Grid,
pdg_id: i32,
xfx: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
alphas: extern "C" fn(q2: f64, state: *mut c_void) -> f64,
state: *mut c_void,
order_mask: *const bool,
channel_mask: *const bool,
xi_ren: f64,
xi_fac: f64,
results: *mut f64,
) {
unsafe {
pineappl_grid_convolve_with_one(
grid,
pdg_id,
xfx,
alphas,
state,
order_mask,
channel_mask,
xi_ren,
xi_fac,
results,
);
}
}
/// Wrapper for [`pineappl_grid_convolve_with_two`].
///
/// # Safety
///
/// See [`pineappl_grid_convolve_with_two`].
#[deprecated(
since = "0.8.0",
note = "use `pineappl_grid_convolve_with_two` instead"
)]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_convolute_with_two(
grid: *const Grid,
pdg_id1: i32,
xfx1: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
pdg_id2: i32,
xfx2: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
alphas: extern "C" fn(q2: f64, state: *mut c_void) -> f64,
state: *mut c_void,
order_mask: *const bool,
channel_mask: *const bool,
xi_ren: f64,
xi_fac: f64,
results: *mut f64,
) {
unsafe {
pineappl_grid_convolve_with_two(
grid,
pdg_id1,
xfx1,
pdg_id2,
xfx2,
alphas,
state,
order_mask,
channel_mask,
xi_ren,
xi_fac,
results,
);
}
}
/// Convolutes the specified grid with the PDF `xfx`, which is the PDF for a hadron with the PDG id
/// `pdg_id`, and strong coupling `alphas`. These functions must evaluate the PDFs for the given
/// `x` and `q2` for the parton with the given PDG id, `pdg_id`, and return the result. Note that
/// the value must be the PDF multiplied with its argument `x`. The value of the pointer `state`
/// provided to these functions is the same one given to this function. The parameter `order_mask`
/// must be as long as there are perturbative orders contained in `grid` and is used to selectively
/// disable (`false`) or enable (`true`) individual orders. If `order_mask` is set to `NULL`, all
/// orders are active. The parameter `channel_mask` can be used similarly, but must be as long as
/// the channels `grid` was created with has entries, or `NULL` to enable all channels. The values
/// `xi_ren` and `xi_fac` can be used to vary the renormalization and factorization from its
/// central value, which corresponds to `1.0`. After convolution of the grid with the PDFs the
/// differential cross section for each bin is written into `results`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The function pointers `xfx` and `alphas` must not
/// be null pointers and point to valid functions. The parameters `order_mask` and `channel_mask`
/// must either be null pointers or point to arrays that are as long as `grid` has orders and
/// channels, respectively. Finally, `results` must be as long as `grid` has bins.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_convolve_with_one(
grid: *const Grid,
pdg_id: i32,
xfx: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
alphas: extern "C" fn(q2: f64, state: *mut c_void) -> f64,
state: *mut c_void,
order_mask: *const bool,
channel_mask: *const bool,
xi_ren: f64,
xi_fac: f64,
results: *mut f64,
) {
let grid = unsafe { &*grid };
let mut xfx = |id, x, q2| xfx(id, x, q2, state);
let mut als = |q2| alphas(q2, state);
let order_mask = if order_mask.is_null() {
&[]
} else {
unsafe { slice::from_raw_parts(order_mask, grid.orders().len()) }
};
let channel_mask = if channel_mask.is_null() {
&[]
} else {
unsafe { slice::from_raw_parts(channel_mask, grid.channels().len()) }
};
let bins = grid.bwfl().len();
let results = unsafe { slice::from_raw_parts_mut(results, bins) };
let mut convolution_cache = ConvolutionCache::new(
vec![Conv::new(ConvType::UnpolPDF, pdg_id)],
vec![&mut xfx],
&mut als,
);
results.copy_from_slice(&grid.convolve(
&mut convolution_cache,
order_mask,
&[],
channel_mask,
&[(xi_ren, xi_fac, 1.0)],
));
}
/// Convolutes the specified grid with the PDFs `xfx1` and `xfx2`, which are the PDFs of hadrons
/// with PDG ids `pdg_id1` and `pdg_id2`, respectively, and strong coupling `alphas`. These
/// functions must evaluate the PDFs for the given `x` and `q2` for the parton with the given PDG
/// id, `pdg_id`, and return the result. Note that the value must be the PDF multiplied with its
/// argument `x`. The value of the pointer `state` provided to these functions is the same one
/// given to this function. The parameter `order_mask` must be as long as there are perturbative
/// orders contained in `grid` and is used to selectively disable (`false`) or enable (`true`)
/// individual orders. If `order_mask` is set to `NULL`, all orders are active. The parameter
/// `channel_mask` can be used similarly, but must be as long as the channels `grid` was created
/// with has entries, or `NULL` to enable all channels. The values `xi_ren` and `xi_fac` can be
/// used to vary the renormalization and factorization from its central value, which corresponds to
/// `1.0`. After convolution of the grid with the PDFs the differential cross section for each bin
/// is written into `results`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The function pointers `xfx1`, `xfx2`, and `alphas` must not
/// be null pointers and point to valid functions. The parameters `order_mask` and `channel_mask`
/// must either be null pointers or point to arrays that are as long as `grid` has orders and
/// channels, respectively. Finally, `results` must be as long as `grid` has bins.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_convolve_with_two(
grid: *const Grid,
pdg_id1: i32,
xfx1: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
pdg_id2: i32,
xfx2: extern "C" fn(pdg_id: i32, x: f64, q2: f64, state: *mut c_void) -> f64,
alphas: extern "C" fn(q2: f64, state: *mut c_void) -> f64,
state: *mut c_void,
order_mask: *const bool,
channel_mask: *const bool,
xi_ren: f64,
xi_fac: f64,
results: *mut f64,
) {
let grid = unsafe { &*grid };
let mut xfx1 = |id, x, q2| xfx1(id, x, q2, state);
let mut xfx2 = |id, x, q2| xfx2(id, x, q2, state);
let mut als = |q2| alphas(q2, state);
let order_mask = if order_mask.is_null() {
&[]
} else {
unsafe { slice::from_raw_parts(order_mask, grid.orders().len()) }
};
let channel_mask = if channel_mask.is_null() {
&[]
} else {
unsafe { slice::from_raw_parts(channel_mask, grid.channels().len()) }
};
let bins = grid.bwfl().len();
let results = unsafe { slice::from_raw_parts_mut(results, bins) };
let mut convolution_cache = ConvolutionCache::new(
vec![
Conv::new(ConvType::UnpolPDF, pdg_id1),
Conv::new(ConvType::UnpolPDF, pdg_id2),
],
vec![&mut xfx1, &mut xfx2],
&mut als,
);
results.copy_from_slice(&grid.convolve(
&mut convolution_cache,
order_mask,
&[],
channel_mask,
&[(xi_ren, xi_fac, 1.0)],
));
}
/// Try to deduplicate channels of `grid` by detecting pairs of them that contain the same
/// subgrids. The numerical equality is tested using a tolerance of `ulps`, given in [units of
/// least precision](https://docs.rs/float-cmp/latest/float_cmp/index.html#some-explanation).
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_dedup_channels(grid: *mut Grid, ulps: i64) {
let grid = unsafe { &mut *grid };
grid.dedup_channels(ulps);
}
/// Delete a grid previously created with `pineappl_grid_new`.
#[no_mangle]
#[allow(unused_variables)]
pub extern "C" fn pineappl_grid_delete(grid: Option<Box<Grid>>) {}
/// Fill `grid` for the given momentum fractions `x1` and `x2`, at the scale `q2` for the given
/// value of the `order`, `observable`, and `lumi` with `weight`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_fill2` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_fill(
grid: *mut Grid,
x1: f64,
x2: f64,
q2: f64,
order: usize,
observable: f64,
lumi: usize,
weight: f64,
) {
let grid = unsafe { &mut *grid };
grid.fill(order, observable, lumi, &[q2, x1, x2], weight);
}
/// Fill `grid` for the given momentum fractions `x1` and `x2`, at the scale `q2` for the given
/// value of the `order` and `observable` with `weights`. The parameter of weight must contain a
/// result for entry of the luminosity function the grid was created with.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_fill_all2` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_fill_all(
grid: *mut Grid,
x1: f64,
x2: f64,
q2: f64,
order: usize,
observable: f64,
weights: *const f64,
) {
let grid = unsafe { &mut *grid };
let weights = unsafe { slice::from_raw_parts(weights, grid.channels().len()) };
for (channel, &weight) in weights.iter().enumerate() {
grid.fill(order, observable, channel, &[q2, x1, x2], weight);
}
}
/// Fill `grid` with as many points as indicated by `size`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. Additionally, all remaining pointer parameters must be
/// arrays as long as specified by `size`.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_fill_array2` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_fill_array(
grid: *mut Grid,
x1: *const f64,
x2: *const f64,
q2: *const f64,
orders: *const usize,
observables: *const f64,
lumis: *const usize,
weights: *const f64,
size: usize,
) {
let grid = unsafe { &mut *grid };
let x1 = unsafe { slice::from_raw_parts(x1, size) };
let x2 = unsafe { slice::from_raw_parts(x2, size) };
let q2 = unsafe { slice::from_raw_parts(q2, size) };
let orders = unsafe { slice::from_raw_parts(orders, size) };
let observables = unsafe { slice::from_raw_parts(observables, size) };
let lumis = unsafe { slice::from_raw_parts(lumis, size) };
let weights = unsafe { slice::from_raw_parts(weights, size) };
for (&x1, &x2, &q2, &order, &observable, &lumi, &weight) in
izip!(x1, x2, q2, orders, observables, lumis, weights)
{
grid.fill(order, observable, lumi, &[q2, x1, x2], weight);
}
}
/// Return the luminosity function of `grid`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_channels` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_lumi(grid: *const Grid) -> Box<Lumi> {
let grid = unsafe { &*grid };
Box::new(Lumi(grid.channels().to_vec()))
}
/// Write the order parameters of `grid` into `order_params`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The pointer `order_params` must point to an array as large
/// as four times the number of orders in `grid`.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_order_params2` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_order_params(grid: *const Grid, order_params: *mut u32) {
let grid = unsafe { &*grid };
let orders = grid.orders();
let order_params = unsafe { slice::from_raw_parts_mut(order_params, 4 * orders.len()) };
for (i, order) in orders.iter().enumerate() {
order_params[4 * i] = order.alphas.into();
order_params[4 * i + 1] = order.alpha.into();
order_params[4 * i + 2] = order.logxir.into();
order_params[4 * i + 3] = order.logxif.into();
}
}
/// Return the number of orders in `grid`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn pineappl_grid_order_count(grid: *const Grid) -> usize {
let grid = unsafe { &*grid };
grid.orders().len()
}
/// Creates a new and empty grid. The creation requires four different sets of parameters:
/// - The luminosity function `lumi`: A pointer to the luminosity function that specifies how the
/// cross section should be reconstructed.
/// - Order specification `orders` and `order_params`. Each `PineAPPL` grid contains a number of
/// different perturbative orders, specified by `orders`. The array `order_params` stores the
/// exponent of each perturbative order and must contain 4 integers denoting the exponent of the
/// string coupling, of the electromagnetic coupling, of the logarithm of the renormalization
/// scale, and finally of the logarithm of the factorization scale.
/// - The observable definition `bins` and `bin_limits`. Each `PineAPPL` grid can store observables
/// from a one-dimensional distribution. To this end `bins` specifies how many observables are
/// stored and `bin_limits` must contain `bins + 1` entries denoting the left and right limit for
/// each bin.
/// - More (optional) information can be given in a key-value storage `key_vals`, which might be
/// a null pointer, to signal there are no further parameters that need to be set.
///
/// # Safety
///
/// The parameter `lumi` must point a valid luminosity function created by `pineappl_lumi_new`.
/// `order_params` must be an array with a length of `4 * orders`, and `bin_limits` an array with
/// length `bins + 1`. `key_vals` must be a valid `KeyVal` object created by `pineappl_keyval_new`.
///
/// # Panics
///
/// TODO
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_new2` instead")]
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn pineappl_grid_new(
lumi: *const Lumi,
orders: usize,
order_params: *const u32,
bins: usize,
bin_limits: *const f64,
key_vals: *const KeyVal,
) -> Box<Grid> {
let order_params = unsafe { slice::from_raw_parts(order_params, 4 * orders) };
let orders: Vec<_> = order_params
.chunks(4)
.map(|s| Order {
// UNWRAP: there shouldn't be orders with exponents larger than 255
alphas: s[0].try_into().unwrap(),
alpha: s[1].try_into().unwrap(),
logxir: s[2].try_into().unwrap(),
logxif: s[3].try_into().unwrap(),
// this function doesn't support fragmentation scale logs
logxia: 0,
})
.collect();
let key_vals = unsafe { key_vals.as_ref() };
let interps = grid_interpolation_params(key_vals);
let lumi = unsafe { &*lumi };
let mut convolutions = vec![Conv::new(ConvType::UnpolPDF, 2212); 2];
if let Some(keyval) = key_vals {
if let Some(value) = keyval.strings.get("initial_state_1") {
convolutions[0] =
Conv::new(ConvType::UnpolPDF, value.to_string_lossy().parse().unwrap());
}
if let Some(value) = keyval.strings.get("initial_state_2") {
convolutions[1] =
Conv::new(ConvType::UnpolPDF, value.to_string_lossy().parse().unwrap());
}
}
let bins = BinsWithFillLimits::from_fill_limits(
unsafe { slice::from_raw_parts(bin_limits, bins + 1) }.to_vec(),
)
.unwrap();
Box::new(Grid::new(
bins,
orders,
lumi.0.clone(),
PidBasis::Pdg,
convolutions,
interps,
vec![Kinematics::Scale(0), Kinematics::X(0), Kinematics::X(1)],
Scales {
ren: ScaleFuncForm::Scale(0),
fac: ScaleFuncForm::Scale(0),
frg: ScaleFuncForm::NoScale,
},
))
}
/// Read a `PineAPPL` grid from a file with name `filename`.
///
/// # Safety
///
/// The parameter `filename` must be a C string pointing to an existing grid file.
///
/// # Panics
///
/// TODO
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn pineappl_grid_read(filename: *const c_char) -> Box<Grid> {
let filename = unsafe { CStr::from_ptr(filename) };
let filename = filename.to_string_lossy();
let reader = File::open(filename.as_ref()).unwrap();
Box::new(Grid::read(reader).unwrap())
}
/// Merges the bins of corresponding to the indices from the half-open interval `[from, to]` into a
/// single bin.
///
/// # Safety
///
/// The parameter `grid` must be valid `Grid` object created by either `pineappl_grid_new` or
/// `pineappl_grid_read`.
///
/// # Panics
///
/// TODO
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_merge_bins(grid: *mut Grid, from: usize, to: usize) {
let grid = unsafe { &mut *grid };
grid.merge_bins(from..to).unwrap();
}
/// Deletes bins with the corresponding `bin_indices`. Repeated indices and indices larger or
/// equal the bin length are ignored.
///
/// # Safety
///
/// The parameter `grid` must be valid `Grid` object created by either `pineappl_grid_new` or
/// `pineappl_grid_read`.
/// The parameter `bin_indices_ptr` must be an array of size `bin_indices_len`.
///
/// # Panics
///
/// TODO
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_delete_bins(
grid: *mut Grid,
bin_indices_ptr: *const usize,
bin_indices_len: usize,
) {
let grid = unsafe { &mut *grid };
let bin_indices = unsafe { std::slice::from_raw_parts(bin_indices_ptr, bin_indices_len) };
grid.delete_bins(bin_indices);
}
/// Merges `other` into `grid` and subsequently deletes `other`.
///
/// # Safety
///
/// Both `grid` and `other` must be valid `Grid` objects created by either `pineappl_grid_new` or
/// `pineappl_grid_read`. If `other` is a `NULL` pointer, this function does not do anything.
///
/// # Panics
///
/// TODO
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_merge_and_delete(grid: *mut Grid, other: Option<Box<Grid>>) {
if let Some(other) = other {
let grid = unsafe { &mut *grid };
grid.merge(*other).unwrap();
}
}
/// Scale all grids in `grid` by `factor`.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_scale(grid: *mut Grid, factor: f64) {
let grid = unsafe { &mut *grid };
grid.scale(factor);
}
/// Splits the grid such that the luminosity function contains only a single combination per
/// channel.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[deprecated(since = "1.0.0", note = "use `pineappl_grid_split_channels` instead")]
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_split_lumi(grid: *mut Grid) {
let grid = unsafe { &mut *grid };
grid.split_channels();
}
/// Change the particle ID basis of a given Grid.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object (for example when `grid` is the null pointer)
/// or if `pid_basis` does not refer to a correct basis, then this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_rotate_pid_basis(grid: *mut Grid, pid_basis: PidBasis) {
let grid = unsafe { &mut *grid };
grid.rotate_pid_basis(pid_basis);
}
/// Get the particle ID basis of a Grid.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the `NULL`
/// pointer, this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_pid_basis(grid: *mut Grid) -> PidBasis {
let grid = unsafe { &mut *grid };
*grid.pid_basis()
}
/// Optimizes the grid representation for space efficiency.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_optimize(grid: *mut Grid) {
let grid = unsafe { &mut *grid };
grid.optimize();
}
/// Optimizes the grid representation for space efficiency. The parameter `flags` determines which
/// optimizations are applied, see [`GridOptFlags`].
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_optimize_using(grid: *mut Grid, flags: GridOptFlags) {
let grid = unsafe { &mut *grid };
grid.optimize_using(flags);
}
/// Scales each subgrid by a bin-dependent factor given in `factors`. If a bin does not have a
/// corresponding entry in `factors` it is not rescaled. If `factors` has more entries than there
/// are bins the superfluous entries do not have an effect.
///
/// # Safety
///
/// If `grid` does not point to a valid `Grid` object, for example when `grid` is the null pointer,
/// this function is not safe to call. The pointer `factors` must be an array of at least the size
/// given by `count`.
#[no_mangle]
pub unsafe extern "C" fn pineappl_grid_scale_by_bin(
grid: *mut Grid,
count: usize,
factors: *const f64,