| 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):
|
|
|
|
|
| topology = []
|
|
|
| level = 0
|
| result = {}
|
| degree = {n: dag.in_degree(n) for n in dag.nodes()}
|
|
|
| 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:
|
|
|
| n = queue.popleft()
|
| topology.append(n)
|
|
|
| f = False
|
| for m in list(dag[n]):
|
| degree[m] -= 1
|
|
|
|
|
| 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)
|
|
|
|
|
| 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),
|
| node_color = 'b',
|
| edge_color = 'r',
|
| with_labels = True,
|
| arrowsize=20,
|
| font_size =15,
|
| node_size =1)
|
|
|
|
|
| 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)
|
|
|
| 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(".")
|
|
|
|
|
| if names[-1] == "Strategy":
|
| return names[-2]
|
|
|
|
|
|
|
|
|
| def get_node_numbers(path, debug=False):
|
|
|
| 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)
|
|
|
|
|
| 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)):
|
|
|
| with multiprocessing.Pool(num_cores) as pool:
|
|
|
| pool.map(run_subclass_and_set_empty, [subclasses_obj[j] for j in node_dict[i]])
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|