libcint 0.2.3

FFI binding and GTO wrapper for libcint (C library)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! Main [`CInt`] with related struct definition, and impl of
//! [`CInt::integrate`].

use crate::prelude::*;

use crate::ffi::cecp_wrapper::get_ecp_integrator;
use crate::ffi::cint_wrapper::get_cint_integrator;

/* #region structs */

/// CInt data structure, which contains **all the necessary information** for
/// GTO electronic integral evaluation, and almost **all methods to evaluate**
/// GTO electronic integrals for basic usage.
///
/// Most users may wish to use the [`integrate`](Self::integrate) and
/// [`integrate_spinor`](Self::integrate_spinor) methods, which correspond to
/// PySCF's `mol.intor` method. We refer to those functions for more
/// documentations.
///
/// Please also note column-major and row-major conventions. In most cases,
/// [`CInt`] will be column-major. However, for electronic integrals, we also
/// provide row-major functions
/// [`integrate_row_major`](Self::integrate_row_major) and
/// [`integrate_row_major_spinor`](Self::integrate_row_major_spinor). User
/// should be very clear about the memory layout difference.
///
/// Also, function [`eval_gto`](Self::eval_gto) will evaluate GTO values on
/// grids, which can be utilized in DFT computations.
///
/// Documentation and code conventions:
///
/// | code name | description |
/// |------------|-------------|
/// | `atm` | atom |
/// | `bas` | shell |
/// | `shl` | shell |
/// | `ao` | atomic orbital basis (for users, absolute where starting shell is always the first shell from `bas`) |
/// | `cgto` | atomic orbital basis (for developers, relative to specified starting shell by `shls_slice`) |
/// | `cint`, `CInt` | libcint's [`CInt`] structure or instances |
/// | `c_int` | [`std::ffi::c_int`] type ([`i32`] in most cases) |
#[derive(Debug, Clone, PartialEq)]
pub struct CInt {
    /// Slots of atoms.
    ///
    /// Names of this field can be retrieved in [`cint_ffi`].
    ///
    /// | Index | Name          | Description | Related getter | Related setter |
    /// |-------|---------------|-------------|----------------|----------------|
    /// | 0 | `CHARGE_OF`       | atomic charge (ECP core electrons excluded)       | [`atom_charge`](Self::atom_charge) <br/> [`atom_charges`](Self::atom_charges) |
    /// | 1 | `PTR_COORD`       | coordinates location (pointer to `env` field)     | [`atom_coord`](Self::atom_coord) <br/> [`atom_coords`](Self::atom_coords) | [`set_geom`](Self::set_geom) |
    /// | 2 | `NUC_MOD_OF`      | nuclear mode of the atom                          | | [`set_nuc_mod`](Self::set_nuc_mod) |
    /// | 3 | `PTR_ZETA`        | pointer to zeta values (pointer to `env` field)   | | [`set_rinv_at_nucleus`](Self::set_rinv_at_nucleus) |
    /// | 4 | `PTR_FRAC_CHARGE` | fractional charge (pointer to `env` field)        | [`atom_charge`](Self::atom_charge) <br/> [`atom_charges`](Self::atom_charges) |
    /// | 5 | `RESERVE_ATMSLOT` |
    /// | 6 | `ATM_SLOTS`       |
    ///
    /// - 2 - `NUC_MOD_OF` can be three kinds:
    ///     - 1 - `POINT_NUC` point charge, which is the most common case.
    ///     - 2 - `GAUSSIAN_NUC` nuclear charge is represented by a gaussian
    ///       distribution, with a zeta value (related to `PTR_ZETA`).
    ///     - 3 - `MM_NUC` is a point charge with fractional charge, which is
    ///       used in molecular mechanics (MM) calculations, with a fractional
    ///       value (related to `PTR_FRAC_CHARGE`).
    /// - 3 - Zeta value is atomic charge that is gaussian-distributed.
    ///   (`NUC_MOD_OF` refers to `GAUSSIAN_NUC`). In other cases, this value
    ///   should be zero.
    pub atm: Vec<[c_int; 6]>,

    /// Slot of shells (as minimal building block of contracted GTO).
    ///
    /// | Index | Name          | Description | Related getter |
    /// |-------|---------------|-------------|----------------|
    /// | 0 | `ATOM_OF`        | 0-based index of corresponding atom                            |
    /// | 1 | `ANG_OF`         | angular momentum                                               | [`bas_angular`](Self::bas_angular) |
    /// | 2 | `NPRIM_OF`       | number of primitive GTO in basis                               | [`bas_nprim`](Self::bas_nprim) |
    /// | 3 | `NCTR_OF`        | number of contracted GTO in basis                              | [`bas_nctr`](Self::bas_nctr) |
    /// | 4 | `KAPPA_OF`       | kappa for spinor GTO                                           | [`bas_kappa`](Self::bas_kappa) |
    /// | 5 | `PTR_EXP`        | exponents of primitive GTOs (pointer to `env` field)           |
    /// | 6 | `PTR_COEFF`      | column-major contraction coefficients (pointer to `env` field) |
    /// | 7 | `RESERVE_BASLOT` |
    /// | 8 | `BAS_SLOTS`      |
    pub bas: Vec<[c_int; 8]>,

    /// Slot of shells for ECP (effective core potential).
    ///
    /// Other entries are the same as `bas` field, but with some additional:
    ///
    /// | Index | Name         | Description |
    /// |-------|--------------|-------------|
    /// | 1 | `ANG_OF`         | angular momentum (refers to angular of $U_L$) |
    /// | 3 | `RADI_POWER`     | number of maximum radial power to be summed   |
    /// | 4 | `SO_TYPE_OF`     | spin-orb type                                 |
    pub ecpbas: Vec<[c_int; 8]>,

    /// Slot of floating-point variables.
    ///
    /// | Index | Name          | Description | Related getter | Related setter |
    /// |-------|---------------|-------------|----------------|----------------|
    /// |  0 | `PTR_EXPCUTOFF`     | Overall cutoff for integral prescreening, value needs to be ln (threshold) | [`get_integral_screen`](Self::get_integral_screen) | [`set_integral_screen`](Self::set_integral_screen) |
    /// |  1 | `PTR_COMMON_ORIG`   | $R_C$ (common origin) of $r-R_C$ in dipole, GIAO operators                 | [`get_common_origin`](Self::get_common_origin) | [`set_common_origin`](Self::set_common_origin) |
    /// |  4 | `PTR_RINV_ORIG`     | $R_O$ (rinv origin) of $1/(r-R_O)$                                         | [`get_rinv_origin`](Self::get_rinv_origin) | [`set_rinv_origin`](Self::set_rinv_origin) |
    /// |  7 | `PTR_RINV_ZETA`     | ZETA parameter for Gaussian charge distribution (Gaussian nuclear model)   | [`get_rinv_zeta`](Self::get_rinv_zeta) | [`set_rinv_zeta`](Self::set_rinv_zeta) |
    /// |  8 | `PTR_RANGE_OMEGA`   | omega parameter in range-separated coulomb operator (>0 for LR, <0 for SR) | [`get_range_coulomb`](Self::get_range_coulomb) <br/> [`omega`](`Self::omega`) | [`set_range_coulomb`](Self::set_range_coulomb) <br/> [`set_omega`](Self::set_omega) |
    /// |  9 | `PTR_F12_ZETA`      | Yukawa potential and Slater-type geminal $e^{-\zeta r}$                    |
    /// | 10 | `PTR_GTG_ZETA`      | Gaussian type geminal $e^{-\zeta r^2}$                                     |
    /// | 11 | `NGRIDS`            | For hybrid integrals with grids                                            |
    /// | 12 | `PTR_GRIDS`         | Location of grids for `int1e_grids` or variants                            |
    /// | 17 | `AS_RINV_ORIG_ATOM` | Position of atom to be used as origin in $1/(r-R_O)$ for ECP derivatives   | [`get_rinv_origin_atom`](Self::get_rinv_origin_atom) <br/> [`set_rinv_origin_atom`](Self::set_rinv_origin_atom) |
    /// | 18 | `AS_ECPBAS_OFFSET`  | Offset of ECP basis in `bas` field, used for ECP integrals                 | | [`merge_ecpbas`](Self::merge_ecpbas) <br/> [`decopule_ecpbas`](Self::decopule_ecpbas) |
    /// | 19 | `AS_NECPBAS`        | Number of ECP shells in `ecpbas` field                                     | | [`merge_ecpbas`](Self::merge_ecpbas) <br/> [`decopule_ecpbas`](Self::decopule_ecpbas) |
    /// | 20 | `PTR_ENV_START`     | Start of data                                                              |
    pub env: Vec<f64>,

    /// Type of integral.
    ///
    /// - `Spheric`: spherical harmonics, which is the most common case.
    /// - `Cartesian`: cartesian coordinates.
    /// - `Spinor`: spinor integrals, which are used in relativistic
    ///   calculations.
    pub cint_type: CIntType,
}

/// Distinguish between general integral or ECP (effective core potential)
/// integral.
///
/// This enum is mostly used internally, not for user usage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CIntKind {
    /// General integral type, which is used for most of the integrals.
    Int,
    /// ECP integral type, which is used for effective core potential integrals.
    Ecp,
}

/// Integral types.
///
/// You can also use `&str` type to convert to this type:
/// - `"sph"` or `"spheric"` for spherical integrals (default);
/// - `"cart"` or `"cartesian"` for cartesian integrals;
/// - `"spinor"` for spinor integrals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CIntType {
    #[default]
    /// Spherical integrals, output double float `f64`.
    Spheric,
    /// Cartesian integrals, output double float `f64`.
    Cartesian,
    /// Spinor integrals, output `Complex<f64>`, and should be called by
    /// functions with `_spinor` suffix.
    Spinor,
}

/// Symmetry of the integral.
///
/// Naming convention is
/// - 2-center integrals $(\mu | \nu)$ or `uv` or `ij`;
/// - 3-center integrals $(\mu \nu | \kappa)$ or `uvk` or `ijk`;
/// - 4-center integrals $(\mu \nu | \kappa \lambda)$ or `uvkl` or `ijkl`.
///
/// You can also use `&str` type to convert to this type: `"s1"`, `"s2ij"` or
/// `"s2uv"`, `"s2kl"`, `"s4"`, `"s8"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CIntSymm {
    #[default]
    /// No symmetry (default).
    S1,
    /// Symmetry of the first two indices; for example of 3-center integrals,
    /// $$(\mu \nu | \kappa) = (\nu \mu | \kappa)$$
    S2ij,
    /// Symmetry of the last two indices in 4-center integrals, i.e.
    /// $$(\mu \nu | \kappa \lambda) = (\mu \nu | \lambda \kappa)$$
    S2kl,
    /// Symmetry of the first and last indices in 4-center integrals, i.e.
    /// $$(\mu \nu | \kappa \lambda) = (\mu \nu | \lambda \kappa) = (\nu \mu |
    /// \kappa \lambda) = (\nu \mu | \lambda \kappa)$$
    S4,
    /// symmetry of all indices in 4-center integrals, i.e., additional symmetry
    /// beyond `"s4"`, there is
    /// $$(\mu \nu | \kappa \lambda) = (\kappa \lambda | \mu \nu)$$
    S8,
}

/// Optimizer to be used in integral evaluation (not intended for user).
#[derive(Debug, PartialEq)]
pub enum CIntOptimizer {
    Int(*mut CINTOpt),
    Ecp(*mut ECPOpt),
}

/// Output of the integral evaluation (output buffer with col-major shape).
///
/// You can use `.into()` to convert it to a tuple of `(Vec<F>, Vec<usize>)`,
/// where `F` is `f64` for sph and cart integrals, and `Complex<f64>` for spinor
/// integrals.
pub struct CIntOutput<F> {
    /// Output buffer.
    ///
    /// It can be `None` when user provided the output buffer for integral: the
    /// integral will be written directly to the buffer user provided, and this
    /// crate will not allocate an output buffer. Note that in this case,
    /// `.into()` will panic.
    pub out: Option<Vec<F>>,

    /// Shape of the output buffer. Please see [`CInt::integrate`] for more
    /// information.
    ///
    /// **Note**: The shape can be in row-major or col-major order, depending on
    /// the function to be called. User should take care of this.
    pub shape: Vec<usize>,
}

/// Integrate arguments for function [`CInt::integrate_with_args`] and
/// [`CInt::integrate_with_args_spinor`].
///
/// Builder of this struct can be retrieved by [`CInt::integrate_args_builder`]
/// and [`CInt::integrate_args_builder_spinor`].
#[derive(Builder, Debug)]
#[builder(pattern = "owned", build_fn(error = "CIntError"))]
pub struct IntegrateArgs<'l, F> {
    /// Integrator name, such as `"int1e_ovlp"`, `"int2e"`, etc.
    #[builder(setter(into))]
    pub intor: &'l str,

    /// Shell slices for evaluating sub-tensor of the total integral.
    #[builder(default = "&[]")]
    pub shls_slice: &'l [[usize; 2]],

    /// Symmetry of the integral. This will affect shape of output tensor.
    #[builder(default, setter(into))]
    pub aosym: CIntSymm,

    /// Output buffer for the integral evaluation.
    ///
    /// If this is `None`, the integral engine will generate a buffer for
    /// output.
    #[builder(default, setter(strip_option))]
    pub out: Option<&'l mut [F]>,

    /// Col-major or row-major output buffer (col-major default).
    ///
    /// - Col-major: the same **data layout** to PySCF's 2/3-center integrals;
    ///   shape presented in col-major.
    /// - Row-major: the same **shape** to PySCF's integrals; shape presented in
    ///   row-major.
    #[builder(default = false)]
    pub row_major: bool,

    /// Grids setting for `int1e_grids` and related integrators.
    #[builder(default, setter(strip_option))]
    pub grids: Option<&'l [[f64; 3]]>,
}

/// Integrate arguments for function [`CInt::integrate_cross_with_args`] and
/// [`CInt::integrate_cross_with_args_spinor`].
///
/// Builder of this struct can be retrieved by
/// [`CInt::integrate_cross_args_builder`]
/// and [`CInt::integrate_cross_args_builder_spinor`].
#[derive(Builder, Debug)]
#[builder(pattern = "owned", build_fn(error = "CIntError"))]
pub struct IntorCrossArgs<'l, F> {
    /// Integrator name, such as `"int1e_ovlp"`, `"int2e"`, etc.
    #[builder(setter(into))]
    pub intor: &'l str,

    /// Molecules for which the integral will be evaluated.
    ///
    /// The length of molecules must be accordance with the `shls_slice` and
    /// number of centers of integrator.
    pub mols: &'l [&'l CInt],

    /// Shell slices for evaluating sub-tensor of the total integral.
    #[builder(default = "&[]")]
    pub shls_slice: &'l [[usize; 2]],

    /// Symmetry of the integral. This will affect shape of output tensor.
    #[builder(default, setter(into))]
    pub aosym: CIntSymm,

    /// Output buffer for the integral evaluation.
    ///
    /// If this is `None`, the integral engine will generate a buffer for
    /// output.
    #[builder(default, setter(strip_option))]
    pub out: Option<&'l mut [F]>,

    /// Col-major or row-major output buffer (col-major default).
    ///
    /// - Col-major: the same **data layout** to PySCF's 2/3-center integrals;
    ///   shape presented in col-major.
    /// - Row-major: the same **shape** to PySCF's integrals; shape presented in
    ///   row-major.
    #[builder(default = false)]
    pub row_major: bool,
}

/* #endregion */

/* #region get_integrator */

/// Obtain integrator by name.
///
/// # Panics
///
/// - integrator not found
///
/// # See also
///
/// [`get_integrator_f`], [`CInt::get_integrator`]
pub fn get_integrator(intor: &str) -> Box<dyn Integrator> {
    get_integrator_f(intor).cint_unwrap()
}

/// Obtain integrator by name, failable version.
///
/// # See also
///
/// [`get_integrator`], [`CInt::get_integrator`]
pub fn get_integrator_f(intor: &str) -> Result<Box<dyn Integrator>, CIntError> {
    // explicitly check cint and ecp differently
    let intor = if let Some(intor) = get_cint_integrator(&intor.to_lowercase()) {
        Ok(intor)
    } else if let Some(intor) = get_ecp_integrator(&intor.to_lowercase()) {
        Ok(intor)
    } else {
        cint_raise!(IntegratorNotFound, "{intor}")
    }?;

    // should have checked anything, gracefully returns
    Ok(intor)
}

/* #endregion */

/* #region CIntType impl */

impl From<&str> for CIntType {
    #[inline]
    fn from(cint_type: &str) -> Self {
        match cint_type.to_lowercase().as_str() {
            "sph" | "spheric" | "spherical" => CIntType::Spheric,
            "cart" | "cartesian" => CIntType::Cartesian,
            "spinor" => CIntType::Spinor,
            _ => panic!("Unknown integral type: {cint_type}"),
        }
    }
}

/* #endregion */

/* #region CIntSymm impl */

impl From<&str> for CIntSymm {
    #[inline]
    fn from(aosym: &str) -> Self {
        match aosym {
            "S1" | "s1" => CIntSymm::S1,
            "S2ij" | "s2ij" | "S2uv" | "s2uv" => CIntSymm::S2ij,
            "S2kl" | "s2kl" => CIntSymm::S2kl,
            "S4" | "s4" => CIntSymm::S4,
            "S8" | "s8" => CIntSymm::S8,
            _ => panic!("Unknown symmetry: {aosym}"),
        }
    }
}

impl From<Option<&str>> for CIntSymm {
    #[inline]
    fn from(aosym: Option<&str>) -> Self {
        aosym.unwrap_or("s1").into()
    }
}

/* #endregion */

/* #region CIntOptimizer impl */

unsafe impl Send for CIntOptimizer {}
unsafe impl Sync for CIntOptimizer {}

impl Drop for CIntOptimizer {
    fn drop(&mut self) {
        match self {
            Self::Int(opt) => unsafe { cint_ffi::CINTdel_optimizer(opt) },
            Self::Ecp(opt) => unsafe { cecp_ffi::ECPdel_optimizer(opt) },
        }
    }
}

impl CIntOptimizer {
    #[inline]
    pub fn as_ptr(&self) -> *const c_void {
        match self {
            Self::Int(opt) => *opt as *const c_void,
            Self::Ecp(opt) => *opt as *const c_void,
        }
    }
}

/* #endregion */

/* #region CIntOutput impl */

impl<F> From<CIntOutput<F>> for (Vec<F>, Vec<usize>) {
    fn from(output: CIntOutput<F>) -> Self {
        if output.out.is_none() {
            panic!(
                "You have called integral with output buffer, and should not call `into` to get the integral buffer, but use your mutable reference instead."
            );
        }
        (output.out.unwrap_or_default(), output.shape)
    }
}

/* #endregion */

/// Implementation of integral at higher API level (for basic user usage).
impl CInt {
    /// Main electronic integral driver (for non-spinor type) in column-major.
    ///
    /// Following kinds of integrals are supported:
    /// - general integrals,
    /// - ECP integrals,
    /// - 2c-1e integrals with grids.
    ///
    /// # PySCF equivalent
    ///
    /// `mol.intor(intor, aosym, shls_slice)`
    ///
    /// # Arguments
    ///
    /// - `intor`: name of the integral to be evaluated, such as `"int1e_ovlp"`,
    ///   `"int2e"`, `"ECPscalar_iprinvip"`, `"int2e_giao_sa10sp1spsp2"`, etc.
    /// - `aosym`: symmetry of the integral, you can specify `"s1"`, `"s2ij"`,
    ///   `"s2kl"`, `"s4"`, `"s8"`.
    /// - `shls_slice`: shell slices for evaluating sub-tensor of the total
    ///   integral. Please note that this is either be `None`, or a slice of
    ///   type `&[[usize; 2]]` or something similar (vectors, arrays) **with
    ///   length the same to the number of centers in integral**.
    ///
    /// <div class="warning">
    ///
    /// **Does not check whether AO symmetry is correct to the corresponding
    /// integrator**
    ///
    /// For example,
    /// - `int2e_ip2` $(\mu \nu | \kappa \nabla \lambda)$ is meaningful for
    ///   `"s1"` and `"s2ij"` symmetry, not meaningful for other kinds of
    ///   symmetry.
    /// - `int2e_ip1` $(\nabla \mu \nu | \kappa \lambda)$ is meaningful for
    ///   `"s1"` and `"s2kl"` symmetry, not meaningful for other kinds of
    ///   symmetry.
    /// - `int2e` is meaningful for all symmetries.
    /// - `int1e_ovlp` is meaningful for `"s1"` and `"s2ij"` symmetry.
    ///
    /// However, this wrapper will generally not panic, nor raise error, if you
    /// use an incorrect symmetry for the integral. An exception is that if
    /// you specify `"s2kl"`, `"s4"`, `"s8"` on non-4-center integrals, it will
    /// raise error.
    ///
    /// </div>
    ///
    /// # Outputs
    ///
    /// Returns a [`CIntOutput<f64>`] for the integral evaluation, which
    /// contains
    /// - `out` (`Vec<f64>`): the output buffer for the integral evaluation.
    /// - `shape` (`Vec<usize>`): the shape of the output buffer.
    ///
    /// You can use `.into()` to convert it to a tuple of `(Vec<f64>,
    /// Vec<usize>)`:
    ///
    /// ```rust
    /// # use libcint::prelude::*;
    /// # let cint_data = init_h2o_def2_tzvp();
    /// let (out, shape) = cint_data.integrate("int1e_ovlp", "s2ij", None).into();
    /// ```
    ///
    /// # Examples
    ///
    /// The following example uses a pre-defined water molecule with def2-TZVP
    /// basis set.
    ///
    /// The construction of [`CInt`] is not performed in this crate,
    /// but should be provided by user. We refer to function
    /// [`init_h2o_def2_tzvp`] for how to define a [`CInt`] instance.
    ///
    /// ## General Example
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let cint_data = init_h2o_def2_tzvp();
    ///
    /// // aosym default: "s1"
    /// // shls_slice default: None (evaluating all shells)
    /// let (out, shape) = cint_data.integrate("int1e_ovlp", None, None).into();
    /// assert_eq!(shape, vec![43, 43]);
    ///
    /// // utilize "s2ij" symmetry
    /// let (out, shape) = cint_data.integrate("int3c2e_ip2", "s2ij", None).into();
    /// assert_eq!(shape, vec![946, 43, 3]);
    ///
    /// // calculate sub-tensor of the integral
    /// let nbas = cint_data.nbas();
    /// let shl_slices = [[0, nbas], [0, nbas], [3, 12]]; // 3-centers for int3c2e_ip2
    /// let (out, shape) = cint_data.integrate("int3c2e_ip2", "s2ij", shl_slices).into();
    /// assert_eq!(shape, vec![946, 29, 3]);
    ///
    /// let shls_slice = [[0, nbas], [0, nbas], [3, 12], [4, 15]]; // 4-centers for int2e_ip2
    /// let (out, shape) = cint_data.integrate("int2e_ip2", "s2ij", shls_slice).into();
    /// assert_eq!(shape, vec![946, 29, 33, 3]);
    /// ```
    ///
    /// ## ECP
    ///
    /// ECP (effective core potential) integrals are also supported.
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let cint_data = init_sb2me4_cc_pvtz();
    ///
    /// let (out, shape) = cint_data.integrate("ECPscalar_iprinvip", "s1", None).into();
    /// assert_eq!(shape, vec![366, 366, 9]);
    /// ```
    ///
    /// ## Integral with Grids
    ///
    /// For integrals with grids, such as `int1e_grids`, `int1e_grids_ip`, you
    /// may perform integrate with function `with_grids` or directly set by
    /// `set_grids`:
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let mut cint_data = init_h2o_def2_tzvp();
    /// let grids = vec![[0., 1., 2.], [3., 4., 5.]]; // ngrids = 2
    ///
    /// let (out, shape) = cint_data.with_grids(&grids, |data| {
    ///     data.integrate("int1e_grids_ip", "s1", None).into()
    /// });
    /// // [grids, bas_i, bas_j, components]
    /// assert_eq!(shape, vec![2, 43, 43, 3]);
    /// ```
    ///
    /// # Column-major convention
    ///
    /// <div class="warning">
    ///
    /// [`integrate`](CInt::integrate) always returns column-major shape with
    /// its output buffer.
    ///
    /// **Please note that [`integrate`](CInt::integrate) is somehow different
    /// to PySCF's convention.** The user should be very clear about the
    /// convention before using this function, especially when you are
    /// evaluating integrals with derivatives or using `shls_slice` option.
    ///
    /// </div>
    ///
    /// The following table summarizes difference between PySCF and [`CInt`]
    /// conventions.
    /// - "Strides" are indicated by numbers. Recall that a tensor is defined by
    ///   its data buffer in RAM and layout; the layouot contains shape, strides
    ///   and offset.
    ///
    ///   Those numbers are not the actual stride size, but actually indicates
    ///   the relative size of that axis in  tensor. For row-major tensors of
    ///   3-dimensional tensor, it is $[2, 1, 0]$; for col-major tensors, it is
    ///   $[0, 1, 2]$.
    /// - $t$ indicates the number of components in the integral.
    /// - $\mu, \nu, \kappa, \lambda$ indicate the indices of the atomic
    ///   orbitals (basis).
    /// - $\mathrm{tp}(\mu \nu)$ means triangular-packed shape of the $(\mu,
    ///   \nu)$ indices pair. This is always packed by upper-triangular indices
    ///   for col-major, or equivalently lower-triangular indices for row-major.
    /// - $g$ indicates grids, which is used in integrals like `int1e_grids`,
    ///   `int1e_grids_ip`.
    /// - "same layout" means the underlying data is the same, regardless of how
    ///   shape and strides are defined. If same data layout, it means [`CInt`]
    ///   data is the transposed PySCF's data, without any additional copy or
    ///   memory allocation.
    ///
    /// | center | comp | symm | example | PySCF shape | PySCF strides | [`CInt`] shape | [`CInt`] strides | same layout |
    /// |--------|------|------|---------|-------------|---------------|----------------|------------------|-------------|
    /// | 2 | ✘ | `s1`   | `int1e_ovlp`     | $[\mu, \nu]$                                   | $[0, 1]$          | $[\mu, \nu]$                                  | $[0, 1]$          | ✔ |
    /// | 2 | ✔ | `s1`   | `int1e_ipkin`    | $[t, \mu, \nu]$                                | $[2, 0, 1]$       | $[\mu, \nu, t]$                               | $[0, 1, 2]$       | ✔ |
    /// | 2 | ✘ | `s2ij` | `int1e_ovlp`     | Not supported                                  | -                 | $[\mathrm{tp}(\mu \nu)]$                      | $\[0\]$           | - |
    /// | 2 | ✔ | `s2ij` | `int1e_ovlp`     | Not supported                                  | -                 | $[\mathrm{tp}(\mu \nu), t]$                   | $[0, 1]$          | - |
    /// | 2 | ✘ | `s1`   | `int1e_grids`    | $[g, \mu, \nu]$                                | $[0, 1, 2]$       | $[g, \mu, \nu]$                               | $[0, 1, 2]$       | ✔ |
    /// | 2 | ✔ | `s1`   | `int1e_grids_ip` | $[t, g, \mu, \nu]$                             | $[3, 0, 1, 2]$    | $[g, \mu, \nu, t]$                            | $[0, 1, 2, 3]$    | ✔ |
    /// | 3 | ✘ | `s1`   | `int3c2e`        | $[\mu, \nu, \kappa]$                           | $[0, 1, 2]$       | $[\mu, \nu, \kappa]$                          | $[0, 1, 2]$       | ✔ |
    /// | 3 | ✔ | `s1`   | `int3c2e_ip1`    | $[t, \mu, \nu, \kappa]$                        | $[3, 0, 1, 2]$    | $[\mu, \nu, \kappa, t]$                       | $[0, 1, 2, 3]$    | ✔ |
    /// | 3 | ✘ | `s2ij` | `int3c2e`        | $[\mathrm{tp}(\mu \nu), \kappa]$               | $[0, 1]$          | $[\mathrm{tp}(\mu \nu), \kappa]$              | $[0, 1]$          | ✔ |
    /// | 3 | ✔ | `s2ij` | `int3c2e_ip2`    | $[t, \mathrm{tp}(\mu \nu), \kappa]$            | $[2, 0, 1]$       | $[\mathrm{tp}(\mu \nu), \kappa, t]$           | $[0, 1, 2]$       | ✔ |
    /// | 4 | ✘ | `s1`   | `int2e`          | $[\mu, \nu, \kappa, \lambda]$                  | $[3, 2, 1, 0]$    | $[\mu, \nu, \kappa, \lambda]$                 | $[0, 1, 2, 3]$    | ✘ |
    /// | 4 | ✔ | `s1`   | `int2e_ip1`      | $[t, \mu, \nu, \kappa, \lambda]$               | $[4, 3, 2, 1, 0]$ | $[\mu, \nu, \kappa, \lambda, t]$              | $[0, 1, 2, 3, 4]$ | ✘ |
    /// | 4 | ✘ | `s2ij` | `int2e`          | $[\mathrm{tp}(\mu \nu), \kappa, \lambda]$      | $[2, 1, 0]$       | $[\mathrm{tp}(\mu \nu), \kappa, \lambda]$     | $[0, 1, 2]$       | ✘ |
    /// | 4 | ✔ | `s2ij` | `int2e_ip2`      | $[t, \mathrm{tp}(\mu \nu), \kappa, \lambda]$   | $[3, 2, 1, 0]$    | $[\mathrm{tp}(\mu \nu), \kappa, \lambda, t]$  | $[0, 1, 2, 3]$    | ✘ |
    /// | 4 | ✘ | `s2kl` | `int2e`          | $[\mu, \nu, \mathrm{tp}(\kappa \lambda)]$      | $[2, 1, 0]$       | $[\mu, \nu, \mathrm{tp}(\kappa \lambda)]$     | $[0, 1, 2]$       | ✘ |
    /// | 4 | ✔ | `s2kl` | `int2e_ip1`      | $[t, \mu, \nu, \mathrm{tp}(\kappa \lambda)]$   | $[3, 2, 1, 0]$    | $[\mu, \nu, \mathrm{tp}(\kappa \lambda), t]$  | $[0, 1, 2, 3]$    | ✘ |
    /// | 4 | ✘ | `s4`   | `int2e`          | $[\mathrm{tp}(\mu \nu), \mathrm{tp}(\kappa \lambda)]$ | $[1, 0]$ | $[\mathrm{tp}(\mu \nu), \mathrm{tp}(\kappa \lambda)]$ | $[0, 1]$ | ✘ |
    /// | 4 | ✘ | `s8`   | `int2e`          | $[\mathrm{tp}(\mathrm{tp}(\mu \nu) \mathrm{tp}(\kappa \lambda))]$ | $\[0\]$ | $[\mathrm{tp}(\mathrm{tp}(\mu \nu) \mathrm{tp}(\kappa \lambda))]$ | $\[0\]$ | ✔ |
    ///
    /// # Spheric or Cartesian
    ///
    /// The `CInt` supports both spherical and cartesian integrals. You can
    /// either set [`CInt::cint_type`] or use `_sph` or `_cart` suffix in
    /// integrator name argument `intor`:
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let mut cint_data = init_h2o_def2_tzvp();
    ///
    /// // spherical integral
    /// let (out, shape) = cint_data.integrate("int1e_ovlp", None, None).into();
    /// assert_eq!(shape, vec![43, 43]);
    ///
    /// // cartesian integral using with-clause
    /// let (out, shape) = cint_data.with_cint_type("cart", |cint_data| {
    ///     cint_data.integrate("int1e_ovlp", None, None).into()
    /// });
    /// assert_eq!(shape, vec![48, 48]);
    ///
    /// // cartesian integral using suffix
    /// let (out, shape) = cint_data.integrate("int1e_ovlp_cart", None, None).into();
    /// assert_eq!(shape, vec![48, 48]);
    /// ```
    ///
    /// <div class="warning">
    ///
    /// **This function cannot handle spinor integral**
    ///
    /// Due to rust's strict type system, it is very difficult to handle both
    /// spinor and spheric/cartesian integrals in the same function. So spinor
    /// integral should be called by
    /// [`integrate_spinor`](Self::integrate_spinor), which output is
    /// [`Complex<f64>`].
    ///
    /// ```should_panic
    /// # use libcint::prelude::*;
    /// # let cint_data = init_h2o_def2_tzvp();
    /// let (out, shape) = cint_data.integrate("int1e_ovlp_spinor", None, None).into();
    /// // panics: Expected float type size 16 bytes, but got 8 bytes.
    /// ```
    ///
    /// </div>
    ///
    /// # See also
    ///
    /// - [`integrate_f`](Self::integrate_f) for fallible counterpart.
    /// - [`integrate_spinor`](Self::integrate_spinor) for spinor type
    ///   integrals.
    /// - [`integrate_cross`](Self::integrate_cross) for cross integrals between
    ///   multiple molecules.
    /// - [`integrate_row_major`](Self::integrate_row_major) for row-major
    ///   output.
    /// - [`integrate_with_args`](Self::integrate_with_args) and
    ///   [`integrate_cross_with_args`](Self::integrate_cross_with_args) for
    ///   more advanced usage (full arguments that this crate supports).
    pub fn integrate(&self, intor: &str, aosym: impl Into<CIntSymm>, shls_slice: impl Into<ShlsSlice>) -> CIntOutput<f64> {
        self.integrate_f(intor, aosym, shls_slice.into()).cint_unwrap()
    }

    /// Main electronic integral driver (for spinor type) **in column-major**.
    ///
    /// We refer most documentation to [`integrate`](Self::integrate).
    ///
    /// # PySCF equivalent
    ///
    /// `mol.intor(f"{intor}_spinor", aosym, shls_slice)`
    ///
    /// # Examples
    ///
    /// The following example uses a pre-defined water molecule with def2-TZVP
    /// basis set.
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let mut cint_data = init_h2o_def2_tzvp();
    ///
    /// // spinor integral using with-clause
    /// let (out, shape) = cint_data.with_cint_type("spinor", |cint_data| {
    ///    cint_data.integrate_spinor("int1e_ovlp", None, None).into()
    /// });
    /// assert_eq!(shape, vec![86, 86]);
    ///
    /// // spinor integral using suffix
    /// let (out, shape) = cint_data.integrate_spinor("int1e_ovlp_spinor", None, None).into();
    /// assert_eq!(shape, vec![86, 86]);
    /// ```
    ///
    /// <div class="warning">
    ///
    /// **This function cannot handle spheric or cartesian integral**
    ///
    /// Due to rust's strict type system, it is very difficult to handle both
    /// spinor and spheric/cartesian integrals in the same function. So spheric
    /// and cartesian integral should be called by
    /// [`integrate`](Self::integrate), which output is `f64`.
    ///
    /// ```should_panic
    /// # use libcint::prelude::*;
    /// # let cint_data = init_h2o_def2_tzvp();
    /// let (out, shape) = cint_data.integrate_spinor("int1e_ovlp_sph", None, None).into();
    /// // panics: Expected float type size 8 bytes, but got 16 bytes.
    /// ```
    ///
    /// </div>
    ///
    /// # See also
    ///
    /// - [`integrate`](Self::integrate) for non-spinor type integrals.
    /// - [`integrate_spinor_f`](Self::integrate_spinor_f) for fallible
    ///   counterpart.
    /// - [`integrate_cross_spinor`](Self::integrate_cross_spinor) for cross
    ///   integrals between multiple molecules.
    /// - [`integrate_with_args_spinor`](Self::integrate_with_args_spinor) and
    ///   [`integrate_cross_with_args_spinor`](Self::integrate_cross_with_args_spinor)
    ///   for more advanced usage (full arguments that this crate supports).
    pub fn integrate_spinor(&self, intor: &str, aosym: impl Into<CIntSymm>, shls_slice: impl Into<ShlsSlice>) -> CIntOutput<Complex<f64>> {
        self.integrate_spinor_f(intor, aosym, shls_slice.into()).cint_unwrap()
    }

    /// Main electronic integral driver (for non-spinor type) in column-major.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate`](Self::integrate) for non-fallible counterpart.
    pub fn integrate_f(
        &self,
        intor: &str,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<f64>, CIntError> {
        let shls_slice = shls_slice.into();
        let integrate_args = self.integrate_args_builder().intor(intor).aosym(aosym).shls_slice(shls_slice.as_ref()).build()?;
        self.integrate_with_args_inner(integrate_args)
    }

    /// Main electronic integral driver (for spinor type) in column-major.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_spinor`](Self::integrate_spinor) for non-fallible
    ///   counterpart.
    pub fn integrate_spinor_f(
        &self,
        intor: &str,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<Complex<f64>>, CIntError> {
        let shls_slice = shls_slice.into();
        let integrate_args = self.integrate_args_builder_spinor().intor(intor).aosym(aosym).shls_slice(shls_slice.as_ref()).build()?;
        self.integrate_with_args_inner(integrate_args)
    }

    /// Integrate with multiple molecules **in column-major**.
    ///
    /// # PySCF equivalent
    ///
    /// - 2-center: `gto.intor_cross(intor, mol1, mol2)`
    /// - 3-center: `df.incore.aux_e2(mol1, mol2, intor, aosym, shls_slice)`,
    ///   `df.incore.aux_e1(mol1, mol2, intor, aosym, shls_slice)`
    ///
    /// # Arguments
    ///
    /// - `intor`: name of the integral to be evaluated, such as `"int1e_ovlp"`,
    ///   `"int2e"`, `"ECPscalar_iprinvip"`, `"int2e_giao_sa10sp1spsp2"`, etc.
    /// - `mols`: references to a list of [`CInt`] molecules; the number of
    ///   molecules must be the same value to number of centers in the integral.
    /// - `aosym`: symmetry of the integral, you can specify `"s1"`, `"s2ij"`,
    ///   `"s2kl"`, `"s4"`, `"s8"`.
    /// - `shls_slice`: shell slices for evaluating sub-tensor of the total
    ///   integral. Please note that this is either be `None`, or a slice of
    ///   type `&[[usize; 2]]` or something similar (vectors, arrays) **with
    ///   length the same to the number of components in integral**. Also, the
    ///   slices corresponds to molecules in `mols` argument accordingly.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let data_tzvp = init_h2o_def2_tzvp();
    /// let data_jk = init_h2o_def2_jk();
    ///
    /// // pyscf equilvant
    /// //     out = gto.intor_cross("int1e_ovlp", mol_tzvp, mol_jk)
    /// //     lib.fp(out.T), out.shape
    /// let (out, shape) = CInt::integrate_cross("int1e_ovlp", [&data_tzvp, &data_jk], None, None).into();
    /// assert_eq!(shape, vec![43, 113]);
    /// assert!((cint_fp(&out) - 11.25500947854174).abs() < 1e-10);
    ///
    /// // pyscf equilvant
    /// //     out = df.incore.aux_e2(mol_tzvp, mol_jk, "int3c2e_ip2", "s2ij")
    /// //     out_c = out.transpose(0, 2, 1)
    /// //     lib.fp(out_c), out_c.shape[::-1]
    /// let (out, shape) = CInt::integrate_cross("int3c2e_ip2", [&data_tzvp, &data_tzvp, &data_jk], "s2ij", None).into();
    /// assert_eq!(shape, vec![946, 113, 3]);
    /// assert!((cint_fp(&out) - 10.435234769997802).abs() < 1e-10);
    /// ```
    ///
    /// # See also
    ///
    /// - [`integrate`](Self::integrate) for general integrals.
    /// - [`integrate_cross_f`](Self::integrate_cross_f) for fallible
    ///   counterpart.
    /// - [`integrate_cross_spinor`](Self::integrate_cross_spinor) for spinor
    ///   type integrals.
    /// - [`integrate_cross_with_args`](Self::integrate_cross_with_args) for
    ///   more advanced usage (full arguments that this crate supports).
    pub fn integrate_cross<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> CIntOutput<f64> {
        CInt::integrate_cross_f(intor, mols, aosym, shls_slice).cint_unwrap()
    }

    /// Integrate with multiple molecules **in column-major**.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_cross`](Self::integrate_cross) for non-fallible
    ///   counterpart.
    pub fn integrate_cross_f<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<f64>, CIntError> {
        let shls_slice = shls_slice.into();
        let args = IntorCrossArgsBuilder::default()
            .intor(intor)
            .mols(mols.as_ref())
            .shls_slice(shls_slice.as_ref())
            .aosym(aosym.into())
            .build()?;
        CInt::integrate_cross_with_args_inner(args)
    }

    /// Integrate with multiple molecules (for spinor type) **in
    /// column-major**.
    ///
    /// # See also
    ///
    /// - [`integrate_cross`](Self::integrate_cross) for non-spinor type
    ///   integrals.
    pub fn integrate_cross_spinor<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> CIntOutput<Complex<f64>> {
        CInt::integrate_cross_spinor_f(intor, mols, aosym, shls_slice).cint_unwrap()
    }

    /// Integrate with multiple molecules (for spinor type) **in
    /// column-major**.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_cross_spinor`](Self::integrate_cross_spinor) for
    ///   non-fallible counterpart.
    pub fn integrate_cross_spinor_f<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<Complex<f64>>, CIntError> {
        let shls_slice = shls_slice.into();
        let args = IntorCrossArgsBuilder::default()
            .intor(intor)
            .mols(mols.as_ref())
            .shls_slice(shls_slice.as_ref())
            .aosym(aosym.into())
            .build()?;
        CInt::integrate_cross_with_args_inner(args)
    }

    /// Main electronic integral driver (for non-spinor type) **in row-major**.
    ///
    /// Following kinds of integrals are supported:
    /// - general integrals,
    /// - ECP integrals,
    /// - 2c-1e integrals with grids.
    ///
    /// We refer most documentation to [`integrate`](Self::integrate). Those two
    /// functions share the same arguments, but the output buffer is in
    /// row-major shape; the shape of [`integrate`](Self::integrate) and
    /// [`integrate_row_major`](Self::integrate_row_major) are also different.
    /// Follow the rest documentation of this function for more information.
    ///
    /// # Examples
    ///
    /// The following example uses a pre-defined water molecule with def2-TZVP
    /// basis set.
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let cint_data = init_h2o_def2_tzvp();
    ///
    /// // aosym default: "s1"
    /// // shls_slice default: None (evaluating all shells)
    /// let (out, shape) = cint_data.integrate_row_major("int1e_ovlp", None, None).into();
    /// assert_eq!(shape, vec![43, 43]);
    ///
    /// // utilize "s2ij" symmetry
    /// let (out, shape) = cint_data.integrate_row_major("int3c2e_ip2", "s2ij", None).into();
    /// assert_eq!(shape, vec![3, 946, 43]);
    ///
    /// // calculate sub-tensor of the integral
    /// let nbas = cint_data.nbas();
    /// let shl_slices = [[0, nbas], [0, nbas], [3, 12]]; // 3-centers for int3c2e_ip2
    /// let (out, shape) = cint_data.integrate_row_major("int3c2e_ip2", "s2ij", shl_slices).into();
    /// assert_eq!(shape, vec![3, 946, 29]);
    ///
    /// let shls_slice = [[0, nbas], [0, nbas], [3, 12], [4, 15]]; // 4-centers for int2e_ip2
    /// let (out, shape) = cint_data.integrate_row_major("int2e_ip2", "s2ij", shls_slice).into();
    /// assert_eq!(shape, vec![3, 946, 29, 33]);
    /// ```
    ///
    /// # Row-major convention
    ///
    /// <div class="warning">
    ///
    /// [`integrate_row_major`](CInt::integrate_row_major) always returns
    /// column-major shape with its output buffer.
    ///
    /// Though shape of this function is the same to PySCF's convention,
    /// **please note that [`integrate_row_major`](CInt::integrate_row_major)
    /// does not share the same memory layout to PySCF's 2/3-center integrals**.
    /// The user should use these integrals with caution, especially when you
    /// are concerned for efficiency, or performing triangular matrices unpack.
    /// Same algorithms in PySCF when performing density fitting may not show
    /// the same efficiency using this function.
    ///
    /// Also, component of integrals in function
    /// [`integrate_row_major`](CInt::integrate_row_major) are presented in the
    /// first axis (the most non-contiguous memory layout for row-major).
    /// Compared to function, [`integrate`](CInt::integrate), where components
    /// are presented in the last axis (the most non-contiguous memory layout
    /// for column-major).
    ///
    /// </div>
    ///
    /// | center | comp | symm | example | shape | PySCF strides | [`CInt`] strides | same layout |
    /// |--------|------|------|---------|-------|---------------|------------------|-------------|
    /// | 2 | ✘ | `s1`   | `int1e_ovlp`     | $[\mu, \nu]$                                                      | $[0, 1]$          | $[1, 0]$          | ✘ |
    /// | 2 | ✔ | `s1`   | `int1e_ipkin`    | $[t, \mu, \nu]$                                                   | $[2, 0, 1]$       | $[2, 1, 0]$       | ✘ |
    /// | 2 | ✘ | `s2ij` | `int1e_ovlp`     | Not supported                                                     | -                 | $\[0\]$           | - |
    /// | 2 | ✔ | `s2ij` | `int1e_ovlp`     | Not supported                                                     | -                 | $[1, 0]$          | - |
    /// | 2 | ✘ | `s1`   | `int1e_grids`    | $[g, \mu, \nu]$                                                   | $[0, 1, 2]$       | $[2, 1, 0]$       | ✘ |
    /// | 2 | ✔ | `s1`   | `int1e_grids_ip` | $[t, g, \mu, \nu]$                                                | $[3, 0, 1, 2]$    | $[3, 2, 1, 0]$    | ✘ |
    /// | 3 | ✘ | `s1`   | `int3c2e`        | $[\mu, \nu, \kappa]$                                              | $[0, 1, 2]$       | $[2, 1, 0]$       | ✘ |
    /// | 3 | ✔ | `s1`   | `int3c2e_ip1`    | $[t, \mu, \nu, \kappa]$                                           | $[3, 0, 1, 2]$    | $[3, 2, 1, 0]$    | ✘ |
    /// | 3 | ✘ | `s2ij` | `int3c2e`        | $[\mathrm{tp}(\mu \nu), \kappa]$                                  | $[0, 1]$          | $[1, 0]$          | ✘ |
    /// | 3 | ✔ | `s2ij` | `int3c2e_ip2`    | $[t, \mathrm{tp}(\mu \nu), \kappa]$                               | $[2, 0, 1]$       | $[2, 1, 0]$       | ✘ |
    /// | 4 | ✘ | `s1`   | `int2e`          | $[\mu, \nu, \kappa, \lambda]$                                     | $[3, 2, 1, 0]$    | $[3, 2, 1, 0]$    | ✔ |
    /// | 4 | ✔ | `s1`   | `int2e_ip1`      | $[t, \mu, \nu, \kappa, \lambda]$                                  | $[4, 3, 2, 1, 0]$ | $[4, 3, 2, 1, 0]$ | ✔ |
    /// | 4 | ✘ | `s2ij` | `int2e`          | $[\mathrm{tp}(\mu \nu), \kappa, \lambda]$                         | $[2, 1, 0]$       | $[2, 1, 0]$       | ✔ |
    /// | 4 | ✔ | `s2ij` | `int2e_ip2`      | $[t, \mathrm{tp}(\mu \nu), \kappa, \lambda]$                      | $[3, 2, 1, 0]$    | $[3, 2, 1, 0]$    | ✔ |
    /// | 4 | ✘ | `s2kl` | `int2e`          | $[\mu, \nu, \mathrm{tp}(\kappa \lambda)]$                         | $[2, 1, 0]$       | $[2, 1, 0]$       | ✔ |
    /// | 4 | ✔ | `s2kl` | `int2e_ip1`      | $[t, \mu, \nu, \mathrm{tp}(\kappa \lambda)]$                      | $[3, 2, 1, 0]$    | $[3, 2, 1, 0]$    | ✔ |
    /// | 4 | ✘ | `s4`   | `int2e`          | $[\mathrm{tp}(\mu \nu), \mathrm{tp}(\kappa \lambda)]$             | $[1, 0]$          | $[1, 0]$          | ✔ |
    /// | 4 | ✘ | `s8`   | `int2e`          | $[\mathrm{tp}(\mathrm{tp}(\mu \nu) \mathrm{tp}(\kappa \lambda))]$ | $\[0\]$           | $\[0\]$           | ✔ |
    ///
    /// # See also
    ///
    /// - [`integrate`](Self::integrate) for general integrals.
    /// - [`integrate_row_major_f`](Self::integrate_row_major_f) for fallible
    ///   counterpart.
    /// - [`integrate_row_major_spinor`](Self::integrate_row_major_spinor) for
    ///   spinor type integrals.
    /// - [`integrate_cross_row_major`](Self::integrate_cross_row_major) for
    ///   cross integrals between multiple molecules.
    /// - [`integrate_with_args`](Self::integrate_with_args) and
    ///   [`integrate_cross_with_args`](Self::integrate_cross_with_args) for
    ///   more advanced usage (full arguments that this crate supports).
    pub fn integrate_row_major(&self, intor: &str, aosym: impl Into<CIntSymm>, shls_slice: impl Into<ShlsSlice>) -> CIntOutput<f64> {
        self.integrate_row_major_f(intor, aosym, shls_slice.into()).cint_unwrap()
    }

    /// Main electronic integral driver (for non-spinor type) in row-major.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_row_major`](Self::integrate_row_major) for non-fallible
    ///   counterpart.
    pub fn integrate_row_major_f(
        &self,
        intor: &str,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<f64>, CIntError> {
        let shls_slice = shls_slice.into();
        let integrate_args =
            self.integrate_args_builder().intor(intor).aosym(aosym).shls_slice(shls_slice.as_ref()).row_major(true).build()?;
        self.integrate_with_args_inner(integrate_args)
    }

    /// Main electronic integral driver (for spinor type) **in row-major**.
    ///
    /// We refer most documentation to
    /// [`integrate_spinor`](Self::integrate_spinor) and
    /// [`integrate_row_major`](Self::integrate_row_major) for more information.
    ///
    /// # Examples
    ///
    /// The following example uses a pre-defined water molecule with def2-TZVP
    /// basis set.
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let cint_data = init_h2o_def2_tzvp();
    ///
    /// let (out, shape) = cint_data.integrate_row_major_spinor("int1e_ipovlp_spinor", None, None).into();
    /// assert_eq!(shape, vec![3, 86, 86]);
    /// ```
    ///
    /// # See also
    ///
    /// - [`integrate_spinor`](Self::integrate_spinor) for column-major
    ///   counterpart.
    /// - [`integrate_row_major`](Self::integrate_row_major) for non-spinor type
    ///   integrals in row-major.
    /// - [`integrate_row_major_spinor_f`](Self::integrate_row_major_spinor_f)
    ///   for fallible counterpart.
    pub fn integrate_row_major_spinor(
        &self,
        intor: &str,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> CIntOutput<Complex<f64>> {
        self.integrate_row_major_spinor_f(intor, aosym, shls_slice.into()).cint_unwrap()
    }

    /// Main electronic integral driver (for spinor type) in row-major.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_row_major_spinor`](Self::integrate_row_major_spinor) for
    ///   non-fallible counterpart.
    pub fn integrate_row_major_spinor_f(
        &self,
        intor: &str,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<Complex<f64>>, CIntError> {
        let shls_slice = shls_slice.into();
        let integrate_args =
            self.integrate_args_builder_spinor().intor(intor).aosym(aosym).shls_slice(shls_slice.as_ref()).row_major(true).build()?;
        self.integrate_with_args_inner(integrate_args)
    }

    /// Integrate with multiple molecules **in row-major**.
    ///
    /// We refer most documentation to
    /// [`integrate_cross`](Self::integrate_cross), and also notice the
    /// row-major convention that described in
    /// [`integrate_row_major`](Self::integrate_row_major).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use libcint::prelude::*;
    /// let data_tzvp = init_h2o_def2_tzvp();
    /// let data_jk = init_h2o_def2_jk();
    ///
    /// // pyscf equilvant
    /// //     out = gto.intor_cross("int1e_ovlp", mol_tzvp, mol_jk)
    /// //     lib.fp(out), out.shape
    /// let (out, shape) = CInt::integrate_cross_row_major("int1e_ovlp", [&data_tzvp, &data_jk], None, None).into();
    /// assert_eq!(shape, vec![43, 113]);
    /// assert!((cint_fp(&out) - 7.422726471473346).abs() < 1e-10);
    ///
    /// // pyscf equilvant
    /// //     out = df.incore.aux_e2(mol_tzvp, mol_jk, "int3c2e_ip2", "s2ij")
    /// //     lib.fp(out), out.shape
    /// let (out, shape) = CInt::integrate_cross_row_major("int3c2e_ip2", [&data_tzvp, &data_tzvp, &data_jk], "s2ij", None).into();
    /// assert_eq!(shape, vec![3, 946, 113]);
    /// assert!((cint_fp(&out) - 15.423815120360992).abs() < 1e-10);
    /// ```
    ///
    /// # See also
    ///
    /// - [`integrate_cross`](Self::integrate_cross) for column-major
    ///   counterpart.
    /// - [`integrate_cross_row_major_f`](Self::integrate_cross_row_major_f) for
    ///   fallible counterpart.
    /// - [`integrate_cross_row_major_spinor`](Self::integrate_cross_row_major_spinor)
    ///   for spinor type integrals.
    /// - [`integrate_cross_with_args`](Self::integrate_cross_with_args) for
    ///   more advanced usage (full arguments that this crate supports).
    pub fn integrate_cross_row_major<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> CIntOutput<f64> {
        CInt::integrate_cross_row_major_f(intor, mols, aosym, shls_slice).cint_unwrap()
    }

    /// Integrate with multiple molecules **in row-major**.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_cross_row_major`](Self::integrate_cross_row_major) for
    ///   non-fallible counterpart.
    pub fn integrate_cross_row_major_f<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<f64>, CIntError> {
        let shls_slice = shls_slice.into();
        let args = IntorCrossArgsBuilder::default()
            .intor(intor)
            .mols(mols.as_ref())
            .shls_slice(shls_slice.as_ref())
            .aosym(aosym.into())
            .row_major(true)
            .build()?;
        CInt::integrate_cross_with_args_inner(args)
    }

    /// Integrate with multiple molecules (for spinor type) **in row-major**.
    ///
    /// # See also
    ///
    /// - [`integrate_cross_row_major`](Self::integrate_cross_row_major) for
    ///   non-spinor type integrals.
    /// - [`integrate_cross_row_major_f`](Self::integrate_cross_row_major_f) for
    ///   fallible counterpart.
    pub fn integrate_cross_row_major_spinor<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> CIntOutput<Complex<f64>> {
        CInt::integrate_cross_row_major_spinor_f(intor, mols, aosym, shls_slice).cint_unwrap()
    }

    /// Integrate with multiple molecules (for spinor type) **in row-major**.
    ///
    /// This function is fallible.
    ///
    /// # See also
    ///
    /// - [`integrate_cross_row_major_spinor`](Self::integrate_cross_row_major_spinor) for
    ///   non-fallible counterpart.
    pub fn integrate_cross_row_major_spinor_f<'l>(
        intor: &str,
        mols: impl AsRef<[&'l CInt]>,
        aosym: impl Into<CIntSymm>,
        shls_slice: impl Into<ShlsSlice>,
    ) -> Result<CIntOutput<Complex<f64>>, CIntError> {
        let shls_slice = shls_slice.into();
        let args = IntorCrossArgsBuilder::default()
            .intor(intor)
            .mols(mols.as_ref())
            .shls_slice(shls_slice.as_ref())
            .aosym(aosym.into())
            .row_major(true)
            .build()?;
        CInt::integrate_cross_with_args_inner(args)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cint_data() {
        let cint_data = init_h2o_def2_tzvp();
        let opt = cint_data.optimizer("int2e");
        println!("int2e opt: {opt:?}");
        if let CIntOptimizer::Int(opt) = opt {
            println!("int2e opt inner {:?}", unsafe { opt.read() });
        }
    }
}