def flessenpost(shiplist, parcellist): # get sorted lists sorted_parcels = sortparcels(parcellist) sorted_ships = sortspacecrafts(shiplist) # create an extra list for remaining parcels remainders = [] extra = [] length = len(sorted_parcels) #worklist = sorted_parcels[0:int(length)] for parcel in reversed(range(len(sorted_parcels))): #print(f"parcel {parcel}") #print(f"mass = {sorted_parcels[parcel].mass}") if sorted_parcels[parcel].mass > 370: print("te groot") remainders.append(sorted_parcels[parcel]) elif checkmove(sorted_parcels[parcel], sorted_ships[3]): assign(sorted_ships[3], sorted_parcels[parcel]) elif checkmove(sorted_parcels[parcel], sorted_ships[2]): assign(sorted_ships[2], sorted_parcels[parcel]) elif checkmove(sorted_parcels[parcel], sorted_ships[1]): assign(sorted_ships[1], sorted_parcels[parcel]) elif checkmove(sorted_parcels[parcel], sorted_ships[0]): assign(sorted_ships[0], sorted_parcels[parcel]) else: remainders.append(sorted_parcels[parcel]) print("---------------------------------------") print(f"remainders1: {len(remainders)}") #print(f"space0 assigned/weight/vol: {sorted_ships[0].name}{len(sorted_ships[0].assigned)}/{sorted_ships[0].payload}/{sorted_ships[0].volume}") #print(f"space1 assigned/weight/vol: {sorted_ships[1].name}{len(sorted_ships[1].assigned)}/{sorted_ships[1].payload}/{sorted_ships[1].volume}") #print(f"space2 assigned/weight/vol: {sorted_ships[2].name}{len(sorted_ships[2].assigned)}/{sorted_ships[2].payload}/{sorted_ships[2].volume}") #print(f"space3 assigned/weight/vol: {sorted_ships[3].name}{len(sorted_ships[3].assigned)}/{sorted_ships[3].payload}/{sorted_ships[3].volume}") #print(possiblemovesA(shiplist, remainders)) dofirstmove(shiplist, remainders)
def postnl(shiplist, parcellist): """Takes as input a clear shiplist and parcellist. Greedily assigns parcels to spacecrafts. Saves the solution to a pickle file the filename of which is returned.""" # get sorted lists sorted_parcels = sortParcels(parcellist) sorted_ships = sortSpacecrafts(shiplist) # keep track of remainders remainders = [] # get the left half of the shiplist, from middle to left-end halfcrafts = len(sorted_ships) / 2 leftcrafts = sorted_ships[0:int(halfcrafts)] leftcrafts.reverse() # get the left half of the parcellist, from middle to left-end halfparcels = len(sorted_parcels) / 2 worklistleft = sorted_parcels[0:int(halfparcels)] worklistleft.reverse() # append parcels from left half of parcellist to ships from left half # of shiplist for i in range(int(halfparcels)): assigned = False for ship in leftcrafts: if checkmove(worklistleft[i], ship): assign(ship, worklistleft[i]) assigned = True break if assigned is False: remainders.append(worklistleft[i]) # get the right half of the parcellist, from middle to right-end worklistright = sorted_parcels[int(halfparcels):] # append parcels from half of both the parcel- and shiplist, back to the # right end of both lists for i in range(int(halfparcels)): assigned = False for ship in sorted_ships[int(halfcrafts):]: if checkmove(worklistright[i], ship): assign(ship, worklistright[i]) assigned = True break if assigned is False: remainders.append(worklistright[i]) # try to assign remainders assignRemainders(shiplist, remainders) # save shiplist of solution as a pickle file filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(shiplist, open(picklename, 'wb')) return picklename
def flessenpost2(shiplist, parcellist): sorted_parcels = sortparcels(parcellist) sorted_ships = sortspacecrafts(shiplist) remainders = [] for ship in range(len(sorted_ships)): for parcel in range(len(sorted_parcels)): print(f"parcel {parcel}") print(f"lengthparcels {len(sorted_parcels)}") if sorted_parcels[parcel].mass > 370: print("te groot") elif checkmove(sorted_parcels[parcel], sorted_ships[ship]): assign(sorted_ships[ship], sorted_parcels[parcel]) sorted_parcels.remove(sorted_parcels[parcel]) #else: #remainders.append(sorted_parcels[parcel]) print(f"remainders initieel: {len(sorted_parcels)}") print("---------------------------------------") #print(f"space0 assigned/weight/vol: {sorted_ships[0].name}{len(sorted_ships[0].assigned)}/{sorted_ships[0].payload}/{sorted_ships[0].volume}") #print(f"space1 assigned/weight/vol: {sorted_ships[1].name}{len(sorted_ships[1].assigned)}/{sorted_ships[1].payload}/{sorted_ships[1].volume}") #print(f"space2 assigned/weight/vol: {sorted_ships[2].name}{len(sorted_ships[2].assigned)}/{sorted_ships[2].payload}/{sorted_ships[2].volume}") #print(f"space3 assigned/weight/vol: {sorted_ships[3].name}{len(sorted_ships[3].assigned)}/{sorted_ships[3].payload}/{sorted_ships[3].volume}") #print(possiblemovesA(shiplist, remainders)) dofirstmove(shiplist, sorted_parcels)
def hillclimber(shiplist, parcellist): max = int(input("How many times do you want to run this algorithm: ")) while max == "": max = int(input("How many times do you want to run this algorithm: ")) startcost = calculatetotal(shiplist) startpackages = calculatepackages(shiplist) startsolution = solution(shiplist) for c in range(max): assignedparcellist = [e for i in shiplist for e in i.assigned] remainparcellist = [ i for i in parcellist if i not in assignedparcellist ] ship1 = shiplist[random.randint(0, len(shiplist) - 1)] ship2 = shiplist[random.randint(0, len(shiplist) - 1)] while ship1 == ship2: ship2 = shiplist[random.randint(0, len(shiplist) - 1)] package1 = ship1.assigned[random.randint(0, len(ship1.assigned) - 1)] package2 = ship2.assigned[random.randint(0, len(ship2.assigned) - 1)] undomove(ship1, package1) undomove(ship2, package2) if checkmove(package2, ship1) and checkmove(package1, ship2): assign(ship1, package2) assign(ship2, package1) shiplist = dhl(shiplist, remainparcellist) if startcost <= calculatetotal(shiplist): startcost = calculatetotal(shiplist) startsolution = solution(shiplist) if startpackages < calculatepackages(shiplist): startcost <= calculatetotal(shiplist) startpackages = calculatepackages(shiplist) startsolution = solution(shiplist) else: assign(ship1, package1) assign(ship2, package2) loadstate(startsolution, shiplist) filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(shiplist, open(picklename, 'wb')) return picklename
def dhl(shiplist, parcellist): """Takes as input a clear shiplist and parcellist. Greedily assigns parcels to spacecrafts, based on mass-volume ratio. Returns a shiplist of the solution.""" # keep track of remainders extralist = [] # for each parcel, find the best move based on mass-volume ratio for i in parcellist: defaultship = calculateoptimal(i, shiplist) # check if the move is possible, else make this parcel a remainder if checkmove(i, defaultship): assign(defaultship, i) else: extralist.append(i) # keep track of final remainders finallist = [] # for each remainder, find a move, beginning with the best move possible # based on mass-volume ratio for c in extralist: shipmv = [x.mv for x in shiplist] while True: defaultship = (0, 400) for z in range(len(shipmv)): difference = max(shipmv[z], i.mv) - min(shipmv[z], i.mv) if difference < defaultship[1]: defaultship = (z, difference) if checkmove(i, shiplist[defaultship[0]]): assign(shiplist[defaultship[0]], i) break else: shipmv.pop(defaultship[0]) if len(shipmv) == 0: finallist.append(i) break return shiplist
def flessenpost(shiplist, parcellist): """Takes as input a clear shiplist and parcellist. Greedily assigns parcels to spacecrafts, taking into consideration outliers. Saves the solution to a pickle file the filename of which is returned.""" # get sorted outlierbound and reversed parcel- and shiplist outlierbound = computeOutliers(parcellist) sorted_parcels = sortParcels(parcellist) sorted_parcels.reverse() sorted_ships = sortSpacecrafts(shiplist) sorted_ships.reverse() # keep track of remaining parcels and outliers remainders = [] outliers = [] # assign parcels to ships beginning with the highest ratios, skip outliers for parcel in range(len(sorted_parcels)): assigned = False if sorted_parcels[parcel].mv > outlierbound: outliers.append(sorted_parcels[parcel]) for ship in sorted_ships: if checkmove(sorted_parcels[parcel], ship): assign(ship, sorted_parcels[parcel]) assigned = True break if assigned is False: remainders.append(sorted_parcels[parcel]) # try to assign remainders assignRemainders(shiplist, remainders) # try to assign outliers assignRemainders(shiplist, outliers) # save shiplist of solution as a pickle file filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(shiplist, open(picklename, 'wb')) return picklename
def ns(shiplist, parcellist): '''ns takes in two arguments, a list of ship objects and a list of cargo objects. it assigns parcels to spaceships untill they're full. after a spaceship has been filled it chooses a random new ship''' randomchoice = random.randint(0, len(shiplist) - 1) ship = shiplist[randomchoice] spacecraft = Spacecraft(ship.name, ship.nation, ship.payload, ship.volume, ship.mass, ship.basecost, ship.ftw) fleet = [spacecraft] for i in parcellist: if checkmove(i, fleet[-1]): assign(fleet[-1], i) else: randomchoice = random.randint(0, len(shiplist) - 1) ship = shiplist[randomchoice] spacecraft = Spacecraft(ship.name, ship.nation, ship.payload, ship.volume, ship.mass, ship.basecost, ship.ftw) fleet.append(spacecraft) assign(fleet[-1], i) return solution(fleet)
def Beam(shiplist, parcellist): """Takes as input a clear ship- and parcellist. Performs a beamsearch of width n, based on correspondence of mass-volume ratio. Writes the shiplist of the best found solution to a pickle file the filename of which is returned .""" print( f"Running this beam algorithm might take a while depending on the chosen beamwidth. If you're looking for a fast result advice a beamwidth between 2-5." ) # get beamwidth beamwidth = GetInput(shiplist, parcellist) # compute amount of moves optimal solution maxmoves = len(parcellist) # initialize queue with empty Parcellist object queue = [] solutions = [] bestsolution = None counter = len(queue) object = Packinglist(counter, [], 0) queue.append(object) solutions.append(object) kidlist = [] # while there's objects in queue while len(queue) != 0: quelength = len(queue) for i in range(quelength): # get first object from queue to work with first = queue.pop(0) # perform the moves this object has with him already for j in range(len(first.moves)): shiplist, parcellist = assignBeam(shiplist, parcellist, first.moves[j][0], first.moves[j][1]) # compute this object's children kids = possiblemovesA(shiplist, parcellist) # create a packinglist object for each child for move in kids: base = copy.deepcopy(first.moves) base.append(move) ratiodiff = abs(1 - (move[0].mv / move[1].mv)) kid = Packinglist(counter, base, ratiodiff) counter += 1 kidlist.append(kid) for k in range(len(first.moves)): shiplist, parcellist = undoBeam(shiplist, parcellist, first.moves[k][0], first.moves[k][1]) if len(kidlist) == 0: break # sort kidlist ascending based on mass-volume ratio difference between # parcel and ship of last appended move sortedkids = sorted(kidlist, key=lambda packinglist: packinglist.ratiodiff, reverse=False) # choose beamwidth amount of children you want to keep for i in range(beamwidth): if i < len(sortedkids): queue.append(sortedkids[i]) # if child appends more parcels than the current best solution, # make it the current best solution for sol in solutions: if len(sortedkids[i].moves) >= len(sol.moves): solutions.append(sortedkids[i]) break for sol in solutions: if len(sortedkids[i].moves) > len(sol.moves): solutions.remove(sol) else: break kidlist.clear() # calculate cost of each solution for solution in solutions: for move in solution.moves: shiplist, parcellist = assignBeam(shiplist, parcellist, move[0], move[1]) cost = calculatetotal(shiplist) solution.cost = cost for move in solution.moves: shiplist, parcellist = undoBeam(shiplist, parcellist, move[0], move[1]) # sort solutions based on cost, the cheapest solution will be saved sortedsolutions = sorted(solutions, key=lambda packinglist: packinglist.cost, reverse=False) bestsolution = sortedsolutions[0] # make the shiplist for the best solution for move in bestsolution.moves: if checkmove(move[1], move[0]): shiplist, parcellist = assignBeam(shiplist, parcellist, move[0], move[1]) # save the best solution filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(shiplist, open(picklename, 'wb')) return picklename
def planetexpress(shiplist, parcellist): ''' Planetexpress is a greedy algorithm for problem E of the spacefreight case. Planetexpres takes in two arguments, a list of shipobjects and a list of cargo objects. planetexpress creates a list of spaceships to assign the parcellist to based on the mass to volume ratio of spaceships and parcels. Planetexpress does this while also obiding to the constraint that every country with a ship doesnt launch more than 1 ship extra than any other country involed. Planetexpress returns a dictionary with the spaceship objects as keys and their assigned parcels as values. it also prints the amount of ships used and the total costs of launching the fleet.''' selectedlist = [] # the list that contains the fleet of spaceships countrydict = {} # dictionary containing the N of launches per country countryships = {} # the dictionary with countries and their ships c = 0 for i in shiplist: # starts up the countrydict countrydict[i.nation] = 0 if i.nation in countryships.keys(): worklist = countryships[i.nation] worklist.append(i) countryships[i.nation] = worklist else: countryships[i.nation] = [i] for i in parcellist: # turns the list of the current fleet into a list of classes namelist = [x.name for x in selectedlist] ship = calculateoptimal(i, shiplist) bool = False lowestpartner = min(countrydict, key=countrydict.get) difference = countrydict[ship.nation] - countrydict[lowestpartner] # checks if the matched ship is in fleetlist if ship.name in namelist: indexes = [] for z in range(len(namelist)): if namelist[z] == ship.name: indexes.append(z) # checks all ships of that class in the fleet list for y in indexes: if checkmove(i, selectedlist[z]): assign(selectedlist[z], i) bool = True break if bool is False: if difference > 0: # checks constraint if len(countryships[lowestpartner]) > 1: ship = calculateoptimal(i, countryships[lowestpartner]) else: ship = countryships[lowestpartner][0] spacecraft = Spacecraft(ship.name, ship.nation, ship.payload, ship.volume, ship.mass, ship.basecost, ship.ftw) newnumber = countrydict[ship.nation] newnumber += 1 countrydict[ship.nation] = newnumber assign(spacecraft, i) selectedlist.append(spacecraft) else: if difference > 0: if len(countryships[lowestparner]) > 1: ship = calculateoptimal(i, countryships[lowestparner]) else: ship = countryships[lowestparner][0] print(ship) spacecraft = Spacecraft(ship.name, ship.nation, ship.payload, ship.volume, ship.mass, ship.basecost, ship.ftw) newnumber = countrydict[ship.nation] newnumber += 1 countrydict[ship.nation] = newnumber assign(spacecraft, i) selectedlist.append(spacecraft) sol = solution(selectedlist) filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(sol, open(picklename, 'wb')) print("amount of ships: " + str(len(selectedlist))) print("total costs: " + str(calculatetotal(selectedlist))) # return the found solution in dictionary form return picklename
def maersk(shiplist, parcellist): '''Maersk is is a greedy algorithm for problem D. It takes two arguments. The first argument is a list of spaceship objects to use, the second a list of cargo objects to assign. The function is used to Solve problem D and is designed for very large cargolists and a list of spaceships that can be used without constraints. Maersk will loop through the parcellist and will do the following for each cargo object. It calculates the optimal space ship to assign the parcel to based on matching the parcels mass to volume ratio and the spaceships carrymass to carryvolume ratio. If there is an ship of that class in the current fleet with room it will assign the parcel to that ship, otherwise it will add another spaceship of this class to the current fleet. The algorithm is a greedy constructive algoritm with the mass to volume match as it's heuristic. ''' selectedlist = [] # the list that represents the current fleet timelist = shiplist countrylist = [i.nation for i in shiplist] print( "You're running the greedy algorithm for problem D. You can now select some options to run it. " ) bool = input( "You can choose to remove the spaceships from a country to improve the solution. Type 'yes' if you want this, any other input will result in a normal run: " ) bool = bool.lower() if bool == 'yes': country = input( "What country do you want to remove? options: 'Russia', 'Europe', 'USA', 'China' or 'Japan'. (Removing 'USA' gives best solution): " ) if country in countrylist: for i in timelist: if i.nation == country: shiplist.remove(i) # the list that gets the MV from all spacecship classes shipmv = [x.mv for x in shiplist] for i in parcellist: bool = False shipname = calculateoptimal(i, shiplist) namelist = [i.name for i in selectedlist] if shipname.name not in namelist: spacecraft = Spacecraft(shipname.name, shipname.nation, shipname.payload, shipname.volume, shipname.mass, shipname.basecost, shipname.ftw) assign(spacecraft, i) selectedlist.append(spacecraft) elif shipname.name in namelist: indexes = [] for z in range(len(namelist)): if namelist[z] == shipname.name: indexes.append(z) for y in indexes: if checkmove(i, selectedlist[z]): if bool is False: assign(selectedlist[z], i) bool = True break if bool is False: spacecraft = Spacecraft(shipname.name, shipname.nation, shipname.payload, shipname.volume, shipname.mass, shipname.basecost, shipname.ftw) assign(spacecraft, i) selectedlist.append(spacecraft) sol = solution(selectedlist) filename = input("Please name how you want to save this solution: ") while filename == "": filename = input("Please name how you want to save this solution: ") picklename = str(f"results/Newsolutions/{filename}.p") pickle.dump(sol, open(picklename, 'wb')) print("amount of ships: " + str(len(selectedlist))) print("total costs: " + str(calculatetotal(selectedlist))) return picklename