A Python package for form field helpers and payload translation utilities.
pip install git+https://github.com/MassDynamics/md_form.git
The package provides field helper functions for creating form fields with validation rules and conditional visibility. All helpers accept common parameters via the decorator:
name: Display namedescription: Help textwhen: AWhencondition to control visibilityrules: A rule or list of rules frommd_form.field_utils.rulesparameters: Dict of custom UI parameters to merge intojson_schema_extra.parameters. These are merged with any existing parameters from the field helper, allowing you to customise or extend the default behaviour.
Note: Fields are optional by default (default=None). Include is_required() in rules to make a field required.
The parameters argument allows you to customise field behaviour by merging custom UI parameters with the field helper's default parameters. The merging logic works as follows:
- Field helpers provide default parameters - Each helper function includes sensible defaults (e.g.,
select_fieldincludesoptions,control_variables_fieldincludesradioOptions) - Custom parameters are merged - Your custom
parametersdict is merged into the existingjson_schema_extra.parameters - Custom parameters take precedence - If you provide a parameter with the same key as a default, your value will override the default
- New parameters are added - Any new parameters you provide are added to the existing set
Example:
# control_variables_field has default parameters.radioOptions = ["categorical", "numerical"] control_vars = control_variables_field( name="Control Variables", parameters={ "placeholder": "Select control variable type", # New parameter "radioOptions": ["custom", "other"] # Override default } ) # Result: parameters.radioOptions = ["custom", "other"], parameters.placeholder = "Select control variable type"
A select_field's (or multiple_select_field's) options can resolve at runtime from another field's value. Pass a {ref, cases} object — either directly as options or via parameters — and cases[key] may be a flat list of strings or a pre-shaped list of {name, value} dicts. Flat string lists are normalized to [{"name": s, "value": s}, ...] automatically (mirroring the flat-list behaviour of options=["a", "b"]).
species = select_field( name="Species", options=["Human", "Mouse"], ) # Flat-string cases (recommended when name == value) knowledge_bases = select_field( name="Knowledge Bases", options={ "ref": "species", "cases": { "Human": ["reactome_human", "kegg_human"], "Mouse": ["reactome_mouse", "kegg_mouse"], }, }, ) # Pre-shaped cases (when display name differs from value) knowledge_bases = select_field( name="Knowledge Bases", parameters={ "options": { "ref": "species", "cases": { "Human": [ {"name": "Reactome (Human)", "value": "reactome_human"}, {"name": "KEGG (Human)", "value": "kegg_human"}, ], "Mouse": [ {"name": "Reactome (Mouse)", "value": "reactome_mouse"}, {"name": "KEGG (Mouse)", "value": "kegg_mouse"}, ], }, }, }, )
- When the referenced field's value matches a case, that array is used as the options.
- When the referenced field is empty or its value doesn't match any case, resolved options are
undefinedand the dependent field renders with no options. - When the user changes the referenced field, the dependent field's value resets and re-renders.
- At the helper level (
options={...}), eachcases[key]must be a list of strings — mixed or pre-shaped lists raiseValueError. When passing pre-shaped lists, useparameters={"options": {...}}; thetranslate_payloadpipeline passes already-normalizedcasesthrough untouched.
boolean_field(default=None, label=None)string_field(default=None, disabled=False)blob_field(default=None, placeholder=None, rows=None)- Free text in a multi-line text area (
fieldType: "Blob"); the value's type isn't checked placeholderis shown while it is empty;rowsis its height in lines and must be an int of at least 1 (it doesn't limit the value, longer text scrolls)
- Free text in a multi-line text area (
number_field(field_data_type, default=None, ge=None, le=None)field_data_typemust always be passed:FieldDataType.INTorFieldDataType.FLOAT(emitted asparameters.fieldDataType), orNoneto accept either
select_field(default=None, options=None, discriminator=None)optionsis a list of strings; each option becomes{ "name": v, "value": v }(name equals value)discriminatoris passed through for downstream oneOf selection
radio_selection_field(default=None, options=None, inline=None)- Picks one option, shown as radio buttons (
fieldType: "RadioSelectionField") optionsworks as inselect_field;inline=Truelays the buttons out on one line
- Picks one option, shown as radio buttons (
selection_type_field(default="selection", inline=None, include_single_entity=False, include_all=False)- A
radio_selection_fieldthat always has the options{"name": "Use Selection", "value": "selection"}and{"name": "Use List", "value": "list"} include_single_entity=Trueadds{"name": "Single Entity", "value": "single_entity"}; a"single_entity"default without it raisesValueErrorinclude_all=Trueadds{"name": "All", "value": "all"}; an"all"default without it raisesValueError- Emits
parameters.selectionType: trueso the frontend can tell it apart from an ordinary radio
- A
numberrange_field(field_data_type, default=None, ge=None, le=None, interval=None)field_data_typemust always be passed, as fornumber_field
experiment_design_field(datasets_ref="input_datasets", column_names_ref=["condition_column", "control_variables[].column"], hidden=None)datasets_refnames the field holding the datasets whose sample metadata fills the tablecolumn_names_refnames the fields holding columns the table must carry, as one path or a list of paths: a plain field ("condition_column") or an array projection ("x_axis_list[].field")hidden=Truestill builds and sends the table but doesn't show it
condition_column_field(datasets_ref="input_datasets")datasets_refnames the field holding the datasets whose sample metadata columns are offered
condition_comparisons_field()- Picks any number of comparisons from the conditions in this form's own experiment design
(
fieldType: "PairwiseConditionComparisons") - The value is
{"condition_comparison_pairs": [["C1", "C2"], ...]}
- Picks any number of comparisons from the conditions in this form's own experiment design
(
condition_comparison_field(datasets_ref="input_datasets")- Picks one comparison already in the dataset chosen in the
datasets_reffield (fieldType: "ConditionComparison"), and which way round to read it - The value is
{"comparison": {"condition_pair": "C7 - C5", "left": "C5", "right": "C7"}}:condition_pairis the dataset's comparison, andleftandrightare its two conditions, each of which must appear incondition_pair, in either order
- Picks one comparison already in the dataset chosen in the
control_variables_field(default=None)intensity_input_dataset_field()intensity_input_datasets_field(entity_types=None, min=1, max=None)entity_typesis a list ofEntityTypevalues, e.g.["protein", "gene"]
datasets_field(type=None, multiple=None, entity_types=None)typelimits the datasets to one type, e.g."PAIRWISE", or to any of a list of types, e.g.["PAIRWISE", "ANOVA"]; omit it to allow any typemultiple=Falseallows at most one datasetentity_typesis a list ofEntityTypevalues; each selected dataset must have at least one of them
entity_type_field(default=None, datasets_ref="input_datasets")defaultis anEntityTypevalue, e.g."protein"datasets_refnames the dataset field it applies to; the datasets selected there must have the chosen entity type
sample_metadata_values_filter_field(column_ref="filter_based_on_condition", datasets_ref="input_datasets", filterable=None, sortable=None, advanced_filtering=None, ignored_values=None)- Picks values to keep from the sample metadata column chosen in the
column_reffield (fieldType: "SampleMetadataValuesFilter") - The value is
{"values": ["C1", "C3"], "filters": [{"column": "batch", "value": ["B1"]}]}:valuesare different, non-empty strings, none of them inignored_values;filters(only filled in withadvanced_filtering) may be left out
- Picks values to keep from the sample metadata column chosen in the
dataset_param_multiple_field(datasets_ref="input_datasets", initialise_with_all=True)- Picks any of the databases recorded in the job run params of the dataset chosen in the
datasets_reffield (fieldType: "DatasetParamMultiple"): the knowledge bases and analysis set names of itsDatabasesparams or, failing those, itssets - The value is a list of different database names, e.g.
["GO - Biological Process", "MSigDB-H (hallmark gene sets)"] - With
initialise_with_all, the frontend starts with every database selected - When
validate_formis givendatasets, each name must be one of the dataset's databases
- Picks any of the databases recorded in the job run params of the dataset chosen in the
plot_size_field(width=None, height=None)- The value is
{"fixed": False}(fit to module) or{"fixed": True, "width": <px>, "height": <px>}, with width and height ints between 1 and 1000 - The default is
{"fixed": False}; pass bothwidthandheightto default to a fixed size
- The value is
scientific_notation_field(default=None)- The value is a string holding a finite number, such as
"1.5e-3"or"0.0015" - A
defaultthat isn't such a number raisesValueError
- The value is a string holding a finite number, such as
fold_change_threshold_field(default=None)- The value is a float of at least 1 (an int such as
2counts, as JSON sends2.0as2); the frontend also shows its log2 ratio - A
defaultbelow 1 raisesValueError
- The value is a float of at least 1 (an int such as
entity_list_field(type=None, owner_only=None)- Picks a single entity list (
fieldType: "ProteinList"); the value is the list's id, a non-empty string typefilters the lists by entity type;owner_only=Trueoffers only the user's own lists- Unlike
entity_list_entity_ids_fieldthe value is the id rather than the list's entity ids, and unlikeentity_lists_fieldonly one list is picked
- Picks a single entity list (
entity_title_field(entity_type=None, datasets_ref=None, include_hierarchical_entities=None)- Picks the column used to label entities (
fieldType: "EntityTitle"); the value is a column name such as"protein_name" - The entity type comes from
entity_type(a value or a{"ref": "<field>"}dict) or else the datasets indatasets_ref; with neither the frontend uses"protein" - The value must be one of that entity type's title columns: protein
protein_name/gene_name, peptidemodified_sequence/gene_name, genegene_name/gene_id, metabolitemetabolite_id, ptmptm_protein/gene_name include_hierarchical_entities=Truealso allows the parent type's columns (protein's for peptide and ptm)- When the entity type comes from the datasets, only that the value is a string is checked
- Picks the column used to label entities (
orderable_sample_metadata_columns_field(datasets_ref="input_datasets", default=None, entity_type=None, include_hierarchical_entities=None, orderable_protein_ids=None, allow_dataset=None)- Picks an ordered list of columns to group samples by, such as a hierarchical x axis
(
fieldType: "OrderableSampleMetadataColumns") - The value is a list of
{"field", "field_type", "order", "type", "order_by_values", "entity_label"}objects; onlyfieldis required, and fields must not repeat field_typeis"sample_metadata","entity"or"dataset";orderis"asc","desc","none"or"custom", where"custom"needs a non-emptyorder_by_valueslist;typeis"categorical"or"numeric"; an entity column'sentity_labelis one of that entity's title columns (seeentity_title_field)datasets_refnames the field holding the dataset whose sample metadata columns are offered;entity_typealso offers that entity as a column (with its parent types wheninclude_hierarchical_entities=True),orderable_protein_ids=Truelets an entity column be custom-ordered, andallow_dataset=Trueoffers the dataset
- Picks an ordered list of columns to group samples by, such as a hierarchical x axis
(
pairwise_condition_pairs_field(datasets_ref="input_datasets", filterable=None, sortable=None, conditions_orderable=None)- Picks condition pairs from the comparisons a PAIRWISE dataset was run with (
fieldType: "PairwiseConditionPairs") - The value is
[{"condition_pair": ["C1", "C2"], "left": "C2", "right": "C1"}, ...], defaulting to[];leftandrightare only sent withconditions_orderable=True - Each pair is two different conditions, picked once;
leftandrightare its conditions, in either order - With
datasets, each pair must be in the dataset'sjob_run_params.condition_comparisons.condition_comparison_pairs(in the same order), and the dataset must be PAIRWISE filterable=Truelets the user pick some pairs (otherwise all are selected);sortable=Truelets them be reordered
- Picks condition pairs from the comparisons a PAIRWISE dataset was run with (
dataset_table_values_field(table_name, datasets_ref="input_datasets", show_custom_field_settings=None, initially_select_all=None, column_regex=None)- Picks and orders columns of the
table_nametable (a name, or a{"ref": "<field>"}dict) of the datasets in thedatasets_reffield (fieldType: "DatasetTableValues") - The value is
[{"name": "column", ...}, ...]; each column name is a non-empty string, picked once - With
show_custom_field_settings=Falsea column is{"name": "column", "value": "column"}, wherevalueis optional, and nothing else - Otherwise (the frontend's default) each column carries its display settings, and nothing else:
replaceValues(a boolean), alwayslabel(a string),type("percentage"or"decimal") anddecimalPlaces(a whole number of at least 0, only with atype)renderedValuesReplace, only and always whenreplaceValuesis true:{"condition": {"field", "operation", "value"}, "replacementType": "text" | "computed", "text": ..., "computed": {"name", "aggregation", "operation", "operationValue"}}, withtextonly for a"text"replacement andcomputedonly (and always) for a"computed"one, andoperationValueonly with anoperation- Unset settings may be
None
initially_select_all=Truepicks every column when emptycolumn_regexoffers only the columns whose name it matches (a JavaScript regular expression, searched anywhere in the name), andinitially_select_allpicks only those. Each picked column must match it; a pattern Python can't compile isn't checked
- Picks and orders columns of the
colour_palette_field()- Picks one of the organisation's colour palettes (
fieldType: "ColourPalette"); the value is its id, a string, orNonefor no palette
- Picks one of the organisation's colour palettes (
databases_field()- The value is
{"knowledgeBases": [...], "analysisSets": [{"name": ..., "entityLists": [{"id": ..., "name": ..., "entityIds": [...]}, ...]}, ...]} - Knowledge bases must be different, non-empty strings, and among
knowledge_baseswhen it is set analysisSetscan be empty, but holding any needsallow_custom_databases=True. Their names must be different, non-empty and not a selected knowledge base, and each needs at least one entity list- Each entity list needs a non-empty
id, a non-emptynamethat is different within its analysis set, and at least one entity id inentityIds, none of them blank
- The value is
EntityTypeisLiteral["protein", "peptide", "gene", "metabolite", "ptm", "precursor"]. It is also taken byintensity_input_dataset_field,datasets_field(entity_types), and byentity_list_entity_ids_field,entity_list_field,entity_lists_field(type),entity_title_field,orderable_sample_metadata_columns_field(entity_type) anddatabases_field(entity_type), which also accept a{"ref": "<field>"}dict. Any other string is rejected.
Example:
from md_form.field_utils import ( condition_column_field, is_not_equal_to_value, is_not_equal_to_value_from_field, is_required, When ) # Create a condition column field with validation rules condition_column = condition_column_field( name="Condition Column", rules=[ is_not_equal_to_value("sample_name"), is_not_equal_to_value_from_field("control_variables"), is_required(), ], when=When.not_equals("input_datasets", None) )
is_equal_to_value(value)- Validates that a field equals a specific literal valueis_not_equal_to_value(value)- Validates that a field does not equal a specific literal valueis_equal_to_value_from_field(field)- Validates that a field equals the value of another specified fieldis_not_equal_to_value_from_field(field)- Validates that a field does not equal the value of another specified fieldis_required()- Marks a field as required/mandatoryis_all_unique_in_column(column)- Ensures all values in a specified column are unique (no duplicates)has_unique_in_column(column)- Ensures at least one unique value exists in a specified columnis_all_unique_in_column_from_field(field)- Ensures all values in a column (specified by another field) are uniquehas_unique_in_column_from_field(field)- Ensures at least one unique value exists in a column (specified by another field)
Use the When class to create conditional logic:
from md_form.field_utils import When # Field is shown when input_datasets is not None when = When.not_equals("input_datasets", None) # Field is shown when some_field equals "value" when = When.equals("some_field", "value")
Use the translate_payload function to transform JSON-schema-like payloads to a simplified form schema suitable for UI rendering.
Key behaviours:
- Keeps only allowed second-layer keys:
fieldType,parameters,name,rules,description,default,when - Converts
enum: [v1, v2]toparameters.options: [{"name": v, "value": v}](name equals value) - Renames keys:
maximum/minimum -> max/min,maxItems/minItems -> max/min - Moves
options,min,maxintoparameters - Flattens
$refand nestedproperties; resolvesoneOfwithdiscriminatorby inlining referenced sub-properties - Removes top-level
output_dataset_typeand non-object nodes
from md_form import translate_payload # Transform function parameters schema (example) parameters_new = translate_payload(dict(fn.parameters))
To install in development mode:
pip install -e .