|
| 1 | +from datetime import datetime |
| 2 | +from pathlib import Path |
| 3 | +from typing import Any, Dict, List, Optional, Tuple, Union |
| 4 | + |
| 5 | +import yaml |
| 6 | +from pydantic import BaseModel, Field |
| 7 | + |
| 8 | + |
| 9 | +class BaseConfig(BaseModel): |
| 10 | + alias: Dict[str, str] = {} |
| 11 | + param: Dict[str, Any] = {} |
| 12 | + |
| 13 | + def __getitem__(self, key: str) -> Any: |
| 14 | + if key in self.param: |
| 15 | + return self.param[key] |
| 16 | + return getattr(self, key) |
| 17 | + |
| 18 | + def __setitem__(self, key: str, value: Any): |
| 19 | + if key in self.model_fields: |
| 20 | + setattr(self, key, value) |
| 21 | + else: |
| 22 | + self.param[key] = value |
| 23 | + |
| 24 | + def __getattr__(self, name): |
| 25 | + """Handles alias access and custom parameters.""" |
| 26 | + if name in self.alias: |
| 27 | + return getattr(self, self.alias[name]) |
| 28 | + if name in self.param: |
| 29 | + return self.param[name] |
| 30 | + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") |
| 31 | + |
| 32 | + def __setattr__(self, name, value): |
| 33 | + """Handles alias assignment, field setting, or adding to _param.""" |
| 34 | + if name in self.alias: |
| 35 | + name = self.alias[name] |
| 36 | + |
| 37 | + # Check if it's a field defined in the model |
| 38 | + if name in self.model_fields: |
| 39 | + super().__setattr__(name, value) |
| 40 | + else: |
| 41 | + # Otherwise, treat it as a custom parameter |
| 42 | + self.param[name] = value |
| 43 | + |
| 44 | + def __contains__(self, key: str) -> bool: |
| 45 | + return key in self.param or hasattr(self, key) |
| 46 | + |
| 47 | + |
| 48 | +class ExperimentConfig(BaseConfig): |
| 49 | + """ |
| 50 | + configurations regarding the experiment |
| 51 | + """ |
| 52 | + |
| 53 | + name: Optional[str] = None |
| 54 | + patient: Optional[Union[List[int], int]] = None |
| 55 | + |
| 56 | + |
| 57 | +class ModelConfig(BaseConfig): |
| 58 | + name: Optional[str] = None |
| 59 | + learning_rate: Optional[float] = Field(1e-4, alias="lr") |
| 60 | + learning_rate_drop: Optional[int] = Field(50, alias="lr_drop") |
| 61 | + batch_size: Optional[int] = 128 |
| 62 | + epochs: Optional[int] = 100 |
| 63 | + hidden_size: Optional[int] = 192 |
| 64 | + num_hidden_layers: Optional[int] = 4 |
| 65 | + num_attention_heads: Optional[int] = 6 |
| 66 | + patch_size: Optional[Tuple[int, int]] = None |
| 67 | + |
| 68 | + alias: Dict[str, str] = { |
| 69 | + "lr": "learning_rate", |
| 70 | + "lr_drop": "learning_rate_drop", |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | +class DataConfig(BaseConfig): |
| 75 | + data_type: Optional[str] = None |
| 76 | + sd: Optional[float] = None |
| 77 | + root_path: Optional[Union[str, Path]] = None |
| 78 | + data_path: Optional[Union[str, Path]] = None |
| 79 | + |
| 80 | + |
| 81 | +class PipelineConfig(BaseModel): |
| 82 | + experiment: Optional[ExperimentConfig] = ExperimentConfig() |
| 83 | + model: Optional[ModelConfig] = ModelConfig() |
| 84 | + data: Optional[DataConfig] = DataConfig() |
| 85 | + |
| 86 | + # class Config: |
| 87 | + # arbitrary_types_allowed = True |
| 88 | + |
| 89 | + @classmethod |
| 90 | + def read_config(cls, config_file: Union[str, Path]) -> "PipelineConfig": |
| 91 | + """Reads a YAML configuration file and returns an instance of PipelineConfig.""" |
| 92 | + with open(config_file, "r") as file: |
| 93 | + config_dict = yaml.safe_load(file) |
| 94 | + return cls(**config_dict) |
| 95 | + |
| 96 | + def export_config(self, output_file: Union[str, Path] = "config.yaml") -> None: |
| 97 | + """Exports current properties to a YAML configuration file.""" |
| 98 | + if isinstance(output_file, str): |
| 99 | + output_file = Path(output_file) |
| 100 | + |
| 101 | + if not output_file.suffix: |
| 102 | + output_file = output_file / "config.yaml" |
| 103 | + |
| 104 | + # Create new path with the suffix added before the extension |
| 105 | + output_file = output_file.with_name(f"{output_file.stem}{self._file_tag}{output_file.suffix}") |
| 106 | + |
| 107 | + dir_path = output_file.parent |
| 108 | + dir_path.mkdir(parents=True, exist_ok=True) |
| 109 | + |
| 110 | + with open(output_file, "w") as file: |
| 111 | + yaml.safe_dump(self.model_dump(), file) |
| 112 | + |
| 113 | + @property |
| 114 | + def _file_tag(self) -> str: |
| 115 | + current_time = datetime.now() |
| 116 | + formatted_time = current_time.strftime("%Y-%m-%d-%H:%M:%S") |
| 117 | + return f"_{self.experiment.name}-{self.model.name}-{self.data.data_type}_{formatted_time}" |
| 118 | + |
| 119 | + |
| 120 | +if __name__ == "__main__": |
| 121 | + pipeline_config = PipelineConfig() |
| 122 | + pipeline_config.model.name = "vit" |
| 123 | + pipeline_config.model.learning_rate = 0.001 |
| 124 | + pipeline_config.experiment.name = "movie-decoding" |
| 125 | + |
| 126 | + # Access and print properties |
| 127 | + print(f"Experiment Name: {pipeline_config.experiment.name}") |
| 128 | + print(f"Patient ID: {pipeline_config.experiment.patient}") |
| 129 | + print(f"Model Name: {pipeline_config.model.name}") |
| 130 | + print(f"Learning Rate: {pipeline_config.model.learning_rate}") |
| 131 | + print(f"Batch Size: {pipeline_config.model.batch_size}") |
| 132 | + |
| 133 | + # Access using aliases |
| 134 | + print(f"Learning Rate (alias 'lr'): {pipeline_config.model['lr']}") |
| 135 | + print(f"Learning Rate (alias 'lr'): {pipeline_config.model.lr}") |
| 136 | + |
| 137 | + # Set new custom parameters |
| 138 | + pipeline_config.model["new_param"] = "custom_value" |
| 139 | + print(f"Custom Parameter 'new_param': {pipeline_config.model['new_param']}") |
| 140 | + pipeline_config.model.new_param2 = "custom_value" |
| 141 | + print(f"Custom Parameter 'new_param2': {pipeline_config.model.new_param2}") |
| 142 | + |
| 143 | + # Try to access a non-existent field (will raise AttributeError) |
| 144 | + try: |
| 145 | + print(pipeline_config.model.some_non_existent_field) |
| 146 | + except AttributeError as e: |
| 147 | + print(e) |
| 148 | + |
| 149 | + # Export config: |
| 150 | + pipeline_config.export_config() |
0 commit comments