coseda package¶
Subpackages¶
- coseda.centerfinding package
- Submodules
- coseda.centerfinding.findcenters_beamstop module
divide_into_batches()find_friedel_pairs()fit_gaussian_to_largest_cluster()get_frame_stack_shape()get_pixels_per_meter()iterative_gaussian_fitting_on_subset()plot_batch_centers()plot_deviation_cloud()plot_linear_fit()process_batch()quartering()quartering_batch()refine_center_with_friedel()resolve_frame_dataset()set_center_based_on_batch()set_center_based_on_line_fit()update_detector_shifts()
- coseda.centerfinding.findcenters_direct module
- Module contents
- coseda.centerrefinement package
- coseda.exporters package
- coseda.ici package
- Submodules
- coseda.ici.build_early_break_from_log module
- coseda.ici.build_overlays_and_list module
- coseda.ici.create_run_sh module
- coseda.ici.evaluate_stream module
- coseda.ici.extract_mille_shifts module
- coseda.ici.fix_stream_paths module
- coseda.ici.no_run_prep_singlelist module
- coseda.ici.orchestrator module
- coseda.ici.overlay_elink module
- coseda.ici.propose_next_shifts module
- coseda.ici.run_contract module
- coseda.ici.run_sh module
- coseda.ici.step1_hillmap_wrmsd module
- coseda.ici.step2_dxdy module
- coseda.ici.summarize_image_run_log module
- coseda.ici.update_image_run_log_grouped module
- Module contents
- coseda.importers package
- Submodules
- coseda.importers.convert_dm4 module
- coseda.importers.gatan_metareader module
- coseda.importers.h5convert module
- coseda.importers.import_h5 module
- coseda.importers.import_mrc module
- coseda.importers.import_tiff module
- coseda.importers.import_velox module
add_intesities_batch()calculate_mean_intensities()calculate_mean_intensities_chunked()calculate_total_intensities()calculate_total_intensities_chunked()decode_column()export_hdf5_images_to_tiff()extract_instrument_data()extract_pos_data()extract_stage_pos()find_dataset_paths()find_path_in_h5()get_image_mode()plot_4Dstem()plot_crystamorphus()refine_stagepos_x()remap_framestack()save_4Dstem()velox_batch()velox_process()velox_true_conversion()write_stage_pos_to_hdf5()
- Module contents
- coseda.initialize package
- Submodules
- coseda.initialize.insfiles module
- coseda.initialize.project_files module
- coseda.initialize.settings module
- Module contents
config_to_paths()create_insfiles()create_insfiles_emd()create_insfiles_gatan()create_plain_insfile()find_configfiles()generate_parent_ini_file()get_parent_ini_file()handle_input()is_parent_config_file()log_result()log_start()parse_config()read_config()resume_processing()shoutout()write_centerfindersettings()write_centerrefinementsettings()write_gandalfiteratorsettings()write_h5conversionsettings()write_icisettings()write_index_file()write_mergingsettings()write_peakfindersettings()write_stripsettings()write_xgandalfsettings()
- coseda.map package
- Submodules
- coseda.map.findscanlines module
compare_strokes()cross_correlate_lines()find_closest_minimum()find_closest_stroke()find_line_breaks()find_strokes_by_xpos()find_strokes_by_ypos()get_line_bounds_from_index()get_three_line_bounds()moving_average()plot_correlation()plot_line_profiles()plot_stagepos_y_with_breaks()plot_stagepos_y_with_breaks_debug()write_combined_stroke_info()
- coseda.map.mapping module
Diskare_touching()cluster_segments()distance()find_clusters()find_matrix()find_seeds()find_touching_disks()get_line_bounds()has_common_angle()interlacecorrection()linearize_map()plot_clusters()plot_crystamorphusvac()plot_crystamorphusvac_overlap()plot_map_peaks()plot_nPeaks_histogram()refine_clusters()write_cluster_ids()
- coseda.map.streaks module
- Module contents
- coseda.nexus package
- coseda.peakfinding package
- coseda.pipeline package
Submodules¶
coseda.crystfel_cell module¶
CrystFEL unit-cell naming helpers.
coseda.dask_client_manager module¶
Singleton-style helpers to start/reuse Dask clusters for COSEDA tasks.
- class coseda.dask_client_manager.DaskClientManager[source]¶
Bases:
objectCreate or reuse a LocalCluster, honoring optional override scheduler addresses.
- classmethod close_client()[source]¶
Close the active client handle (does not kill external clusters).
- classmethod get_client()[source]¶
Return the singleton Dask client, preferring reuse over new clusters.
Preference order: 1) explicit override address 2) existing scheduler file in temp dir 3) brand new LocalCluster
If an existing client reports zero workers, it is discarded and rebuilt.
- classmethod get_client_info()[source]¶
Return dashboard URL, worker count, threads per worker, and memory per worker.
- classmethod kill_all_dask_clusters()[source]¶
Terminate all local Dask worker/scheduler processes (last resort).
- classmethod kill_current_cluster()[source]¶
Gracefully shutdown the current Dask cluster via the client API and clean up.
Removes any persisted scheduler file so the next run does not attempt to reuse a stale cluster.
- classmethod log_client_info(logfile_path)[source]¶
Log current worker counts, thread counts, and memory per worker to a logfile.
If no client is running, writes a short note instead of raising.
- classmethod set_scheduler_address(address)[source]¶
Force all new Dask connections to use this scheduler address.
Useful when pointing the UI/CLI to a remote or pre-existing cluster instead of spawning a LocalCluster.
- Parameters:
address (str)
- temp_dir = '/tmp'¶
coseda.detector_geometry module¶
Helpers to parse and apply optional detector panel geometry.
- coseda.detector_geometry.corrected_to_raw(corrected_xy, geometry, panel_hint=None)[source]¶
Map one corrected coordinate back to raw coordinates.
- Parameters:
corrected_xy (Sequence[float])
geometry (dict | None)
panel_hint (str | None)
- Return type:
Tuple[numpy.ndarray, str | None]
- coseda.detector_geometry.corrected_to_raw_points(corrected_points, geometry, panel_hints=None)[source]¶
Map N corrected points back to raw coordinates.
- Parameters:
corrected_points (numpy.ndarray)
geometry (dict | None)
panel_hints (Sequence[str | None] | None)
- Return type:
Tuple[numpy.ndarray, List[str | None]]
- coseda.detector_geometry.load_detector_geometry(config)[source]¶
Parse optional [DetectorGeometry] section from a ConfigParser.
- Return type:
dict | None
- coseda.detector_geometry.raw_to_corrected(raw_xy, geometry, panel_hint=None)[source]¶
Map one raw coordinate to corrected coordinates.
- Parameters:
raw_xy (Sequence[float])
geometry (dict | None)
panel_hint (str | None)
- Return type:
Tuple[numpy.ndarray, str | None]
coseda.export module¶
- coseda.export.hkl2mtz(input_hkl, output_dir, cellfile_path)[source]¶
Convert a .hkl file to .mtz using get_hkl. All outputs (MTZ, logs) will be written into a new export_<timestamp> folder under output_dir.
- Parameters:
input_hkl (str) – Path to the input CrystFEL .hkl file (absolute or relative).
output_dir (str) – Directory under which to create export_<timestamp> folder.
cellfile_path (str) – Path to the cell file (.cell or .inp) for get_hkl (absolute or relative).
coseda.geomfile module¶
- coseda.geomfile.build_geomfile_from_ini(ini_path)[source]¶
Build a dictionary of geometry file parameters from an ini file. Returns a tuple (geomfile_dict, missing_values).
- coseda.geomfile.write_geomfile(output_path, wavelength, adu_per_photon, clen, res, data, dim0, dim1, dim2, peak_list, peak_list_type, detector_shift_x, detector_shift_y, min_ss, max_ss, min_fs, max_fs, corner_x, corner_y, fs_axis, ss_axis, mask, mask_file, mask_good, mask_bad)[source]¶
Write a CrystFEL-style geometry file with the specified parameters.
coseda.indexintegrate module¶
coseda.io module¶
Shared INI/path helpers used across the COSEDA pipeline.
- coseda.io.config_to_paths(configfile)[source]¶
Given the path to a .ini configfile, determine and return: outputfolder, outputfolder_path, logfile, logfile_path, h5file, h5file_path
- Path A: if <basename>.h5 exists in the same directory as the .ini:
outputfolder: basename of the ini (without extension)
outputfolder_path: same directory as ini
logfile: <basename>.log
logfile_path: same directory as ini
h5file: <basename>.h5
h5file_path: same directory as ini
- Path B: otherwise, read the [Paths] section of the INI:
outputfolder: config.get(‘Paths’,’outputfolder’)
outputfolder_path: parent_dir/outputfolder
logfile: config.get(‘Paths’,’logfile’)
logfile_path: parent_dir/logfile
h5file: config.get(‘Paths’,’h5file’)
h5file_path: outputfolder_path/h5file
- Parameters:
configfile (str)
- coseda.io.get_dir_size(directory)[source]¶
Calculate total size of a directory tree, skipping symlinks.
- coseda.io.get_free_space_windows(path)[source]¶
Return available bytes for a Windows path via GetDiskFreeSpaceEx.
- coseda.io.handle_input(input_path)[source]¶
Normalize user input (folder, INI file, or list of INIs) into child INI paths.
Rejects hidden files and parent configs
Enforces a single directory when a list is provided
Returns (configfiles, base_path) where base_path is the containing folder
Raises ValueError when the input is invalid or yields no child INIs.
- coseda.io.is_parent_config_file(file_path)[source]¶
Return True if the INI declares [General] config_type = parent.
- coseda.io.parse_config(configfile)[source]¶
Parse an INI file (UTF-8 with latin-1 fallback) and resolve common paths.
Returns: (config, outputfolder, originalfile, logfile, path, outputfolder_path, originalfile_path, logfile_path, framepath, h5file, h5file_path)
coseda.logging_utils module¶
Logging helpers for consistent stdout formatting.
- coseda.logging_utils.configure_logging(level=None)[source]¶
Configure the root COSEDA logger once.
- Parameters:
level (str | None)
- Return type:
None
- coseda.logging_utils.get_logger(name=None)[source]¶
Return a configured logger for the given module or the root COSEDA logger.
- Parameters:
name (str | None)
- Return type:
Logger
- coseda.logging_utils.log_print(*args, sep=' ', end='', file=None, flush=False, level=None)[source]¶
Drop-in replacement for print() that routes through the COSEDA logger.
level can be one of: “debug”, “info”, “warning”, “error”.
- Parameters:
sep (str)
end (str)
flush (bool)
level (str | None)
- coseda.logging_utils.log_result(logfile_path, message, error)[source]¶
Log a success or failure message to stdout and, when available, to the logfile.
coseda.merge module¶
coseda.pixmask module¶
- coseda.pixmask.generate_full_mask(shape)[source]¶
Generate a binary mask with all pixels valid (1) for a given 2D shape.
Parameters: shape : tuple of (height, width)
The dimensions of the mask to create.
Returns: mask : np.ndarray of uint8
2D array of ones with the specified shape.
- Parameters:
shape (Tuple[int, int])
- Return type:
numpy.ndarray
- coseda.pixmask.generate_full_mask_hdf5(hdf5_path, image_dataset='entry/data/images', mask_dataset='mask')[source]¶
Inspect the given HDF5 file, read the shape of the specified 2D image stack dataset, generate a full-valid (all ones) mask of the same [height, width], and save it to the file. Overwrites any existing mask dataset at mask_dataset.
- Parameters:
hdf5_path (Path) – Path Path to the HDF5 file containing the image stack.
image_dataset (str) – str Name of the dataset in the HDF5 file that contains the image stack (expected shape: (n_frames, height, width) or (height, width)).
mask_dataset (str) – str Name of the dataset under which to store the generated mask.
- Return type:
None
- coseda.pixmask.generate_mask(image_path, threshold=127)[source]¶
Load an image (BMP, PNG, JPG), convert to grayscale, and create a binary mask: valid pixels (above threshold) -> 1, invalid (at or below threshold) -> 0 Returns the grayscale and mask arrays.
- Parameters:
image_path (Path)
threshold (int)
- Return type:
(numpy.ndarray, numpy.ndarray)
- coseda.pixmask.load_mask_hdf5(hdf5_path)[source]¶
Load the mask dataset from HDF5 file (NeXus path preferred).
- Parameters:
hdf5_path (Path)
- Return type:
numpy.ndarray
- coseda.pixmask.plot_comparison(gray, mask)[source]¶
Display original grayscale image and mask side by side for debugging.
- Parameters:
gray (numpy.ndarray)
mask (numpy.ndarray)
- coseda.pixmask.remove_mask_hdf5(hdf5_path, dataset='mask')[source]¶
Remove the specified mask dataset from the HDF5 file. If the dataset does not exist, no error is raised.
- Parameters:
hdf5_path (Path)
dataset (str)
- coseda.pixmask.save_mask_hdf5(mask, hdf5_path, dataset='mask')[source]¶
Add (or overwrite) a mask array in an existing HDF5 file under dataset. - If the file doesn’t exist, it will be created. - If the dataset already exists, only that dataset is replaced.
- Parameters:
mask (numpy.ndarray)
hdf5_path (Path)
dataset (str)
coseda.unitcell_fit module¶
Workspace unit-cell histogram aggregation and Gaussian fitting helpers.
- class coseda.unitcell_fit.WorkspaceStreamSource(ini_path: 'str', run_dir: 'str', stream_path: 'str', cell_path: 'str')[source]¶
Bases:
object- Parameters:
ini_path (str)
run_dir (str)
stream_path (str)
cell_path (str)
- cell_path: str¶
- ini_path: str¶
- run_dir: str¶
- stream_path: str¶
- coseda.unitcell_fit.discover_workspace_unit_cell_streams(ini_paths)[source]¶
Discover one usable unit-cell stream per workspace INI.
The newest run folder with an existing stream is selected for each INI, matching the indexing UI’s “latest run per file” behavior.
- Parameters:
ini_paths (Iterable[str])
- Return type:
list[WorkspaceStreamSource]
- coseda.unitcell_fit.fit_gaussian_to_values(values, value_range, bins=60)[source]¶
Fit a Gaussian to unit-cell values inside
value_range.- Parameters:
value_range (tuple[float, float])
bins (int)
- Return type:
dict
- coseda.unitcell_fit.parse_workspace_cell(path)[source]¶
Return workspace cell header values, including
Cell.*keys.- Parameters:
path (str)
- Return type:
dict[str, str]
- coseda.unitcell_fit.resolve_stream_path_for_run(run_dir)[source]¶
Resolve the best stream path for a simple indexamajig or ICI run.
- Parameters:
run_dir (str)
- Return type:
str | None
- coseda.unitcell_fit.run_base_candidates_for_ini(ini_path)[source]¶
Return plausible folders containing indexing runs for a workspace INI.
- Parameters:
ini_path (str)
- Return type:
list[str]
- coseda.unitcell_fit.update_cell_file_parameter(cell_path, param, value)[source]¶
Update one CrystFEL cell parameter in-place, preserving the line suffix.
- Parameters:
cell_path (str)
param (str)
value (float)
- Return type:
bool
- coseda.unitcell_fit.update_workspace_refined_cell_parameter(workspace_path, param, value)[source]¶
Update one fitted cell parameter in the workspace header and mark it refined.
- Parameters:
workspace_path (str)
param (str)
value (float)
- Return type:
bool
- coseda.unitcell_fit.workspace_has_refined_cell(path)[source]¶
- Parameters:
path (str)
- Return type:
bool