def slot_terminate_simulation(self): # 加一步状态检测 if self.flag == "running": # 加一步询问 reply = QtWidgets.QMessageBox.question( self, "Terminate Simulation", "Are you sure you want to teminate this simulation?", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if reply == QtWidgets.QMessageBox.Yes: self.MyThread.terminate() self.end_moment = datetime.now() self.service_msg_log_text.append( str(self.end_moment) + ": Simulation task terminated.") record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml") record_dom_root = record_dom.getElementsByTagName("Result")[0] record_dom_root.setAttribute("EndMoment", str(self.end_moment)) record_dom_root.setAttribute( "TimeConsuming", str(self.end_moment - self.start_moment)) write_xml( self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom) self.current_generation = 0 self.flag = "waiting" self.start_btn.setEnabled(True) self.pause_btn.setEnabled(False) self.MyThread.flag = False self.MyThread.current_generation = 0 self.start_moment = None self.end_moment = None
def slot_return_from(self, current): # 一个迭代的仿真结束了,需要判断一下仿真是否需要继承数据。 self.current_generation = current # print("in widget, current_generation:{}".format(self.current_generation)) self.exe_progress_bar.setValue(self.current_generation / external_func.round_number * 100) if current == external_func.round_number: self.slot_btn_pause() self.end_moment = datetime.now() self.service_msg_log_text.append( str(self.end_moment) + ": Simulation task completed.") record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml") record_dom_root = record_dom.getElementsByTagName("Result")[0] record_dom_root.setAttribute("EndMoment", str(self.end_moment)) record_dom_root.setAttribute( "TimeConsuming", str(self.end_moment - self.start_moment)) write_xml( self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom) if current % int(self.step_size_Edit.text()) == 0: self.MyThread.flag = False save_member_round_record(self.record_dir_path_edit.text(), current, self.global_dict, len(self.generation_Edit.text())) save_global_attribute_record(self.record_dir_path_edit.text(), current, self.global_dict) self.MyThread.flag = True
def start_check(self): if self.members_xml_path_edit.text() is "" or \ self.def_xml_path_edit.text() is "" or \ self.record_dir_path_edit.text() is "" or \ self.version_edit.text() is "" or \ self.step_size_Edit.text() is "" or \ self.ex_ID_edit.text() is "" or \ self.step_size_Edit.text() is "": return False else: record_dom = read_xml(self.record_dir_path_edit.text() + "/Simulation_Record.xml") record_dom_root = record_dom.getElementsByTagName("Result")[0] record_dom_root.setAttribute("ID", self.ex_ID_edit.text()) record_dom_root.setAttribute("version", self.version_edit.text()) record_dom_root.setAttribute("MetaMemberID", self.meta_member_ID_edit.text()) record_dom_root.setAttribute("DefinitionID", self.definition_ID_edit.text()) record_dom_root.setAttribute("RecordStepSize", self.step_size_Edit.text()) record_dom_root.setAttribute("Inherited", str(eval(self.inherited_Edit.text()))) record_dom_root.setAttribute("Datetime", self.modify_dateEdit.text()) self.start_moment = datetime.now() record_dom_root.setAttribute("StartMoment", str(self.start_moment)) write_xml( self.record_dir_path_edit.text() + "/Simulation_Record.xml", record_dom) return True
def slot_btn_set_members_path(self): """ 读取所有成员的路径的槽函数 :return: no return """ try: # 打开文件对话框 xml_members_path = QtWidgets.QFileDialog.getOpenFileName( self, "选择仿真成员xml文件", "./", "XML Files (*.xml);;All Files (*)") self.members_xml_path_edit.setText(xml_members_path[0]) # 根据这个路径来读取成员 member_dom = read_xml(self.members_xml_path_edit.text()) members.member_file_path = self.members_xml_path_edit.text() # 服务信息更新显示 self.service_msg_log_text.append( str(datetime.now()) + ': ' + 'Read member from: ' + self.members_xml_path_edit.text()) # 解析成员 # global net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c # net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c = net_work_read(member_dom) # global primitives, advisers, monitorMembers, collectives # primitives, advisers, monitorMembers, collectives = member_read(member_dom) # 读取一下文件中的成员基本信息与数目,并在界面上刷新显示 id_role_dict, member_number, p_number, c_number, a_number, m_number = format_members_id_role( member_dom) read_member(member_dom) read_network(member_dom) read_pattern(member_dom) read_component_methods(member_dom) members.member_dom = member_dom members.member_file_path = self.members_xml_path_edit.text() members.member_num = member_number self.reset_member_tableWidget(member_number, id_role_dict) self.primitive_num_edit.setText(str(p_number)) self.adviser_num_edit.setText(str(a_number)) self.monitor_num_edit.setText(str(m_number)) self.collective_num_edit.setText(str(c_number)) self.service_msg_log_text.append( str(datetime.now()) + ': ' + "Primitive:{}|Adviser:{}|Monitor:{}|Collective:{}".format( p_number, a_number, m_number, c_number)) except: QtWidgets.QMessageBox.critical(self, "Error", traceback.print_exc()) self.members_xml_path_edit.clear() self.service_msg_log_text.append( str(datetime.now()) + ': ' + 'Setting member XML file error. ') raise
def save_global_attribute_record(record_path, round_number, global_dict): """ 保存全局属性记录 :param record_path:仿真记录保存路径 :param round_number: 第几轮仿真 :param global_dict: 保存所有变量的字典 :return: no return """ # 获取总览记录文件 record_dom = read_xml(record_path + "/" + "Simulation_Record.xml") root = record_dom.getElementsByTagName("Result")[0] round_record_dom = record_dom.createElement("Record") for v in external_func.global_attribute_dict.values(): round_record_dom.setAttribute(v['aName'], str(global_dict[v['aName']])) round_record_dom.setAttribute("round", str(round_number)) root.appendChild(round_record_dom) write_xml(record_path + "/" + "Simulation_Record.xml", record_dom)
def slot_btn_load_script(self): """ 保存已经设置的脚本信息为xml文件槽函数 :return: """ # 设置将表格中的内容按列保存为xml if self.all_fill() and self.save_scripts_to_xml(): # 设置脚本表格不可编辑 self.script_table_widget.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) self.add_script_button.setEnabled(False) self.delete_script_button.setEnabled(False) # 一点提示信息 self.script_setting_widget_status_label.setText("Script loaded.") QtWidgets.QMessageBox.information(self, 'Success', 'Scripts save succeed.') read_scripts(xml_dom=read_xml(external_func.scripts_file_path)) else: QtWidgets.QMessageBox.warning( self, 'failure', 'Scripts save failed.\n Please check the form.')
def evolution_init(global_dict): print(members.primitive_dict['memberID-0']) task_dom = read_xml(r"external_file_for_cEvolution/Task.xml") task_labels = task_dom.getElementsByTagName("task") task_dict = {} class Task(object): def __init__(self, task_label): self.task_id = task_label.getAttribute("ID") self.task_detail = eval(task_label.getAttribute("taskDetail")) self.time_limit = float(task_label.getAttribute("time_limit")) self.spend_time = None self.earn = float(task_label.getAttribute("earn")) self.executant = None self.e_flag = False self.past_list = [] for a_p_dict in members.primitive_dict.values(): a_p_dict.update({'任务列表': []}) a_p_dict.update({'学习列表': []}) a_p_dict.update({'耗时': 0}) a_p_dict.update({'CIQ': 0}) a_p_dict.update({'自退化率': random()}) a_p_dict.update({'收益总和': 0}) if a_p_dict['决策器ID'].__class__ is not str and a_p_dict['决策器ID'][ '任务ID集合'].__len__() != 0: if a_p_dict['决策器ID']['任务ID集合'][0].__class__ is not dict: for task_label in task_labels: a_task = Task(task_label) a_task_dict = object2dict(a_task) task_dict.update({a_task.task_id: a_task_dict}) # 任务装配 for a_p_dict in members.primitive_dict.values(): true_id_list = [] for ti_id in a_p_dict['决策器ID']['任务ID集合']: true_id_list.append(task_dict[ti_id]) a_p_dict['决策器ID']['任务ID集合'] = true_id_list a_p_dict.update({'初始任务列表': true_id_list.copy()})
from other_tools import read_xml, write_xml from external_file_for_cEvolution.create_task import dimension from scipy import stats from random import shuffle, randint import numpy as np member_dom = read_xml(r"ceMemberXml_C.xml") primitive_labels = member_dom.getElementsByTagName("primitiveInfo") # 原子型成员标签 shuffle(primitive_labels) affector_labels = member_dom.getElementsByTagName("affectorInfo") # 影响器标签 shuffle(affector_labels) decider_labels = member_dom.getElementsByTagName("deciderInfo") # 决策器标签 shuffle(decider_labels) executor_labels = member_dom.getElementsByTagName("executorInfo") # 执行器标签 shuffle(executor_labels) connector_labels = member_dom.getElementsByTagName("connectorInfo") # 联接器标签 shuffle(connector_labels) name_list = ["决策器ID", "影响器ID", "执行器ID", "联接器ID", "监控器ID"] for the_iter, the_labels in zip( name_list, [decider_labels, affector_labels, executor_labels, connector_labels]): for the_label, primitive_label in zip(the_labels, primitive_labels): primitive_label.setAttribute(the_iter, the_label.getAttribute(the_iter)) # 各种器安排完了,安排能够依照概率分布来设置属性值的属性 attribute_settings = [ ("自律水平期望", "自律水平方差", "自律水平"), ("自信水平期望", "自信水平方差", "自信水平"), ("自退化率期望", "自退化率方差", "自退化率"), ("起始学习期望", "起始学习方差", "起始学习时间"),
read_monitorMember_component_methods(member_xml_dom) def read_network(member_xml_dom: xml.dom.minidom.Document): network_labels = member_xml_dom.getElementsByTagName('networkStructure') for network_label in network_labels: G = nx.DiGraph(TYPE=network_label.getAttribute('type'), ID=network_label.getAttribute('ID')) edges_labels = network_label.getElementsByTagName('connectInfo') for edges_label in edges_labels: # 双向添加 G.add_edge(edges_label.getAttribute('from'), edges_label.getAttribute('to'), strength=float(edges_label.getAttribute('strength'))) G.add_edge(edges_label.getAttribute('to'), edges_label.getAttribute('from'), strength=float(edges_label.getAttribute('strength'))) members.network_list.append(G) members.network_dict.update({network_label.getAttribute('ID'): G}) members.old_network_list = members.network_list.copy() if __name__ == '__main__': from other_tools import read_xml dom = read_xml( r"E:\code\PycharmProjects\execution_tool\external_file_for_cEvolution\ceMemberXml_C.xml" ) read_component_methods(dom) input()
count += 1 earn_list = [] time_list = [] attr_mu_sigma_list = [[60, 10, 'earn_list'], [600, 100, 'time_list']] for earn_mu, earn_sigma, i in attr_mu_sigma_list: l, u = earn_mu - 2 * earn_sigma, earn_mu + 2 * earn_sigma E = stats.truncnorm((l - earn_mu) / earn_sigma, (u - earn_mu) / earn_sigma, loc=earn_mu, scale=earn_sigma) the_list = eval(i) for j in list(E.rvs(task_num)): the_list.append(j) task_dom = read_xml("Task.xml") tasks_label = task_dom.createElement("Tasks") for i in range(task_matrix.shape[1]): task_label = task_dom.createElement("task") task_label.setAttribute("ID", "Task-" + str(i)) task_label.setAttribute("taskDetail", str(list(task_matrix[:, i]))) task_label.setAttribute("earn", str(earn_list[i])) task_label.setAttribute("time_limit", str(time_list[i])) tasks_label.appendChild(task_label) for j in range(task_matrix.shape[0]): tasks_label.setAttribute("dimension-{}-mu".format(j), str(mu_sigma_list[j][0])) tasks_label.setAttribute("dimension-{}-sigma".format(j), str(mu_sigma_list[j][1]))
def slot_btn_set_definition_path(self): """ 设置仿真定义文件路径 :return: no return """ try: xml_definition_path = QtWidgets.QFileDialog.getOpenFileName( self, "选择仿真定义xml文件", "./", "XML Files (*.xml);;All Files (*)") if xml_definition_path[0] == '' and xml_definition_path[0] == '': return self.def_xml_path_edit.setText(xml_definition_path[0]) definition_dom = read_xml(xml_definition_path[0]) external_func.external_func_file_path = xml_definition_path[0] read_xml_to_module(definition_dom, self.global_dict) external_func.round_method_dict['attributes']['num'] = 16549 member_path_label = definition_dom.getElementsByTagName( "memberModelFilePath")[0] self.members_xml_path_edit.setText( member_path_label.firstChild.data) def_id_label = definition_dom.getElementsByTagName( "simulationExecutionMetaModel")[0] self.definition_ID_edit.setText(def_id_label.firstChild.data) member_meta_label = definition_dom.getElementsByTagName( "memberMetaModelFilePath")[0] self.meta_member_ID_edit.setText(member_meta_label.firstChild.data) generation_label = definition_dom.getElementsByTagName( "simulationRoundNumber")[0] self.generation_Edit.setText(generation_label.firstChild.data) self.MyThread.generation_upper = int( generation_label.firstChild.data) inherited_label = definition_dom.getElementsByTagName( "inherited")[0] global inherited if int(inherited_label.firstChild.data): # 如果继承数据 self.inherited_Edit.setText("True") inherited = True else: self.inherited_Edit.setText("False") inherited = False self.step_size_Edit.setText( "1") # 如果不继承,则说明每一轮仿真都是从最初始状态开始的,那么步长将不存在意义 self.step_size_Edit.setEnabled(False) # 根据这个路径来读取成员 member_dom = read_xml(self.members_xml_path_edit.text()) # 服务信息更新显示 self.service_msg_log_text.append( str(datetime.now()) + ': ' + 'Read member from: ' + self.members_xml_path_edit.text()) # 解析成员 # global net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c # net_p2p, net_p2a, net_p2m, net_p2c, net_c2m, net_c2c = net_work_read(member_dom) # global primitives, advisers, monitorMembers, collectives # primitives, advisers, monitorMembers, collectives = member_read(member_dom) # 读取一下各个成员的数目与基本信息,并在界面上显示 id_role_dict, member_number, p_number, c_number, a_number, m_number = format_members_id_role( member_dom) read_member(member_dom) read_network(member_dom) read_pattern(member_dom) read_component_methods(member_dom) members.member_dom = member_dom members.member_file_path = self.members_xml_path_edit.text() members.member_num = member_number self.reset_member_tableWidget(member_number, id_role_dict) self.primitive_num_edit.setText(str(p_number)) self.adviser_num_edit.setText(str(a_number)) self.monitor_num_edit.setText(str(m_number)) self.collective_num_edit.setText(str(c_number)) self.service_msg_log_text.append( str(datetime.now()) + ': ' + "Primitive:{}|Adviser:{}|Monitor:{}|Collective:{}".format( p_number, a_number, m_number, c_number)) self.service_msg_log_text.append( str(datetime.now()) + ': ' + 'Read definition from: ' + member_path_label.firstChild.data) except Exception: raise
from other_tools import read_xml, write_xml from random import shuffle, randint member_dom = read_xml(r"ceMemberXml_C.xml") task_dom = read_xml(r"Task.xml") task_labels = task_dom.getElementsByTagName("task") decider_labels = member_dom.getElementsByTagName("deciderInfo") task_id_list = [] # 取出所有任务ID for task_label in task_labels: task_id = task_label.getAttribute("ID") task_id_list.append(task_id) # 集合划分 shuffle(task_id_list) # 插板 tmp_indx = list(range(task_id_list.__len__() - 1)) index_ = [] for _ in range(len(decider_labels) - 1): shuffle(tmp_indx) index_.append(tmp_indx.pop(0)) index_.append(task_id_list.__len__() - 1) index_.sort() the_i = 0 # 取出所有原子型成员的决策器 for decider_label, k in zip(decider_labels, range(len(index_))): the_j = index_[k] decider_label.setAttribute("任务ID集合", str(task_id_list[the_i:the_j])) the_i = the_j
from other_tools import read_xml from matplotlib import pyplot as plt dom = read_xml( r"E:\code\PycharmProjects\execution_tool\record_dir\data100.xml") root = dom.documentElement results = [] result_labels = dom.getElementsByTagName("Result") one_attribute_dict0 = {} one_attribute_dict1 = {} one_attribute_dict2 = {} a_list = [one_attribute_dict0, one_attribute_dict1, one_attribute_dict2] for result_label, one_attribute_dict in zip(result_labels, a_list): records = result_label.getElementsByTagName("Record") for record in records: for key, value in record.attributes.items(): if key not in one_attribute_dict: the_list = [] the_list.append(eval(value)) one_attribute_dict.update({key: the_list}) else: one_attribute_dict[key].append(eval(value)) key_list = list(record.attributes.keys()) for idx in range(len(key_list) - 1): plt.figure(idx) plt.plot(one_attribute_dict0[key_list[idx]], label='dynamic communication', color="blue", linewidth=1.5, linestyle="-") plt.plot(one_attribute_dict1[key_list[idx]],