DesignConstraints.from_dict

classmethod DesignConstraints.from_dict(dict_constraints)[source]

Rebuild a constraint set from the dictionary produced by DesignConstraints.to_dict().

Every field is re-validated, so a dictionary that has been through JSON is accepted: integer position keys that JSON turned into digit strings are converted back, and a malformed field raises the same message the constructor would.

Parameters:

dict_constraints (dict) – Constraint fields, as produced by DesignConstraints.to_dict(). Missing keys default to None; unknown keys are rejected.

Returns:

constraints – A new object equal to the one dict_constraints was exported from.

Return type:

DesignConstraints

Raises:

ValueError – If dict_constraints is not a dictionary, carries a key that is not a constraint field, or holds a value the constructor rejects.

See also

Added in version 1.2.0.

Examples

:meth:DesignConstraints.from_dict rebuilds a constraint set from the dictionary :meth:DesignConstraints.to_dict produces, which is how a design campaign is restored from a configuration file. Its single parameter dict_constraints is re-validated field by field, so a hand-written dictionary is accepted on exactly the same terms as the constructor.

import json

import pandas as pd
import aaanalysis as aa
aa.options["verbose"] = False

df_seq = aa.load_dataset(name="DOM_GSEC", n=5)
seq = df_seq["sequence"].iloc[0]
tmd_start = int(df_seq["tmd_start"].iloc[0])

# A hand-written configuration, e.g. read from a JSON file
dict_constraints = {"immutable_positions": [tmd_start],
                    "permitted_substitutions": ["A", "L", "V", "I"],
                    "forbidden_substitutions": {tmd_start + 6: ["V"]},
                    "n_mut_max": 2,
                    "min_identity": 0.95,
                    "forbidden_motifs": ["WW"],
                    "parent": seq}
dc = aa.DesignConstraints.from_dict(dict_constraints=dict_constraints)
df_constraints = pd.DataFrame({"field": list(dc.to_dict()),
                               "value": [str(v)[:60] for v in dc.to_dict().values()]})
aa.display_df(df_constraints, n_rows=10, show_shape=True)
DataFrame shape: (10, 2)
  field value
1 immutable_positions [37]
2 mutable_positions None
3 permitted_substitutions ['A', 'L', 'V', 'I']
4 forbidden_substitutions {43: ['V']}
5 n_mut_max 2
6 min_identity 0.95
7 max_identity None
8 forbidden_motifs ['WW']
9 required_motifs None
10 parent MQKVTLGLLVFLAGF...GVLCAMGIIIVMSAK

Missing keys default to None, so a partial dictionary is a valid constraint set, while an unknown key is rejected instead of being silently ignored. A dictionary that has been through JSON is accepted as well: the integer position keys JSON turned into digit strings are converted back.

# Partial configuration, JSON round trip, and a rejected key
dc = aa.DesignConstraints.from_dict(dict_constraints={"n_mut_max": 3})
dc_json = aa.DesignConstraints.from_dict(dict_constraints=json.loads(json.dumps(dict_constraints)))
try:
    aa.DesignConstraints.from_dict(dict_constraints={"n_mut_max": 3, "max_mutations": 5})
    error = "-"
except ValueError as e:
    error = str(e).split(";")[0][:70]

df_from_dict = pd.DataFrame([dict(source="partial dict", n_mut_max=str(dc.n_mut_max),
                                  min_identity=str(dc.min_identity), note="missing fields are None"),
                             dict(source="JSON round trip", n_mut_max=str(dc_json.n_mut_max),
                                  min_identity=str(dc_json.min_identity),
                                  note="string keys converted back"),
                             dict(source="unknown key", n_mut_max="-", min_identity="-", note=error)])
aa.display_df(df_from_dict, n_rows=10, show_shape=True)
print("JSON round trip rebuilds an equal object:",
      dc_json == aa.DesignConstraints.from_dict(dict_constraints=dict_constraints))
DataFrame shape: (3, 4)
  source n_mut_max min_identity note
1 partial dict 3 None missing fields are None
2 JSON round trip 2 0.95 string keys converted back
3 unknown key - - 'dict_constrain...nly the DesignC
JSON round trip rebuilds an equal object: True