coseda package

Subpackages

Submodules

coseda.crystfel_cell module

CrystFEL unit-cell naming helpers.

coseda.crystfel_cell.crystfel_unique_axis_allowed(lattice_type)[source]

Return whether CrystFEL accepts unique_axis for this lattice type.

coseda.crystfel_cell.normalize_crystfel_lattice_type(lattice_type, centering='')[source]

Return a CrystFEL-accepted lattice_type value.

coseda.dask_client_manager module

Singleton-style helpers to start/reuse Dask clusters for COSEDA tasks.

class coseda.dask_client_manager.DaskClientManager[source]

Bases: object

Create 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.detector_geometry.raw_to_corrected_points(raw_points, geometry)[source]

Map N raw points to corrected coordinates.

Parameters:
  • raw_points (numpy.ndarray)

  • geometry (dict | None)

Return type:

Tuple[numpy.ndarray, List[str | None]]

coseda.detector_geometry.validate_geometry_for_frame(geometry, frame_size_x, frame_size_y)[source]

Validate detector geometry against actual frame shape.

Returns (errors, warnings).

Parameters:
  • geometry (dict | None)

  • frame_size_x (int)

  • frame_size_y (int)

Return type:

Tuple[List[str], List[str]]

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.indexintegrate.run_index_and_integrate(geom_file, list_file, output_stream, threads, cell_file, push_res, integration_mode, int_radius, min_peaks, xgandalf_tolerance, xgandalf_pitch, xgandalf_min_len, xgandalf_max_len, xgandalf_iter, tolerance, profile_radius, use_cell=True)[source]

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_unix(path)[source]

Return available bytes for a Unix path via statvfs.

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.io.read_config(configfile)[source]

Read an INI file and return the ConfigParser, tolerating legacy encodings.

Attempts UTF-8 first, then falls back to latin-1 so older datasets do not fail early when metadata contains non-UTF characters.

coseda.io.update_paths_old(configfile_path)[source]

Legacy helper to rebuild logfile path from an INI location and [Paths].

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.logging_utils.log_start(logfile_path, message)[source]

Print a message and append it (timestamped) to the logfile if a path is provided.

coseda.logging_utils.shoutout(configfile_path)[source]

Print which config file is being processed (tiny UX helper for loops).

coseda.merge module

coseda.merge.parse_scaling_file(input_filepath, output_filepath)[source]

Parse the scaling/refinement log output from partialator and save a CSV summary.

coseda.merge.run_merging(input_path)[source]

Read merging parameters from the INI file and execute partialator merging. If ‘merging_threads’ is not set, defaults to the number of available CPU cores.

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.gaussian_curve(x, amplitude, mean, sigma, baseline)[source]
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

coseda.unitcell_fit.workspace_refined_cell_file_path(workspace_path)[source]
Parameters:

workspace_path (str)

Return type:

str

coseda.unitcell_fit.write_workspace_refined_cell_file(workspace_path)[source]

Materialize the refined workspace cell header into a CrystFEL .cell file.

Parameters:

workspace_path (str)

Return type:

str | None

Module contents