Esempio n. 1
0
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)
Esempio n. 2
0
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
Esempio n. 3
0
def assignRemainders(shiplist, extralist):
    """Takes as input a shiplist of a solution and a list of remaining parcels.
    Randomly assigns remainders if possible. Edits the shiplist."""
    possiblelist = [1]
    while len(possiblelist) != 0:
        possiblelist = possiblemovesA(shiplist, extralist)
        if len(possiblelist) == 0:
            break
        chosenmove = possiblelist[0]
        assign(chosenmove[0], chosenmove[1])
        extralist.remove(chosenmove[1])
Esempio n. 4
0
def dofirstmove(shiplist, extralist):
    possiblelist =[1]
    while len(possiblelist) != 0:
        possiblelist = possiblemovesA(shiplist, extralist)
        #print(f"possiblelist = {possiblelist}")
        if len(possiblelist) == 0:
            break
        chosenmove = possiblelist[0]
        assign(chosenmove[0], chosenmove[1])
        extralist.remove(chosenmove[1])
    print(f"remainders3: {len(extralist)}")
Esempio n. 5
0
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)
Esempio n. 6
0
def dofirstmove(shiplist, extralist):
    possiblelist = [1]
    while len(possiblelist) != 0:
        possiblelist = possiblemovesA(shiplist, extralist)
        print(f"possiblelist = {possiblelist}")
        if len(possiblelist) == 0:
            break
        chosenmove = possiblelist[0]
        assign(chosenmove[0], chosenmove[1])
        extralist.remove(chosenmove[1])
    #print(f"space0 assigned/weight/vol: {shiplist[0].name}{len(shiplist[0].assigned)}/{shiplist[0].payload}/{shiplist[0].volume}")
    #print(f"space1 assigned/weight/vol: {shiplist[1].name}{len(shiplist[1].assigned)}/{shiplist[1].payload}/{shiplist[1].volume}")
    #print(f"space2 assigned/weight/vol: {shiplist[2].name}{len(shiplist[2].assigned)}/{shiplist[2].payload}/{shiplist[2].volume}")
    #print(f"space3 assigned/weight/vol: {shiplist[3].name}{len(shiplist[3].assigned)}/{shiplist[3].payload}/{shiplist[3].volume}")
    print(f"remainders na herverdeling: {len(extralist)}")
Esempio n. 7
0
def randomsolver(shiplist, parcellist):
    """Takes as input a clear shiplist and parcellist. Randomly assigns parcels
    to spacecrafts. Edits the shiplist and returns the amount of moves of the
    found solution."""
    # do random moves until no more moves possible
    movelist = [1]
    while movelist != []:
        movelist = possiblemovesA(shiplist, parcellist)
        if movelist != []:
            randomchoice = random.randint(0, len(movelist))
            randomchoice -= 1
            move = movelist[randomchoice]
            assign(move[0], move[1])
            parcellist.remove(move[1])
    totalnumber = 0
    for i in shiplist:
        totalnumber += len(i.assigned)
    return totalnumber
Esempio n. 8
0
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
Esempio n. 9
0
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
Esempio n. 10
0
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)
Esempio n. 11
0
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
Esempio n. 12
0
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
Esempio n. 13
0
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