File size: 2,108 Bytes
0161e74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
Data loading for CCFM.
Imports scDFM Data/PerturbationDataset by temporarily swapping sys.modules
so that scDFM's 'src.*' packages are visible during import.
"""

import sys
import os
import types

_SCDFM_ROOT = os.path.normpath(
    os.path.join(os.path.dirname(__file__), "..", "..", "..", "scDFM")
)

# Cache to avoid repeated imports
_cached_classes = {}


def get_data_classes():
    """Lazily import scDFM data classes with proper module isolation."""
    if _cached_classes:
        return (
            _cached_classes["Data"],
            _cached_classes["PerturbationDataset"],
            _cached_classes["TrainSampler"],
            _cached_classes["TestDataset"],
        )

    # Save CCFM's src modules
    saved = {}
    for key in list(sys.modules.keys()):
        if key == "src" or key.startswith("src."):
            saved[key] = sys.modules.pop(key)

    # Ensure __init__.py exists for scDFM data_process
    for d in ["src", "src/data_process", "src/utils", "src/tokenizer"]:
        init_path = os.path.join(_SCDFM_ROOT, d, "__init__.py")
        if not os.path.exists(init_path):
            os.makedirs(os.path.dirname(init_path), exist_ok=True)
            with open(init_path, "w") as f:
                f.write("# Auto-created by CCFM\n")

    sys.path.insert(0, _SCDFM_ROOT)
    try:
        from src.data_process.data import Data, PerturbationDataset, TrainSampler, TestDataset
        _cached_classes["Data"] = Data
        _cached_classes["PerturbationDataset"] = PerturbationDataset
        _cached_classes["TrainSampler"] = TrainSampler
        _cached_classes["TestDataset"] = TestDataset
    finally:
        # Remove scDFM's src.* entries
        for key in list(sys.modules.keys()):
            if (key == "src" or key.startswith("src.")) and not key.startswith("scdfm_"):
                del sys.modules[key]

        # Restore CCFM's src modules
        for key, mod in saved.items():
            sys.modules[key] = mod

        if _SCDFM_ROOT in sys.path:
            sys.path.remove(_SCDFM_ROOT)

    return Data, PerturbationDataset, TrainSampler, TestDataset