원시데이터 수집 시스템
선정목록으로

Fast and reliable probabilistic reflectometry inversion with prior-amortized neural posterior estimation

간접 관련 필름·전자재료 · (11) 배리어 필름 (15) 디스플레이 패널재료(16) CPI(투명 폴리이미드)

기본 정보

저자
  1. Vladimir Starostin — Cluster of Excellence Machine Learning for Science, University of Tübingen, Tübingen, Germany
  2. Maximilian Dax — Max Planck Institute for Intelligent Systems, Tübingen, Germany
  3. Alexander Gerlach — Institute of Applied Physics, University of Tübingen, Tübingen, Germany
  4. Alexander Hinderhofer — Institute of Applied Physics, University of Tübingen, Tübingen, Germany
  5. Álvaro Tejero-Cantero — Cluster of Excellence Machine Learning for Science, University of Tübingen, Tübingen, Germany
  6. Frank Schreiber — Institute of Applied Physics, University of Tübingen, Tübingen, Germany
DOI
10.1126/sciadv.adr9668
저널
Science Advances
발행년도
2025
발행기관
American Association for the Advancement of Science
피인용수
3
라이선스
cc-by-nc
논문 유형
–
언어
–
원문 페이지
https://doi.org/10.1126/sciadv.adr9668
토픽
Electron and X-Ray Spectroscopy Techniques
OpenAlex ID
W4408423560

평가 내용

관련도
간접 관련
사업분야
필름·전자재료 · (11) 배리어 필름
부 분야
(15) 디스플레이 패널재료, (16) CPI(투명 폴리이미드)
R&D 측면
분석·모델링
확신도
0.80
근거 용어
reflectometry, thin films, multilayers, X-ray reflectometry, structural reconstruction
판단 근거
이 논문은 X-선 및 중성자 반사율 측정(reflectometry) 데이터를 활용하여 박막(thin films) 및 다층 구조(multilayers)의 물리적 구조를 빠르고 정확하게 역추적하는 딥러닝 알고리즘을 다룹니다. 이는 코오롱인더스트리의 배리어 필름, 디스플레이 패널재료, CPI 필름 등의 다층 박막 구조 분석 및 물성 제어 R&D에 응용될 수 있는 분석 방법론입니다.
R&D 활용 포인트
배리어 필름이나 CPI 필름과 같은 다층 박막 소재의 두께, 밀도, 계면 거칠기(roughness) 등을 비파괴적으로 정밀 분석하고 실시간 모니터링하는 공정 분석 기술로 활용 가능합니다.
평가 입력
섹션 본문 66,411자 중 30,032자 발췌

초록

Reconstructing the structure of thin films and multilayers from measurements of scattered x-rays or neutrons is key to progress in physics, chemistry, and biology. However, finding all structures compatible with reflectometry data is computationally prohibitive for standard algorithms, which typically results in unreliable analysis with only a single potential solution identified. We address this lack of reliability with a probabilistic deep learning method that identifies all realistic structures in seconds, redefining standards in reflectometry. Our method, prior-amortized neural posterior estimation (PANPE), combines simulation-based inference with adaptive priors that inform the inference network about known structural properties and controllable experimental conditions. PANPE networks support key scenarios such as high-throughput sample characterization, real-time monitoring of evolving structures, or the corefinement of several experimental datasets and can be adapted to provide fast, reliable, and flexible inference across many other inverse problems.

본문 69,086자

본문 펼치기
Reconstructing the structure of thin films and multilayers from measurements of scattered X-rays or neutrons is key to progress in physics, chemistry, and biology.However, finding all structures compatible with reflectometry data is computationally prohibitive for standard algorithms, which typically results in unreliable analysis with only a single potential solution identified.We address this lack of reliability with a probabilistic deep learning method that identifies all realistic structures in seconds, setting new standards in reflectometry.Our method, Prior-Amortized Neural Posterior Estimation (PANPE), combines simulation-based inference with novel adaptive priors that inform the inference network about known structural properties and controllable experimental conditions.PANPE networks support key scenarios such as high-throughput sample characterization, real-time monitoring of evolving structures, or the co-refinement of several experimental data sets, and can be adapted to provide fast, reliable, and flexible inference across many other inverse problems. I. INTRODUCTION Scattering techniques enable the reconstruction of object structures through the analysis of scattered radiation [1,2].At the nanoscale, this requires radiation with short wavelengths, such as X-rays and thermal neutrons.While for the reconstruction of images from visible scattered light there are more established tools including optical lenses, employing these tools for X-rays and neutrons frequently poses significant challenges, leading to the use of algorithms for the reconstruction process [3].These algorithms, however, receive incomplete information, as detectors capture intensities, but not the phase information of the scattered waves.This gives rise to the phaseless inverse problem in scattering physics.While physical models can simulate scattered intensities from a given structure, reconstructing the structure from actual measurements is analytically intractable, and experimental data can be consistent with multiple physical structures [4].This ambiguity can be then resolved through complementary measurements or physical knowledge, but it is crucial to first acknowledge the existence of multiple solutions to avoid costly misinterpretations of the data. I. INTRODUCTION Together with advances in experimental methods enabling time-resolved online experiments and high-throughput pipelines [5,6], this creates a pressing need for algorithms that are (1) fast, (2) capable of reliably identifying all possible solutions, and (3) flexible enough to integrate additional data and physics-informed constraints. I. INTRODUCTION The need of fast and reliable algorithms is especially evident for neutron and X-ray reflectometry [7,8].The reflected intensity R in specular geometry as a function of momentum transfer q (see Figure 1a) can inform about the scattering length density (SLD) profile for a broad range of thin films and layered structures, ranging from solar cells [9] to biological membranes [10,11].The SLD profile is typically modeled by parameters θ that include layer thicknesses d l , densities ρ l , and interface roughnesses σ l .Obtaining these parameters θ from a reflectivity curve R(q) in a fast and reliable way is a longstanding inverse problem (Figure 1b) due to the phase loss, measurement noise, and the limited range and resolution of q.For a long time, a common approach was to search for the "best" single set of parameters θ * maximizing the likelihood of the measured data.However, maximum likelihood estimation remains fundamentally unreliable as it overlooks other potential physical solutions arising from ambiguity in the inverse problem.To address ambiguity, we need to embark on a principled probabilistic approach, and estimate the posterior probability density of the parameters θ given the measured data R.In such a Bayesian posterior p(θ|R), different probable structures appear as distributional modes (Figure 1c).In practice, the inference of a high-dimensional posterior is inherently challenging, and particularly so in reflectometry where multiple narrow distributional modes are common.Conventional Bayesian likelihood-based techniques such as Markov Chain Monte Carlo (MCMC) [12] are neither fast nor reliable, as they generally miss distributional modes. I. INTRODUCTION Here, we present a machine learning solution for Bayesian reflectometry analysis that provides fast, reliable and accurate inference along with the flexibility that online experiments demand.Speed is achieved by pre-training a neural network across large amounts of representative data, an amortization procedure that then allows for real-time inference on new samples.Reliability stems from the use of recent simulation-based inference which, in contrast to likelihood-based modes provides comprehensive coverage of the search space. I. INTRODUCTION Accuracy in the identified solutions is achieved via a subsequent likelihood-based step, that refines machine learning-based estimates.Fast likelihood evaluations are possible thanks to a novel GPU-parallel transfer-matrix simulator.Finally, we enable great flexibility for a wide range of standard scenarios in experimental setups by extending neural posterior estimation (NPE) with prior amortization, which we term Prior-Amortized Neural Posterior Estimation (PANPE).Our method PANPE can use dynamically set, adaptive prior distributions, allowing to track online expriments, leverages equivariance transformations to enable amortization over different q ranges, and can combine evidence from multiple measurements for efficient inference.Below, we describe in detail how PANPE works and benchmark its performance on real and synthetic reflectometry data. II. RESULTS We describe our method in Section II A. We then evaluate it on synthetic data, which encompasses a broad range of structures, in Section II B. Subsequently, we apply it to Xray reflectometry (XRR) data from online in situ experiments in Section II C. Finally, we showcase our approach for combining multiple measurements in neutron reflectometry (NR) data in Section II D. A. Overview of PANPE Bayesian framework for inverse problems. A. Overview of PANPE Reflectometry analysis aims to infer physical parameters θ from measured data R.Each parameter set θ describes a hypothetical SLD profile of the studied structure (SLD parameterization is discussed in Methods IV A). A. Overview of PANPE For a given reflectometry measurement R, the Bayesian posterior distribution [13] p(θ|R) ∝ p(R|θ)p(θ) A. Overview of PANPE offers a probabilistic estimate of θ, characterized by the likelihood p(R|θ) provided by scattering theory and a prior p(θ) provided by experimentalists. A. Overview of PANPE Importantly, the prior physical knowledge about the studied structure, formulated as a prior distribution p(θ) over parameters θ in Bayesian framework, serves as a crucial tool for resolving ambiguity in reflectometry and, more broadly, in scattering physics.It facilitates methods commonly employed for reflectometry analysis, as well as our proposed approach.The standard maximum likelihood estimation approach provides a single solution by design.MCMC locally explores the parameter space and can overlook distributional modes.In contrast, (PA)NPE posterior estimate is guaranteed to cover all the solutions, with further refinement based on likelihood evaluation improving accuracy.Our prior amortization method, PANPE, enables the analysis of multiple experimental scenarios using a single neural network.intervals.To compute them, we need to draw samples {θ i } N i=1 ∼ p(θ|R) from the posterior distribution, i.e. randomly selecting parameter sets θ i in proportion to their posterior density p(θ i |R).The complexity of this operation for high-dimensional parameters θ renders Bayesian inference a highly challenging task, traditionally limiting the applicability of the Bayesian approach to simple cases. A. Overview of PANPE Coverage and refinement of Neural Posterior Estimation.To reliably sample from the Bayesian posterior, we adopt a recent Neural Posterior Estimation (NPE) method [14,15].It employs a normalizing flow architecture [15][16][17] A key property of normalizing flows is that the exact density evaluation enables training the model by minimizing the forward Kullback-Leibler (KL) divergence (see Methods IV C ).This ensures the coverage property of NPE, i.e. it contains the full support of the true unknown posterior p(θ|R) and does not miss distributional modes [18].However, the "shape" of the NN-based density estimate might deviate from the target posterior.To address this, likelihood-based methods such as IS and MCMC can refine the NPE results for more accurate estimates.Thus, NPE ensures the coverage property, while likelihood-based refinement enhances accuracy. IV C Our custom-made GPU-accelerated transfer-matrix reflectometry simulator [19] implemented using PyTorch [20] accelerates both the training and inference stages.This allows us to simulate new curves directly during the training process without reusing simulations, thereby preventing overfitting.Furthermore, as shown in Section II B, our reflectometry analysis with importance sampling refinement -which requires likelihood evaluations -typically takes just seconds to less than a minute on a single graphics card, the NVIDIA RTX 2080 Ti. IV C Amortization across various experimental scenarios.Along with reliability due to the coverage property, NPE provides fast inference, since its computational cost is amortized by the training process.However, the amortization also introduces a key practical limitation, as a trained model can only operate within some predefined training ranges of parameters.In the case of reflectometry, this limitation not only includes the parameter ranges, but also experimental settings such as the discretization of the momentum transfer axis q or the measurement uncertainties, all of which may significantly affect the resulting posterior estimate.We address these limitations by implementing intensive amortization, taking into account the diverse varying aspects of the experiment, such as q discretization and range, measurement uncertainties, and prior information. IV C Measurements of the reflected intensity R(q) are taken at different discrete values of momentum transfer q (see Figure 1a).Together, these measurements form an input dataset R = {q p , R(q p ), s p } nq p=1 consisting of n q measured points (here s p represents the uncertainty of each data point).Our approach accommodates experiments featuring arbitrarily spaced q points and varying numbers of measurements n q , by utilizing an efficient embedding neural network equipped with trainable interpolation kernels (see Methods IV F). IV C However, in the context of reflectometry analysis, the most significant variable component is the prior information.Indeed, known constraints on physical properties vary substantially across different structures under study.Furthermore, in the online experiments discussed in Section II C, the experimentalists may modify the structure by changing control parameters -and accordingly, the respective priors.Adjustments to the priors are also necessary when combining multiple measurements in neutron reflectometry, as considered in Section II D. In these and other scenarios, the analysis must adapt to the changing prior distribution.Standard machine learning solutions like NPE, which typically assume a fixed prior distribution, fall short under these experimental conditions.To overcome this limitation, we introduce Prior-Amortized Neural Posterior Estimation (PANPE) that accommodates a variety of prior distributions within a single model. IV C Prior-Amortized Neural Posterior Estimation (PANPE).We incorporate dynamic prior information into a neural network by choosing a class of distributions p(θ|ϕ) parameterized by ϕ.The newly-introduced parameters ϕ reflect prior information about the system.They are supplied as an additional input to the flow-based neural network p NN (θ|R, ϕ) alongside the measured data.This allows us to train a single neural network and amortize inference across both measurements R and priors p(θ|ϕ): p NN (θ|R, ϕ) ≈ p(θ|R, ϕ) ∝ p(R|θ)p(θ|ϕ) . IV C ( IV C In reflectometry analysis, it is typically sufficient to employ uniform prior distributions IV C ), where n is the number of parameters θ.Thus, we define ϕ as a set of corresponding parameter ranges: ϕ = {θ min j , θ max j } n j=1 .This results in 2n = 20 additional input values for a task with n = 10 parameters θ.In this manner, the model is trained to approximate posterior distribution for a continuous set p(ϕ) of (uniform) prior distributions p(θ|ϕ) within a larger parameter space.Indeed, our approach can be extended to other classes of distributions by providing suitable parameterization.We discuss why the likelihood-based refinement (or rejection sampling in the case of uniform prior distribution) is not a practical alternative to the prior amortization in out case in Section II B. Our prior amortization approach is discussed in detail in Methods IV C. IV C We explain the inference pipeline in Methods IV F. Given the data R and the prior distribution characterized by parameters ϕ, we sample from the trained PANPE model and apply likelihood-based refinement either using importance sampling [18] (PANPE-IS) or MCMC (PANPE-MCMC). Parameter-conditioned posterior estimation. MCMC (PANPE-MCMC). In certain cases, it is required to estimate parameter-conditioned posterior estimation, where instead of providing narrow priors for a parameter, it is fixed.We show one such case in Section II D where parameterconditioned posterior estimation is necessary for combining multiple measurements with partially shared parameters. MCMC (PANPE-MCMC). Another scenario relevant for future reflectometry applications considers choosing the appropriate physical model: by setting the thicknesses of a subset of layers to zero, one can effectively change the number of layers in the physical model.Consequently, several physical models represented by different numbers of free parameters can be compared via standard criteria such as the Bayes factor p(R|ϕ 1 ) p(R|ϕ 2 ) using the same neural network.Fixing some parameters indeed changes the dimensionality of the remaining free parameters, which is not supported by standard implementations of the normalizing flow.To circumvent this limitation, we introduce a reparameterization procedure of the parameter space that enables us to sample from the parameter-conditioned posterior estimation by providing "zero-width" prior.We discuss this approach in Methods IV C and employ it in Section II D. MCMC (PANPE-MCMC). Preserved equivariances in the density estimator.The reflectometry simulator features a number of simple deterministic functional relationships between the input {q, θ} and the simulated reflectivity curve R(q, θ).We systematically review them in Methods IV B. For instance, these include the unit scaling invariance: rescaling the momentum transfer axis q → u • q (u ∈ R >0 ) together with a certain parameter rescaling transformation θ → T u (θ) does not alter the result: R(u • q, T u (θ)) = R(q, θ).Conventional reflectometry analysis does not need to consider these relationships, but they become critical in amortized machine learning solutions: the trained model must reflect these relationships, ensuring that specific changes in the input data to the density estimator result in corresponding changes in the posterior distribution.To enhance the performance of the model, we directly incorporate these relationships into the inference pipeline (see Methods IV B and IV F), rather than having the model learn them from data.We note that the prior amortization is generally required for this operation, since the considered transformations alter the prior distribution. Related work. Sequential NPE [21][22][23][24] effectively applies data-informed prior updates, but such methods require simulation and neural network training at inference time. Related work. The Simformer [25] framework enables prior updates by leveraging diffusion guidance. Related work. Equivariances between parameter and data spaces can be integrated with group-equivariant NPE [26,27], but this method requires iterative inference and is therby slower than NPE. Related work. The Dingo-BNS framework [28] for gravitational-wave inference combines adaptive priors with amortized NPE to achieve improved data compression.Our study builds on and extends upon these works, demonstrating how adaptive SBI priors enable posterior zooming into arbitrary parts of the parameter space in a high-profile science application. B. Performance on simulated data We first test our model on the test simulated dataset with a broad range of two-layer structures with 10 parameters.Performance on the X-ray reflectometry data is discussed in Section II C. For the results on neutron reflectometry (NR), refer to Section II D. B. Performance on simulated data Multiple modes in the posterior.Figure 2 showcases the inference results obtained with PANPE-IS for a curve simulated from a two-layer structure.For reflectometry, generated samples {θ i } N i=1 represent SLD profiles that could potentially produce the measured data according to the neural network.Efficiency gain from prior amortization.Figure 2(c-d) shows the inference result for the same reflectivity curve, but with narrower prior distribution, resulting in a single mode.In this case, the prior amortization allows excluding all the samples outside the domain of a more informative prior distribution. B. Performance on simulated data The necessity for prior amortization might not be immediately obvious when likelihood evaluation is fast.A viable alternative could seem to be training a standard NPE model across a wide parameter range without prior amortization and refining results via likelihoodbased methods later.For uniform priors, calculations of likelihood are not even required: B. Performance on simulated data samples outside the prior domain can be simply rejected without the need of likelihood evaluation.However, the main issue with rejection sampling is its low acceptance rate.In practice, this quantity can be exceedingly small.In our case, an acceptance rate of less than one in a million applies to about 70 % of the synthetic test data.Consequently, in order to obtain a single sample within the prior domain, an immense number of samples would need to be generated through neural network evaluations, making this approach essentially inapplicable.We also illustrate this problem on an experimental data in Section II C. Sample efficiencies on the simulated dataset. We evaluate PANPE-IS on a set of 1000 simulated test samples.These samples are generated following the same procedure as outlined for the training data in Methods IV D. Each curve has different q discretization and is accompanied by its own prior distribution p(θ|ϕ). Sample efficiencies on the simulated dataset. We assess the performance of the model on each test sample by evaluating its sample efficiency ϵ eff : Sample efficiencies on the simulated dataset. , where w i are the importance weights.In practice, during inference, importance weights can be employed for Monte Carlo estimates Sample efficiencies on the simulated dataset. The sample efficiency ϵ eff effectively quantifies the efficient sample size ESS = N • ϵ eff as a share of the total number of samples and, therefore, determines the time required for obtaining a desired ESS.By using our efficient reflectometry simulator, we are able to obtain ESS = 100 for ϵ eff = 10 −4 for less than a minute, but the same ESS would take more than a month for ϵ eff = 10 −10 . Sample efficiencies on the simulated dataset. Each test sample is characterized by its prior distribution, which results in different complexity of the inference task: wider prior distributions that simulate the cases of higher uncertainty about the studied structure are generally more complex to analyse using conventional methods.We quantify this complexity through the sample efficiency of the con-ventional importance sampling (IS) method with prior acting as a proposal distribution.In this case, it replaces the "neural" proposal distribution in the Equation 3, and the respective importance weights simply equal to the likelihood w IS i = p(R|θ i ), where θ i ∼ p(θ|ϕ).We discuss how we estimate low sample efficiencies for IS in Methods IV G. Evaluating PANPE performance without refinement. Sample efficiencies on the simulated dataset. Additionally, we evaluate the performance of raw PANPE estimates without likelihood-based refinement.Specifically, we evaluate the quality of marginal distributions, i.e. one-dimensional distributions p NN (θ j |R, ϕ) for each jth parameter.For that, we perform standard Kolmogorov-Smirnov tests that employ the "true" parameters θ used for simulating the test data [26].These tests determine whether the true parameters could realistically be sampled from PANPEgenerated marginal distributions by checking if their percentile scores are uniformly distributed.SM Figure 1 shows the p-p plots, and the obtained p-values demonstrate satisfactory performance on simulated data.These findings imply that one can rely on raw PANPE estimates derived from marginal distributions like means and variances for analysis.However, in the context of reflectometry, we always apply likelihood-based refinement as it is cost-effective, and importantly, enhances the accuracy of our estimates while also providing a means to evaluate their quality. C. Performance on experimental XRR data In this Section, we evaluate the performance of PANPE-IS on the largest publicly available reflectometry dataset [29] that has been previously employed for evaluating the performance of ML-based regression models [30][31][32]. Experimental data. As experimental XRR data, we utilize 208 curves, accompanied by a manual analysis using a conventional fitting procedure via maximum likelihood estimation.This data originates from three online in situ experiments conducted at different synchrotron facilities.Each experiment recorded in real time a process of growing an organic layer, specifically diindenoperylene (DIP), on a silicon substrate.DIP, an organic semiconductor, has gained interest due to its prospective uses in the field of electronics and photovoltaics [33].Real-time XRR measurements can provide insights into growth processes of such thin films.Furthermore, this type of experiment can indeed benefit from rapid analysis.In this way, a machine learning-based solution was recently deployed for the first closed-loop XRR experiment [34].However, the ambiguity problem presented limitations to the regression-based model, rendering our probabilistic method a potential successor in such closed-loop systems (see SM Figure 6).to conventional manual fits performed via differential evolution reported in [29].SM Figure 4 shows time-dependent sample efficiencies and the log evidence estimations for both methods.simulated curves that correspond to the maximum likelihood from both the narrow and wide prior distributions.While both fits are satisfactory, the unphysical solution (in red) has a likelihood that is more than 10 6 times greater than its physical counterpart due to larger residuals (c).In this case, when trained solely with a wide prior distribution, the NPE network mainly samples unphysical solutions, which appear much more probable without the physics-informed prior.The use of prior amortization addresses this issue. Experimental data. For each experimental curve, we set uniform priors based on a physical understanding of the experiment, aligning with conventional analysis.The parameters of the known silicon substrate and the oxide layer are essentially fixed by designating narrow ranges.In contrast, the parameters for the thickness d 1 , roughness σ 1 , and density ρ 1 of the growing organic layer have broader prior ranges due to uncertainty.Furthermore, as the film thickness d 1 increases, its ranges are set to increase linearly with time, in line with the anticipated growth rate. Experimental data. Although the physical model contains 10 parameters, in this case, the physics-informed prior information about the structure allows us to effectively constrain most of the parameters. Experimental data. Nonetheless, prior amortization allows us to use the same PANPE model that was applied to simulated data featuring two-layer structures. Experimental data. We also note that the datasets under consideration feature different q ranges and resolutions.Nevertheless, a single model can process them due to the prior amortization that exploits the scaling invariance of the reflectometry data, as well as due to the amortized discretization of our model. Experimental data. Comparison with conventional data analysis. Experimental data. The defined prior distributions are narrow enough to enable conventional importance sampling for validation purposes.Despite the relative simplicity of the dataset due to a small number of free parameters, the resulting distributions feature two solution branches for the density parameter ρ 1 visible in Figure 4 (see also SM Figure 3).The upper branches vanish beyond a certain time for each dataset, suggesting that the correct solution corresponds to the lower branches.Conventional fits, indicated by purple dots in Figure 4(b), deviate from the maximum likelihood, underscoring the relevance of probabilistic methods even in such straightforward cases.Therefore, the axis for IS sample efficiency in Figure 3 can be approximately divided into ranges: ϵ IS eff > 10 −3 for "zero-layer" structures, ϵ IS eff ∈ [10 −6 , 10 −3 ] for "one-layer" structures that constitute the rest of the experimental curves, and ϵ IS eff < 10 −6 for more complex, simulated two-layer structures.The respective estimated inference time axis in Figure 3 suggests that pure conventional likelihood-based methods become largely impractical for two-layer structures.On the other hand, PANPE-IS delivers accurate and reliable solutions in under a minute for most of these cases.SM Figure 5 displays the inference results for a simulated four-layer structure with 16 parameters, revealing a highly ambiguous outcome (the result is obtained via PANPE-IS using an additional model trained on four-layer structures).This example underscores the increasing complexity and ambiguity in reflectometry analysis as the number of free parameters grows.To maintain the high sample efficiency of PANPE in these more challenging scenarios, it is necessary to enhance the capacity of the density estimator.This enhancement could be achieved not only by enlarging the size of the neural network, but also through the use of more sophisticated density estimators, such as continuous normalizing flows [35][36][37], Experimental data. without necessitating significant changes to the overall framework presented in this paper. Experimental data. Improving performance for more complex scenarios may also involve customizing the hyperprior distribution and other solution aspects, such as q discretization, to better suit the specific application and experimental conditions. Role of physics-informed priors. Figure 5 illustrates the essential role of prior amortization in the analysis of the presented experimental data.Without providing the physics-informed prior distribution to the neural network, the resulting samples span all possible solutions (represented by the red SLD profiles in Figure 5a) within the expansive prior distribution that covers the complete training range.Yet, all of these solutions are unphysical, due to factors such as a too thick oxide layer.The physical solution, depicted by the blue SLD profiles, is practically unattainable without prior amortization given that the share of samples within the corresponding narrow prior is less than 10 −6 .This scenario emphasizes once more the essential role of incorporating additional physical information into inverse scattering problems with missing phase. Role of physics-informed priors. Adaptive q discretization.The ability of our model to support arbitrary q discretization significantly broadens its applicability.In this way, the number of q points in the analyzed X-ray data ranges from 25 to 52, yet it is processed by the same model.We note that an alternative approach involving interpolation to conform to a fixed q axis can generally lead to missed solutions.For instance, if a model trained on 52 q points is subsequently tested on experimental data comprising only 25 q points, interpolating these data to 52 points could create a falsely narrow distribution.This occurs because the interpolation process artificially adds "information" that the original experimental data does not possess, compromising the guarantee of the coverage property. Role of physics-informed priors. SM Figure 6 demonstrates another relevant experimental scenario that requires adap-tive q discretization: while performing an X-ray reflectometry measurement by sequentially measuring intensities at distinct points, one can use the model to analyze the data at any particular moment.This analysis can inform whether additional data are needed to reduce uncertainty and can even guide the selection of the next most informative q point to measure.Obtaining such points is straightforward using reflectometry curves simulated using parameters sampled via PANPE-IS. D. Combination of multiple neutron reflectometry measurements In this Section, we demonstrate that PANPE can be successfully employed for the simultaneous analysis of several combined neutron reflectometry datasets, which is an indispensable tool in the context of contrast variation (e.g. using different levels of deuteration [38,39]). D. Combination of multiple neutron reflectometry measurements Co-refinement of neutron data.A common method to resolve ambiguity involves combining measurements taken under controlled variation of experimental conditions.In the context of reflectometry, such conditions can be determined by the different energies of the X-ray beam (i.e.anomalous scattering near an absorption edge), polarizations of neutrons for magnetic materials, or by employing different contrasts via changing materials adjacent to the sample. D. Combination of multiple neutron reflectometry measurements We demonstrate this co-refinement procedure using publicly available neutron data [40]. D. Combination of multiple neutron reflectometry measurements Specifically The reparameterization operation that we introduce as a part of our prior-amortized approach offers a means to approximate such conditional probability densities with the same model by setting very narrow priors, essentially fixing the required parameters.However, this approach provides only samples and not density evaluation required for importance sampling refinement (see Methods IV C).Therefore, we use PANPE-MCMC for likelihood refinement of the combined posterior in this case. D. Combination of multiple neutron reflectometry measurements Inference results for combined measurements.c-d).The single measurement yields two distinct solutions (Figure 6a), one of which is (implicitly) ruled out when performing a co-refinement of two measurements (Figure 6c), thereby resolving ambiguity in data interpretation.Non-zero ambient density is processed as discussed in Methods IV B. D. Combination of multiple neutron reflectometry measurements In the case of the neutron data analyzed in this work, the parameters unique for each measurement θ unique include scaling misalignment, background, and densities of contrasts. D. Combination of multiple neutron reflectometry measurements The shared parameters correspond to the constant parameters (i.e.those that do not change in-between these measurements) of the system under study, such as thicknesses, roughnesses, and densities of Si and SiO 2 .Notably, following the parameterization described in the refnx package, we account for the volume fraction v solv ∈ (0, 1) of the solvent that modifies the SLD of the polymer layer according to ρ = (1 − v solv )ρ polymer + v solv ρ solv .We regard these densities ρ as parameters unique to each measurement, utilizing them to compute v solv and ρ polymer .The mixture of solvent with polymer results in a small difference of polymer SLDs for measurements with different contrasts in Figure 6. D. Combination of multiple neutron reflectometry measurements It is worth noting that in certain cases of application-specific parameterization on an SLD profile, it might be more practical to retrain the model using a more suitable parameterization, but it is not necessary in this case.In general, the demonstrated approach can be equally well applied to other cases of parameter co-refinement such as polarized neutron reflectometry, XRR measurements with different energies, or other similar applications that require combining several measurements. III. DISCUSSION In reconstructing physical systems from scattered intensities, the phase problem poses a fundamental challenge.This problem is encountered in numerous scattering techniques, including X-ray and neutron reflectometry.The prevailing standard in reflectometry analysis is maximum likelihood estimation, which uses a differential evolution-based search over the parameter space.This method, by design, produces a single system reconstruction, even when multiple solutions exist due to phase loss, making it inherently unreliable.In contrast, Bayesian inference provides a foundational pathway to a more reliable analysis by inherently accounting for all possible solutions as a distribution over the considered physical parameters. III. DISCUSSION However, despite its conceptual advantages, conventional likelihood-based Bayesian methods struggle with high-dimensional parameter spaces and multimodality, often falling short in real-world experimental contexts.This underscores the pressing need for more efficient and reliable Bayesian methods in reflectometry analysis. III. DISCUSSION In this work, we present a new approach that enables reliable, accurate, and fast Bayesian reflectometry analysis.The high inference speed essential for various experimental contexts is achieved via neural network-based amortization.The training strategy reliably provides an approximate posterior distribution that fully covers the true posterior, while likelihoodbased inference is subsequently employed to obtain the accurate distribution. III. DISCUSSION Importantly, our method enables reliable reflectometry experiments: it can guide experimentalists by indicating whether the remaining ambiguity requires additional measurements, thereby directing the experiment until the singular physical solution is determined.Furthermore, preparing experiments in advance by investigating ambiguities in simulated settings becomes possible. III. DISCUSSION Prior amortization crucially broadens the applicability of NPE to multiple experimental settings.In the context of reflectometry, constraining the parameter space based on individual characteristics of a studied structure is essential to resolve ambiguity.As shown, prior amortization allows to infer a physical solution that can feature a million times smaller likelihood and filter out an unphysical solution that is yet legitimate in other experimental settings or for other systems.This, in particular, underscores the importance of prior amortization when applying simulation-based inference methods to scattering problems with phase loss. III. DISCUSSION Complex parameterizations of prior distributions can be used and should be investigated in future research aiming at adapting PANPE to specific applications. III. DISCUSSION Real-world benchmarks are valuable for the developing field of simulation-based inference.In this context, reflectometry analysis offers a notable benchmark, characterized by challenging multimodal distributions and bolstered by an efficient simulator.Importantly, it can be straightforwardly scaled up by increasing the number of layers in the physical model. III. DISCUSSION Simulation-based inference is often seen as advantageous for applications where likelihood is costly or intractable to evaluate.Reflectometry does not fit into this category and it exemplifies the broader utility of SBI methods beyond intractable likelihoods due to the coverage property and acceleration of inference through amortization.Moreover, the combination of SBI with likelihood-based methods presents as the optimal way to both preserve the coverage and achieve high accuracy. III. DISCUSSION Prior amortization can be beneficial for multiple applications, especially in experimental science like scattering where various experimental scenarios require adaptive prior distributions.In this manner, our method is suitable for a wide range of scientific experiments that permit simulation-based inference. A. Parameterization of the SLD profile We consider the standard parameterization of the SLD profile of a layered structure with n l layers through parameters θ = {d, ρ, σ, ∆R, ∆q, log 10 (R 0 )}, and we primarily consider two-layer structures n l = 2.Here d = {d 1 , d 2 } are layer thicknesses in the top-bottom order, ρ = {ρ 1 , ρ 2 , ρ sub } are densities of two layers and the substrate, and σ = {σ 1 , σ 2 , σ sub } are roughnesses of three interfaces modeled via Névot-Croce factors.We exclude absorption in this work due to our focus on organic materials, but it can be straightforwardly included into our framework.Additionally, we consider standard misalignment parameters: normalization misalignment ∆R and systematic misalignent of the q axis ∆q.We only consider the parameter for scattering background log 10 (R 0 ) for neutron data (see Section II D), which results in 11 parameters.Consequently, the model for X-ray data has 10 free parameters. B. Equivariant transformations in reflectometry Reflectometry features several equivariant transformations that can be considered to improve the performance of an amortized machine learning solution.In this section, we discuss these transformations and how we incorporate them into our PANPE model. B. Equivariant transformations in reflectometry Unit-based scaling equivariance.Reflectometry simulation R(q, θ) = R(q, d, σ, ρ) features an invariant scaling transformation that represents the change in employed parameter units u: B. Equivariant transformations in reflectometry where B. Equivariant transformations in reflectometry and u ∈ R >0 is a positive value that defines the employed units.The standard units are inverse Angstroms ( Å−1 ) for q values, Angstroms ( Å) for layer thicknesses d and roughnesses σ, and inverse squared Angstroms ( Å−2 ) for (scattering length) densities ρ.If we set u = 1 for these standard units, for instance, the transformation with u = 10 would correspond to the change of units from Angstroms to nanometers, which does not alter the resulting reflectivity curve.Similarly, u = 2 doubles the q range, halves thicknesses and roughnesses, and increases densities by a factor of u 2 = 4, leaving the reflectivity curve unchanged. B. Equivariant transformations in reflectometry This invariance of the reflectometry simulator leads to the equivariance of the density estimator under the joint unit transformation of input and parameters.Specifically, stretching or squeezing the q axis in the input data and adjusting the input prior parameters ϕ accordingly should result in respective transformations of the parameters θ as per Equation 4. We note that the transformation of prior distribution is commonly required in order to preserve equivariance in the density estimator.Applying this transformation indeed requires prior amortization. B. Equivariant transformations in reflectometry To incorporate this equivariance into our model, we can standardize the "pose" of the data [27] (the terminology is adopted from computer vision) to simplify the problem for the neural network.We do so by fixing the q range, on which our model is trained.During inference, we first preprocess the data by applying the transformation from Equation 4 so that the measured q range matches the standard one.The corresponding scaling factor is the ratio of two ranges u = q max /q exp .We use this scaling factor to apply the respective transformation on the prior parameters ϕ.After obtaining samples from the PANPE model, we rescale the parameters back using u −1 .Respectively, the probability densities are corrected by a constant Jacobian determinant of the transformation, which equals u −2 in our case. B. Equivariant transformations in reflectometry We note that this property should also be taken into account when considering parameter ranges for training.For instance, some unreasonably large parameter ranges that might seem unphysical, such as density values that do not correspond to any known materials, can be practically justified since they correspond to smaller densities when scaling the q axis.This relation is illustrated in SM Figure 8. B. Equivariant transformations in reflectometry Density shifting equivariance.Reflectometry is sensitive to density contrasts rather than absolute density values.As a result, shifting all the densities ρ (SLDs) in the system, including the ambient and the substrate, is an invariant operation that does not change the resulting reflectivity curve.In the context of the density estimator, this leads to the equivariant operation: shifting the respective prior parameters ϕ should result in the shift of the parameters θ (specifically, layer densities ρ). B. Equivariant transformations in reflectometry We employ this property by defining a natural standard pose in a form of the zero ambient density, on which the model is trained.During inference, the data with nonzero ambient density is first preprocessed by shifting the densities (i.e., the respective prior parameters) so that the ambient density becomes zero.We apply this transformation for neutron reflectometry in section II D. The Jacobian determinant of this transformation equals to 1. Misalignment shifting equivariances. The misalignment parameter ∆R results from the incorrect normalization when calculating reflected intensities as per R(q, θ) • (1 + ∆R), which effectively shifts the reflectometry curve in the "vertical" direction in the log space, resulting in an equivariant shifting transformation.A natural "standard pose" in this case corresponds to ∆R = 0. We note that in this case the standard pose depends on the (unknown) parameter ∆R rather than the data and cannot be performed as a onestep preprocessing.This scenario is similar to the one considered previously [27], where an iterative inference scheme is proposed that allows converging to the standard pose.In our case, the range of the misalignment parameter is already very limited, making a direct application of the iterative scheme impractical.Our preliminary tests suggest that this does not lead to improved performance, so we do not utilize this equivariance in our solution. Misalignment shifting equivariances. The same applies to the other misalignment parameter ∆q. C. PANPE training We amortize Bayesian inference for a class of prior distributions p(θ|ϕ), parameterized by ϕ.To specify the range of priors for which the model is trained, we introduce the hyperprior distribution -a distribution over prior parameters p(ϕ), that generally depends on the range of anticipated applications and can reflect various physical and practical parameter constraints.We set it to cover a broad range of practical scenarios where some of the parameters are known better (with lower uncertainty) than others. C. PANPE training The training process of the PANPE model involves adjusting the trainable parameters, denoted as w, of the neural network to minimize a forward Kullback-Leibler (KL) divergence between the true posterior distribution p(θ|ϕ) and the flow-based density estimator p w (θ|ϕ): C. PANPE training The loss in Equation 6 is approximated by the Monte Carlo estimation: C. PANPE training where the constant does not depend on the model parameters w.Evaluating Equation 7requires evaluating log density log(p w (θ i |R i , ϕ i )) and drawing samples {ϕ i , θ i , R i } N i from the training distribution p(ϕ, θ, R) ∝ p(R|θ)p(θ|ϕ)p(ϕ). C. PANPE training Exact density evaluation, and consequently the utilization of the forward KL divergence, is facilitated by normalizing flows, distinguishing them from many variational architectures. C. PANPE training The forward KL divergence is a mass-covering loss, meaning that the optimized density density covers the whole support of the target distribution (otherwise the loss diverges), thereby ensuring no distributional modes are missed in the posterior estimation.Hence, although the training scheme of PANPE is independent of the specific architecture of the density estimator, the selection of normalizing flows as the density estimator and the corresponding loss function is crucial for the method's reliability.It is also noteworthy that some other recent density estimators exhibit the mass-covering property and can thus be integrated into the PANPE framework for future reflectometry applications. C. PANPE training Sampling from the training distribution can be performed in two principled ways.The first one is employed in this paper and it goes as follows: C. PANPE training 1. First, the prior parameters are sampled from the hyperprior distribution (ϕ i ∼ p(ϕ)) defining the corresponding prior p(θ|ϕ i ). C. PANPE training 2. Then, the parameter θ i is sampled from this specific prior distribution, θ i ∼ p(θ|ϕ i ). C. PANPE training 3. Finally, the corresponding reflectometry curve, R i ∼ p(R|θ i ), is sampled from the likelihood. C. PANPE training We note that a similar training scheme, involving sampling from a hyperparameter distribution, has been previously employed in group-equivariant neural posterior estimation (GNPE) [27]. C. PANPE training The second possible way of sampling from the training distribution relies on the relation p(ϕ)p(θ|ϕ) = p(ϕ|θ)p(θ).Therefore, instead of first sampling prior parameters ϕ and then parameters θ, this order can be reversed to sample (potentially, multiple sets of) prior parameters ϕ that correspond to the same parameters θ, hence the same simulations.The gain in this case comes from the opportunity to re-use the same simulations by coupling them with different priors and potentially reduce the required number of simulations, which is critical for certain applications.Since this is not applicable to reflectometry, we do not investigate this method any further.We only note that its implementation would involve additional Bayesian inference p(ϕ|θ) ∝ p(ϕ)p(θ|ϕ), the complexity of which depends on the chosen prior parameterization p(θ|ϕ).For instance, in the case of the parameterization employed in our work, the inference can even be performed analytically (via inverse transform sampling). C. PANPE training As an optional improvement of our method, we introduce a reparameterization transformation θ = T ϕ (θ) of the parameters θ to effectively "rescale" the parameters according to the respective prior.The reparameterization is chosen to ensure that the prior for the rescaled parameters p( θ) does not depend on the prior parameters ϕ.The flow-based model then is trained to perform inference on these rescaled parameters: C. PANPE training This reparameterization effectively re-frames the problem as a standard Neural Posterior Estimation, only now the likelihood depends on both the parameters θ and the prior parameters ϕ.By doing so, we can now apply narrow priors without running into numerical issues.This approach accelerates the training process and decreases the number of samples generated outside the prior support. C. PANPE training Importantly, when setting the prior width of some parameter θ j to zero, we effectively fix it.The respective parameter θj estimated by the model does not influence the likelihood and is essentially trained to match the reparameterized prior distribution (uniform in our case).Consequently, the connection between the reparameterized space θ and the parameter space θ becomes surjective.To sample from the lower-dimensional distribution conditioned on the fixed parameter θ j , we need to marginalize over the parameter θj in the reparameterized space.It is not directly possible to evaluate density of a marginalized distribution in normalizing flows.We note that in the ideal scenario when the parameter θj is uniformly distributed, density evaluation becomes straightforward.Our tests suggest that marginal distributions p( θj ) can deviate from a uniform distribution in practice.However, sampling from a distribution marginalized over θj is straightforward as it simply requires omitting the marginalized parameters.In this way, our reparameterization scheme enables us to sample from the parameter-conditioned posterior estimation. D. Trained models and parameter ranges Trained models. D. Trained models and parameter ranges We present the main results for X-ray (XRR) and neutron (NR) reflectometry.Due to certain differences in the underlying physics and subsequent differences in the simulator, we have trained two PANPE models: one for XRR and another for NR.The results on the simulated data are presented for the XRR model.Most properties are shared between these models, except for the ranges of density parameters used (the scattering length density (SLD) for neutrons can be negative), the instrumental resolution (more pronounced in NR), and the presence of strong constant background scattering.Although we focus on these two models in the paper, we also show some examples from other models, such as those with four-layer structures. D. Trained models and parameter ranges Parameter ranges.The training parameters are constrained by the predefined ranges. D. Trained models and parameter ranges In this paper, we employ the following ranges shared by all the layers.Densities range within We note that due to the equivariant transformations discussed in Methods IV B, during inference the model can also operate outside these parameter ranges.This also means that one can set rather unphysical training ranges, such as large roughness or density, to cover certain realistic scenarios at different q ranges and ambient densities. D. Trained models and parameter ranges Hyperprior distribution. D. Trained models and parameter ranges During training, the parameters ϕ = {θ min j , θ max j } n j=1 are generated as follows.First, for each parameter θ j , the width of the uniform prior ∆θ j = θ max j − θ min j is sampled, which generally can range from 0 to the the total parameter ranges introduced above.In this paper, we use the weighted sum of the uniform and the truncated exponential distribution for sampling prior widths.The latter term is added to better represent narrow prior widths corresponding to higher certainty in the prior knowledge. D. Trained models and parameter ranges Then, the "center" of a prior c j = (θ max j + θ min j )/2 is sampled uniformly within the allowed range.The parameters ϕ are then calculated from ∆θ j and c j .Finally, the upper bounds for interface roughnesses are rescaled to not exceed half the maximum thickness of adjacent layers [32].This overall sampling scheme effectively defines the hyperprior distribution p(ϕ). D. Trained models and parameter ranges The test simulated data was produced using the same sampling procedure as the training data.However, some of the curves (less than 5%) were manually excluded from the test dataset since they exhibited pathological properties such as nearly zero contrast between the layers.This scenario essentially reduces the number of physical layers in the studied structure and results in exact linear correlation between thicknesses of these layers.The proper way to reduce the number of layers in PANPE would be by setting the thicknesses of redundant layers to zero. E. Data simulations During training, we simulate reflectometry data using the training parameters θ i sampled as per Methods IV D. Each reflectometry simulation R i ∼ p(R|θ i ), R = {q p , R(q p ), s p } nq p=1 is performed in several steps discussed below.Q discretization.First, q values are sampled uniformly from the range q p ∼ U (0, q max ) to enable arbitrary discretization.As discussed in Methods IV B, the q range corresponding to the "standard pose" is set equal to q max = 0.15 Å−1 .However, we can vary this during inference by exploiting the unit-scaling equivariant transformation.The number of points n q is also sampled uniformly n q ∼ U (20, 64).In practice, it is implemented by masking out some of the input data from the model during training. E. Data simulations Amortized discretization is generally necessary because the posterior can be highly sensitive to it in reflectometry applications.Our tests show that by fixing the q discretization during training, we are able to considerably improve the model performance on the simulated data.However, different discretization of the experimental data necessitates interpolation procedure, that can deteriorate the performance of the model and generally lifts the massprobability coverage guarantees, especially for experimental data with the lower number of points. E. Data simulations Furthermore, amortized discretization is especially important in online XRR experiments, where time limitations constrain the number of measured q points.It in principle enables closed-loop AI-guided measurements that enable choosing the most informative q point to measure given the current data to speed up the overall process and be able to real-time phenomena with higher time resolution. E. Data simulations Nevertheless, fixing discretization might be beneficial for applications with more standardized experimental setup.Furthermore, we acknowledge possible ways to improve q simulations for neutron data to better reflect the physical nature of the process and possibly even tailor it for the use at certain neutron sources. Measurement uncertainty. Next, we generate relative measurement uncertainties s p ∼ U (5%, 30%), independently for each q point.We treat these uncertainties as error bars that correspond to standard errors typically employed in reflectometry analysis.As a noise model, we employ the normal distribution as a common approximation of Poisson counting statistics for a high number of counts.We note that generally the use of the Poisson likelihood should be preferred in the case of low counts, which are especially frequent in neutron reflectometry.However, that requires reporting raw intensities, which are typically not included in the published data. Measurement uncertainty. Reflectivity curves.Finally, we simulate reflectivity curves, using the generated parameters θ = {d, σ, ρ, ∆q, ∆R, log 10 (R 0 )}, q points and measurement uncertainties s.We simulate curves in mini-batches using our parallelized GPU-accelerated PyTorch implementation of Abelès transfer-matrix method [19]: Measurement uncertainty. varying sizes.Our tests suggest that for a fixed discretization, convolutional neural networks (CNN) provide the best performance on reflectometry data among different architectures. Measurement uncertainty. To this end, for arbitrary discretization, we implement a trainable neural kernel, which acts as an intermediary step, adapting the data before it reaches the CNN.The kernel is a neural network K(q k , q, R q , s q ) that "interpolates" reflectivity levels and the measurement uncertainties to a set of predefined points {q k } n k k=1 .We utilize three such kernels, featuring 16, 32, and 64 equidistant points, respectively.The spacing between these points defines the kernel's "window".The kernel outputs are averaged for q points falling within this window. Measurement uncertainty. Each kernel is a multilayer perceptron with GELU activation functions and 4-channel input, a hidden layer with 32 channels, and a 2-channel output layer.Each of three kernels is coupled with a convolutional network discussed below.We note that this architecture is not supposed to be discretization-invariant, as the posterior can be highly sensitive to the choice of q points in reflectometry. Measurement uncertainty. Each CNN is a sequence of 5 blocks, each block containing a 1D convolutional layer, followed by a batch-normalization layer and a GELU activation function.Convolutional layers features a kernel of size 3, stride= 2, and padding= 1.Consequently, the dimension of the processed data is (approximately) halved after each layer.The number of channels is doubled in each block, starting from 32 up to 512. Measurement uncertainty. Outputs from three CNNs are concatenated with the preprocessed parameters ϕ and provided to a multilayer perceptron.The final 256-dimensional latent representation of the input is supplied to the flow-based model. Flow-based model. A normalizing flow [16] employs a series of reversible and differentiable transformations on a simple, base distribution (in our case, the standard normal distribution).This approach generates a complex distribution from which samples can be efficiently drawn and evaluated.In this work, we employ a series of 40 transformations, each transformation block being a composition of a coupling layer with monotonic rationalquadratic splines [17] and a batch normalization layer [41].After each transformation block, the parameters are randomly permuted. Flow-based model. Refinement by likelihood-based methods. Flow-based model. During the inference, we sample parameters θ i ∼ p NN (θ|R) and generate parameters in batches with the corresponding log probabilities.The obtained curves are used for calculating importance sampling weights (PANPE-IS) and streaming estimation of sample efficiency ϵ eff .We continue this procedure until the effective sample size ESS = N • ϵ eff reaches an adequate threshold which we set equal to 500.The same criterion is employed for the traditional importance sampling, where the prior distribution p(θ|ϕ) is used as the proposal distribution. Flow-based model. Alternatively, samples generated by PANPE are used as efficient initialization points for MCMC (PANPE-MCMC).In our work, we introduce GPU-accelerated PyTorch-based implementations of several Affine Invariant MCMC algorithms [42][43][44] enabling near realtime MCMC-based refinement operation. G. Low sample efficiency estimation We consider two approaches for estimating sample efficiency for the conventional importance sampling method with prior acting as a proposal distribution.The first approach is the use of importance sampling weights via direct sampling from the prior distribution p(θ): G. Low sample efficiency estimation where w IS i = p(R|θ i ), θ i ∼ p(θ), and ⟨•⟩ is the average operation over all samples i.An accurate estimation requires N = ESS/ϵ eff samples, e.g.sample efficiency ϵ eff = 10 −12 requires more than 10 12 samples, which is computationally unfeasible.An insufficient number of samples N only provides an upper bound ϵ eff < 1/N .Therefore, it can only be employed in practice for sufficiently high sample efficiencies. G. Low sample efficiency estimation The alternative approach employs the analytical form [45]: G. Low sample efficiency estimation p(θ|R) p(θ) G. Low sample efficiency estimation In the case of the uniform prior distribution p(θ), the equation simplifies to (see the orange and green simulated curves in (a)).This approach can reduce the total number of required q points and speed up the measurements. G. Low sample efficiency estimation importance sampling (ϵ IS as per Equation 6) and via our model (ϵ * IS as per Equation 10) calculated for simulated samples with sufficiently high efficiency ϵ IS .FIG. 8. Scaling invariance of the SLD parameters and momentum transfer q.A model trained with a fixed q range q max = 0.2 Å−1 (blue dashed lines) can be then applied to the measured data with a different q range, but the total parameter ranges are scaled accordingly.The red dashed lines demonstrate this scaling effect for q max = 0.1 Å−1 .The colored areas denote the ranges within which the trained model can be applied. FIG. 1 . FIG. 1. Reflectometry analysis.(a) A schematic experimental setup for reflectometry measurements.The reflected intensity R(q) from a studied layered structure as a function of momentum transfer q contains information about parameters θ of the studied sample.The momentum transfer is typically controlled by the geometry in X-ray reflectometry or by the energy in time-of-flight neutron measurements.(b) Inverse problem in reflectometry: the forward simulations provided by the scattering theory should be inverted during inference, which is generally ambiguous.(c) Inference FIG. 2 . FIG. 2. Multimodal posterior distribution obtained by PANPE-IS on a simulated reflectivity curve with 10 free parameters for a two-layer structure.The neural network produces results in accordance with the provided prior information, identifying (a) multiple solutions for a "wide" prior distribution and (c) a single distributional mode for a "narrow" prior (gray dashed lines).Colors denote distinct distributional modes obtained by clustering samples.The corresponding reflectivity curves (b) and (d) enable real-time likelihood-based refinement, resulting in accurate posterior estimation.The corner plot (e) shows the resulting marginalized 4d distributions obtained for both priors along with the colored samples related to the colored profiles in (a). FIG. 2 . represents the "true" structure used to simulate the reflectometry curve.The forward reflectometry simulations enable immediate visual validation of the result.In Figure2(a) the studied blue reflectometry curve is superimposed with the colored curves simulated from the NN-produced SLD profiles.The colored reflectometry curves are mostly invisible since they overlap very well with the original curve and each other, despite a diverse variety of corresponding SLD profiles.Figure2(e) provides an alternative visualization of samples and the estimated posterior on a corner plot.For visual purposes, only 4 out of 10 parameters are shown here. FIG. 3 . FIG. 3. Sample efficiencies for conventional importance sampling (left) and our PANPE-IS model (right) on a test dataset of 1000 simulated curves (blue) and a experimental dataset of 208 X-ray reflectometry curves (orange).An additional axis on the right-hand side indicates the estimated time it takes to generate 100 effective samples (ESS) on our hardware with the efficient GPUaccelerated reflectometry simulator (see text).Both the simulated and experimental data consist of two-layered structures with 10 parameters, but in the experimental data, only the top layer is unknown, as the parameters of the silicon substrate and the silicon oxide layer are largely constrained through their respective priors. Figure 3 Figure 3 shows sample efficiency distribution of conventional IS on the left-hand side and our PANPE-IS on the right hand side, with lines in the middle connecting the same test samples and indicating the difference in sample efficiency between the two methods.Blue color corresponds to the synthetic test dataset (we discuss the experimental data in the next Section).The axis on the right shows an average time required to obtain ESS = 100 for different sample efficiencies on a single graphics card, NVIDIA GeForce RTX 2080 Ti, with our GPU-accelerated reflectometry simulator.It shows that our PANPE model can perform inference in under a minute where the conventional IS approach would require days and even months of computation. FIG. 4 . FIG. 4. Marginal distributions of the thickness d 1 , roughness σ 1 , and density ρ 1 of the diindenoperylene (DIP) layer growing on a silicon substrate for three in situ experimental XRR datasets obtained by our model (on the left) and via conventional importance sampling from prior distribution (on the right).The colors designate normalized probability densities.Purple dots correspond FIG. 5 . FIG. 5. Experimental XRR curve analyzed using both a wide prior distribution that encompasses the entire training range (shown in red) and a narrow, physics-informed prior distribution (shown in blue).(a) SLD profiles associated with the PANPE-IS samples.Profiles with the highest likelihood are highlighted with bold lines.(b) The observed reflectivity curve (in gray) is compared with Figure 4 Figure 4 displays the time-dependent marginal distributions for three parameters obtained by both our PANPE-IS model (on the left) and the conventional importance sampling (IS) method (on the right), showing equivalent solutions.SM Figure 2 demonstrates a corner plot with posterior estimates obtained for an experimental curve using PANPE, PANPE-IS, and PANPE-MCMC, where two refinement methods lead to equivalent distributions. Figure 3 ( Figure3(orange color) demonstrates sample efficiencies on the experimental data for the conventional IS and our PANPE solution.Notably, in the case where most parameters are effectively known and constrained, conventional IS can be a practical solution, unless a realtime analysis is required.For most of the considered experimental data, our model performs the analysis in under a second, where IS may require tens of minutes per sample.Several curves where IS is almost as efficient as PANPE-IS correspond to the beginning of the growth process, when there is essentially still no organic layer, and the other parameters are known. FIG. 6 . FIG. 6. Co-refinement of two neutron reflectometry measurements of a polymer on a silicon substrate using H 2 O and D 2 O contrasts, conducted via PANPE-MCMC.(a-b) An analysis of a single measurement with H 2 O contrast (b) yields two distinct solutions and their corresponding SLD profiles (a).(c-d) Co-refinement of the measurements using H 2 O contrast (blue) and D 2 O contrast (orange) resolves ambiguity by eliminating one of the solutions.Data and priors are sourced from the refnx package [40].The combination of several measurements is enabled in this case by the use of parameter-conditioned posterior estimation. Figure 6 demonstrates the results of the PANPE-MCMC analysis of a single neutron reflectivity curve measured with H 2 O contrast (a-b), as well as the joint analysis of two measurements incorporating both H 2 O and D 2 O contrasts ( [ 0 , 60•10 −6 Å−2 ] for the XRR model and ρ ∈ [−20•10 −6 Å−2 , 60•10 −6 Å−2 ] for the NR model.Thicknesses and roughnesses range within [0, 500 Å] and [0, 50 Å], respectively.Additionally, we limit the maximum roughness of the interface by the half thickness of the thickest adjacent layer.For the misalignment parameters, the ranges are [−2 • 10 −3 Å−1 , 2 • 10 −3 Å−1 ] for ∆q and [−5%, 5%] for ∆I.Additionally, for the NR model, we introduce the (log) background parameter log 10 (R 0 ), R 0 ∈ [10 −9 , 10 −4 ], which is set to 10 −10 for XRR. 1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 . FIG. 2. PANPE results on a measured XRR.The marginalized corner plot of 10-dimensional posterior distribution shows probability-mass covering proposal distribution provided by PANPE and two independently refined distributions via PANPE-IS and PANPE-MCMC, both of which yield equivalent solutions. 1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 . as the neural network-based density estimator.Normalizing flows can learn complex high-dimensional conditional distributions and have been employed for Bayesian inference in multiple applications.Once trained on a broad range of simulated data, the flow-based model p 1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 . NN (θ|R) can efficiently generate samples {θ i } N i=1 ∼ p NN (θ|R) and evaluate densities p i = p NN (θ i |R) for different measurements R. 1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 . H 2 O and R D 2 O is a product p(R H 2 O |θ)p(R D 2 O |θ). 1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 . , we consider two neutron reflectometry measurements of a polymer on a silicon substrate performed separately with H 2 O (ρ = −0.56• 10 −6 Å−2 ) and D 2 O (ρ = 6.36 • 10 −6 Å−2 ) solvents.Neutron reflectometry differs from X-ray data in several aspects, such as instrumental resolution, high scattering background, and negative SLD.Therefore, we trained an additional PANPE model for neutron data that incorporates these features and has 11 free parameters that now also include scattering background.specificallytrained on such combined measurements.However, using our model trained on single curves, one can combine two (or more) sets of samples generated independently for each measurement for constructing a proposal distribution 1 2 (p NN (θ|R H 2 O ) + p NN (θ|R D 2 O )).Such a proposal distribution exhibits the probability mass-coverage property and can be

섹션 본문 144문단 · 65,242자

(제목 없음)

1Reconstructing the structure of thin films and multilayers from measurements of scattered X-rays or neutrons is key to progress in physics, chemistry, and biology.However, finding all structures compatible with reflectometry data is computationally prohibitive for standard algorithms, which typically results in unreliable analysis with only a single potential solution identified.We address this lack of reliability with a probabilistic deep learning method that identifies all realistic structures in seconds, setting new standards in reflectometry.Our method, Prior-Amortized Neural Posterior Estimation (PANPE), combines simulation-based inference with novel adaptive priors that inform the inference network about known structural properties and controllable experimental conditions.PANPE networks support key scenarios such as high-throughput sample characterization, real-time monitoring of evolving structures, or the co-refinement of several experimental data sets, and can be adapted to provide fast, reliable, and flexible inference across many other inverse problems.

I. INTRODUCTION

2Scattering techniques enable the reconstruction of object structures through the analysis of scattered radiation [1,2].At the nanoscale, this requires radiation with short wavelengths, such as X-rays and thermal neutrons.While for the reconstruction of images from visible scattered light there are more established tools including optical lenses, employing these tools for X-rays and neutrons frequently poses significant challenges, leading to the use of algorithms for the reconstruction process [3].These algorithms, however, receive incomplete information, as detectors capture intensities, but not the phase information of the scattered waves.This gives rise to the phaseless inverse problem in scattering physics.While physical models can simulate scattered intensities from a given structure, reconstructing the structure from actual measurements is analytically intractable, and experimental data can be consistent with multiple physical structures [4].This ambiguity can be then resolved through complementary measurements or physical knowledge, but it is crucial to first acknowledge the existence of multiple solutions to avoid costly misinterpretations of the data.

3Together with advances in experimental methods enabling time-resolved online experiments and high-throughput pipelines [5,6], this creates a pressing need for algorithms that are (1) fast, (2) capable of reliably identifying all possible solutions, and (3) flexible enough to integrate additional data and physics-informed constraints.

4The need of fast and reliable algorithms is especially evident for neutron and X-ray reflectometry [7,8].The reflected intensity R in specular geometry as a function of momentum transfer q (see Figure 1a) can inform about the scattering length density (SLD) profile for a broad range of thin films and layered structures, ranging from solar cells [9] to biological membranes [10,11].The SLD profile is typically modeled by parameters θ that include layer thicknesses d l , densities ρ l , and interface roughnesses σ l .Obtaining these parameters θ from a reflectivity curve R(q) in a fast and reliable way is a longstanding inverse problem (Figure 1b) due to the phase loss, measurement noise, and the limited range and resolution of q.For a long time, a common approach was to search for the "best" single set of parameters θ * maximizing the likelihood of the measured data.However, maximum likelihood estimation remains fundamentally unreliable as it overlooks other potential physical solutions arising from ambiguity in the inverse problem.To address ambiguity, we need to embark on a principled probabilistic approach, and estimate the posterior probability density of the parameters θ given the measured data R.In such a Bayesian posterior p(θ|R), different probable structures appear as distributional modes (Figure 1c).In practice, the inference of a high-dimensional posterior is inherently challenging, and particularly so in reflectometry where multiple narrow distributional modes are common.Conventional Bayesian likelihood-based techniques such as Markov Chain Monte Carlo (MCMC) [12] are neither fast nor reliable, as they generally miss distributional modes.

5Here, we present a machine learning solution for Bayesian reflectometry analysis that provides fast, reliable and accurate inference along with the flexibility that online experiments demand.Speed is achieved by pre-training a neural network across large amounts of representative data, an amortization procedure that then allows for real-time inference on new samples.Reliability stems from the use of recent simulation-based inference which, in contrast to likelihood-based modes provides comprehensive coverage of the search space.

6Accuracy in the identified solutions is achieved via a subsequent likelihood-based step, that refines machine learning-based estimates.Fast likelihood evaluations are possible thanks to a novel GPU-parallel transfer-matrix simulator.Finally, we enable great flexibility for a wide range of standard scenarios in experimental setups by extending neural posterior estimation (NPE) with prior amortization, which we term Prior-Amortized Neural Posterior Estimation (PANPE).Our method PANPE can use dynamically set, adaptive prior distributions, allowing to track online expriments, leverages equivariance transformations to enable amortization over different q ranges, and can combine evidence from multiple measurements for efficient inference.Below, we describe in detail how PANPE works and benchmark its performance on real and synthetic reflectometry data.

II. RESULTS

7We describe our method in Section II A. We then evaluate it on synthetic data, which encompasses a broad range of structures, in Section II B. Subsequently, we apply it to Xray reflectometry (XRR) data from online in situ experiments in Section II C. Finally, we showcase our approach for combining multiple measurements in neutron reflectometry (NR) data in Section II D.

A. Overview of PANPE

8Bayesian framework for inverse problems.

9Reflectometry analysis aims to infer physical parameters θ from measured data R.Each parameter set θ describes a hypothetical SLD profile of the studied structure (SLD parameterization is discussed in Methods IV A).

10For a given reflectometry measurement R, the Bayesian posterior distribution [13] p(θ|R) ∝ p(R|θ)p(θ)

11offers a probabilistic estimate of θ, characterized by the likelihood p(R|θ) provided by scattering theory and a prior p(θ) provided by experimentalists.

12Importantly, the prior physical knowledge about the studied structure, formulated as a prior distribution p(θ) over parameters θ in Bayesian framework, serves as a crucial tool for resolving ambiguity in reflectometry and, more broadly, in scattering physics.It facilitates methods commonly employed for reflectometry analysis, as well as our proposed approach.The standard maximum likelihood estimation approach provides a single solution by design.MCMC locally explores the parameter space and can overlook distributional modes.In contrast, (PA)NPE posterior estimate is guaranteed to cover all the solutions, with further refinement based on likelihood evaluation improving accuracy.Our prior amortization method, PANPE, enables the analysis of multiple experimental scenarios using a single neural network.intervals.To compute them, we need to draw samples {θ i } N i=1 ∼ p(θ|R) from the posterior distribution, i.e. randomly selecting parameter sets θ i in proportion to their posterior density p(θ i |R).The complexity of this operation for high-dimensional parameters θ renders Bayesian inference a highly challenging task, traditionally limiting the applicability of the Bayesian approach to simple cases.

13Coverage and refinement of Neural Posterior Estimation.To reliably sample from the Bayesian posterior, we adopt a recent Neural Posterior Estimation (NPE) method [14,15].It employs a normalizing flow architecture [15][16][17] A key property of normalizing flows is that the exact density evaluation enables training the model by minimizing the forward Kullback-Leibler (KL) divergence (see Methods

IV C

14).This ensures the coverage property of NPE, i.e. it contains the full support of the true unknown posterior p(θ|R) and does not miss distributional modes [18].However, the "shape" of the NN-based density estimate might deviate from the target posterior.To address this, likelihood-based methods such as IS and MCMC can refine the NPE results for more accurate estimates.Thus, NPE ensures the coverage property, while likelihood-based refinement enhances accuracy.

15Our custom-made GPU-accelerated transfer-matrix reflectometry simulator [19] implemented using PyTorch [20] accelerates both the training and inference stages.This allows us to simulate new curves directly during the training process without reusing simulations, thereby preventing overfitting.Furthermore, as shown in Section II B, our reflectometry analysis with importance sampling refinement -which requires likelihood evaluations -typically takes just seconds to less than a minute on a single graphics card, the NVIDIA RTX 2080 Ti.

16Amortization across various experimental scenarios.Along with reliability due to the coverage property, NPE provides fast inference, since its computational cost is amortized by the training process.However, the amortization also introduces a key practical limitation, as a trained model can only operate within some predefined training ranges of parameters.In the case of reflectometry, this limitation not only includes the parameter ranges, but also experimental settings such as the discretization of the momentum transfer axis q or the measurement uncertainties, all of which may significantly affect the resulting posterior estimate.We address these limitations by implementing intensive amortization, taking into account the diverse varying aspects of the experiment, such as q discretization and range, measurement uncertainties, and prior information.

17Measurements of the reflected intensity R(q) are taken at different discrete values of momentum transfer q (see Figure 1a).Together, these measurements form an input dataset R = {q p , R(q p ), s p } nq p=1 consisting of n q measured points (here s p represents the uncertainty of each data point).Our approach accommodates experiments featuring arbitrarily spaced q points and varying numbers of measurements n q , by utilizing an efficient embedding neural network equipped with trainable interpolation kernels (see Methods IV F).

18However, in the context of reflectometry analysis, the most significant variable component is the prior information.Indeed, known constraints on physical properties vary substantially across different structures under study.Furthermore, in the online experiments discussed in Section II C, the experimentalists may modify the structure by changing control parameters -and accordingly, the respective priors.Adjustments to the priors are also necessary when combining multiple measurements in neutron reflectometry, as considered in Section II D. In these and other scenarios, the analysis must adapt to the changing prior distribution.Standard machine learning solutions like NPE, which typically assume a fixed prior distribution, fall short under these experimental conditions.To overcome this limitation, we introduce Prior-Amortized Neural Posterior Estimation (PANPE) that accommodates a variety of prior distributions within a single model.

19Prior-Amortized Neural Posterior Estimation (PANPE).We incorporate dynamic prior information into a neural network by choosing a class of distributions p(θ|ϕ) parameterized by ϕ.The newly-introduced parameters ϕ reflect prior information about the system.They are supplied as an additional input to the flow-based neural network p NN (θ|R, ϕ) alongside the measured data.This allows us to train a single neural network and amortize inference across both measurements R and priors p(θ|ϕ): p NN (θ|R, ϕ) ≈ p(θ|R, ϕ) ∝ p(R|θ)p(θ|ϕ) .

20(

21In reflectometry analysis, it is typically sufficient to employ uniform prior distributions

22), where n is the number of parameters θ.Thus, we define ϕ as a set of corresponding parameter ranges: ϕ = {θ min j , θ max j } n j=1 .This results in 2n = 20 additional input values for a task with n = 10 parameters θ.In this manner, the model is trained to approximate posterior distribution for a continuous set p(ϕ) of (uniform) prior distributions p(θ|ϕ) within a larger parameter space.Indeed, our approach can be extended to other classes of distributions by providing suitable parameterization.We discuss why the likelihood-based refinement (or rejection sampling in the case of uniform prior distribution) is not a practical alternative to the prior amortization in out case in Section II B. Our prior amortization approach is discussed in detail in Methods IV C.

23We explain the inference pipeline in Methods IV F. Given the data R and the prior distribution characterized by parameters ϕ, we sample from the trained PANPE model and apply likelihood-based refinement either using importance sampling [18] (PANPE-IS) or

MCMC (PANPE-MCMC).

24Parameter-conditioned posterior estimation.

25In certain cases, it is required to estimate parameter-conditioned posterior estimation, where instead of providing narrow priors for a parameter, it is fixed.We show one such case in Section II D where parameterconditioned posterior estimation is necessary for combining multiple measurements with partially shared parameters.

26Another scenario relevant for future reflectometry applications considers choosing the appropriate physical model: by setting the thicknesses of a subset of layers to zero, one can effectively change the number of layers in the physical model.Consequently, several physical models represented by different numbers of free parameters can be compared via standard criteria such as the Bayes factor p(R|ϕ 1 ) p(R|ϕ 2 ) using the same neural network.Fixing some parameters indeed changes the dimensionality of the remaining free parameters, which is not supported by standard implementations of the normalizing flow.To circumvent this limitation, we introduce a reparameterization procedure of the parameter space that enables us to sample from the parameter-conditioned posterior estimation by providing "zero-width" prior.We discuss this approach in Methods IV C and employ it in Section II D.

27Preserved equivariances in the density estimator.The reflectometry simulator features a number of simple deterministic functional relationships between the input {q, θ} and the simulated reflectivity curve R(q, θ).We systematically review them in Methods IV B. For instance, these include the unit scaling invariance: rescaling the momentum transfer axis q → u • q (u ∈ R >0 ) together with a certain parameter rescaling transformation θ → T u (θ) does not alter the result: R(u • q, T u (θ)) = R(q, θ).Conventional reflectometry analysis does not need to consider these relationships, but they become critical in amortized machine learning solutions: the trained model must reflect these relationships, ensuring that specific changes in the input data to the density estimator result in corresponding changes in the posterior distribution.To enhance the performance of the model, we directly incorporate these relationships into the inference pipeline (see Methods IV B and IV F), rather than having the model learn them from data.We note that the prior amortization is generally required for this operation, since the considered transformations alter the prior distribution.

Related work.

28Sequential NPE [21][22][23][24] effectively applies data-informed prior updates, but such methods require simulation and neural network training at inference time.

29The Simformer [25] framework enables prior updates by leveraging diffusion guidance.

30Equivariances between parameter and data spaces can be integrated with group-equivariant NPE [26,27], but this method requires iterative inference and is therby slower than NPE.

31The Dingo-BNS framework [28] for gravitational-wave inference combines adaptive priors with amortized NPE to achieve improved data compression.Our study builds on and extends upon these works, demonstrating how adaptive SBI priors enable posterior zooming into arbitrary parts of the parameter space in a high-profile science application.

B. Performance on simulated data

32We first test our model on the test simulated dataset with a broad range of two-layer structures with 10 parameters.Performance on the X-ray reflectometry data is discussed in Section II C. For the results on neutron reflectometry (NR), refer to Section II D.

33Multiple modes in the posterior.Figure 2 showcases the inference results obtained with PANPE-IS for a curve simulated from a two-layer structure.For reflectometry, generated samples {θ i } N i=1 represent SLD profiles that could potentially produce the measured data according to the neural network.Efficiency gain from prior amortization.Figure 2(c-d) shows the inference result for the same reflectivity curve, but with narrower prior distribution, resulting in a single mode.In this case, the prior amortization allows excluding all the samples outside the domain of a more informative prior distribution.

34The necessity for prior amortization might not be immediately obvious when likelihood evaluation is fast.A viable alternative could seem to be training a standard NPE model across a wide parameter range without prior amortization and refining results via likelihoodbased methods later.For uniform priors, calculations of likelihood are not even required:

35samples outside the prior domain can be simply rejected without the need of likelihood evaluation.However, the main issue with rejection sampling is its low acceptance rate.In practice, this quantity can be exceedingly small.In our case, an acceptance rate of less than one in a million applies to about 70 % of the synthetic test data.Consequently, in order to obtain a single sample within the prior domain, an immense number of samples would need to be generated through neural network evaluations, making this approach essentially inapplicable.We also illustrate this problem on an experimental data in Section II C.

Sample efficiencies on the simulated dataset.

36We evaluate PANPE-IS on a set of 1000 simulated test samples.These samples are generated following the same procedure as outlined for the training data in Methods IV D. Each curve has different q discretization and is accompanied by its own prior distribution p(θ|ϕ).

37We assess the performance of the model on each test sample by evaluating its sample efficiency ϵ eff :

38, where w i are the importance weights.In practice, during inference, importance weights can be employed for Monte Carlo estimates

39The sample efficiency ϵ eff effectively quantifies the efficient sample size ESS = N • ϵ eff as a share of the total number of samples and, therefore, determines the time required for obtaining a desired ESS.By using our efficient reflectometry simulator, we are able to obtain ESS = 100 for ϵ eff = 10 −4 for less than a minute, but the same ESS would take more than a month for ϵ eff = 10 −10 .

40Each test sample is characterized by its prior distribution, which results in different complexity of the inference task: wider prior distributions that simulate the cases of higher uncertainty about the studied structure are generally more complex to analyse using conventional methods.We quantify this complexity through the sample efficiency of the con-ventional importance sampling (IS) method with prior acting as a proposal distribution.In this case, it replaces the "neural" proposal distribution in the Equation 3, and the respective importance weights simply equal to the likelihood w IS i = p(R|θ i ), where θ i ∼ p(θ|ϕ).We discuss how we estimate low sample efficiencies for IS in Methods IV G. Evaluating PANPE performance without refinement.

41Additionally, we evaluate the performance of raw PANPE estimates without likelihood-based refinement.Specifically, we evaluate the quality of marginal distributions, i.e. one-dimensional distributions p NN (θ j |R, ϕ) for each jth parameter.For that, we perform standard Kolmogorov-Smirnov tests that employ the "true" parameters θ used for simulating the test data [26].These tests determine whether the true parameters could realistically be sampled from PANPEgenerated marginal distributions by checking if their percentile scores are uniformly distributed.SM Figure 1 shows the p-p plots, and the obtained p-values demonstrate satisfactory performance on simulated data.These findings imply that one can rely on raw PANPE estimates derived from marginal distributions like means and variances for analysis.However, in the context of reflectometry, we always apply likelihood-based refinement as it is cost-effective, and importantly, enhances the accuracy of our estimates while also providing a means to evaluate their quality.

C. Performance on experimental XRR data

42In this Section, we evaluate the performance of PANPE-IS on the largest publicly available reflectometry dataset [29] that has been previously employed for evaluating the performance of ML-based regression models [30][31][32].

Experimental data.

43As experimental XRR data, we utilize 208 curves, accompanied by a manual analysis using a conventional fitting procedure via maximum likelihood estimation.This data originates from three online in situ experiments conducted at different synchrotron facilities.Each experiment recorded in real time a process of growing an organic layer, specifically diindenoperylene (DIP), on a silicon substrate.DIP, an organic semiconductor, has gained interest due to its prospective uses in the field of electronics and photovoltaics [33].Real-time XRR measurements can provide insights into growth processes of such thin films.Furthermore, this type of experiment can indeed benefit from rapid analysis.In this way, a machine learning-based solution was recently deployed for the first closed-loop XRR experiment [34].However, the ambiguity problem presented limitations to the regression-based model, rendering our probabilistic method a potential successor in such closed-loop systems (see SM Figure 6).to conventional manual fits performed via differential evolution reported in [29].SM Figure 4 shows time-dependent sample efficiencies and the log evidence estimations for both methods.simulated curves that correspond to the maximum likelihood from both the narrow and wide prior distributions.While both fits are satisfactory, the unphysical solution (in red) has a likelihood that is more than 10 6 times greater than its physical counterpart due to larger residuals (c).In this case, when trained solely with a wide prior distribution, the NPE network mainly samples unphysical solutions, which appear much more probable without the physics-informed prior.The use of prior amortization addresses this issue.

44For each experimental curve, we set uniform priors based on a physical understanding of the experiment, aligning with conventional analysis.The parameters of the known silicon substrate and the oxide layer are essentially fixed by designating narrow ranges.In contrast, the parameters for the thickness d 1 , roughness σ 1 , and density ρ 1 of the growing organic layer have broader prior ranges due to uncertainty.Furthermore, as the film thickness d 1 increases, its ranges are set to increase linearly with time, in line with the anticipated growth rate.

45Although the physical model contains 10 parameters, in this case, the physics-informed prior information about the structure allows us to effectively constrain most of the parameters.

46Nonetheless, prior amortization allows us to use the same PANPE model that was applied to simulated data featuring two-layer structures.

47We also note that the datasets under consideration feature different q ranges and resolutions.Nevertheless, a single model can process them due to the prior amortization that exploits the scaling invariance of the reflectometry data, as well as due to the amortized discretization of our model.

48Comparison with conventional data analysis.

49The defined prior distributions are narrow enough to enable conventional importance sampling for validation purposes.Despite the relative simplicity of the dataset due to a small number of free parameters, the resulting distributions feature two solution branches for the density parameter ρ 1 visible in Figure 4 (see also SM Figure 3).The upper branches vanish beyond a certain time for each dataset, suggesting that the correct solution corresponds to the lower branches.Conventional fits, indicated by purple dots in Figure 4(b), deviate from the maximum likelihood, underscoring the relevance of probabilistic methods even in such straightforward cases.Therefore, the axis for IS sample efficiency in Figure 3 can be approximately divided into ranges: ϵ IS eff > 10 −3 for "zero-layer" structures, ϵ IS eff ∈ [10 −6 , 10 −3 ] for "one-layer" structures that constitute the rest of the experimental curves, and ϵ IS eff < 10 −6 for more complex, simulated two-layer structures.The respective estimated inference time axis in Figure 3 suggests that pure conventional likelihood-based methods become largely impractical for two-layer structures.On the other hand, PANPE-IS delivers accurate and reliable solutions in under a minute for most of these cases.SM Figure 5 displays the inference results for a simulated four-layer structure with 16 parameters, revealing a highly ambiguous outcome (the result is obtained via PANPE-IS using an additional model trained on four-layer structures).This example underscores the increasing complexity and ambiguity in reflectometry analysis as the number of free parameters grows.To maintain the high sample efficiency of PANPE in these more challenging scenarios, it is necessary to enhance the capacity of the density estimator.This enhancement could be achieved not only by enlarging the size of the neural network, but also through the use of more sophisticated density estimators, such as continuous normalizing flows [35][36][37],

50without necessitating significant changes to the overall framework presented in this paper.

51Improving performance for more complex scenarios may also involve customizing the hyperprior distribution and other solution aspects, such as q discretization, to better suit the specific application and experimental conditions.

Role of physics-informed priors.

52Figure 5 illustrates the essential role of prior amortization in the analysis of the presented experimental data.Without providing the physics-informed prior distribution to the neural network, the resulting samples span all possible solutions (represented by the red SLD profiles in Figure 5a) within the expansive prior distribution that covers the complete training range.Yet, all of these solutions are unphysical, due to factors such as a too thick oxide layer.The physical solution, depicted by the blue SLD profiles, is practically unattainable without prior amortization given that the share of samples within the corresponding narrow prior is less than 10 −6 .This scenario emphasizes once more the essential role of incorporating additional physical information into inverse scattering problems with missing phase.

53Adaptive q discretization.The ability of our model to support arbitrary q discretization significantly broadens its applicability.In this way, the number of q points in the analyzed X-ray data ranges from 25 to 52, yet it is processed by the same model.We note that an alternative approach involving interpolation to conform to a fixed q axis can generally lead to missed solutions.For instance, if a model trained on 52 q points is subsequently tested on experimental data comprising only 25 q points, interpolating these data to 52 points could create a falsely narrow distribution.This occurs because the interpolation process artificially adds "information" that the original experimental data does not possess, compromising the guarantee of the coverage property.

54SM Figure 6 demonstrates another relevant experimental scenario that requires adap-tive q discretization: while performing an X-ray reflectometry measurement by sequentially measuring intensities at distinct points, one can use the model to analyze the data at any particular moment.This analysis can inform whether additional data are needed to reduce uncertainty and can even guide the selection of the next most informative q point to measure.Obtaining such points is straightforward using reflectometry curves simulated using parameters sampled via PANPE-IS.

D. Combination of multiple neutron reflectometry measurements

55In this Section, we demonstrate that PANPE can be successfully employed for the simultaneous analysis of several combined neutron reflectometry datasets, which is an indispensable tool in the context of contrast variation (e.g. using different levels of deuteration [38,39]).

56Co-refinement of neutron data.A common method to resolve ambiguity involves combining measurements taken under controlled variation of experimental conditions.In the context of reflectometry, such conditions can be determined by the different energies of the X-ray beam (i.e.anomalous scattering near an absorption edge), polarizations of neutrons for magnetic materials, or by employing different contrasts via changing materials adjacent to the sample.

57We demonstrate this co-refinement procedure using publicly available neutron data [40].

58Specifically The reparameterization operation that we introduce as a part of our prior-amortized approach offers a means to approximate such conditional probability densities with the same model by setting very narrow priors, essentially fixing the required parameters.However, this approach provides only samples and not density evaluation required for importance sampling refinement (see Methods IV C).Therefore, we use PANPE-MCMC for likelihood refinement of the combined posterior in this case.

59Inference results for combined measurements.c-d).The single measurement yields two distinct solutions (Figure 6a), one of which is (implicitly) ruled out when performing a co-refinement of two measurements (Figure 6c), thereby resolving ambiguity in data interpretation.Non-zero ambient density is processed as discussed in Methods IV B.

60In the case of the neutron data analyzed in this work, the parameters unique for each measurement θ unique include scaling misalignment, background, and densities of contrasts.

61The shared parameters correspond to the constant parameters (i.e.those that do not change in-between these measurements) of the system under study, such as thicknesses, roughnesses, and densities of Si and SiO 2 .Notably, following the parameterization described in the refnx package, we account for the volume fraction v solv ∈ (0, 1) of the solvent that modifies the SLD of the polymer layer according to ρ = (1 − v solv )ρ polymer + v solv ρ solv .We regard these densities ρ as parameters unique to each measurement, utilizing them to compute v solv and ρ polymer .The mixture of solvent with polymer results in a small difference of polymer SLDs for measurements with different contrasts in Figure 6.

62It is worth noting that in certain cases of application-specific parameterization on an SLD profile, it might be more practical to retrain the model using a more suitable parameterization, but it is not necessary in this case.In general, the demonstrated approach can be equally well applied to other cases of parameter co-refinement such as polarized neutron reflectometry, XRR measurements with different energies, or other similar applications that require combining several measurements.

III. DISCUSSION

63In reconstructing physical systems from scattered intensities, the phase problem poses a fundamental challenge.This problem is encountered in numerous scattering techniques, including X-ray and neutron reflectometry.The prevailing standard in reflectometry analysis is maximum likelihood estimation, which uses a differential evolution-based search over the parameter space.This method, by design, produces a single system reconstruction, even when multiple solutions exist due to phase loss, making it inherently unreliable.In contrast, Bayesian inference provides a foundational pathway to a more reliable analysis by inherently accounting for all possible solutions as a distribution over the considered physical parameters.

64However, despite its conceptual advantages, conventional likelihood-based Bayesian methods struggle with high-dimensional parameter spaces and multimodality, often falling short in real-world experimental contexts.This underscores the pressing need for more efficient and reliable Bayesian methods in reflectometry analysis.

65In this work, we present a new approach that enables reliable, accurate, and fast Bayesian reflectometry analysis.The high inference speed essential for various experimental contexts is achieved via neural network-based amortization.The training strategy reliably provides an approximate posterior distribution that fully covers the true posterior, while likelihoodbased inference is subsequently employed to obtain the accurate distribution.

66Importantly, our method enables reliable reflectometry experiments: it can guide experimentalists by indicating whether the remaining ambiguity requires additional measurements, thereby directing the experiment until the singular physical solution is determined.Furthermore, preparing experiments in advance by investigating ambiguities in simulated settings becomes possible.

67Prior amortization crucially broadens the applicability of NPE to multiple experimental settings.In the context of reflectometry, constraining the parameter space based on individual characteristics of a studied structure is essential to resolve ambiguity.As shown, prior amortization allows to infer a physical solution that can feature a million times smaller likelihood and filter out an unphysical solution that is yet legitimate in other experimental settings or for other systems.This, in particular, underscores the importance of prior amortization when applying simulation-based inference methods to scattering problems with phase loss.

68Complex parameterizations of prior distributions can be used and should be investigated in future research aiming at adapting PANPE to specific applications.

69Real-world benchmarks are valuable for the developing field of simulation-based inference.In this context, reflectometry analysis offers a notable benchmark, characterized by challenging multimodal distributions and bolstered by an efficient simulator.Importantly, it can be straightforwardly scaled up by increasing the number of layers in the physical model.

70Simulation-based inference is often seen as advantageous for applications where likelihood is costly or intractable to evaluate.Reflectometry does not fit into this category and it exemplifies the broader utility of SBI methods beyond intractable likelihoods due to the coverage property and acceleration of inference through amortization.Moreover, the combination of SBI with likelihood-based methods presents as the optimal way to both preserve the coverage and achieve high accuracy.

71Prior amortization can be beneficial for multiple applications, especially in experimental science like scattering where various experimental scenarios require adaptive prior distributions.In this manner, our method is suitable for a wide range of scientific experiments that permit simulation-based inference.

A. Parameterization of the SLD profile

72We consider the standard parameterization of the SLD profile of a layered structure with n l layers through parameters θ = {d, ρ, σ, ∆R, ∆q, log 10 (R 0 )}, and we primarily consider two-layer structures n l = 2.Here d = {d 1 , d 2 } are layer thicknesses in the top-bottom order, ρ = {ρ 1 , ρ 2 , ρ sub } are densities of two layers and the substrate, and σ = {σ 1 , σ 2 , σ sub } are roughnesses of three interfaces modeled via Névot-Croce factors.We exclude absorption in this work due to our focus on organic materials, but it can be straightforwardly included into our framework.Additionally, we consider standard misalignment parameters: normalization misalignment ∆R and systematic misalignent of the q axis ∆q.We only consider the parameter for scattering background log 10 (R 0 ) for neutron data (see Section II D), which results in 11 parameters.Consequently, the model for X-ray data has 10 free parameters.

B. Equivariant transformations in reflectometry

73Reflectometry features several equivariant transformations that can be considered to improve the performance of an amortized machine learning solution.In this section, we discuss these transformations and how we incorporate them into our PANPE model.

74Unit-based scaling equivariance.Reflectometry simulation R(q, θ) = R(q, d, σ, ρ) features an invariant scaling transformation that represents the change in employed parameter units u:

75where

76and u ∈ R >0 is a positive value that defines the employed units.The standard units are inverse Angstroms ( Å−1 ) for q values, Angstroms ( Å) for layer thicknesses d and roughnesses σ, and inverse squared Angstroms ( Å−2 ) for (scattering length) densities ρ.If we set u = 1 for these standard units, for instance, the transformation with u = 10 would correspond to the change of units from Angstroms to nanometers, which does not alter the resulting reflectivity curve.Similarly, u = 2 doubles the q range, halves thicknesses and roughnesses, and increases densities by a factor of u 2 = 4, leaving the reflectivity curve unchanged.

77This invariance of the reflectometry simulator leads to the equivariance of the density estimator under the joint unit transformation of input and parameters.Specifically, stretching or squeezing the q axis in the input data and adjusting the input prior parameters ϕ accordingly should result in respective transformations of the parameters θ as per Equation 4. We note that the transformation of prior distribution is commonly required in order to preserve equivariance in the density estimator.Applying this transformation indeed requires prior amortization.

78To incorporate this equivariance into our model, we can standardize the "pose" of the data [27] (the terminology is adopted from computer vision) to simplify the problem for the neural network.We do so by fixing the q range, on which our model is trained.During inference, we first preprocess the data by applying the transformation from Equation 4 so that the measured q range matches the standard one.The corresponding scaling factor is the ratio of two ranges u = q max /q exp .We use this scaling factor to apply the respective transformation on the prior parameters ϕ.After obtaining samples from the PANPE model, we rescale the parameters back using u −1 .Respectively, the probability densities are corrected by a constant Jacobian determinant of the transformation, which equals u −2 in our case.

79We note that this property should also be taken into account when considering parameter ranges for training.For instance, some unreasonably large parameter ranges that might seem unphysical, such as density values that do not correspond to any known materials, can be practically justified since they correspond to smaller densities when scaling the q axis.This relation is illustrated in SM Figure 8.

80Density shifting equivariance.Reflectometry is sensitive to density contrasts rather than absolute density values.As a result, shifting all the densities ρ (SLDs) in the system, including the ambient and the substrate, is an invariant operation that does not change the resulting reflectivity curve.In the context of the density estimator, this leads to the equivariant operation: shifting the respective prior parameters ϕ should result in the shift of the parameters θ (specifically, layer densities ρ).

81We employ this property by defining a natural standard pose in a form of the zero ambient density, on which the model is trained.During inference, the data with nonzero ambient density is first preprocessed by shifting the densities (i.e., the respective prior parameters) so that the ambient density becomes zero.We apply this transformation for neutron reflectometry in section II D. The Jacobian determinant of this transformation equals to 1.

Misalignment shifting equivariances.

82The misalignment parameter ∆R results from the incorrect normalization when calculating reflected intensities as per R(q, θ) • (1 + ∆R), which effectively shifts the reflectometry curve in the "vertical" direction in the log space, resulting in an equivariant shifting transformation.A natural "standard pose" in this case corresponds to ∆R = 0. We note that in this case the standard pose depends on the (unknown) parameter ∆R rather than the data and cannot be performed as a onestep preprocessing.This scenario is similar to the one considered previously [27], where an iterative inference scheme is proposed that allows converging to the standard pose.In our case, the range of the misalignment parameter is already very limited, making a direct application of the iterative scheme impractical.Our preliminary tests suggest that this does not lead to improved performance, so we do not utilize this equivariance in our solution.

83The same applies to the other misalignment parameter ∆q.

C. PANPE training

84We amortize Bayesian inference for a class of prior distributions p(θ|ϕ), parameterized by ϕ.To specify the range of priors for which the model is trained, we introduce the hyperprior distribution -a distribution over prior parameters p(ϕ), that generally depends on the range of anticipated applications and can reflect various physical and practical parameter constraints.We set it to cover a broad range of practical scenarios where some of the parameters are known better (with lower uncertainty) than others.

85The training process of the PANPE model involves adjusting the trainable parameters, denoted as w, of the neural network to minimize a forward Kullback-Leibler (KL) divergence between the true posterior distribution p(θ|ϕ) and the flow-based density estimator p w (θ|ϕ):

86The loss in Equation 6 is approximated by the Monte Carlo estimation:

87where the constant does not depend on the model parameters w.Evaluating Equation 7requires evaluating log density log(p w (θ i |R i , ϕ i )) and drawing samples {ϕ i , θ i , R i } N i from the training distribution p(ϕ, θ, R) ∝ p(R|θ)p(θ|ϕ)p(ϕ).

88Exact density evaluation, and consequently the utilization of the forward KL divergence, is facilitated by normalizing flows, distinguishing them from many variational architectures.

89The forward KL divergence is a mass-covering loss, meaning that the optimized density density covers the whole support of the target distribution (otherwise the loss diverges), thereby ensuring no distributional modes are missed in the posterior estimation.Hence, although the training scheme of PANPE is independent of the specific architecture of the density estimator, the selection of normalizing flows as the density estimator and the corresponding loss function is crucial for the method's reliability.It is also noteworthy that some other recent density estimators exhibit the mass-covering property and can thus be integrated into the PANPE framework for future reflectometry applications.

90Sampling from the training distribution can be performed in two principled ways.The first one is employed in this paper and it goes as follows:

911. First, the prior parameters are sampled from the hyperprior distribution (ϕ i ∼ p(ϕ)) defining the corresponding prior p(θ|ϕ i ).

922. Then, the parameter θ i is sampled from this specific prior distribution, θ i ∼ p(θ|ϕ i ).

933. Finally, the corresponding reflectometry curve, R i ∼ p(R|θ i ), is sampled from the likelihood.

94We note that a similar training scheme, involving sampling from a hyperparameter distribution, has been previously employed in group-equivariant neural posterior estimation (GNPE) [27].

95The second possible way of sampling from the training distribution relies on the relation p(ϕ)p(θ|ϕ) = p(ϕ|θ)p(θ).Therefore, instead of first sampling prior parameters ϕ and then parameters θ, this order can be reversed to sample (potentially, multiple sets of) prior parameters ϕ that correspond to the same parameters θ, hence the same simulations.The gain in this case comes from the opportunity to re-use the same simulations by coupling them with different priors and potentially reduce the required number of simulations, which is critical for certain applications.Since this is not applicable to reflectometry, we do not investigate this method any further.We only note that its implementation would involve additional Bayesian inference p(ϕ|θ) ∝ p(ϕ)p(θ|ϕ), the complexity of which depends on the chosen prior parameterization p(θ|ϕ).For instance, in the case of the parameterization employed in our work, the inference can even be performed analytically (via inverse transform sampling).

96As an optional improvement of our method, we introduce a reparameterization transformation θ = T ϕ (θ) of the parameters θ to effectively "rescale" the parameters according to the respective prior.The reparameterization is chosen to ensure that the prior for the rescaled parameters p( θ) does not depend on the prior parameters ϕ.The flow-based model then is trained to perform inference on these rescaled parameters:

97This reparameterization effectively re-frames the problem as a standard Neural Posterior Estimation, only now the likelihood depends on both the parameters θ and the prior parameters ϕ.By doing so, we can now apply narrow priors without running into numerical issues.This approach accelerates the training process and decreases the number of samples generated outside the prior support.

98Importantly, when setting the prior width of some parameter θ j to zero, we effectively fix it.The respective parameter θj estimated by the model does not influence the likelihood and is essentially trained to match the reparameterized prior distribution (uniform in our case).Consequently, the connection between the reparameterized space θ and the parameter space θ becomes surjective.To sample from the lower-dimensional distribution conditioned on the fixed parameter θ j , we need to marginalize over the parameter θj in the reparameterized space.It is not directly possible to evaluate density of a marginalized distribution in normalizing flows.We note that in the ideal scenario when the parameter θj is uniformly distributed, density evaluation becomes straightforward.Our tests suggest that marginal distributions p( θj ) can deviate from a uniform distribution in practice.However, sampling from a distribution marginalized over θj is straightforward as it simply requires omitting the marginalized parameters.In this way, our reparameterization scheme enables us to sample from the parameter-conditioned posterior estimation.

D. Trained models and parameter ranges

99Trained models.

100We present the main results for X-ray (XRR) and neutron (NR) reflectometry.Due to certain differences in the underlying physics and subsequent differences in the simulator, we have trained two PANPE models: one for XRR and another for NR.The results on the simulated data are presented for the XRR model.Most properties are shared between these models, except for the ranges of density parameters used (the scattering length density (SLD) for neutrons can be negative), the instrumental resolution (more pronounced in NR), and the presence of strong constant background scattering.Although we focus on these two models in the paper, we also show some examples from other models, such as those with four-layer structures.

101Parameter ranges.The training parameters are constrained by the predefined ranges.

102In this paper, we employ the following ranges shared by all the layers.Densities range within We note that due to the equivariant transformations discussed in Methods IV B, during inference the model can also operate outside these parameter ranges.This also means that one can set rather unphysical training ranges, such as large roughness or density, to cover certain realistic scenarios at different q ranges and ambient densities.

103Hyperprior distribution.

104During training, the parameters ϕ = {θ min j , θ max j } n j=1 are generated as follows.First, for each parameter θ j , the width of the uniform prior ∆θ j = θ max j − θ min j is sampled, which generally can range from 0 to the the total parameter ranges introduced above.In this paper, we use the weighted sum of the uniform and the truncated exponential distribution for sampling prior widths.The latter term is added to better represent narrow prior widths corresponding to higher certainty in the prior knowledge.

105Then, the "center" of a prior c j = (θ max j + θ min j )/2 is sampled uniformly within the allowed range.The parameters ϕ are then calculated from ∆θ j and c j .Finally, the upper bounds for interface roughnesses are rescaled to not exceed half the maximum thickness of adjacent layers [32].This overall sampling scheme effectively defines the hyperprior distribution p(ϕ).

106The test simulated data was produced using the same sampling procedure as the training data.However, some of the curves (less than 5%) were manually excluded from the test dataset since they exhibited pathological properties such as nearly zero contrast between the layers.This scenario essentially reduces the number of physical layers in the studied structure and results in exact linear correlation between thicknesses of these layers.The proper way to reduce the number of layers in PANPE would be by setting the thicknesses of redundant layers to zero.

E. Data simulations

107During training, we simulate reflectometry data using the training parameters θ i sampled as per Methods IV D. Each reflectometry simulation R i ∼ p(R|θ i ), R = {q p , R(q p ), s p } nq p=1 is performed in several steps discussed below.Q discretization.First, q values are sampled uniformly from the range q p ∼ U (0, q max ) to enable arbitrary discretization.As discussed in Methods IV B, the q range corresponding to the "standard pose" is set equal to q max = 0.15 Å−1 .However, we can vary this during inference by exploiting the unit-scaling equivariant transformation.The number of points n q is also sampled uniformly n q ∼ U (20, 64).In practice, it is implemented by masking out some of the input data from the model during training.

108Amortized discretization is generally necessary because the posterior can be highly sensitive to it in reflectometry applications.Our tests show that by fixing the q discretization during training, we are able to considerably improve the model performance on the simulated data.However, different discretization of the experimental data necessitates interpolation procedure, that can deteriorate the performance of the model and generally lifts the massprobability coverage guarantees, especially for experimental data with the lower number of points.

109Furthermore, amortized discretization is especially important in online XRR experiments, where time limitations constrain the number of measured q points.It in principle enables closed-loop AI-guided measurements that enable choosing the most informative q point to measure given the current data to speed up the overall process and be able to real-time phenomena with higher time resolution.

110Nevertheless, fixing discretization might be beneficial for applications with more standardized experimental setup.Furthermore, we acknowledge possible ways to improve q simulations for neutron data to better reflect the physical nature of the process and possibly even tailor it for the use at certain neutron sources.

Measurement uncertainty.

111Next, we generate relative measurement uncertainties s p ∼ U (5%, 30%), independently for each q point.We treat these uncertainties as error bars that correspond to standard errors typically employed in reflectometry analysis.As a noise model, we employ the normal distribution as a common approximation of Poisson counting statistics for a high number of counts.We note that generally the use of the Poisson likelihood should be preferred in the case of low counts, which are especially frequent in neutron reflectometry.However, that requires reporting raw intensities, which are typically not included in the published data.

112Reflectivity curves.Finally, we simulate reflectivity curves, using the generated parameters θ = {d, σ, ρ, ∆q, ∆R, log 10 (R 0 )}, q points and measurement uncertainties s.We simulate curves in mini-batches using our parallelized GPU-accelerated PyTorch implementation of Abelès transfer-matrix method [19]:

113varying sizes.Our tests suggest that for a fixed discretization, convolutional neural networks (CNN) provide the best performance on reflectometry data among different architectures.

114To this end, for arbitrary discretization, we implement a trainable neural kernel, which acts as an intermediary step, adapting the data before it reaches the CNN.The kernel is a neural network K(q k , q, R q , s q ) that "interpolates" reflectivity levels and the measurement uncertainties to a set of predefined points {q k } n k k=1 .We utilize three such kernels, featuring 16, 32, and 64 equidistant points, respectively.The spacing between these points defines the kernel's "window".The kernel outputs are averaged for q points falling within this window.

115Each kernel is a multilayer perceptron with GELU activation functions and 4-channel input, a hidden layer with 32 channels, and a 2-channel output layer.Each of three kernels is coupled with a convolutional network discussed below.We note that this architecture is not supposed to be discretization-invariant, as the posterior can be highly sensitive to the choice of q points in reflectometry.

116Each CNN is a sequence of 5 blocks, each block containing a 1D convolutional layer, followed by a batch-normalization layer and a GELU activation function.Convolutional layers features a kernel of size 3, stride= 2, and padding= 1.Consequently, the dimension of the processed data is (approximately) halved after each layer.The number of channels is doubled in each block, starting from 32 up to 512.

117Outputs from three CNNs are concatenated with the preprocessed parameters ϕ and provided to a multilayer perceptron.The final 256-dimensional latent representation of the input is supplied to the flow-based model.

Flow-based model.

118A normalizing flow [16] employs a series of reversible and differentiable transformations on a simple, base distribution (in our case, the standard normal distribution).This approach generates a complex distribution from which samples can be efficiently drawn and evaluated.In this work, we employ a series of 40 transformations, each transformation block being a composition of a coupling layer with monotonic rationalquadratic splines [17] and a batch normalization layer [41].After each transformation block, the parameters are randomly permuted.

119Refinement by likelihood-based methods.

120During the inference, we sample parameters θ i ∼ p NN (θ|R) and generate parameters in batches with the corresponding log probabilities.The obtained curves are used for calculating importance sampling weights (PANPE-IS) and streaming estimation of sample efficiency ϵ eff .We continue this procedure until the effective sample size ESS = N • ϵ eff reaches an adequate threshold which we set equal to 500.The same criterion is employed for the traditional importance sampling, where the prior distribution p(θ|ϕ) is used as the proposal distribution.

121Alternatively, samples generated by PANPE are used as efficient initialization points for MCMC (PANPE-MCMC).In our work, we introduce GPU-accelerated PyTorch-based implementations of several Affine Invariant MCMC algorithms [42][43][44] enabling near realtime MCMC-based refinement operation.

G. Low sample efficiency estimation

122We consider two approaches for estimating sample efficiency for the conventional importance sampling method with prior acting as a proposal distribution.The first approach is the use of importance sampling weights via direct sampling from the prior distribution p(θ):

123where w IS i = p(R|θ i ), θ i ∼ p(θ), and ⟨•⟩ is the average operation over all samples i.An accurate estimation requires N = ESS/ϵ eff samples, e.g.sample efficiency ϵ eff = 10 −12 requires more than 10 12 samples, which is computationally unfeasible.An insufficient number of samples N only provides an upper bound ϵ eff < 1/N .Therefore, it can only be employed in practice for sufficiently high sample efficiencies.

124The alternative approach employs the analytical form [45]:

125p(θ|R) p(θ)

126In the case of the uniform prior distribution p(θ), the equation simplifies to (see the orange and green simulated curves in (a)).This approach can reduce the total number of required q points and speed up the measurements.

127importance sampling (ϵ IS as per Equation 6) and via our model (ϵ * IS as per Equation 10) calculated for simulated samples with sufficiently high efficiency ϵ IS .FIG. 8. Scaling invariance of the SLD parameters and momentum transfer q.A model trained with a fixed q range q max = 0.2 Å−1 (blue dashed lines) can be then applied to the measured data with a different q range, but the total parameter ranges are scaled accordingly.The red dashed lines demonstrate this scaling effect for q max = 0.1 Å−1 .The colored areas denote the ranges within which the trained model can be applied.

FIG. 1 .

128FIG. 1. Reflectometry analysis.(a) A schematic experimental setup for reflectometry measurements.The reflected intensity R(q) from a studied layered structure as a function of momentum transfer q contains information about parameters θ of the studied sample.The momentum transfer is typically controlled by the geometry in X-ray reflectometry or by the energy in time-of-flight neutron measurements.(b) Inverse problem in reflectometry: the forward simulations provided by the scattering theory should be inverted during inference, which is generally ambiguous.(c) Inference

FIG. 2 .

129FIG. 2. Multimodal posterior distribution obtained by PANPE-IS on a simulated reflectivity curve with 10 free parameters for a two-layer structure.The neural network produces results in accordance with the provided prior information, identifying (a) multiple solutions for a "wide" prior distribution and (c) a single distributional mode for a "narrow" prior (gray dashed lines).Colors denote distinct distributional modes obtained by clustering samples.The corresponding reflectivity curves (b) and (d) enable real-time likelihood-based refinement, resulting in accurate posterior estimation.The corner plot (e) shows the resulting marginalized 4d distributions obtained for both priors along with the colored samples related to the colored profiles in (a).

130represents the "true" structure used to simulate the reflectometry curve.The forward reflectometry simulations enable immediate visual validation of the result.In Figure2(a) the studied blue reflectometry curve is superimposed with the colored curves simulated from the NN-produced SLD profiles.The colored reflectometry curves are mostly invisible since they overlap very well with the original curve and each other, despite a diverse variety of corresponding SLD profiles.Figure2(e) provides an alternative visualization of samples and the estimated posterior on a corner plot.For visual purposes, only 4 out of 10 parameters are shown here.

FIG. 3 .

131FIG. 3. Sample efficiencies for conventional importance sampling (left) and our PANPE-IS model (right) on a test dataset of 1000 simulated curves (blue) and a experimental dataset of 208 X-ray reflectometry curves (orange).An additional axis on the right-hand side indicates the estimated time it takes to generate 100 effective samples (ESS) on our hardware with the efficient GPUaccelerated reflectometry simulator (see text).Both the simulated and experimental data consist of two-layered structures with 10 parameters, but in the experimental data, only the top layer is unknown, as the parameters of the silicon substrate and the silicon oxide layer are largely constrained through their respective priors.

Figure 3

132Figure 3 shows sample efficiency distribution of conventional IS on the left-hand side and our PANPE-IS on the right hand side, with lines in the middle connecting the same test samples and indicating the difference in sample efficiency between the two methods.Blue color corresponds to the synthetic test dataset (we discuss the experimental data in the next Section).The axis on the right shows an average time required to obtain ESS = 100 for different sample efficiencies on a single graphics card, NVIDIA GeForce RTX 2080 Ti, with our GPU-accelerated reflectometry simulator.It shows that our PANPE model can perform inference in under a minute where the conventional IS approach would require days and even months of computation.

FIG. 4 .

133FIG. 4. Marginal distributions of the thickness d 1 , roughness σ 1 , and density ρ 1 of the diindenoperylene (DIP) layer growing on a silicon substrate for three in situ experimental XRR datasets obtained by our model (on the left) and via conventional importance sampling from prior distribution (on the right).The colors designate normalized probability densities.Purple dots correspond

FIG. 5 .

134FIG. 5. Experimental XRR curve analyzed using both a wide prior distribution that encompasses the entire training range (shown in red) and a narrow, physics-informed prior distribution (shown in blue).(a) SLD profiles associated with the PANPE-IS samples.Profiles with the highest likelihood are highlighted with bold lines.(b) The observed reflectivity curve (in gray) is compared with

Figure 4

135Figure 4 displays the time-dependent marginal distributions for three parameters obtained by both our PANPE-IS model (on the left) and the conventional importance sampling (IS) method (on the right), showing equivalent solutions.SM Figure 2 demonstrates a corner plot with posterior estimates obtained for an experimental curve using PANPE, PANPE-IS, and PANPE-MCMC, where two refinement methods lead to equivalent distributions.

Figure 3 (

136Figure3(orange color) demonstrates sample efficiencies on the experimental data for the conventional IS and our PANPE solution.Notably, in the case where most parameters are effectively known and constrained, conventional IS can be a practical solution, unless a realtime analysis is required.For most of the considered experimental data, our model performs the analysis in under a second, where IS may require tens of minutes per sample.Several curves where IS is almost as efficient as PANPE-IS correspond to the beginning of the growth process, when there is essentially still no organic layer, and the other parameters are known.

FIG. 6 .

137FIG. 6. Co-refinement of two neutron reflectometry measurements of a polymer on a silicon substrate using H 2 O and D 2 O contrasts, conducted via PANPE-MCMC.(a-b) An analysis of a single measurement with H 2 O contrast (b) yields two distinct solutions and their corresponding SLD profiles (a).(c-d) Co-refinement of the measurements using H 2 O contrast (blue) and D 2 O contrast (orange) resolves ambiguity by eliminating one of the solutions.Data and priors are sourced from the refnx package [40].The combination of several measurements is enabled in this case by the use of parameter-conditioned posterior estimation.

Figure 6

138demonstrates the results of the PANPE-MCMC analysis of a single neutron reflectivity curve measured with H 2 O contrast (a-b), as well as the joint analysis of two measurements incorporating both H 2 O and D 2 O contrasts (

[ 0 ,

13960•10 −6 Å−2 ] for the XRR model and ρ ∈ [−20•10 −6 Å−2 , 60•10 −6 Å−2 ] for the NR model.Thicknesses and roughnesses range within [0, 500 Å] and [0, 50 Å], respectively.Additionally, we limit the maximum roughness of the interface by the half thickness of the thickest adjacent layer.For the misalignment parameters, the ranges are [−2 • 10 −3 Å−1 , 2 • 10 −3 Å−1 ] for ∆q and [−5%, 5%] for ∆I.Additionally, for the NR model, we introduce the (log) background parameter log 10 (R 0 ), R 0 ∈ [10 −9 , 10 −4 ], which is set to 10 −10 for XRR.

1 ( 13 )FIG. 2 .FIG. 5 .FIG. 6 .

140FIG. 2. PANPE results on a measured XRR.The marginalized corner plot of 10-dimensional posterior distribution shows probability-mass covering proposal distribution provided by PANPE and two independently refined distributions via PANPE-IS and PANPE-MCMC, both of which yield equivalent solutions.

141as the neural network-based density estimator.Normalizing flows can learn complex high-dimensional conditional distributions and have been employed for Bayesian inference in multiple applications.Once trained on a broad range of simulated data, the flow-based model p

142NN (θ|R) can efficiently generate samples {θ i } N i=1 ∼ p NN (θ|R) and evaluate densities p i = p NN (θ i |R) for different measurements R.

143H 2 O and R D 2 O is a product p(R H 2 O |θ)p(R D 2 O |θ).

144, we consider two neutron reflectometry measurements of a polymer on a silicon substrate performed separately with H 2 O (ρ = −0.56• 10 −6 Å−2 ) and D 2 O (ρ = 6.36 • 10 −6 Å−2 ) solvents.Neutron reflectometry differs from X-ray data in several aspects, such as instrumental resolution, high scattering background, and negative SLD.Therefore, we trained an additional PANPE model for neutron data that incorporates these features and has 11 free parameters that now also include scattering background.specificallytrained on such combined measurements.However, using our model trained on single curves, one can combine two (or more) sets of samples generated independently for each measurement for constructing a proposal distribution 1 2 (p NN (θ|R H 2 O ) + p NN (θ|R D 2 O )).Such a proposal distribution exhibits the probability mass-coverage property and can be

참고문헌 43건

  1. Surface structure determination by X-ray diffraction Surface Science Reports · Elsevier BV · 1989 10.1016/0167-5729(89)90002-2
  2. A New Lipid Anchor for Sparsely Tethered Bilayer Lipid Membranes Langmuir · American Chemical Society · 2009 10.1021/la8033275
  3. Phase retrieval algorithms: a comparison Applied Optics · Optica Publishing Group · 1982 10.1364/ao.21.002758
  4. La théorie générale des couches minces Journal de Physique · EDP Sciences · 1950 10.1051/jphysrad:01950001107030700
  5. Equation of State Calculations by Fast Computing Machines The Journal of Chemical Physics · American Institute of Physics · 1953 10.1063/1.1699114
  6. <tt>emcee</tt>: The MCMC Hammer Publications of the Astronomical Society of the Pacific · Institute of Physics · 2013 10.1086/670067
  7. X-ray and neutron scattering from rough surfaces Physical review. B, Condensed matter · American Physical Society · 1988 10.1103/physrevb.38.2297
  8. High Fill Factor and Open Circuit Voltage in Organic Photovoltaic Cells with Diindenoperylene as Donor Material Advanced Functional Materials · Wiley · 2010 10.1002/adfm.201001028
  9. Surface Studies of Solids by Total Reflection of X-Rays Physical Review · American Institute of Physics · 1954 10.1103/physrev.95.359
  10. Ensemble samplers with affine invariance Communications in Applied Mathematics and Computational Science · Mathematical Sciences Publishers · 2010 10.2140/camcos.2010.5.65
  11. A Markov Chain Monte Carlo version of the genetic algorithm Differential Evolution: easy Bayesian computing for real parameter spaces Statistics and Computing · Springer Science+Business Media · 2006 10.1007/s11222-006-8769-1
  12. Elements of Modern X‐ray Physics 2011 10.1002/9781119998365
  13. Flexible statistical inference for mechanistic models of neural dynamics arXiv (Cornell University) · Cornell University · 2017 10.48550/arxiv.1711.01861
  14. Neural Ordinary Differential Equations arXiv (Cornell University) · Cornell University · 2018
  15. Synchrotron Big Data Science Small · Wiley · 2018 10.1002/smll.201802291
  16. <i>refnx</i>: neutron and X-ray reflectometry analysis in Python Journal of Applied Crystallography · Wiley · 2019 10.1107/s1600576718017296
  17. Automatic Posterior Transformation for Likelihood-Free Inference International Conference on Machine Learning · 2019
  18. Variational Inference with Normalizing Flows International Conference on Machine Learning · 2015
  19. PyTorch: An Imperative Style, High-Performance Deep Learning Library arXiv (Cornell University) · Cornell University · 2019
  20. Fast fitting of reflectivity data of growing thin films using neural networks Journal of Applied Crystallography · Wiley · 2019 10.1107/s1600576719013311
  21. Normalizing Flows for Probabilistic Modeling and Inference arXiv (Cornell University) · Cornell University · 2019
  22. The frontier of simulation-based inference Proceedings of the National Academy of Sciences · National Academy of Sciences · 2020 10.1073/pnas.1912789117
  23. <tt>emcee</tt>: The MCMC Hammer Publications of the Astronomical Society of the Pacific · Institute of Physics · 2013 10.1086/670067
  24. Normalizing Flows for Probabilistic Modeling and Inference arXiv (Cornell University) · Cornell University · 2019 10.48550/arxiv.1912.02762
  25. Neural network analysis of neutron and x-ray reflectivity data: pathological cases, performance and perspectives Machine Learning Science and Technology · IOP Publishing · 2021 10.1088/2632-2153/abf9b1
  26. Real-Time Gravitational Wave Science with Neural Posterior Estimation Physical Review Letters · American Physical Society · 2021 101103physrevlett127241103
  27. Effective sample size, dimensionality, and generalization in covariate shift adaptation Neural Computing and Applications · Springer Science+Business Media · 2022 10.1007/s00521-021-06615-1
  28. Group equivariant neural posterior estimation arXiv (Cornell University) · Cornell University · 2021
  29. Perovskite–organic tandem solar cells with indium oxide interconnect Nature · Nature Portfolio · 2022 10.1038/s41586-022-04455-0
  30. Neural network analysis of neutron and X-ray reflectivity data: automated analysis using <i>mlreflect</i>, experimental errors and feature engineering Journal of Applied Crystallography · Wiley · 2022 10.1107/s1600576722002230
  31. LII. An essay towards solving a problem in the doctrine of chances. By the late Rev. Mr. Bayes, F. R. S. communicated by Mr. Price, in a letter to John Canton, A. M. F. R. S Philosophical Transactions of the Royal Society of London · Royal Society · 1763 10.1098/rstl.1763.0053
  32. Automatic Posterior Transformation for Likelihood-Free Inference arXiv (Cornell University) · Cornell University · 2019 10.48550/arxiv.1905.07488
  33. Truncated proposals for scalable and hassle-free simulation-based inference arXiv (Cornell University) · Cornell University · 2022 10.48550/arxiv.2210.04815
  34. Probing the Separation Distance between Biological Nanoparticles and Cell Membrane Mimics Using Neutron Reflectometry with Sub-Nanometer Accuracy Journal of the American Chemical Society · American Chemical Society · 2022 10.1021/jacs.2c08456
  35. Machine learning for scattering data: strategies, perspectives and applications to surface scattering Journal of Applied Crystallography · Wiley · 2023 10.1107/s1600576722011566
  36. Neural Importance Sampling for Rapid and Reliable Gravitational-Wave Inference Physical Review Letters · American Physical Society · 2023 10.1103/physrevlett.130.171403
  37. Flow Matching for Scalable Simulation-Based Inference arXiv (Cornell University) · Cornell University · 2023 10.48550/arxiv.2305.17161
  38. Closing the loop: autonomous experiments enabled by machine-learning-based online data analysis in synchrotron beamline environments Journal of Synchrotron Radiation · Wiley · 2023 10.1107/s160057752300749x
  39. Sensitivity-Aware Amortized Bayesian Inference arXiv (Cornell University) · Cornell University · 2023 10.48550/arxiv.2310.11122
  40. Neutron reflectometry as a powerful tool to elucidate membrane interactions of drug delivery systems Advances in Colloid and Interface Science · Elsevier BV · 2024 10.1016/j.cis.2024.103120
  41. Millisecond X-ray reflectometry and neural network analysis: unveiling fast processes in spin coating Journal of Applied Crystallography · Wiley · 2024 10.1107/s1600576724001171
  42. Deuteration-enhanced neutron contrasts to probe amorphous domain sizes in organic photovoltaic bulk heterojunction films Nature Communications · Nature Portfolio · 2024 10.1038/s41467-024-47052-7
  43. Real-time inference for binary neutron star mergers using machine learning Nature · Nature Portfolio · 2025 10.1038/s41586-025-08593-z