autoemx.runners.analyze_sample module

Single-sample clustering and analysis of X-ray spectra.

This module loads configurations and acquired X-ray spectra for a single sample, performs clustering/statistical analysis, and prints results. It is suitable for both interactive use and integration into larger workflows.

Import this module in your own code and call the analyze_sample() function, passing the sample ID (and optional arguments) to perform analysis programmatically.

Workflow:
  • Loads sample configuration and spectral data from ledger.json. Results saved in the legacy Data.csv format are converted to a ledger.json automatically

  • Performs clustering/statistical analysis

  • Prints summary results

Notes

  • Requires sample_ID (and optionally results_path if not using the default directory).

  • Designed to be robust and flexible for both batch and single-sample workflows.

Typical usage:
  • Edit the sample_ID and options in the script, or

  • Import and call analyze_sample() with your own arguments.

Created on Tue Jul 29 13:18:16 2025

@author: Andrea

autoemx.runners.analyze_sample.analyze_sample(sample_ID: str, results_path: str | None = None, output_filename_suffix: str = '', ref_formulae: List[str] | None = None, els_excluded_clust_plot: List[str] | None = None, els_to_plot: List[str] | None = None, clustering_features: str | None = None, clustering_method: str | None = None, dbscan_params: dict | None = None, clustering_geometry: str | None = None, aitchison_params: dict | None = None, k_finding_method: str | None = None, k_forced: int | bool | None = None, max_k: int | None = None, auto_merge_clusters: bool | None = None, cluster_merge_params: dict | None = None, do_matrix_decomposition: bool = True, mixture_params: dict | None = None, max_analytical_error_percent: float = 5.0, quant_flags_accepted: List[int] | None = None, min_bckgrnd_cnts: float | None = None, show_plots: bool = True, plot_custom_plots: bool = False, show_unused_compositions_cluster_plot: bool = True, plot_best_mixture: bool | None = None, intermixing_violin_plots: bool | None = None, show_legend_clustering: bool | None = None, activate_new_analysis: bool | str = True) → EMXSp_Composition_Analyzer | None[source]

Run clustering and analysis for a single sample.

sample_IDstr

Sample identifier.

results_pathstr, optional

Directory where results are loaded and stored. If None, defaults to autoemx/Results

output_filename_suffixstr, optional

Suffix for output files.

ref_formulaelist of str, optional

Reference formulae for clustering. If the first entry is “” or None, the rest are appended to the list loaded from Comp_analysis_configs.json; otherwise, the provided list replaces it.

els_excluded_clust_plotlist of str, optional

Elements to exclude from cluster plot.

els_to_plotlist of str, optional

Elements forced onto the clustering plot axes (opposite of els_excluded_clust_plot). When provided with 2 or 3 elements, those become the plot axes. A single element is kept and filled from remaining detectable elements until 2 or 3 axes are available. Must yield exactly 2 or 3 axes; unknown elements raise ValueError.

clustering_featureslist of str, optional

Features to use for clustering.

clustering_methodstr, optional

Clustering algorithm to use. One of "kmeans" or "dbscan". If None, the value stored in the sample’s clustering config is kept.

dbscan_paramsdict, optional

Overrides for DBSCAN parameters (only used when clustering_method="dbscan"). Recognized keys: eps (float), min_samples (int), metric (str). If eps is not set, it defaults to 0.05 in Euclidean and 0.3 in Aitchison geometry. Unspecified keys keep their existing/default values.

clustering_geometrystr, optional

Geometry in which clustering distances are computed. One of "euclidean", "aitchison" (clusters CLR-transformed compositions; applies to both k-means and DBSCAN, and DBSCAN eps is then in CLR units, default 0.3) or "auto" (Euclidean when at most two elements are present or a major element is near zero in many spectra, Aitchison otherwise; see AitchisonParams). Reported centroids and cluster statistics remain in fraction space. If None, the saved value is kept.

aitchison_paramsdict, optional

Overrides for Aitchison parameters (used when clustering_geometry is "aitchison" or "auto"). Recognized keys: detection_limit_percent (float > 0, default 0.5). Before the log-ratio transform, exact zeros, and all values below the limit for trace elements (median below 2x the limit), are set to 0.65 x the limit. auto_near_zero_percent (default 1.0) and auto_max_near_zero_fraction (default 0.10) set the near-zero criterion used by "auto".

k_finding_methodstr, optional
Method for determining optimal number of clusters. Set to “forced” if a value of ‘k’ is specified manually.

Allowed methods are “silhouette”, “calinski_harabasz”, “elbow”.

k_forcedint or bool, optional
Controls the number of clusters:
  • int: force clustering to use exactly this number of clusters.

  • False: force recomputation of the optimal number of clusters, discarding any previously saved forced k. Uses k_finding_method when provided, otherwise the saved (or default) finding method.

  • None (default): reuse the clustering settings saved in the ledger.

max_kint, optional

Maximum number of clusters tested when k is determined automatically (k-means only). If None, the saved value is kept (default 6).

auto_merge_clustersbool, optional

Whether to merge k-means clusters that are pieces of one continuous population, e.g. a mixture line cut into several clusters (only when k is chosen automatically; see ClusterMergeParams). If None, the saved value is kept (True for new samples, False for samples analysed before this option).

cluster_merge_paramsdict, optional

Overrides for the cluster-merging criteria (see ClusterMergeParams). Recognized keys: dip_alpha, max_gap_ratio, dbscan_min_samples, dbscan_eps_factor. Unspecified keys keep their existing/default values.

do_matrix_decompositionbool, optional

Whether to compute matrix decomposition for intermixed phases. Slow if many candidate phases are provided. Default: True..

mixture_paramsdict, optional

Overrides for the decomposition of clusters into mixtures of candidate phases (see MixtureParams). Main keys: max_n_phases (int >= 2, default 4) and max_recon_error (float, default 0.4). Pairs of candidate phases are always tested; combinations of more phases are only tested when no combination with fewer phases reconstructs the cluster with an error below max_recon_error. Use {'max_n_phases': 2} to only consider binary mixtures. Other keys (reconstruction error and confidence definitions, single-phase and free-NMF criteria) are described in MixtureParams. Unspecified keys keep their existing/default values.

max_analytical_error_percentfloat, optional

Maximum analytical error allowed for clustering.

quant_flags_acceptedlist of int, optional

Accepted quantification flags. See the user documentation page “Quantification flags (quant_flag)”.

min_bckgrnd_cntsfloat, optional

Minimum background counts under the reference peaks: spectra below are flagged (quant_flag 8), with no need to re-quantify (ClusteringConfig.min_bckgrnd_cnts). If None, the saved value is kept.

plot_custom_plotsbool, optional

Whether to use custom plots.

show_unused_compositions_cluster_plotbool, optional

Whether to show unused compositions in cluster plot.

plot_best_mixturebool, optional

Whether to save the plot of the top-ranked mixture of each cluster. If None, the saved value is kept.

intermixing_violin_plotsbool, optional

Whether to plot the intermixing of the reported mixtures as violin plots. If None, the saved value is kept (by default, they are plotted for samples quantified as known phase mixtures).

show_legend_clusteringbool, optional

Whether to show the legend in the clustering plot. If None, the saved value is kept.

activate_new_analysisbool or “ask”, optional

If the settings create a new clustering analysis, whether it becomes the active one (whose settings are reused by later analyses, and shown by default in the GUI). “ask” asks once the analysis is done (if no answer can be given, e.g. without a console, it becomes active). The new analysis is saved either way; the active one can be changed later with set_active_analysis. Default: True.

returns:

comp_analyzer – The composition analysis object containing the results and methods for further analysis.

rtype:

EMXSp_Composition_Analyzer

autoemx.runners.analyze_sample.refresh_custom_plot_template(sample_ID: str, results_path: str | None = None, overwrite: bool = True) → str[source]

(Re)create sample-local custom_plot.py from the packaged template.