def getbininfo(nop, folders, methods): writer = pandas.ExcelWriter(folders[nop] + 'IndividualBinInfo.xlsx', engine='openpyxl') for opal in range(nop): itemfile = glob(folders[opal] + '*.txt') binc, binh, items = itemmaker.makeitems(itemfile[0]) info = itemmaker.getiteminfo(items) xs, ys = getxys(folders[opal], len(items)) for f in range(len(xs)): xmatrix = np.zeros((len(items), len(items))) for i in range(len(items)): for j in range(len(items)): xmatrix[i, j] = xs[f].get_value(i, j, takeable=True) binws = np.dot(xmatrix, info[0]) binhs = np.dot(xmatrix, info[1]) binws_series = [] binhs_series = [] end = np.where(ys[f] == 0) for i in range(end[0][0]): binws_series.append(binws[i, 0]) binhs_series.append(binhs[i, 0]) if f == 0: dfw = pandas.DataFrame(binws_series) dfh = pandas.DataFrame(binhs_series) else: df1 = pandas.DataFrame(binws_series) df2 = pandas.DataFrame(binhs_series) dfw = pandas.concat([dfw, df1], ignore_index=True, axis=1) dfh = pandas.concat([dfh, df2], ignore_index=True, axis=1) dfw.to_excel(writer, sheet_name=methods[opal] + '_weight') dfh.to_excel(writer, sheet_name=methods[opal] + '_height') writer.save()
def main(): # Get info to create items n = eval(input('Please enter the number of items to be sorted: \n')) folder = input( 'Please enter the name of the folder where your input file is: \n') datafile = input('Please enter the name of the input file: \n') # Create item objects and initialize a bin packing problem class data = folder + datafile binc, binh, items = makeitems(data) bpp = BPP(n, binc, binh, items) # Input items into the heuristic in the way they were ordered in # the datafile. Each "gene" should correspond to an item's index. solid = 1 # give this solution an id number chromosome = list(range(1, n + 1)) x, y = ed(solid, chromosome, bpp) np.savetxt(folder + str(solid) + '_x.txt', x, fmt='%i', header='Item Location Matrix x:') np.savetxt(folder + str(solid) + '_y.txt', y, fmt='%i', header='Bins Used Matrix y:')
def setUp(self): data = 'GAMMA-PC/SBSBPP500/Experiment01/SBSBPP500_run1.txt' self.n = 500 pop = 50 # members per gen. end = 750 # function evaluations binc, binh, items = makeitems(data) moop = mop.MOproblem(pop, items) self.bpp = grasp.BPP(self.n, binc, binh, items, moop)
def setUp(self): data = 'example/example500.txt' self.n = 500 pop = 50 # members per gen. end = 750 # function evaluations binc, binh, items = makeitems(data) moop = mop.MOproblem(pop, items) self.bpp = grasp.BPP(self.n, binc, binh, items, moop)
def moma(n, folder, datafile): existing_files = glob(folder + '*.out') filename = folder + 'run%d.out' % (len(existing_files) + 1) data = folder + datafile # Initialize algorithm pop = 100 # members per gen. end = 25000 # function evaluations or 250 gen. outf.startout(filename, n, end, data, 'MOMA') startt = datetime.now() print(' ', startt) print( '*******************************************************************************' ) print(' Method: MOMA\n') print(' data: ', datafile) print( '*******************************************************************************' ) binc, binh, items = makeitems(data) bpp = bp.BPP(n, binc, binh, items) moop = mop.MOproblem(pop, items) gen = Generation(n, pop, end, items, bpp, moop) gen.initialp() gen.makeq() # NSGA-II - Local search while not gen.endgen(): gen.rungen() outf.genout(filename, gen.gett(), pop, gen.getq(), [gen.getarch(), []]) # Get final nondominated set aslimit = 75 r, allfronts = fnds(gen.getarch()) if len(allfronts[0]) > aslimit: gen.fittruncation(allfronts[0], aslimit) ndset = approx(gen.getarch()) # Make output see(ndset, folder) import csv with open(folder + 'ApproximationSet.csv', 'w') as csvfile: csvwriter = csv.writer(csvfile, dialect='excel', delimiter=',') csvwriter.writerow(['Solution ID', 'f[1]', 'f[2]', 'f[3]']) for m in ndset: csvwriter.writerow( [m.getindex(), m.getbins(), m.getmaxh(), m.getavgw()]) outf.endout(filename) print('This algorithm has completed successfully.')
def algorithm(n, folder, datafile): existing_files = glob(folder + '*.out') fname = folder + 'run%d.out' % (len(existing_files) + 1) data = folder + datafile # Initialize algorithm pop = 100 # members per gen. end = 25000 # function evaluations outf.startout(fname, n, end, data, 'GAMMA-PC') startt = datetime.now() print(' ', startt) print( '*******************************************************************************' ) print(' Method: GAMMA-PC\n') print(' data: ', datafile) print( '*******************************************************************************' ) binc, binh, items = makeitems(data) moop = mop.MOproblem(pop, items) bpp = grasp.BPP(n, binc, binh, items, moop) gen = Generation(n, pop, end, items, bpp, moop) gen.initialq() # Remove this after finishing import warnings warnings.simplefilter('error', RuntimeWarning) # Algorithm while not gen.endgen(): outf.gen_probabilities(fname, gen.gett() + 1, **gen.get_probabilities()) gen.rungen() outf.genout(fname, gen.gett(), pop, gen.getq(), gen.getarch(), onlyapprox=True) # Make output ndset = gen.finalapproxset() savefitvals(ndset, folder) savexys(ndset, folder) see(ndset, folder) outf.endout(fname) print('This algorithm has completed successfully.')
def nsgaii(n, folder, file): import outformat as outf from glob import glob existing_files = glob(folder + '*.out') filename = folder + 'run%d.out' % (len(existing_files) + 1) data = folder + file # Initialize algorithm pop = 100 # members per gen. end = 25000 # function evaluations or 250 gen. outf.startout(filename, n, end, data, 'NSGA-II') startt = datetime.datetime.now() print(' ', startt) print( '*******************************************************************************' ) print(' Method: NSGA-II\n') print(' data: ', file) print( '*******************************************************************************' ) binc, binh, items = makeitems(data) bpp = bp.BPP(n, binc, binh, items) gen = Generation(n, pop, end, items, bpp) gen.initialp() gen.makeq() # NSGA-II while not gen.endgen(): gen.rungen() outf.genout(filename, gen.gett(), pop, gen.getq(), gen.getfnts()) # Make output ndset = approx(gen.getarch()) see(ndset, folder) import csv with open(folder + 'ApproximationSet.csv', 'w') as csvfile: csvwriter = csv.writer(csvfile, dialect='excel', delimiter=',') csvwriter.writerow(['Solution ID', 'f[1]', 'f[2]', 'f[3]']) for m in ndset: csvwriter.writerow( [m.getindex(), m.getbins(), m.getmaxh(), m.getavgw()]) outf.endout(filename) print('This algorithm has completed successfully.')
def main(): # Get info to create items n = eval(input('Please enter the number of items to be sorted: \n')) folder = input('Please enter the name of the folder where your input file is: \n') datafile = input('Please enter the name of the input file: \n') # Create item objects and initialize a bin packing problem class data = folder + datafile binc, binh, items = makeitems(data) bpp = BPP(n, binc, binh, items) # Input items into the heuristic in the way they were ordered in # the datafile. Each "gene" should correspond to an item's index. solid = 1 # give this solution an id number chromosome = list(range(1, n + 1)) x, y = ed(solid, chromosome, bpp) np.savetxt(folder + str(solid) + '_x.txt', x, fmt='%i', header='Item Location Matrix x:') np.savetxt(folder + str(solid) + '_y.txt', y, fmt='%i', header='Bins Used Matrix y:')
def recheck(n, folder, filename, flag=None): # This module allows the user to recheck solutions for constraint # violations after calculations have been completed. # - n is the number of items to be sorted # - folder is the main folder where the input file is located # - filename is the input file name # - flag (optional) is the name of the folder where the solution # matrices are stored data = folder + filename # Reformulate item objects and bin packing problem binc, binh, items = itemmaker.makeitems(data) bpp = bp.BPP(n, binc, binh, items) print('Max bin weight:', binc) print('Max bin height:', binh) # Go through each solution (x-y pair) to find violations xs, ys, solids = getxys(folder + flag, n) for m in range(len(xs)): concheck(solids[m], xs[m], bpp) xycheck(solids[m], xs[m], ys[m])
def getbinplots(nop, folders, methods): # This function sorts through the data to make plots about # individual bin characteristics. print('Making Bin Weights plot.') wplot = pyplot.figure() ax = wplot.add_subplot(111) dfseries = [] for opal in range(nop): itemfile = glob(folders[opal] + '*.txt') binc, binh, items = itemmaker.makeitems(itemfile[0]) info = itemmaker.getiteminfo(items) xs, ys = getxys(folders[opal], len(items)) xplot = [] for f in range(len(xs)): xplot.append(np.zeros((len(items), len(items)))) for i in range(len(items)): for j in range(len(items)): xplot[f][i, j] = xs[f].get_value(i, j, takeable=True) sols_wavg, sols_wmax = binwsplot(xplot, ys, info[0], colors[opal], methods[opal]) df1 = pandas.DataFrame({ 'Solution Number': range(1, 1 + len(sols_wavg)), 'Weight': sols_wavg, 'Statistic': 'Average', 'Method': methods[opal] }) df2 = pandas.DataFrame({ 'Solution Number': range(1, 1 + len(sols_wavg)), 'Weight': sols_wmax, 'Statistic': 'Maximum', 'Method': methods[opal] }) dfopal = pandas.concat((df1, df2), axis=0) dfseries.append(dfopal) fig = folders[nop] + 'BinWeight_comparison.eps' ax.set_xlim(xmin=0) ax.set_xlabel('Bin Weight') ax.legend(loc='upper right', frameon=True) pyplot.savefig(fig, format='eps', dpi=2000) pyplot.close() dfstats = pandas.concat(dfseries, axis=0) getbinstatsplot(dfstats, folders[nop])
def momad(n, folder, file): existing_files = glob(folder + '*.out') filename = folder + 'run%d.out' % (len(existing_files) + 1) data = folder + file # Initialize Algorithm end = 25000 # function evaluations method = 'MOMAD' outf.startout(filename, n, end, data, method) startt = datetime.now() print(' ', startt) print('*******************************************************************************') print(' Method: MOMAD \n') print(' data: ', file) print('*******************************************************************************') if n <= 600: nso = n else: nso = 600 # number of single-objective functions binc, binh, items = makeitems(data) bpp = bp.BPP(n, binc, binh, items) moop = MOproblem(nso, items) gen = MOMADgen(n, bpp, moop, items, end) gen.initialize() # MOMAD while not gen.endgen(): gen.rungen() fronts = [] fronts.append(gen.getpe()) fronts.append([]) outf.genout(filename, gen.gett(), nso, gen.getpl(), fronts) see(gen.pe, folder) import csv with open(folder + 'ApproximationSet.csv', 'w') as csvfile: csvwriter = csv.writer(csvfile, dialect='excel', delimiter=',') csvwriter.writerow(['Solution ID', 'f[1]', 'f[2]', 'f[3]']) for m in gen.pe: csvwriter.writerow([m.getindex(), m.getbins(), m.getmaxh(), m.getavgw()]) outf.endout(filename) print('This algorithm has completed successfully.')
def moepso(n, folder, inputfile): existing_files = glob(folder + '*.out') filename = folder + 'run%d.out' % (len(existing_files) + 1) data = folder + inputfile # Initialize Algorithm pop = 500 # swarm members end = 25000 # function evaluations method = 'MOEPSO' outf.startout(filename, n, end, data, method) startt = datetime.now() print(' ', startt) print('*******************************************************************************') print(' Method: MOEPSO \n') print(' data: ', inputfile) print('*******************************************************************************') binc, binh, items = makeitems(data) bpp = bp.BPP(n, binc, binh, items) moop = mop.MOproblem(pop, items) gen = MOEPSOgen(n, pop, end, bpp, moop, items) # MOEPSO generations while not gen.endgen(): gen.rungen() fronts = [gen.getgbest(), []] outf.genout(filename, gen.gett(), pop, gen.getp(), fronts) see(gen.gbest, folder, 'variables/') import csv with open(folder + 'ApproximationSet.csv', 'w') as csvfile: csvwriter = csv.writer(csvfile, dialect='excel', delimiter=',') csvwriter.writerow(['Solution ID', 'f[1]', 'f[2]', 'f[3]']) for m in gen.gbest: csvwriter.writerow([m.getindex(), m.getbins(), m.getmaxh(), m.getavgw()]) outf.endout(filename) print('This algorithm has completed successfully.')