kromatography.utils package



kromatography.utils.api module

API functions and classes for the Reveal Chromatography UTILS sub-package.


Initialize all Reveal application tools: logging and unit parsers.

kromatography.utils.app_utils module

exception kromatography.utils.app_utils.ProEditionOnlyError[source]

Bases: exceptions.RuntimeError


Collect the version of git hash for the cadet-cs currently set in preferences.


Returns the username as provided by the OS. Returns a constant if it fails.


Add custom units defined in this package to the unit parser.


Returns a minimal ArgumentParser instance for a generic script.

kromatography.utils.app_utils.initialize_logging(prefix='krom_app', **kwargs)[source]

Set up logging for an analysis script, with a console handler and optionally a file handler.

Set :arg:`verbose` to True to get DEBUG level logging calls. Pass a :arg:`prefix` string to create a log file in addition to the console logging. For more documentation on optional arguments, see app_common.logging.base_initialize_logging()


Scratch folder for solver executor temp files (like SLURM files).

kromatography.utils.app_utils.get_preferences(filename=None, fileloc=None)[source]

Load from file and return the current Reveal preference object.

kromatography.utils.app_utils.get_preference_file(filename=None, fileloc=None)[source]

Returns the path to the preference file, optionally overriding its name or location.


Make sure the default preference file is created/updated.


Returns the directory to create log files in.


Returns the directory to create datasource files in.


Returns the directory to create python script files in.


Returns the directory to create CADET input files in.


Returns the directory to store the updater files.


Create the directory for updater files if it doesn’t already exists.


Create the cadet input folder if it doesn’t already exists.

Returns:Returns True if the folder already exists or was successfully created.
Return type:bool

Delete all CADET input files.


Delete all Reveal Chromatography log files.

kromatography.utils.app_utils.launch_app_for_study(study, **kwargs)[source]

Create an application object around a study and run it.

This can be useful for scripting or testing purposes: it allows anyone to create a custom study, and launch the application afterwards, to avoid having to click a lot.

  • study (Study) – Study to build the application around.
  • kwargs (dict) – Additional attributes of the KromatographyApp object being created.

Build a file path that the user can write to for storing the user datasource in a local, file based database.

kromatography.utils.app_utils.get_newest_app_file(dir_to_search='', prefix='user_datasource', extension='.chromds')[source]

Returns the absolute path to the most recent file of type specified.

Files considered must:
  1. be in the standard folder for the type requested.
  2. start with the prefix of the type requested
  3. have the right file extension of the type requested
  • str or None (absolute path to the newest file from the directory specified)
  • or the default directory as specified by the utilities in this folder.
  • Returns None if no file is found or if the directory to search doesn’t
  • exist.

Load or build the default user datasource.

If a datasource was stored in the default, location, load the newest one. Otherwise, build a new SimpleDataSource.

  • tuple with a SimpleDatasource instance and the file if any that it was
  • loaded from.
kromatography.utils.app_utils.save_user_datasource_to(ds, filepath=None)[source]

Export the provided datasource to specified file path.

If the filepath is left blank, the datasource is stored in the app’s DS folder and the provided datasource becomes the application’s default.


Returns the content of the bug report dialog.


Returns the name of the bin folder in the python distro for current platform.


Returns the path to the bin directory of the active python.

kromatography.utils.assertion_utils module

Utilities providing new custom assertions to support unit tests.

kromatography.utils.assertion_utils.assert_roundtrip_identical(obj, ignore=(), eps=1e-09)[source]

Serialize and deserialize an object and assert that the resulting object is identical to the input object.

Returns:Object serialized and recreated is returned if user needs to run additional tests.
Return type:Any
kromatography.utils.assertion_utils.assert_file_roundtrip_identical(obj, ignore=(), eps=1e-09, target_dir=None)[source]

Serialize and deserialize an object to file and assert that the resulting object is identical to the input object.

Returns:Object serialized and recreated is returned if user needs to run additional tests.
Return type:Any

kromatography.utils.build_splash module

Script to build a new splash screen image based on the current version of the Kromatography application.

kromatography.utils.build_splash.build_splash(img_path, target_filepath, edition='Professional')[source]

Generate a new splash screen for the Kromatography application.

  • img_path (str) – Path to the images/ folder with all logos and resources.
  • target_filepath (str) – Path to the file to create.
kromatography.utils.build_splash.compute_x_to_center(img, full_width)[source]

Computes the position of an image to be centered.

  • img (Image) – image object to paste centered
  • full_width (Int) – Size of the screen to paste into.


Return type:

x position to paste the image.

kromatography.utils.cadet_simulation_builder module

Utility module to build CADET models from Simulation data.


Builds a valid CADETModel and CADETInput from the given Simulation.

Note: sections and steps mean the same thing in the CADET and the experimental language respectively.

Parameters:simulation (Simulation) – Simulation for which to build the CADET input file.
Returns:Valid CADET input object that can be serialized to HDF5 and run by CADET.
Return type:CADETInput

kromatography.utils.chromatography_units module

kromatography.utils.chromatography_units.convert_g_per_liter_resin_to_cv(unitted_data, **kwargs)[source]

To convert to volume in CV, divide by the product concentration in g/L.

kromatography.utils.chromatography_units.convert_cv_to_g_per_liter_resin(unitted_data, **kwargs)[source]

To convert to volume in g/L, multiply by product concentration in CV.

kromatography.utils.chromatography_units.convert_units(unitted_data, tgt_unit, **kwargs)[source]

Convert unitted data to the units specified by tgt_unit.

  • unitted_data (UnitScalar or UnitArray) – The data to be converted to tgt_unit
  • tgt_unit (scimath.unit or str) – The target units for unitted_data.
  • kwargs (dict) – Additional arguments that may be needed by custom converters for special units.

The converted data.

Return type:

UnitScalar or UnitArray

kromatography.utils.datasource_utils module

class kromatography.utils.datasource_utils.BaseEntryCreator[source]

Bases: traits.has_traits.HasStrictTraits

Generic object to request, create and add a new datasource entry to the datasource object_catalog dict. This might require to have access to the study to pull data like the chosen product or the user datasource. It might also request to select a product if not already set.

datasource = Any

Datsource being contributed to

datasource_key = Str

Type of object being contributed

data = Property

List of objects being contributed to

factory = Callable

Function that should be invoked to display a GUI model builder.

factory_input = Any

What the model factories need as their main input.

class kromatography.utils.datasource_utils.StudyDataSourceEntryCreator[source]

Bases: kromatography.utils.datasource_utils.BaseEntryCreator

Object to request, create and add a new datasource entry to a study datasource object_catalog dict.

study = Any

Study containing the datasource being contributed to.

datasource = Property(depends_on='study')

Datasource being contributed to

class kromatography.utils.datasource_utils.UserDataSourceEntryCreator[source]

Bases: kromatography.utils.datasource_utils.BaseEntryCreator

Object to request, create and add a new datasource entry to a SimpleDatasource object_catalog dict.


Adds a factory object to add to each entry of a study datasource.


Adds a factory object to add to each entry of a user datasource.

kromatography.utils.extra_file_dialogs module

kromatography.utils.has_traits_utils module

kromatography.utils.has_traits_utils.search_parameters_in_sim(sim, exclude=None, name_filter=None)[source]

Search for parameters that can be scanned in provided simulation.

  • sim (Simulation) – Simulation to search for Parameter type attributes in.
  • exclude (list [OPTIONAL, default=("source_experiment", "output")]) – List of simulation attributes to ignore.
  • name_filter (str [OPTIONAL, default=None]) – Text that all parameters returned should contain. Leave blank to see all parameters.


TODO: Add a caching for parameters so the same list doesn’t get re-computed every time.

kromatography.utils.io_utils module

HDF5 utilities to write and read HDF5 files for CADET runs.


Build a dictionary describing the state of the trait_object to be stored in the CADET HDF5 input file.


Return sanitized data for writing to H5.

kromatography.utils.io_utils.write_trait_obj(h5_grp, trait_obj)[source]

Write Traits object recursively in an HDF5 group.

kromatography.utils.io_utils.write_to_h5(filename, trait_obj, root='/', overwrite=False)[source]

Write a HasStrictTraits object into a H5 file.

NOTE: This function is not meant to be full fledged serialization utility and does not try to preserve metadata/version/class information.

  • filename (file path) – The filename for the output h5 file.
  • trait_obj (instance(HasStrictTraits)) – The traits object that needs to be written to the file.
  • root (posix path) – The h5 group under which the attributes of trait_obj are written.
  • FIXME (Move to ets_future?) –
kromatography.utils.io_utils.read_from_h5(filename, root='/')[source]

Read in all datasets from H5 file into a dictionary, mapping values to their node name.

FIXME: create a hastraits object. FIXME: Move to ets_future?


Display nodes directly in root and list their content.

kromatography.utils.license_manager module

License manager module. Define a license key and a license manager classes.

class kromatography.utils.license_manager.LicenseManager(key=None, **traits)[source]

Bases: app_common.apptools.license_manager.LicenseManager


Utility to validate a license key.

If there is no license file, a new key will be requested by a UI.

Returns:Whether the license found is valid, and which version it is.
Return type:bool
kromatography.utils.license_manager.generate_license_key(start_date, stop_date, username='', salt='default')[source]

Returns valid license key (string) to be used when prompted by the app.

The last use date will be the start date.

  • start_date (str or datetime) – Date in the format set by DATE_FORMAT for the license to start working.
  • stop_date (str or datetime) – Date in the format set by DATE_FORMAT for the license to stop working.

kromatography.utils.preference_utils module

Modifications of old preference versions which aren’t done automatically.


kromatography.utils.preferences module

Module to initialize and update application preferences.


Returns an absolute path on the current system where the current user should have write rights.

Note: Tested on Windows 7, Windows 10 and OSX.

class kromatography.utils.preferences.UIPreferenceGroup[source]

Bases: app_common.apptools.preferences.BasePreferenceGroup

Storage for UI related preferences.

app_width = Int(1200)

Default width of application’s main window

app_height = Int(1000)

Default height of application’s main window

confirm_on_window_close = Bool(True)

Should ask user confirmation everytime she/he closes a window?

auto_close_empty_windows_on_open = Bool(True)

Automatically close empty windows when opening a new one?

remember_layout = Bool

Store the pane layout to file and remember at next launch

class kromatography.utils.preferences.AppPreferenceGroup[source]

Bases: app_common.apptools.preferences.BasePreferenceGroup

Storage for Application related preferences.

console_logging_level = Int(30)

Level of details in the console logging. DEBUG=10, INFO=20, WARNING=30

log_folder = Directory

Location for storing all log files

user_ds_folder = Directory

Location for storing all user datasource files

python_script_folder = Directory

Location for storing all python script files

class kromatography.utils.preferences.FilePreferenceGroup[source]

Bases: app_common.apptools.preferences.BasePreferenceGroup

recent_files = List(Str)

List of recent files loaded by the user

max_recent_files = Int(20)

Max number of recent files to remember

exp_importer_mass_threshold = Range(low=0.0, high=1.0, value=0.02)

Relative different in loaded mass beyond which warning is issued

class kromatography.utils.preferences.OptimizerPreferenceGroup[source]

Bases: app_common.apptools.preferences.BasePreferenceGroup

Storage for explorer and optimizer related preferences.

optimizer_step_chunk_size = Int(100)

Max size of optimizer step groups

class kromatography.utils.preferences.SolverPreferenceGroup[source]

Bases: app_common.apptools.preferences.BasePreferenceGroup

Storage for solver related preferences.

solver_binary_path = File

Path (or name) to the solver executable to use

executor_num_worker = Int

Number of max worker processes to run simulation grids on. 0=all CPUs.

auto_delete_solver_files_on_exit = Bool(True)

Clean up solver input files when exiting?

cadet_num_threads = PositiveInt(1, exclude_low=True)

CADET allows to run 1 simulation using multiple openMP threads

use_slurm_scheduler = Bool

Wrap solver execution with SLURM scheduling?

slurm_binary = File('sbatch')

Slurm scheduler batch run command

slurm_partition = Str

SLURM Partition to run the solver on

slurm_job_name = Str('slurm_chrom_solver')

Name of the SLURM jobs submitted when running the solver

class kromatography.utils.preferences.RevealChromatographyPreferences[source]

Bases: app_common.apptools.preferences.BasePreferences

Drive the loading and saving of preferences for Reveal app to/from file


Reset preferences by overwriting preference file with current defaults.

kromatography.utils.simulation_utils module


Calculate all step start times and stop time of the last step in min from the beginning of the method.

Parameters:sim (_BaseExperiment (Experiment or Simulation)) – Experiment-like object containing the method to analyze.
Returns:Start times for all steps and stop time of last step in minutes.
Return type:UnitArray

kromatography.utils.solution_with_product_utils module

class kromatography.utils.solution_with_product_utils.ProductAssay[source]

Bases: traits.has_traits.HasStrictTraits

Proxy class to adapt a list of product assays and their proportions to a table editor

name = Str

Name of assay

proportion = Instance(UnitScalar)

Proportion of the assay in the product in %


Build a table editor to display a list of product assays.

Parameters:known_assays_names (list(str)) – List of assay names available, if wanting to allow users to add assays.
class kromatography.utils.solution_with_product_utils.ChemicalComponent(**traits)[source]

Bases: kromatography.model.component.Component

Proxy class to adapt a list of chemical components and their concentrations to a table editor


Build a table editor to display a list of chemical components.

kromatography.utils.str_utils module

Utilities to manipulate strings, convert them, identify them, ...

kromatography.utils.str_utils.is_string_valid_variable_name(name, bad_char='', bad_values=())[source]

Returns whether :arg:`name` is a valid variable name.

  • name (str) – Name to be tested.
  • bad_char (str or iterable of str) – Iterable of characters to be treated as bad characters. If name contains any of them, it will be deemed invalid.
  • bad_values (Iterable of strings) – List of string values that name shouldn’t be in to be deemed valid.

Whether the name is valid.

Return type:



Return the type (str or float) for input string data.

kromatography.utils.str_utils.str_list_mostly_float(str_list, limit=None)[source]

Are most of the fields (half or more) floating point values?


Truncate the provided list removing all empty strings at its end.

kromatography.utils.string_definitions module

kromatography.utils.testing_utils module

Utilities to implement unit tests


Returns path containing plot example data for testing.


Returns the full path of the plot test data file named filename.


Returns the path containing model data files used in testing.


Returns the full path of the model test data file named filename.


Returns the path containing IO data files used in testing.


Returns the full path of the IO test data file named filename.


Load a default experiment and already run simulation.

DEPRECATED: use kromatography.model.tests.sample_data_factories.make_sample_experiment2 instead.


Loads a study with two experiments and sims already ran.

DEPRECATED: use kromatography.model.tests.sample_data_factories.make_sample_study instead.

kromatography.utils.trait_object_to_tree_node module

class kromatography.utils.trait_object_to_tree_node.TraitListObjectToTreeNode(adaptee, **traits)[source]

Bases: app_common.traitsui.adapters.trait_object_to_tree_node.TraitListObjectToTreeNode

Adapts a list of objects to an ITreeNode.

This class implements the ITreeNodeAdapter interface thus allowing the use of TreeEditor for viewing any TraitList.

kromatography.utils.traitsui_utils module

class kromatography.utils.traitsui_utils.NoAutoTextEditor(*args, **traits)[source]

Bases: traitsui.editors.text_editor.ToolkitEditorFactory

class kromatography.utils.traitsui_utils.SimpleArrayAdapter[source]

Bases: traitsui.tabular_adapter.TabularAdapter

Adapter to display a 2D array or list of 1D arrays in a TabularEditor.

class kromatography.utils.traitsui_utils.ArrayAdapterEvent[source]

Bases: traits.has_traits.HasStrictTraits

Class to describe an event emitted by a Tabular View

class kromatography.utils.traitsui_utils.SimpleNotifyingArrayAdapter[source]

Bases: kromatography.utils.traitsui_utils.SimpleArrayAdapter

ArrayAdapter which emits an event when a value is modified.

This is useful because we cannot listen to changes to an array, but might want to do things when that array is changed. A common use case would be when that array is proxy-ing other objects and these objects need to be updated when the proxy is updated.

set_text(object, trait, row, column, text)[source]
kromatography.utils.traitsui_utils.build_array_adapter(index_name='Index', column_names=1, row_names=None)[source]

Build a SimpleNotifyingArrayAdapter from the row and column names.

  • column_names (int or list of str) – List of column names or number of column names to auto-generate.
  • index_name (str (Optional)) – Name of the index column.

Returns node information for the first element of a list displayed with a TreeEditor.


Returns node information for a list displayed with a TreeEditor.


Returns the TreeEditor of a ui containing just that editor.

kromatography.utils.traitsui_utils.get_group_items(node_adapter, obj)[source]

Collect the menu groups found in a node.

kromatography.utils.traitsui_utils.prompt_for_new_name(obj, msg='', kind='modal')[source]

Utility to prompt a user to change a name.

  • obj (any) – Object to edit the name of.
  • msg (str [OPTIONAL]) – Optional message to display in the UI to explain what to do, or why doing it for example.
  • kind (None or str) – Kind of the dialog. Set to None to make it non-blocking. Useful for testing purposes.

New name selected in the NameEditor if any, or None if the dialog was cancelled.

Return type:

str or None

kromatography.utils.units_utils module

Utilities around unit conversion and unit management.


Returns a UnitArray given a list of UnitScalars.

FIXME: replace raising an exception by doing a value conversion.


Convert a UnitArray to a list of UnitScalars.

kromatography.utils.units_utils.vol_to_time(volume, flow_rate, column=None, to_unit='minute')[source]

Convert a volume to a time, using a flow rate.

  • volume (UnitScalar) – Volume to convert to a time.
  • flow_rate (UnitScalar) – Flow rate used to convert a volume to a time.
  • column (Column [OPTIONAL]) – Column the volume is flowing through. From that object are read the diameter and colume of the column for unit conversion if needed.
  • to_unit (str [OPTIONAL, default: minutes]) – Target time unit. Must be parsable by scimath’s unit parser.

Value of the time needed for the provided volume to flow through the column.

Return type:


kromatography.utils.units_utils.volume_to_depth(volume, column, to_unit='meters')[source]

Translate a volume of fluid into a depth in infinitely long column.

kromatography.utils.units_utils.time_to_volume(time, flow_rate, column=None, to_unit='CV')[source]

Convert a flow time to a volume, assuming a specified flow rate.

  • time (UnitScalar) – Time of flow.
  • flow_rate (UnitScalar) – Flow rate.
  • column (Column [OPTIONAL]) – Column in which the flow occur. Only needed if providing linear flow rate, or if the output unit must be CV.
  • to_unit (str) – String representation of the output unit.

Volume that flowed during the specified time.

Return type:



Test whether a flow rate (UnitScalar) has a unit of a volume per time.


Test whether a flow rate (UnitScalar) has a unit of a volume per time.

kromatography.utils.units_utils.linear_flow_rate_to_volumetric(linear_flow_rate, diam, to_unit='')[source]

Convert a linear flow rate in a column of diameter diam to a volumetric flow rate.

kromatography.utils.units_utils.volumetric_flow_rate_to_linear(vol_flow_rate, diam, to_unit='')[source]

Convert a linear flow rate in a column of diameter diam to a volumetric flow rate.

kromatography.utils.units_utils.volumetric_CV_flow_rate_to_volumetric_flow_rate(vol_cv_flow_rate, column, to_unit=None)[source]

Convert a volumetric flow rate using the CV unit to a physical unit.

  • vol_cv_flow_rate (UnitScalar) – Fow rate in column volume unit CV per unit time.
  • column (Column) – Column object the flow happens in.
  • to_unit (str or Unit) – Unit of the result flow rate.

Flow rate in SI compatible unit.

Return type:


kromatography.utils.units_utils.unit_scalar_almost_equal(x1, x2, eps=1e-09)[source]

Returns whether 2 UnitScalars are almost equal.

  • x1 (UnitScalar) – First unit scalar to compare.
  • x2 (UnitScalar) – Second unit scalar to compare.
  • eps (float) – Absolute precision of the comparison.
kromatography.utils.units_utils.unit_almost_equal(unit_1, unit_2, eps=1e-09)[source]

Returns whether the units of the 2 values provided are almost equal.

  • unit_1 (SmartUnit or UnitScalar or UnitArray) – First unit or unitted object to compare.
  • unit_2 (SmartUnit or UnitScalar or UnitArray) – First unit or unitted object to compare.

kromatography.utils.url_definitions module