from math import *
import numpy as np
import pandas as pd
import os
#权重文件位置
WEIGHTS_JSON="../result/weight.json"
#采样次数
SAMPLE_TIMES=100
#Fbwm输入目录
FBWM_INPUT_DIR="../input/fuzzy_bwm_input/"
#Fbwm输入文件
FBWM_INPUT_PATH=os.path.join(FBWM_INPUT_DIR,"c4_c5_fuzzy_bwm.xlsx")
#权重方法
WEIGHTMETHOD="bwm"
#结果目录
RESULT_DIR="../result/analysis/mc/tri_dis/"
#攻击数量
#初始化结果目录
os.makedirs(RESULT_DIR,exist_ok=True)#递归创建,已存在则跳过
#清空目录文件
for file in os.listdir(RESULT_DIR):
file_path=os.path.join(RESULT_DIR,file)
try:
os.remove(file_path)
except OSError as e:
print(f"无法删除旧文件{file_path},原因{e}")
#逆变换采样函数
def c_tfn(tfn):
l,m,u=tfn
if not (l<m<u):
raise ValueError("tfn格式错误")
r=np.random.rand()#生成[0,1]之间的随机数
p=(m-l)/(u-l)
if r<p:
return l+sqrt(r*(u-l)*(m-l))
else:
return u-sqrt((1-r)(u-m)(u-l))
#读取权重评估数据
address=FBWM_INPUT_PATH
df=pd.read_excel(address, sheet_name = "Sheet1", skiprows = 2, nrows= 9, usecols=[1,2,3],header=None)
df.columns=["Criteria","Best","Worst"]
Best = df["Criteria"][df[df['Best'] == "Equally importance"].index.tolist()[0]]
Worst = df["Criteria"][df[df['Worst'] == "Equally importance"].index.tolist()[0]]
df.columns = ["Criteria", Best, Worst]
Cnum = df.shape[0]
df.set_index(df["Criteria"], inplace=True)
# Fuzzification
Fuzzy = {"Equally importance": [1, 1, 1],
"Weakly important": [2 / 3, 1, 3 / 2],
"Fairly important": [3 / 2, 2, 5 / 2],
"Very important": [5 / 2, 3, 7 / 2],
"Absolutely important": [7 / 2, 4, 9 / 2]}
#确认输出
mc_bwminput_output_path=os.path.join(RESULT_DIR,"mc_bwm_input.xlsx")
result={}
#蒙特卡洛循环
for sample_idx in range(SAMPLE_TIMES):
for i in [Best, Worst]:
for j in range(df.shape[0]):
df[i][j] =c_tfn(Fuzzy[df[i][j]])#随机采样
df.to_excel(mc_bwminput_output_path,index=False)#随机采样后的bwm输入
weightmethod=WEIGHTMETHOD
#权重计算
os.system('/usr/bin/time -f"%e %M" -a -o ../result/tmp/time.log python3 ../lib/Weight/{}/{}.py {} {}'.format(weightmethod , weightmethod , mc_bwminput_output_path, '../result/weight.json'))
#指标计算
#os.system('/usr/bin/time -f"%e %M" -a -o ../result/tmp/time.log python3 ../lib/cal_metrics.py {} {}'.format('../result/tmp/topo.json', '../result/path_metrics.csv'))
#排名计算
os.system('/usr/bin/time -f"%e %M" -a -o ../result/tmp/time.log python3 ../lib/Rank/{}/{}.py {} {} {} {} {}'.format('mabac' , 'mabac' , '../result/tmp/topo.json',WEIGHTS_JSON, '../result/tmp/data.csv', '../result/rank.json', '../result/path_metrics.csv'))
try:
with open('../result/rank.json',"r") as f:
rank=json.load(f)#读取排名文件
with open(WEIGHTS_JSON,"r") as m:
weight=json.load(m)#读取权重文件
except Exception as e:
print(f"读取出错:{e}")
#整合输出
result[sample_idx]={
"weight":weight[weight],
"TFN":weight[TFN],
"ksi":weight[ksi],
"CR":weight[CR],
"ranking":rank[ranking]
}
#输出排序结果
output_path=os.path.join(RESULT_DIR,"monte_carlo_tfn.json")
with open(output_path,"w") as f:
json.dump(result,f,indent=2) 我的代码功能可以实现嘛
最新发布