Skip to content

Commit

Permalink
change ConfigManager to abc and add ProteinConfig for issue #5
Browse files Browse the repository at this point in the history
  • Loading branch information
andrasmatyassy committed Sep 24, 2024
1 parent 2d71550 commit b7a6695
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 31 deletions.
4 changes: 2 additions & 2 deletions CodonTransformer/CodonData.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
STOP_CODONS,
STOP_SYMBOL,
STOP_SYMBOLS,
ConfigManager,
ProteinConfig,
find_pattern_in_fasta,
get_taxonomy_id,
sort_amino2codon_skeleton,
Expand Down Expand Up @@ -175,7 +175,7 @@ def preprocess_protein_sequence(protein: str) -> str:
)

# Handle ambiguous amino acids based on the specified behavior
config = ConfigManager()
config = ProteinConfig()
ambiguous_aminoacid_map_override = config.get('ambiguous_aminoacid_map_override')
ambiguous_aminoacid_behavior = config.get('ambiguous_aminoacid_behavior')
ambiguous_aminoacid_map = AMBIGUOUS_AMINOACID_MAP.copy()
Expand Down
66 changes: 42 additions & 24 deletions CodonTransformer/CodonUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import os
import pickle
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, Iterator, List, Optional, Tuple

Expand Down Expand Up @@ -545,30 +546,12 @@ def __init__(self, data_path: str, train: bool = True, **kwargs):
self.train = train


class ConfigManager:
class ConfigManager(ABC):
"""
A class to manage configuration settings.
This class ensures that the configuration is a singleton.
It provides methods to get, set, and update configuration values.
Attributes:
_instance (Optional[ConfigManager]): The singleton instance of the ConfigManager.
_config (Dict[str, Any]): The configuration dictionary.
Abstract base class for managing configuration settings.
"""
_instance = None

def __new__(cls):
"""
Create a new instance of the ConfigManager class.
Returns:
ConfigManager: The singleton instance of the ConfigManager.
"""
if cls._instance is None:
cls._instance = super(ConfigManager, cls).__new__(cls)
cls._instance.reset_config()
return cls._instance
def __init__(self):
self._config: Dict[str, Any] = {}

def __enter__(self):
return self
Expand All @@ -578,6 +561,11 @@ def __exit__(self, exc_type, exc_value, traceback):
print(f"Exception occurred: {exc_type}, {exc_value}, {traceback}")
self.reset_config()

@abstractmethod
def reset_config(self) -> None:
"""Reset the configuration to default values."""
pass

def get(self, key: str) -> Any:
"""
Get the value of a configuration key.
Expand Down Expand Up @@ -610,8 +598,37 @@ def update(self, config_dict: dict) -> None:
"""
for key, value in config_dict.items():
self.validate_inputs(key, value)
for key, value in config_dict.items():
self.set(key, value)
self._config.update(config_dict)

@abstractmethod
def validate_inputs(self, key: str, value: Any) -> None:
"""Validate the inputs for the configuration."""
pass

class ProteinConfig(ConfigManager):
"""
A class to manage configuration settings for protein sequences.
This class ensures that the configuration is a singleton.
It provides methods to get, set, and update configuration values.
Attributes:
_instance (Optional[ConfigManager]): The singleton instance of the ConfigManager.
_config (Dict[str, Any]): The configuration dictionary.
"""
_instance = None

def __new__(cls):
"""
Create a new instance of the ProteinConfig class.
Returns:
ProteinConfig: The singleton instance of the ProteinConfig.
"""
if cls._instance is None:
cls._instance = super(ProteinConfig, cls).__new__(cls)
cls._instance.reset_config()
return cls._instance

def validate_inputs(self, key: str, value: Any) -> None:
"""
Expand Down Expand Up @@ -644,6 +661,7 @@ def validate_inputs(self, key: str, value: Any) -> None:
raise ValueError(f"Invalid amino acid in ambiguous_aminoacid_map_override: {ambiguous_aminoacid}")
else:
raise ValueError(f"Invalid configuration key: {key}")

def reset_config(self) -> None:
"""
Reset the configuration to the default values.
Expand Down
4 changes: 2 additions & 2 deletions tests/test_CodonData.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
read_fasta_file,
preprocess_protein_sequence,
)
from CodonTransformer.CodonUtils import ConfigManager
from CodonTransformer.CodonUtils import ProteinConfig

class TestCodonData(unittest.TestCase):
def test_preprocess_protein_sequence(self):
with ConfigManager() as config:
with ProteinConfig() as config:
protein = "Z_"
try:
preprocess_protein_sequence(protein)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_CodonUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import unittest

from CodonTransformer.CodonUtils import (
ConfigManager,
ProteinConfig,
find_pattern_in_fasta,
get_organism2id_dict,
get_taxonomy_id,
Expand All @@ -17,7 +17,7 @@

class TestCodonUtils(unittest.TestCase):
def test_config_manager(self):
with ConfigManager() as config:
with ProteinConfig() as config:
config.set(
"ambiguous_aminoacid_behavior",
"standardize_deterministic"
Expand Down Expand Up @@ -51,7 +51,7 @@ def test_config_manager(self):
self.fail("Expected ValueError")
except ValueError:
pass
with ConfigManager() as config:
with ProteinConfig() as config:
self.assertEqual(
config.get("ambiguous_aminoacid_behavior"),
"raise_error"
Expand Down

0 comments on commit b7a6695

Please sign in to comment.