Python API Reference
This section provides detailed documentation for the Python components of NSphere that are intended for direct import and use in other Python code. Documentation is generated directly from docstrings using Sphinx Autodoc and Napoleon.
NSphere Plot (nsphere_plot.py)
This is the main Python module containing functions for loading simulation data, generating various plots (profiles, trajectories, histograms), and creating animations.
- class nsphere_plot.Configuration(args=None)[source]
Bases:
object
Configuration class that encapsulates all parameters and settings for the nsphere_plot.py script. This reduces the reliance on global variables and improves code maintainability and testability.
- __init__(args=None)[source]
Initialize the configuration with command line arguments.
- Parameters:
args (argparse.Namespace, optional) – The parsed command line arguments. If None, arguments will be parsed from sys.argv.
- need_to_process_rank_files()[source]
Determine if the visualization plan requires processing rank data files.
- Returns:
True if rank files need to be processed for animations or energy plots, False if they can be skipped based on user-selected visualization options.
- Return type:
bool
Notes
Rank files are needed for animations and energy plots. This method checks if either of these visualization types are specifically requested (via “only” flags) or if they haven’t been explicitly excluded (via “no-” flags) in normal mode.
- only_specific_visualizations()[source]
Determine if the user requested specific visualization types only.
- Returns:
True if any “only” flag is specified (e.g., –phase-space, –profile-plots), False if running in normal mode where all visualizations are generated.
- Return type:
bool
Notes
When “only” flags are active, the script will generate only those specific visualization types and skip all others, regardless of –no-* flags.
- setup_file_paths()[source]
Generate a dictionary mapping file types to their full file paths.
- Returns:
Dictionary where keys are file type identifiers (e.g., “particles”, “density_profile”) and values are the corresponding file paths with the configured suffix.
- Return type:
dict
Notes
This method constructs paths for all possible data files that might be used in the visualization process. The actual existence of these files is checked later when they are accessed.
- nsphere_plot.calculate_global_max_values()[source]
Calculate the maximum values of mass, density, and potential across all snapshots. This ensures consistent scaling in animations.
- Returns:
(mass_max, density_max, psi_max) - Maximum values for each quantity
- Return type:
tuple
- nsphere_plot.calculate_reasonable_vmax(H)[source]
Calculate an appropriate maximum value for colorbar scaling based on histogram data.
- Parameters:
H (ndarray) – The 2D histogram data array.
- Returns:
A reasonable maximum value for the colorbar, based on the 99.5th percentile of non-zero values, rounded to a visually pleasing number.
- Return type:
float
Notes
This function helps avoid having too much empty space in the colorbar while still maintaining a consistent scale across different frames in animations.
- nsphere_plot.clear_line()[source]
Clear the current terminal line for clean console output using ANSI escape codes.
Notes
Uses carriage return and the ANSI sequence [2K to erase the entire line. This is more reliable than printing spaces across different terminal widths.
- nsphere_plot.create_density_animation(suffix, duration)[source]
Create density profile animation.
- Parameters:
suffix (str) – Suffix for input/output files.
duration (float) – Duration of each frame in milliseconds.
- Returns:
Function does not return a value, but saves the animation to a file.
- Return type:
None
Notes
Uses parallel processing for rendering animation frames. Saves the animation incrementally using imageio.get_writer to reduce peak memory usage compared to collecting all frames first. Requires imageio v2 (pip install imageio==2.*).
- nsphere_plot.create_mass_animation(suffix, duration)[source]
Create mass profile animation.
- Parameters:
suffix (str) – Suffix for input/output files.
duration (float) – Duration of each frame in milliseconds.
- Returns:
Function does not return a value, but saves the animation to a file.
- Return type:
None
Notes
Uses parallel processing for rendering animation frames. Saves the animation incrementally using imageio.get_writer to reduce peak memory usage compared to collecting all frames first. Requires imageio v2 (pip install imageio==2.*).
- nsphere_plot.create_psi_animation(suffix, duration)[source]
Create psi profile animation.
- Parameters:
suffix (str) – Suffix for input/output files.
duration (float) – Duration of each frame in milliseconds.
- Returns:
Function does not return a value, but saves the animation to a file.
- Return type:
None
Notes
Uses parallel processing for rendering animation frames. Saves the animation incrementally using imageio.get_writer to reduce peak memory usage compared to collecting all frames first. Requires imageio v2 (pip install imageio==2.*).
- nsphere_plot.display_configuration_summary(config)[source]
Prints the execution banner and summarizes the configuration parameters.
- Parameters:
config (Configuration) – The configuration object containing parsed arguments and settings.
- nsphere_plot.ensure_cursor_visible()[source]
Restore cursor visibility when program exits.
Notes
Safety mechanism registered with atexit to ensure the terminal cursor remains visible even if the program terminates unexpectedly.
- nsphere_plot.filter_finite_rows(*arrs)[source]
Filter out rows containing NaN or Inf values across multiple arrays.
- Parameters:
*arrs (array-like) – Variable number of arrays to filter. All must have the same length.
- Returns:
New arrays with invalid rows removed from all input arrays.
- Return type:
list
Notes
This function removes any row that contains NaN or Inf in ANY of the input arrays. All arrays must have the same length for proper row-wise filtering.
- nsphere_plot.find_project_root()[source]
Determines the project root directory.
- Returns:
Path to the project root directory.
- Return type:
str
Notes
The project root is identified by the presence of a ‘src’ directory. Uses path normalization for cross-platform compatibility.
- nsphere_plot.generate_all_1D_animations(suffix, duration)[source]
Generate all three 1D profile animations (mass, density, psi) with optimized parallel processing.
- Parameters:
suffix (str) – Suffix for input/output files.
duration (float) – Duration of each frame in milliseconds.
Notes
This function runs each animation in sequence to ensure clean console output, but each animation internally uses parallel processing for generating and encoding frames. This gets the best performance while maintaining readable output.
- nsphere_plot.generate_all_2d_histograms(config, rank_decimated_data=None)[source]
Generates all 2D histogram plots including particle, nsphere, and rank histograms.
- Parameters:
config (Configuration) – The configuration object.
rank_decimated_data (list or None) – Pre-processed rank data that can be used as fallback for histogram generation.
- nsphere_plot.generate_all_energy_plots(config, file_paths, unsorted_energy_data)[source]
Generates all energy-related plots with status display and progress tracking.
Displays the initial status, generates plots in parallel (unsorted and sorted energy plots), and updates the console output with completion status.
- Parameters:
config (Configuration) – The configuration object containing suffix and other settings.
file_paths (dict or None) – Dictionary of file paths, will be created if None.
unsorted_energy_data (list or None) – Pre-processed unsorted energy data from process_rank_files.
Notes
The console output is managed with a series of up/down cursor movements to create a clean, consistently updated display. Initial status appears immediately while plots are being generated, with the final update overwriting the status lines upon completion.
- nsphere_plot.generate_comparison_plot(suffix)[source]
Creates a side-by-side comparison of the initial and last available snapshot phase space histograms.
- nsphere_plot.generate_convergence_test_plots(suffix)[source]
Generate all convergence test plots.
- Parameters:
suffix (str) – Suffix for input/output files.
- nsphere_plot.generate_initial_phase_histogram(suffix)[source]
Creates a phase space histogram from the initial particles.dat file. This represents the true initial distribution.
- nsphere_plot.generate_phase_space_animation(suffix, fps=10)[source]
Creates an animation showing the evolution of the phase space distribution over time.
- Parameters:
suffix (str) – Suffix for input/output files.
fps (int, optional) – Frames per second for the animation, by default 10.
- Returns:
True if animation was created successfully, False otherwise.
- Return type:
bool
Notes
Uses parallel processing for preprocessing histogram data and rendering frames. Saves the animation incrementally using imageio.get_writer to reduce peak memory usage compared to collecting all frames first. Requires imageio v2 (pip install imageio==2.*).
- nsphere_plot.generate_rank_histogram(rank_decimated_data, suffix, output_file=None)[source]
Generate 2D histogram from rank data.
- Parameters:
rank_decimated_data (list or numpy.ndarray) – Processed rank data, either as a list of (snap, data) tuples or as a single data array for a specific snapshot.
suffix (str) – Suffix for input/output files.
output_file (str, optional) – Custom output file path. If None, a default path will be used.
- nsphere_plot.generate_sorted_energy_plot(suffix)[source]
Generate energy plot from sorted rank files (particles with lowest initial radius).
Uses the efficient process_sorted_energy_file worker which employs seek-based loading to extract energy data only for specific particles. Processes results iteratively to build the final matrix, avoiding intermediate data accumulation.
- Parameters:
suffix (str) – Suffix for input/output files.
- Returns:
Path to the generated plot file, or None if no plot was generated.
- Return type:
str or None
Notes
This function uses memory-efficient file reading by: 1. Identifying specific particle IDs to track 2. Using optimized file reading that seeks to specific rows 3. Processing data incrementally to avoid large intermediate arrays
- nsphere_plot.generate_unsorted_energy_plot(unsorted_energy_list, suffix)[source]
Generate energy plot from unsorted rank files.
- Parameters:
unsorted_energy_list (list) – Pre-processed unsorted energy data.
suffix (str) – Suffix for input/output files.
- Returns:
Path to the generated plot file, or None if no plot was generated.
- Return type:
str or None
- nsphere_plot.get_file_prefix(filepath)[source]
Extract the filename prefix without path, extension or suffix.
- Parameters:
filepath (str) – Full path or filename to process
- Returns:
The extracted filename prefix
- Return type:
str
Examples
>>> get_file_prefix('results/phase_space_initial_kris_40000_1001_5.png') 'phase_space_initial' >>> get_file_prefix('loading_combined_histogram') 'combined_histogram'
Notes
Handles special cases including loading prefixes and various suffix patterns. For files with a standard suffix pattern (_tag_nnn_nnn_n), removes these components to extract the core filename.
- nsphere_plot.get_mem_usage_mb()[source]
Get current memory usage of the Python process.
- Returns:
Current Resident Set Size (RSS) memory usage in megabytes.
- Return type:
float
Notes
Provides the actual physical memory being used by the Python process using the psutil library to access system resource information.
- nsphere_plot.get_separator_line(char='-', fallback_width=100)[source]
Generates a separator line spanning the terminal width.
- Parameters:
char (str, optional) – The character to repeat for the line, by default ‘-‘.
fallback_width (int, optional) – The width to use if terminal size can’t be determined, by default 100.
- Returns:
A string consisting of ‘char’ repeated to fill the terminal width.
- Return type:
str
- nsphere_plot.get_snapshot_number(filename, pattern=None)[source]
Extract the snapshot number from a filename containing a timestamp pattern.
- Parameters:
filename (str) – Filename to extract snapshot number from
pattern (re.Pattern, optional) – Compiled regex pattern to use. If None, defaults to Rank_Mass_Rad_VRad_sorted_t pattern.
- Returns:
Snapshot number extracted from filename, or a very large number if no match found
- Return type:
int
Notes
Uses regular expression matching to extract the snapshot number from filenames that follow a pattern like “Rank_Mass_Rad_VRad_sorted_t00012”. Returns a large value for non-matching files to ensure they sort after valid snapshot files.
- nsphere_plot.hide_cursor()[source]
Hide the terminal cursor.
Notes
Uses ANSI escape code to hide the cursor for cleaner progress bar display.
- nsphere_plot.load_partial_file(filename, dtype=<class 'numpy.float32'>)[source]
Load data from file, handling incomplete or partially-written lines.
- Parameters:
filename (str) – Path to the file to read
dtype (numpy.dtype, optional) – Data type to use for the array, by default np.float32
- Returns:
Array containing the data successfully read from the file, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
The function stops reading if it encounters a line it cannot parse, returning all data successfully read up to that point. This is useful for handling files that might be incomplete or partially written.
Skips blank lines and stops reading at the first parsing error.
- nsphere_plot.load_partial_file_10(filename, dtype=<class 'numpy.float32'>)[source]
Load the first 10 lines from a text file.
- Parameters:
filename (str) – Path to the file to read
dtype (numpy.dtype, optional) – Data type to use for the array, by default np.float32
- Returns:
Array containing the data from the first 10 lines of the file, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
Useful for quickly previewing or analyzing the beginning of a large file without loading the entire dataset into memory. Only reads the first 10 lines that contain valid data.
- nsphere_plot.load_partial_file_bin(filename, ncols, dtype=<class 'numpy.float32'>)[source]
Load data from binary file with support for different data types.
- Parameters:
filename (str) – Path to the binary file to read
ncols (int) – Number of columns expected in the data
dtype (numpy.dtype or list, optional) – Data type(s) to use for the array, by default np.float32
- Returns:
Array containing the data from the file, or None if the file is missing or contains no valid data
- Return type:
numpy.ndarray or None
Notes
Supports two different modes of operation:
Single dtype (e.g., np.float32): Returns array of shape (N, ncols)
List/tuple of dtypes: Returns structured array with fields named ‘f0’, ‘f1’, …, ‘f{ncols-1}’, each with its corresponding dtype from the list
Uses align=False to ensure tight packing of structured arrays. Reads as many complete rows as possible from the file.
- nsphere_plot.load_specific_columns_bin(filename, ncols_total, cols_to_load, dtype_list)[source]
Loads specific columns from a flat binary file using memory mapping.
This version uses numpy.memmap for efficiency with large files, reading only necessary data pages from disk into memory when columns are accessed.
- Parameters:
filename (str) – Path to the binary file.
ncols_total (int) – Total number of columns (fields) in each row of the file.
cols_to_load (list[int]) – List of 0-based column indices to load and return.
dtype_list (list) – List of numpy dtypes corresponding to all columns in the file, in order. E.g., [np.int32, np.float32, np.float32, …].
- Returns:
A list containing 1D numpy arrays (as float32) for each requested column, filtered for finite values based on the loaded columns. Returns None if the file doesn’t exist, cannot be mapped, or contains no valid data in requested columns.
- Return type:
list[np.ndarray] or None
Notes
Requires the dtype_list specifying the type for all columns to correctly interpret the binary structure for memmap. Returned arrays are converted to float32 for consistency.
- nsphere_plot.log_message(message, level='info')[source]
Log a message to the log file based on level and settings.
- Parameters:
message (str) – The message to log
level (str, optional) – The log level (info, warning, error, debug), by default “info”
Notes
Warning and error messages are always logged regardless of enable_logging flag. Info and debug messages are only logged if enable_logging is True (–log specified).
- nsphere_plot.log_plot_saved(output_file, current=0, total=1, section_type='plots')[source]
Log a saved plot to log file and update status on console.
- Parameters:
output_file (str) – Full path to the saved file
current (int, optional) – Current plot number, by default 0
total (int, optional) – Total plots to save, by default 1
section_type (str, optional) – Type of plots being saved, by default “plots”
Notes
Displays a progress bar and updates the console with the current plot being saved. Includes timing information once enough plots have been processed to calculate a reasonable rate.
- nsphere_plot.parse_arguments()[source]
Parse command line arguments for the nsphere_plot.py script.
- Returns:
The parsed arguments.
- Return type:
argparse.Namespace
- nsphere_plot.phase_space_process_rank_file(fname)[source]
Process a single sorted Rank file for phase space plotting.
Extracts snapshot number and reads data using the appropriate data types and safe loader.
- Parameters:
fname (str) – The filename of the sorted Rank file to process.
- Returns:
(snapshot_number, data) if successful, otherwise None. ‘data’ is a structured numpy array containing the file contents.
- Return type:
tuple or None
- nsphere_plot.plot_angular_momentum_time(input_file, output_file)[source]
Plot angular momentum vs. time for multiple particles, showing both current and initial values.
- Parameters:
input_file (str) – Path to the input data file containing angular momentum data.
output_file (str) – Path to save the output plot.
- Returns:
Path to the saved plot file
- Return type:
str
Notes
The input file should contain time in the first column, followed by repeated groups of values (current energy, initial energy, current angular momentum, initial angular momentum) for each particle. Loads full data.
- nsphere_plot.plot_combined_histogram_from_file(input_file, output_file)[source]
Create an overlay histogram comparing initial and final radial distributions.
- Parameters:
input_file (str) – Path to the input data file containing combined histogram data
output_file (str) – Path to save the output plot
- Returns:
Path to the saved plot file
- Return type:
str
Notes
The input file should contain three columns: - bin_centers: The center values of histogram bins - initial counts: Counts in each bin for the initial distribution - final counts: Counts in each bin for the final distribution
The plot shows three categories using different colors: - Overlap between initial and final (purple) - Initial > Final (blue) - Final > Initial (red)
This visualization helps identify which parts of the distribution remained stable and which parts changed during the simulation.
- nsphere_plot.plot_convergence_test(Nint_arr, Nspl_arr, basefile, suffix, xlabel, ylabel, title, output_file)[source]
Generate convergence test plots comparing different integration and spline parameters.
- Parameters:
Nint_arr (list) – List of integration parameter values.
Nspl_arr (list) – List of spline parameter values.
basefile (str) – Base filename to use.
suffix (str) – Suffix for input/output files.
xlabel (str) – X-axis label (already formatted LaTeX string).
ylabel (str) – Y-axis label (already formatted LaTeX string).
title (str) – Plot title (already formatted LaTeX string).
output_file (str) – Output file path.
- nsphere_plot.plot_debug_energy_compare(input_file, output_file='results/energy_compare.png')[source]
Create multi-panel diagnostic plot comparing energy calculation methods.
- Parameters:
input_file (str) – Path to the input data file containing energy comparison data.
output_file (str, optional) – Path to save the output plot. Default is “results/energy_compare.png”.
- Return type:
None
Notes
Input file should have 8 columns:
0: snapIdx - Snapshot index
1: time(Myr) - Time in megayears
2: radius(kpc) - Radius in kiloparsecs
3: approxE - Approximated energy
4: dynE - Dynamically calculated energy
5: (dynE - approxE) - Difference between calculation methods
6: KE - Kinetic Energy
7: PE - Potential Energy
Creates a 5-panel figure in a 2x3 layout:
Top row (3 panels): [0,0]: Radius vs. time [0,1]: Dynamic energy vs. time [0,2]: Energy deviation from mean (%) vs. time
Bottom row (2 panels + 1 blank): [1,0]: Kinetic energy vs. time [1,1]: Potential energy vs. time [1,2]: (empty placeholder)
- nsphere_plot.plot_density(r_values, rho_values, output_file='density_profile.png')[source]
Plot density profile as a function of radius and save to file.
- Parameters:
r_values (array-like) – Radius values in kpc
rho_values (array-like) – Density values (rho) at each radius
output_file (str, optional) – Path to save the output plot, by default “density_profile.png”
- Returns:
Path to the saved plot file
- Return type:
str
Notes
Filters out any non-finite values before plotting. Creates a figure showing density as a function of radius with appropriate labels and grid.
- nsphere_plot.plot_df_at_fixed_radius(v_values, df_values, r_fixed, output_file='df_fixed_radius.png')[source]
Plot the distribution function at a fixed radius.
- Parameters:
v_values (array-like) – Velocity values
df_values (array-like) – Distribution function values
r_fixed (float) – The fixed radius value in kpc
output_file (str, optional) – Path to save the output plot, by default “df_fixed_radius.png”
- Returns:
Path to the saved plot file
- Return type:
str
Notes
Filters out any non-finite values before plotting. Creates a figure showing the distribution function at a specific fixed radius as a function of velocity.
- nsphere_plot.plot_dpsi_dr(r_values, dpsi_values, output_file='dpsi_dr.png')[source]
Plot gravitational acceleration (dPsi/dr) as a function of radius and save to file.
- Parameters:
r_values (array-like) – Radius values in kpc
dpsi_values (array-like) – Gravitational acceleration values at each radius
output_file (str, optional) – Path to save the output plot, by default “dpsi_dr.png”
- Returns:
Function does not return a value, but saves plot to the specified path
- Return type:
None
Notes
Filters out any non-finite values before plotting. Creates a figure showing gravitational acceleration (dPsi/dr) as a function of radius with appropriate labels and grid. Units of dPsi/dr are typically (km/s)^2 / kpc.
- nsphere_plot.plot_drho_dpsi(psi_values, drho_dpsi, output_file='drho_dpsi.png')[source]
Plot derivative of density with respect to potential and save to file.
- Parameters:
psi_values (array-like) – Gravitational potential values (in km^2/s^2)
drho_dpsi (array-like) – Derivative of density with respect to potential
output_file (str, optional) – Path to save the output plot, by default “drho_dpsi.png”
- Returns:
Function does not return a value, but saves plot to the specified path
- Return type:
None
Notes
Filters out any non-finite values before plotting. Creates a figure showing the derivative of density with respect to gravitational potential with appropriate labels and grid.
- nsphere_plot.plot_energy_time(input_file, output_file)[source]
Plot energy vs. time for multiple particles, illustrating integration stability. NOTE: ‘Current’ energy uses the initial static potential for evaluation.
- Parameters:
input_file (str) – Path to the input data file containing energy data.
output_file (str) – Path to save the output plot.
- Returns:
Path to the saved plot file
- Return type:
str
Notes
The input file should contain time in the first column, followed by repeated groups of energy values (current energy evaluated with static potential, initial energy) for each particle. Loads full data.
- nsphere_plot.plot_f_of_E(E_values, f_values, output_file='f_of_E.png')[source]
Plot distribution function as a function of energy and save to file.
- Parameters:
E_values (array-like) – Energy values
f_values (array-like) – Distribution function values at each energy
output_file (str, optional) – Path to save the output plot, by default “f_of_E.png”
- Returns:
Path to the saved plot file
- Return type:
str
Notes
Filters out any non-finite values before plotting. Creates a figure showing the distribution function (f(E)) as a function of energy with appropriate labels and grid.
- nsphere_plot.plot_lowestL_trajectories_3panel(input_file='lowest_l_trajectories.dat', output_file='lowestl_3panel.png')[source]
Create a 3-panel plot showing trajectories of particles with lowest angular momentum.
- Parameters:
input_file (str, optional) – Path to the input data file containing trajectory data. Default is “lowest_l_trajectories.dat”.
output_file (str, optional) – Path to save the output plot. Default is “lowestl_3panel.png”.
- Return type:
None
Notes
The input file should have columns in the format: time r1 E1 L1 r2 E2 L2 … rN EN LN
The function creates a 3-panel plot showing: 1) Radii vs. time for each particle 2) Energies vs. time for each particle 3) Percentage deviation from average energy vs. time for each particle
- nsphere_plot.plot_mass_enclosed(r_values, mass_values, output_file='mass_enclosed.png')[source]
Plot enclosed mass as a function of radius and save to file.
- Parameters:
r_values (array-like) – Radius values in kpc
mass_values (array-like) – Enclosed mass values at each radius in Msun
output_file (str, optional) – Path to save the output plot, by default “mass_enclosed.png”
- Returns:
Path to the saved plot file
- Return type:
str
Notes
Filters out any non-finite values before plotting. Creates a figure showing the mass enclosed within each radius with appropriate labels and grid.
- nsphere_plot.plot_nsphere_histograms(suffix, progress_callback=None)[source]
Plots 2D histograms from the nsphere.c-produced binary histogram files.
Expects each file to contain 3 columns and 40000 records (reshaped to 200 × 200).
data/2d_hist_initial{suffix}.dat for the initial histogram.
data/2d_hist_final{suffix}.dat for the final histogram.
The plots are created using plt.pcolormesh and saved into the “results” folder.
- nsphere_plot.plot_particles_histograms(suffix, progress_callback=None)[source]
Plots 2D histograms from the particles files.
Reads the initial particles file: data/particles{suffix}.dat (expected 4 columns) and plots a histogram with plt.hist2d.
Reads the final particles file: data/particlesfinal{suffix}.dat (expected 4 columns); computes a derived velocity value and then plots a 2D histogram.
Resulting images are saved to the “results” folder.
- Parameters:
suffix (str) – Suffix for input/output files.
progress_callback (callable, optional) – Function to call after each plot is saved, with the output file path as argument.
- nsphere_plot.plot_psi(r_values, psi_values, output_file='psi_profile.png')[source]
Plot gravitational potential (Psi) as a function of radius and save to file.
- Parameters:
r_values (array-like) – Radius values in kpc
psi_values (array-like) – Gravitational potential values at each radius (in km^2/s^2)
output_file (str, optional) – Path to save the output plot, by default “psi_profile.png”
- Returns:
Function does not return a value, but saves plot to the specified path
- Return type:
None
Notes
Filters out any non-finite values before plotting. Creates a figure showing gravitational potential as a function of radius with appropriate labels and grid. Assumes psi_values are already scaled.
- nsphere_plot.plot_single_trajectory(input_file, output_file)[source]
Plot the orbital trajectory (radius vs time) for a single test particle.
- Parameters:
input_file (str) – Path to the input data file containing trajectory data.
output_file (str) – Path to save the output plot.
- Returns:
Path to the saved plot file
- Return type:
str
Notes
The input file should contain columns with time and radial position.
- nsphere_plot.plot_trajectories(input_file, output_file)[source]
Plot particle trajectories (radius vs time) for multiple particles.
- Parameters:
input_file (str) – Path to the input data file containing trajectory data.
output_file (str) – Path to save the output plot.
- Returns:
Path to the saved plot file
- Return type:
str
Notes
The input file should contain column groups with time and radial position for multiple particles over the simulation period.
- nsphere_plot.preprocess_phase_space_file(rank_file_data_with_suffix)[source]
Preprocess a single Rank file for phase space animation.
- Parameters:
rank_file_data_with_suffix (tuple) – Tuple containing (rank_file, placeholder, ncol, max_r_all, max_v_all, nbins, kmsec_to_kpcmyr, project_root_path, local_suffix).
- Returns:
(snap_num, H, frame_vmax) if successful or None if processing failed.
- Return type:
tuple or None
Print a footer for a section and log it if detailed logging is enabled.
- Parameters:
message (str, optional) – The footer message to display. Default is an empty string.
- nsphere_plot.print_header(title, add_newline=True)[source]
Print a consistent section header with configurable delay and log it if detailed logging is enabled.
- Parameters:
title (str) – The section title to display.
add_newline (bool, optional) – Whether to add a newline before the header. Default is True.
- nsphere_plot.print_status(message)[source]
Print a message to the console and also log it if detailed logging is enabled.
- Parameters:
message (str) – The message to print and potentially log.
- nsphere_plot.process_animation_frame(frame)[source]
Process a single animation frame for GIF output.
- Parameters:
frame (numpy.ndarray) – The frame image data
- Returns:
Processed frame ready for GIF encoding
- Return type:
numpy.ndarray
- nsphere_plot.process_particle_data(data, n_cols)[source]
Extracts key quantities and calculates total velocity.
- Parameters:
data (ndarray) – Particle data array
n_cols (int) – Number of columns in the data
- Returns:
(radius, radial_velocity, angular_momentum, total_velocity) for valid particles
- Return type:
tuple
- nsphere_plot.process_profile_plots(file_paths)[source]
Process various profile data files and generate plots.
- Parameters:
file_paths (dict) – Dictionary of file paths for various data files.
- nsphere_plot.process_rank_file(fname)[source]
Process a rank file and return the snapshot number and decimated data.
- Parameters:
fname (str) – The filename to process.
- Returns:
(snapshot_number, decimated_data) if successful or None if there was an error.
- Return type:
tuple or None
- nsphere_plot.process_rank_file_for_1d_anim(task_data_with_suffix)[source]
Processes a single sorted Rank snapshot file for 1D animations. Now accepts suffix explicitly.
Loads only the required columns (Mass, Radius, Psi, Density), sorts by radius, filters invalid data, fits linear splines to Mass, Psi and Density, performs downsampling to a common radius grid, and returns the processed data ready for animation.
- Parameters:
task_data_with_suffix (tuple) – A tuple containing (fname, project_root_path, local_suffix) where: - fname is the path to the sorted Rank data file - project_root_path is the explicit path to the project root directory - local_suffix is the suffix for file identification
- Returns:
On success, returns a tuple: (snap_num, sampled_radii, sampled_mass, sampled_density, sampled_psi) where arrays have the downsampled length. Returns None if loading, processing, or spline fitting fails.
- Return type:
tuple or None
- nsphere_plot.process_rank_files(suffix, start_snap, end_snap, step_snap)[source]
Processes sorted and unsorted Rank snapshot files using multiprocessing.
Sorted Files: Calls worker process_rank_file_for_1d_anim for each filtered sorted file. This worker loads necessary columns, uses linear interpolation/downsampling, and returns processed arrays. The results are used to populate the global mass_snapshots, density_snapshots, and psi_snapshots lists directly.
Unsorted Files: Calls worker process_unsorted_rank_file for each unsorted file. This worker uses optimized seeking to load energy data for the first few particles.
Progress is displayed using tqdm.
- Parameters:
suffix (str) – Suffix for data files.
start_snap (int) – First snapshot number to include.
end_snap (int) – Last snapshot number to include (0 means use max available).
step_snap (int) – Step size between snapshots.
- Returns:
(None, unsorted_energy_list): The first element is always None as sorted data is placed directly into global lists. The second element is a list of (snap, energy_values) tuples from unsorted files.
- Return type:
tuple
- nsphere_plot.process_single_rank_file_for_histogram(suffix)[source]
Process a single rank file (snapshot 0) for generating a histogram. This is more efficient than processing all snapshots when we only need one.
- Parameters:
suffix (str) – Suffix for input/output files.
- Returns:
The processed data from snapshot 0, or None if not available.
- Return type:
numpy.ndarray or None
- nsphere_plot.process_sorted_energy(fname)[source]
Process a rank file for energy plots. This function extracts energy values for specific particles based on their IDs.
- Parameters:
fname (str) – The filename to process.
- Returns:
(snapshot_number, energy_values) if successful or None if there was an error.
- Return type:
tuple or None
- nsphere_plot.process_sorted_energy_file(task_data)[source]
Process an unsorted rank file for energy-time plot, extracting data for specific tracked particle IDs.
- Parameters:
task_data (tuple) – A tuple containing (fname, local_suffix) where: - fname is the path to the unsorted Rank data file - local_suffix is the suffix for file identification
- Returns:
(snapshot_number, energy_data) if successful or None if there was an error.
- Return type:
tuple or None
- nsphere_plot.process_trajectory_energy_plots(file_paths, include_angular_momentum=True)[source]
Process energy plots that are part of the trajectory plots but should also be included in the energy plots category.
- Parameters:
file_paths (dict) – Dictionary of file paths for various data files.
include_angular_momentum (bool, optional) – Whether to include angular momentum plots. Default is True.
- nsphere_plot.process_trajectory_plots(file_paths)[source]
Process trajectory and diagnostic plots.
- Parameters:
file_paths (dict) – Dictionary of file paths for various data files.
- nsphere_plot.process_unsorted_rank_file(task_data_with_suffix)[source]
Process an unsorted rank file and return the snapshot number and energy values.
- Parameters:
task_data_with_suffix (tuple) – A tuple containing (fname, project_root_path, local_suffix) where: - fname is the path to the unsorted Rank data file - project_root_path is the explicit path to the project root directory - local_suffix is the suffix for file identification
- Returns:
(snapshot_number, energy_values) if successful or None if there was an error.
- Return type:
tuple or None
- nsphere_plot.process_variable_histograms(config)[source]
Generates 1D variable distribution histograms comparing initial vs final distributions. Creates histograms for radius, velocity, radial velocity, and angular momentum.
- Parameters:
config (Configuration) – The configuration object containing parsed arguments and settings.
- Returns:
True if successful, False otherwise.
- Return type:
bool
- nsphere_plot.read_lastparams(filename='data/lastparams.dat', return_suffix=True, user_suffix=None)[source]
Read parameters from lastparams.dat file.
- Parameters:
filename (str, optional) – Path to the lastparams.dat file. Default is “data/lastparams.dat”.
return_suffix (bool, optional) – If True, return a suffix string. If False, return individual parameters. Default is True.
user_suffix (str, optional) – If provided, look for lastparams_user_suffix.dat instead of lastparams.dat.
- Returns:
If return_suffix is True, returns a string like “_[filetag]_npts_Ntimes_tfinal_factor” or just “_npts_Ntimes_tfinal_factor” if no file tag is present. If return_suffix is False, returns a tuple of (npts, Ntimes, tfinal_factor, file_tag).
- Return type:
str or tuple
- nsphere_plot.render_density_frame(frame_data)[source]
Render a single frame of density profile animation. Note: Assumes density_snapshots contains 4*pi*r^2*rho.
- Parameters:
frame_data (tuple) – Tuple containing (snapshot_data, tfinal_factor, total_frames, r_max, project_root_path) where snapshot_data is the (snap, radius, density) tuple from density_snapshots.
- Returns:
Image data for the rendered frame.
- Return type:
numpy.ndarray
- nsphere_plot.render_mass_frame(frame_data)[source]
Render a single frame of mass profile animation.
- Parameters:
frame_data (tuple) – Tuple containing (snapshot_data, tfinal_factor, total_frames, r_max, project_root_path) where snapshot_data is the (snap, radius, mass) tuple from mass_snapshots.
- Returns:
Image data for the rendered frame.
- Return type:
numpy.ndarray
- nsphere_plot.render_phase_frame(frame_data)[source]
Renders a single frame for the phase space animation. This function needs to be at the module level for multiprocessing to work.
- Parameters:
frame_data (tuple) –
A tuple containing (snap_num, H, vmax, tfinal_factor, total_snapshots)
- snap_numint
The snapshot number for labeling.
- Hndarray
The 2D histogram data.
- vmaxfloat
The maximum value for the colorbar (consistent across all frames).
- tfinal_factorint
Factor relating simulation time steps to dynamical times.
- total_snapshotsint
Total number of frames/snapshots for calculating normalized time.
- Returns:
Image data for the rendered frame.
- Return type:
numpy.ndarray
- nsphere_plot.render_psi_frame(frame_data)[source]
Render a single frame of psi profile animation.
- Parameters:
frame_data (tuple) – Tuple containing (snapshot_data, tfinal_factor, total_frames, r_max, project_root_path) where snapshot_data is the (snap, radius, psi) tuple from psi_snapshots.
- Returns:
Image data for the rendered frame.
- Return type:
numpy.ndarray
- nsphere_plot.run_main()[source]
Main entry point that runs the application with the cursor hidden. Ensures cursor is always restored when the program exits.
- nsphere_plot.safe_load_and_filter(filename, dtype=<class 'numpy.float32'>)[source]
Load and filter data from file with error handling.
- Parameters:
filename (str) – Path to the file to read
dtype (numpy.dtype, optional) – Data type to use for the array, by default np.float32
- Returns:
Filtered array containing only valid data, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
This function performs three steps:
Verifies the file exists
Loads as much data as possible using load_partial_file
Filters out rows containing NaN or Inf values
Returns None with appropriate warnings if the file is missing or contains no valid data after filtering.
- nsphere_plot.safe_load_and_filter_10(filename, dtype=<class 'numpy.float32'>)[source]
Load and filter the first 10 lines from a text file.
- Parameters:
filename (str) – Path to the file to read
dtype (numpy.dtype, optional) – Data type to use for the array, by default np.float32
- Returns:
Filtered array containing only valid data from the first 10 lines, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
Similar to safe_load_and_filter but only reads the first 10 lines. Useful for analyzing the beginning of large files efficiently.
- nsphere_plot.safe_load_and_filter_10_bin(filename, ncols, dtype=<class 'numpy.float32'>)[source]
Load and filter the first 10 rows from a binary file.
- Parameters:
filename (str) – Path to the binary file to read
ncols (int) – Number of columns expected in the data
dtype (numpy.dtype or list, optional) – Data type(s) to use for the array, by default np.float32
- Returns:
Filtered array containing only valid data from the first 10 rows, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
Performs the following steps:
Checks if file exists
Loads entire binary file via load_partial_file_bin
Slices off the first 10 rows (if available)
Filters out invalid rows (NaN/Inf)
Returns the filtered array, or None if empty/no valid rows
Useful for analyzing the beginning of large binary files efficiently.
- nsphere_plot.safe_load_and_filter_bin(filename, ncols, dtype=<class 'numpy.float32'>)[source]
Load and filter binary data with support for structured arrays.
- Parameters:
filename (str) – Path to the binary file to read
ncols (int) – Number of columns expected in the data
dtype (numpy.dtype or list, optional) – Data type(s) to use for the array, by default np.float32
- Returns:
2D float array containing only valid data, or None if the file doesn’t exist or contains no valid data
- Return type:
numpy.ndarray or None
Notes
This function performs four steps:
Verifies the file exists
Loads binary data using load_partial_file_bin
Converts structured arrays to standard floating-point arrays if needed
Filters out rows containing NaN or Inf values
For structured arrays (when dtype is a list), each field is extracted and converted to float32 before filtering. This ensures consistent handling regardless of the original data types.
- nsphere_plot.safe_load_particle_ids_bin(filename, ncols, particle_ids, dtype=<class 'numpy.float32'>)[source]
Load data for specific particle IDs from a flat binary file.
Uses efficient file seeking for basic numpy dtypes (e.g., np.float32) to read only requested rows. Falls back to loading the full file via load_partial_file_bin for complex/structured dtypes.
- Parameters:
filename (str) – Path to the binary file (assumed flat row data).
ncols (int) – Number of columns per row.
particle_ids (array-like) – Array of particle IDs (0-based row indices) to extract.
dtype (numpy.dtype or list, optional) – Data type of file contents. Basic numpy dtypes trigger optimized seek-based reading. Lists/tuples trigger a full read and fallback extraction. Default is np.float32.
- Returns:
Numpy array (float32) containing only the rows for the specified particle IDs (NaNs for missing/invalid IDs), or None if file doesn’t exist or a fatal error occurs. Returns float32 array even if input dtype has different precision.
- Return type:
numpy.ndarray or None
- nsphere_plot.select_tqdm_format(desc_key, term_width)[source]
Selects tqdm description and format based on terminal width.
- nsphere_plot.setup_file_paths(suffix)[source]
Setup file paths for all data files using the given suffix.
- Parameters:
suffix (str) – The suffix to use for all file names.
- Returns:
Dictionary containing all file paths.
- Return type:
dict
- nsphere_plot.setup_global_parameters(args)[source]
Setup global parameters based on command line arguments.
- Parameters:
args (argparse.Namespace) – The parsed command line arguments.
- Returns:
The calculated parameters (suffix, start_snap, end_snap, step_snap, duration).
- Return type:
tuple
- nsphere_plot.setup_logging()[source]
Configure and initialize the logging system.
- Returns:
Configured logger instance for nsphere_plot.py
- Return type:
logging.Logger
Notes
Creates a log directory if it doesn’t exist and configures a file-based logger that writes to log/nsphere_plot.log with timestamp, log level, and message formatting.
- nsphere_plot.show_cursor()[source]
Show the terminal cursor.
Notes
Uses ANSI escape code to restore cursor visibility after it was hidden.
- nsphere_plot.show_progress_delay(delay_seconds)[source]
Display a minimal visual indicator during progress delay.
- Parameters:
delay_seconds (float) – The number of seconds to delay/pace
Notes
Shows only dots accumulating with each second, without text.
- nsphere_plot.show_section_delay(delay_seconds)[source]
Display a visual timer with dots for section transitions.
- Parameters:
delay_seconds (float) – The number of seconds to delay/pace
Notes
Shows an upward counting timer with dots accumulating each second. Displays the full delay_seconds at the end to ensure consistent timing. Allows the user to skip the delay with spacebar or pause/resume with ‘p’.
- nsphere_plot.signal_handler(sig, frame)[source]
Handle keyboard interrupts gracefully.
- Parameters:
sig (int) – Signal number
frame (frame) – Current stack frame
Notes
Restores the original signal handler to allow a forced exit with a second Ctrl+C if needed.
- nsphere_plot.start_combined_progress(section_key, total_plots)[source]
Initialize a combined progress tracker for a section of related plots.
- Parameters:
section_key (str) – Unique identifier for this plotting section
total_plots (int) – Total number of plots expected in this section
Notes
Sets up a progress tracker in the global _combined_plot_trackers dictionary to monitor progress across multiple related operations. Initializes timing information for rate calculation.
- nsphere_plot.suppress_stdout()[source]
Context manager that suppresses stdout output.
Temporarily redirects stdout to a dummy file object that discards output. Used to prevent unwanted console output during progress bar updates.
- Yields:
None – Control returns to the caller with stdout suppressed
Notes
The original stdout is always restored when leaving the context, even if an exception occurs.
Examples
>>> with suppress_stdout(): ... print("This won't be displayed")
- nsphere_plot.truncate_and_pad_string(text, fallback_width=100)[source]
Truncates a string to the terminal width and pads with spaces.
- Parameters:
text (str) – The string to potentially truncate and pad.
fallback_width (int, optional) – The width to use if terminal size can’t be determined, by default 100.
- Returns:
The string, truncated and padded with spaces to the terminal width.
- Return type:
str
- nsphere_plot.update_combined_progress(section_key, output_file)[source]
Update the combined progress tracker for a specific plot section.
- Parameters:
section_key (str) – Identifier for the plotting section
output_file (str) – Path to the plot file that was saved
- Returns:
(current, total) counts for the section, indicating progress
- Return type:
tuple
Notes
Updates the progress tracker for the specified section, increments the counter, and displays a progress bar showing completion status. Includes timing information and estimated completion time once enough data points are available.
- nsphere_plot.update_timer_energy_plots(stop_timer, energy_plot_start_time, paced_mode)[source]
Continuously update the timer display for energy plot processing.
- Parameters:
stop_timer (threading.Event) – Event to signal when to stop the timer thread
energy_plot_start_time (float) – Time when energy plot processing started
paced_mode (bool) – Whether the visualization is in paced mode (with deliberate delays)
Notes
Runs in a separate thread and updates the console with elapsed time, estimated remaining time, and processing rate. Updates every 0.1 seconds until stop_timer is set.