import pandas as pd import sys import copy import glob import os import xlrd class…
- User
import pandas as pd import sys import copy import glob import os
import xlrd
class Generator:
""" # Generator Class Generates the instances of ALBHW problem """ h1Cost = 100 # type-1工人的成本c1=100 h1Prop = 0.2 # type-1任务所占百分比20% h2Prop = 0.3 # type-2:30% h3Prop = 0.5 # type-3:50% w1 = (1.10,1.20) # 时间因素 w2 = (0.70,0.85) # 成本因素 qntLavoratori = 3 # 代表工人数量的变量l=3 groups = None instances = {} pathInstances =r'D:\sy\python\SALBP_benchmark\large data set_n=100' # SALB实例所在位置的属性 pathDestination = r'D:\sy\python\ALBHW-Instances-master' # 用于存储创建ALBHW实例位置的属性 # pathDetails = r'D:\sy\python\SALBP_benchmark\Details of the small data set (n=20).xlsx' # 用于存储详细信息文件路径的属性 pathDetails=r'D:\sy\python\SALBP_benchmark\Details of the large data set (n=100).xlsx' dict = {"bimodal":"BM", "peak at the bottom":"PB", "peak in the middle": "PM",# 任务时间分布 "extremely tricky":"ET", "very tricky": "VT", "less tricky":"LT", "tricky": "TR", "open (not known yet)": "OP"}#ET极其棘手 def __init__(self, pathDetails : str, pathInstances : str, pathDestination : str): self.pathDetails = pathDetails self.pathInstances = pathInstances self.pathDestination = pathDestination self.create_folders() def create_folders(self): if not os.path.exists(self.pathDestination + "Large/Instance1.0-1.0"): os.makedirs(self.pathDestination + "Large/Instance1.0-1.0") for r1 in self.w1: # self.w1、self.w2分别是时间因素和成本因素的元组。每个元组包含两个值。r1、r2是用来遍历w1w2这些元组中的值的变量。 for r2 in self.w2: if not os.path.exists(self.pathDestination + "Large/Instance" + str(r1) + "-" + str(r2)): os.makedirs(self.pathDestination + "Large/Instance" + str(r1) + "-" + str(r2)) def select_data(self, type: str): details = None try: details = pd.read_excel(self.pathDetails, skiprows=[0]) # 尝试用Pandas库的read_excel函数从指定路径的excel文件中读取数据,跳过第一行(通常是标题行)。 except Exception : print("Not able to open the file: {0}".format('path')) # print(e) selected = details.loc[(details["<Graph structure>"] == type) & (details["<Trickiness category>"] != "open (not known yet)")].copy() # Order by Time Distribuition and Desired OS self.groups = selected.groupby(["<Times Distribution>", "<Desired OS>"]) genera.select_data("ALL") def choosing_instances(self, n : int): for name, group in self.groups: # Create the keys for i in group.iloc[:,5:6].values: if((name[0], name[1], i[0]) not in self.instances): self.instances[(name[0], name[1], i[0])] = [] if(len(group) < n): qnt = len(group) else: qnt = n inst = group.sample(qnt) for i in inst.values: self.instances[(name[0], name[1], i[5])].append(i[1]) def creating_instancesSALB(self): for i,k in self.instances.items(): for ins in k: with open(self.pathInstances + ins + ".alb", "r") as instance: instanceRaw = [i.replace(","," ") for i in instance.readlines()[:-1]] instanceRaw.append("<type workers>\n") instanceRaw.append(str(1)+"\n") nTasks = int(instanceRaw[1].strip('\n')) instanceRaw.append("<task types>\n") tTypes = [] cycT = int(instanceRaw[4]) for aux in range(0, nTasks): instanceRaw.append("1\n") tTypes.append(1) instanceRaw.append("<task times>\n") tTimes = [int(times.strip('\n').split(" ")[1]) for times in instanceRaw[11:nTasks+11]] for aux in range(0, nTasks): instanceRaw.append(str(tTimes[aux]) + "\n") instanceRaw.append("<worker costs>\n") instanceRaw.append(str(self.h1Cost) + "\n") instanceRaw.append("<end>") nameFile = str(ins.split("_")[2])+ "_"+ str(1.0) + "_" + str(1.0) + "_" + str(i[1]) + "_" + self.dict[i[0]]+ "_" + self.dict[i[2]] + ".albhw" namePath = self.pathDestination + "Large/Instance" + str(1.0) + "-" + str(1.0) + "/L" with open(namePath+nameFile, "w") as newInstance: newInstance.writelines(instanceRaw) def creating_instancesALBHW(self): for rule1 in range(len(self.w1)): for rule2 in range(len(self.w2)): for i,k in self.instances.items(): for ins in k: with open(self.pathInstances + ins + ".alb", "r") as instance: instanceRaw = [i.replace(","," ") for i in instance.readlines()[:-1]] instanceRaw.append("<type workers>\n") instanceRaw.append(str(self.qntLavoratori)+"\n") nTasks = int(instanceRaw[1].strip('\n')) instanceRaw.append("<task types>\n") tTypes = [] cycT = int(instanceRaw[4]) for aux in range(0, int(nTasks*self.h1Prop)): instanceRaw.append("1\n") tTypes.append(1) for aux in range(0, int(nTasks*self.h2Prop)): instanceRaw.append("2\n") tTypes.append(2) for aux in range(0, int(nTasks*self.h3Prop)): instanceRaw.append("3\n") tTypes.append(3) instanceRaw.append("<task times>\n") tTimes = [int(times.strip('\n').split(" ")[1]) for times in instanceRaw[11:nTasks+11]] for aux in range(0, nTasks): worker2 = round(tTimes[aux] * self.w1[rule1]) if 2 <= tTypes[aux] else "INF" if(worker2 != "INF" and worker2 <= cycT): worker3 = round(worker2 * self.w1[rule1]) if 3 <= tTypes[aux] else "INF" else: worker3 = "INF" instanceRaw.append(str(tTimes[aux]) + " " + str(worker2) + " " + str(worker3) + "\n") instanceRaw.append("<worker costs>\n") instanceRaw.append(str(self.h1Cost) + "\n") calc = self.h1Cost * self.w2[rule2] calc2 = calc * self.w2[rule2] instanceRaw.append(str(round(calc)) + "\n") instanceRaw.append(str(round(calc2)) + "\n") instanceRaw.append("<end>") namePath = self.pathDestination + "Large/Instance" + str( self.w1[rule1]) + "-" + str( self.w2[rule2]) nameInstance = "/L" + str(ins.split("_")[2])+ "_"+ str(self.w1[rule1]) + "_" + str(self.w2[rule2]) + "_" + str(i[1]) + "_" + self.dict[i[0]]+ "_" + self.dict[i[2]] + ".albhw" with open(namePath + nameInstance, "w") as newInstance: newInstance.writelines(instanceRaw) - Assistant
这个错误是由于在代码中使用了sys.argv来接受命令行传入的参数,但是在运行的时候未传入足够的参数导致的。具体来说,代码中使用了sys.argv[9]来获取第9个参数,但是实际传入的参数数量不足9个,导致索引超出范围报错。
要解决这个问题,你需要确保在运行代码的时候传入足够的参数,或者在代码中对sys.argv进行适当的修改,例如使用if语句来确保获取到足够的参数后再进行相关操作。
另外,你还可以使用argparse库来更方便地处理命令行参数,该库可以帮助你定义期望的参数类型和数量,并提供相关的错误提示信息。
- User
报错: Traceback (most recent call last): File "D:\sy\python\ALBHW-Instances-master\Generator\Generator_vInputset.py", line 192, in genera.choosing_instances(int(sys.argv[5])) ~~~~~~~~^^^ IndexError: list index out of range
- Assistant
这个错误的原因还是由于在代码中使用了sys.argv[index]来获取命令行传入的参数,但实际传入的参数数量不足导致索引超出范围。
解决这个问题的方法是确保在运行代码的时候传入足够的参数。具体来说,这里需要至少传入6个参数给脚本,例如:
python3 Generator_vInputset.py 参数1 参数2 参数3 参数4 参数5 参数6请确保实际传入的参数数量与代码中使用的sys.argv[index]的索引是匹配的。如果你不确定应该传入哪些参数,可以查看代码段中的
sys.argv[5]的索引,然后确保在运行时传入该索引所对应的参数。另外,你还可以通过在代码中添加适当的检查和错误处理来避免这个问题。例如,可以使用条件语句检查sys.argv列表的长度是否足够:
if len(sys.argv) >= 6: genera.choosing_instances(int(sys.argv[5])) else: print("Not enough arguments!")这样就可以避免因为参数数量不足而导致的IndexError。
- User
具体代码怎么改
- Assistant
根据你提供的错误信息,你可以使用以下代码来避免索引超出范围的错误:
if len(sys.argv) >= 6: # 检查是否至少传入了6个参数 n = int(sys.argv[5]) # 获取第6个参数作为实例数量 genera.choosing_instances(n) else: print("Not enough arguments!") # 参数数量不足时输出提示信息这样,如果运行脚本时传入的参数数量不足6个,就会输出提示信息。否则,就会继续执行
genera.choosing_instances(n)来选择实例。另外,请记得将代码中的
sys.argv[5]和sys.argv[9]分别修改为对应要获取的参数的索引。这样就可以根据实际传入参数的数量来调整索引值,以确保安全获取参数和避免索引错误。 - User
将这段代码 if len(sys.argv)>=6: n=int(sys.argv[5]) genera.choosing_instances(n) else: print("Not enough arguments!")加到details = None try: details = pd.read_excel(self.pathDetails, skiprows=[0]) # 尝试用Pandas库的read_excel函数从指定路径的excel文件中读取数据,跳过第一行(通常是标题行)。 except Exception : # 如果读取失败,会打印出错误消息 print("Not able to open the file: {0}".format('path')) # print(e) selected = details.loc[(details[""] == type) & (details[""] != "open (not known yet)")].copy() # Order by Time Distribuition and Desired OS self.groups = selected.groupby(["", ""]) # 将符合条件的数据按""和 ""两列进行分组, genera.select_data("ALL") 的后面对吗
- Assistant
是的,你可以将该段代码添加到
try块的details定义之前。这样能够确保在尝试读取Excel文件之前先检查是否有足够的参数。下面是修改后的代码:details = None try: if len(sys.argv) >= 6: n = int(sys.argv[5]) genera.choosing_instances(n) else: print("Not enough arguments!") details = pd.read_excel(self.pathDetails, skiprows=[0]) except Exception: print("Not able to open the file: {0}".format(self.pathDetails)) selected = details.loc[(details["<Graph structure>"] == type) & (details["<Trickiness category>"] != "open (not known yet)")].copy() self.groups = selected.groupby(["<Times Distribution>", "<Desired OS>"]) genera.select_data("ALL")将这段代码添加到
try块的details定义之前,可以确保先检查参数数量是否足够,然后再进行Excel文件的读取和其他操作。如果参数数量不足,则会输出错误提示信息。 - User
添加了之后还是报错:Traceback (most recent call last): File "D:\sy\python\ALBHW-Instances-master\Generator\Generator_vInputset.py", line 197, in genera.choosing_instances(int(sys.argv[5])) ~~~~~~~~^^^ IndexError: list index out of range
- Assistant
很抱歉,我之前的回答有误。在这种情况下,确保您在运行脚本时传递了足够的参数是关键,否则会导致索引超出范围错误。请再次检查命令行中执行脚本的方式,确保传入了正确数量的参数。
如果您已经传入了正确数量的参数,但仍然遇到索引超出范围的错误,请确保通过正确的方式运行脚本。例如,使用以下命令来运行脚本:
python3 Generator_vInputset.py 参数1 参数2 参数3 参数4 参数5其中
参数1、参数2、参数3等是您在脚本中使用的实际参数,确保按照正确的顺序传递它们。如果第5个参数是用来指定实例数量的,那么应该确保在第5个位置传递一个整数。如果您仍然无法解决问题,请提供更多关于如何运行脚本以及您使用的参数的详细信息。这样我就能帮助您更好地诊断问题并提供解决方案。
- User
具体怎么做
- Assistant
非常抱歉给你带来困惑。如果在运行脚本时无法解决
IndexError错误,并且你确定已经传递了正确数量的参数,那么可能的原因是脚本中的sys.argv[5]索引值不正确。在你的代码中,
sys.argv[5]被用作实例数量。首先,请确保你正确地指定了实例数量,然后按以下步骤进行调试:- 在你的脚本开头,添加以下代码:
print("Number of command line arguments:", len(sys.argv)) print("Command line arguments:", sys.argv)这将打印出命令行参数的数量和参数列表。请检查打印的参数列表是否与你期望的一致