|
| 1 | +r""" |
| 2 | +:mod:`mdsapt.reader` -- Reads input file and saves configuration |
| 3 | +================================================================ |
| 4 | +
|
| 5 | +MDSAPT uses an yaml file to get user's configurations for SAPT calculations |
| 6 | +class`mdsapt.reader.InputReader` is responsible for reading the yaml file and |
| 7 | +returning the information from it. If a yaml file is needed it can be generated |
| 8 | +using the included *mdsapt_get_runinput* script. |
| 9 | +
|
| 10 | +.. autoexception:: ConfigurationError |
| 11 | +
|
| 12 | +.. autoclass:: InputReader |
| 13 | + :members: |
| 14 | + :inherited-members: |
| 15 | +""" |
| 16 | + |
| 17 | +from enum import Enum |
| 18 | +from pathlib import Path |
| 19 | +from typing import List, Dict, Tuple, Literal, Optional, \ |
| 20 | + Union, Any, Set |
| 21 | + |
| 22 | +import yaml |
| 23 | + |
| 24 | +import MDAnalysis as mda |
| 25 | + |
| 26 | +import logging |
| 27 | + |
| 28 | +from pydantic import BaseModel, conint, Field, root_validator, \ |
| 29 | + FilePath, ValidationError, DirectoryPath |
| 30 | + |
| 31 | +logger = logging.getLogger('mdsapt.config') |
| 32 | + |
| 33 | + |
| 34 | +class Psi4Config(BaseModel): |
| 35 | + """Psi4 configuration details |
| 36 | +
|
| 37 | + The SAPT method to use. |
| 38 | +
|
| 39 | + NOTE: You can use any valid Psi4 method, but it might fail if you don't use a SAPT method. |
| 40 | +
|
| 41 | + The basis to use in Psi4. |
| 42 | +
|
| 43 | + NOTE: We do not verify if this is a valid basis set or not. |
| 44 | + """ |
| 45 | + |
| 46 | + method: str |
| 47 | + basis: str |
| 48 | + save_output: bool # whether to save the raw output of Psi4. May be useful for debugging. |
| 49 | + settings: Dict[str, str] # Other Psi4 settings you would like to provide. |
| 50 | + |
| 51 | + |
| 52 | +class SysLimitsConfig(BaseModel): |
| 53 | + """Resource limits for your system.""" |
| 54 | + ncpus: conint(ge=1) |
| 55 | + memory: str |
| 56 | + |
| 57 | + |
| 58 | +class ChargeGuesser(Enum): |
| 59 | + Standard = 'standard' |
| 60 | + RDKit = 'rdkit' |
| 61 | + |
| 62 | + |
| 63 | +class SimulationConfig(BaseModel): |
| 64 | + ph: float |
| 65 | + charge_guesser: ChargeGuesser |
| 66 | + |
| 67 | + |
| 68 | +class DetailedTopologySelection(BaseModel): |
| 69 | + path: FilePath |
| 70 | + charge_overrides: Dict[int, int] = Field(default_factory=dict) |
| 71 | + |
| 72 | + |
| 73 | +TopologySelection = Union[FilePath, DetailedTopologySelection] |
| 74 | + |
| 75 | + |
| 76 | +def topology_selection_path(sel: TopologySelection) -> FilePath: |
| 77 | + if isinstance(sel, DetailedTopologySelection): |
| 78 | + return sel.path |
| 79 | + return sel |
| 80 | + |
| 81 | + |
| 82 | +class RangeFrameSelection(BaseModel): |
| 83 | + start: Optional[conint(ge=0)] |
| 84 | + stop: Optional[conint(ge=0)] |
| 85 | + step: Optional[conint(ge=1)] |
| 86 | + |
| 87 | + @root_validator() |
| 88 | + def check_start_before_stop(cls, values: Dict[str, int]) -> Dict[str, int]: |
| 89 | + assert values['start'] <= values['stop'], "start must be before stop" |
| 90 | + return values |
| 91 | + |
| 92 | + |
| 93 | +class TrajectoryAnalysisConfig(BaseModel): |
| 94 | + """ |
| 95 | + A selection of the frames used in this analysis. |
| 96 | +
|
| 97 | + Serialization behavior |
| 98 | + ---------------------- |
| 99 | + If this value is a range, it will be serialized using start/stop/step. |
| 100 | + Otherwise, it will be serialized into a List[int]. |
| 101 | + """ |
| 102 | + type: Literal['trajectory'] |
| 103 | + topology: TopologySelection |
| 104 | + trajectories: List[FilePath] |
| 105 | + pairs: List[Tuple[conint(ge=0), conint(ge=0)]] |
| 106 | + frames: Union[List[int], RangeFrameSelection] |
| 107 | + output: str |
| 108 | + |
| 109 | + @root_validator() |
| 110 | + def check_valid_md_system(cls, values: Dict[str, Any]) -> Dict[str, Any]: |
| 111 | + errors: List[str] = [] |
| 112 | + |
| 113 | + top_path: TopologySelection = values['topology'] |
| 114 | + trj_path: List[FilePath] = values['trajectories'] |
| 115 | + ag_pair: List[Tuple[conint(ge=0), conint(ge=0)]] = values['pairs'] |
| 116 | + frames: Union[List[int], RangeFrameSelection] = values['frames'] |
| 117 | + |
| 118 | + try: |
| 119 | + unv = mda.Universe(str(topology_selection_path(top_path)), |
| 120 | + [str(p) for p in trj_path]) |
| 121 | + except (mda.exceptions.NoDataError, OSError, ValueError): |
| 122 | + errors.append('Error while creating universe using provided topology and trajectories') |
| 123 | + raise ValidationError(errors) # If Universe doesn't load need to stop |
| 124 | + |
| 125 | + # Ensure that |
| 126 | + items: Set[int] = {i for pair in ag_pair for i in pair} |
| 127 | + |
| 128 | + for sel in items: |
| 129 | + ag: mda.AtomGroup = unv.select_atoms(f'resid {sel}') |
| 130 | + if len(ag) == 0: |
| 131 | + errors.append(f"Selection {sel} returns an empty AtomGroup.") |
| 132 | + |
| 133 | + |
| 134 | + |
| 135 | + trajlen: int = len(unv.trajectory) |
| 136 | + if isinstance(frames, RangeFrameSelection): |
| 137 | + if trajlen <= frames.stop: |
| 138 | + errors.append(f'Stop {frames.stop} exceeds trajectory length {trajlen}.') |
| 139 | + else: |
| 140 | + frames: List[int] |
| 141 | + for frame in frames: |
| 142 | + if frame >= trajlen: |
| 143 | + errors.append(f'Frame {frame} exceeds trajectory length {trajlen}') |
| 144 | + |
| 145 | + if len(errors) > 0: |
| 146 | + raise ValidationError(errors) |
| 147 | + return values |
| 148 | + |
| 149 | + |
| 150 | +class DockingAnalysisConfig(BaseModel): |
| 151 | + type: Literal['docking'] |
| 152 | + topologies: Union[List[TopologySelection], DirectoryPath] |
| 153 | + pairs: List[Tuple[int, int]] |
| 154 | + |
| 155 | + |
| 156 | +class Config(BaseModel): |
| 157 | + psi4: Psi4Config |
| 158 | + simulation: SimulationConfig |
| 159 | + system_limits: SysLimitsConfig |
| 160 | + analysis: Union[TrajectoryAnalysisConfig, DockingAnalysisConfig] = Field(..., discriminator='type') |
| 161 | + |
| 162 | + |
| 163 | +def load_from_yaml_file(path: Union[str, Path]) -> Config: |
| 164 | + if isinstance(path, str): |
| 165 | + path = Path(path) |
| 166 | + |
| 167 | + with path.open() as f: |
| 168 | + try: |
| 169 | + return Config(**yaml.safe_load(f)) |
| 170 | + except ValidationError as err: |
| 171 | + logger.exception(f"Error while loading {path}") |
| 172 | + raise err |
0 commit comments