File size: 7,218 Bytes
1721429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import inspect, os, logging
import networkx as nx
from wby_utils.path.Path import get_all_files, get_folders
from .strategy_base import StrategyBase
from collections import deque
import threading
import multiprocessing
from multiprocessing import freeze_support
import concurrent.futures


logging.getLogger('matplotlib').setLevel(logging.WARNING)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
subclasses_obj = {}

def execute_dag(dag, debug=False):
    # 使用拓扑排序算法推导执行层级
    # sorted_nodes = list(nx.topological_sort(dag))
    topology = []
    # 求每个顶点(A,B,C,D,E,F,G)的入度,保存为字典形式
    level = 0
    result = {}
    degree = {n: dag.in_degree(n)  for n in dag.nodes()}
    # 找到入度为0的顶点,存入一个双向列表
    queue = deque(n  for n, d in degree.items() if not d)
    for i in queue:
        if level not in result.keys():
            result[level] = []
        result[level].append(i)

    while queue:
        #从双向列表的左侧取出第一个入度为0的顶点
        n = queue.popleft()
        topology.append(n)
        # 将所有“以刚取出顶点为前置条件”的顶点的入度-1
        f = False
        for m in list(dag[n]):
            degree[m] -= 1
            # 将新产生的入度为0的顶点存入双向列表
            
            if not degree[m]:
                # 同一拨才添加进去
                if f == False:
                    level += 1
                    f = True
                if level not in result.keys():
                    result[level] = []
                result[level].append(m)
                queue.append(m)
                
    #双向列表为空后,判断是不是所有顶点都进入topology列表了,若不是,说明原图有环,也就不存在拓扑排序了
    if len(topology) < len(dag):
        raise ValueError('graph contains cycle')
    if debug:
        print(result)
        input("按任意键继续....")
    return result


def draw_dag(dag):
    import matplotlib.pyplot as plt

    nx.draw(dag,
            pos = nx.circular_layout(dag), # pos 指的是布局,主要有spring_layout,random_layout,circle_layout,shell_layout
            node_color = 'b',   # node_color指节点颜色,有rbykw,同理edge_color 
            edge_color = 'r',
            with_labels = True,  # with_labels指节点是否显示名字
            arrowsize=20,
            font_size =15,  # font_size表示字体大小,font_color表示字的颜色
            node_size =1)  # font_size表示字体大小,font_color表示字的颜色
    # plt.savefig("network.png")
    # nx.write_gexf(G, 'network.gexf')  # gexf格式文件可以导入gephi中进行分析
    plt.show()


def import_all_factors(folder):
    files = get_all_files(folder)
    for file in files:
        if file[-3:] != ".py":
            continue
        folders = get_folders(file)[:-1]
        file_name = os.path.splitext(os.path.basename(file))[0]
        folders.append(file_name)
        import_path = ""
        for folder in folders:
            if import_path != "":
                import_path += "."
            import_path += f"{folder}"
        import_str = f"from {import_path} import *"
        exec(import_str)


def get_subclasses(cls):
    """

    找到一个抽象父类的所有子类

    :param cls: 抽象父类

    :return: 所有子类的列表

    """
    subclasses = []
    for subclass in cls.__subclasses__():
        if not inspect.isabstract(subclass):
            # 如果子类不是抽象类,添加到列表中
            subclasses.append(subclass)
            # print(str(subclass))
        else:
            # 如果子类是抽象类,递归查找其子类
            subclasses.extend(get_subclasses(subclass))
    return subclasses


def exact_class_name(subclass):
    import re

    # 正则表达式,匹配尖括号内的内容
    pattern = r"'(.*?)'"

    # 在文本中查找匹配项
    matches = re.findall(pattern, str(subclass))

    # 如果没有找到匹配项,尝试匹配单引号中的内容
    if not matches:
        pattern = r"<(.*?)>"
        matches = re.findall(pattern, str(subclass))
        matches = [matches[0].split(" ")[0]]
    

    # 输出匹配项
    names = matches[0].split(".")
    # print(matches, names)

    if names[-1] == "Strategy":
        return names[-2]
    # print(matches[0])
    # return matches[0]


def get_node_numbers(path, debug=False):
    # 创建一个DAG并添加节点
    dag = nx.DiGraph()

    import_all_factors(path)
    subclasses = get_subclasses(StrategyBase)
    logging.info(f"子类:{subclasses}")
    nodes = set()
    edges = []
    for subclass in subclasses:
        name = exact_class_name(subclass)
        print(name)
        pre = subclass.get_pre_factor_name()
        for i in pre:
            edges.append((name, i))
        nodes.add(name)

    for node in nodes:
        dag.add_node(node)
    logging.info(f"因子列表:{nodes}")

    for edge in edges:
        dag.add_edge(edge[1], edge[0])
    logging.info(f"依赖关系:{edges}")

    node_numbers = execute_dag(dag, debug=debug)
    logging.info(f"节点编号:{node_numbers}")
    return node_numbers
    

def run_subclass_and_set_empty(subclass_obj):
    subclass_obj.run()
    key = exact_class_name(subclass_obj)
    print("开始回收内存:", key)
    if key is not None:
        subclasses_obj[key] = None
        print(f"回收{key}内存成功")
    else:
        print(f"回收{key}内存失败")


def cal_all_factors(path, config_path, num_cores=1, debug=False):
    threads = []
    if num_cores == -1:
        num_cores = multiprocessing.cpu_count()
    import_all_factors(path)
    subclasses = get_subclasses(StrategyBase)
    # print(subclasses)

    for subclass in subclasses:
        subclasses_obj[exact_class_name(subclass)] = subclass(config_path)
    node_dict = get_node_numbers(path, debug=debug)

    for i in range(1, len(node_dict)):
        # 创建一个包含num_cores个进程的进程池
        with multiprocessing.Pool(num_cores) as pool:
            # 将任务映射到进程池中的进程
            pool.map(run_subclass_and_set_empty, [subclasses_obj[j] for j in node_dict[i]])

            # print(j)
            # print(subclasses_obj[j].run())


def run_script(script_path):
    cmd = f"python {script_path}"
    print(cmd)
    os.system(cmd)


def run_all(path, thread=4):
    with concurrent.futures.ThreadPoolExecutor(max_workers=thread) as executor:
        for i in os.listdir(path):
            full_path = os.path.join(path, i)
            if os.path.isdir(full_path):
                run_all(full_path, thread)
            else:
                if i[-3:] == ".py":
                    executor.submit(run_script, full_path)


if __name__ == "__main__":
    freeze_support()
    cal_all_factors("factor", num_cores=4, debug=True)