Пример #1
0
def first_fit(list_items, max_size):
	""" Returns list of bins with input items inside. """
	list_bins = []
	list_bins.append(Bin()) # Add first empty bin to list

	for item in list_items:
		# Go through bins and try to allocate
		alloc_flag = False

		for bin in list_bins:
			if bin.sum() + item <= max_size:
				bin.addItem(item)
				alloc_flag = True
				break
		
		# If item not allocated in bins in list, create new bin
		# and allocate it to it.
		if alloc_flag == False:
			newBin = Bin()
			newBin.addItem(item)
			list_bins.append(newBin)

	# Turn bins into list of items and return
	list_items = []
	for bin in list_bins:
		list_items.append(bin.show())

	return(list_items)
Пример #2
0
    def __init__(self):

        #bin for objects and tiles
        self._object_bin = Bin(0, 0, 150, 450)
        self._tile_bin = Bin(600, 225, 150, 225)

        #2d list of tiles that are on the map
        self._tiles = []

        #list of GameObjects on the map
        self._objects = []

        #offsets for the map having been dragged
        self._x_offset = 0
        self._y_offset = 0

        #currently selected Placeable item
        self._selected = None

        #whether or not the map is scrolling currently
        self._scrolling = False

        #list to store any buttons
        self._buttons = []

        self.init_bins()
Пример #3
0
 def setUp(self):
     self.bin = Bin([])
     self.bin.addOutcome(TestOutcome.oc1)
     self.bin.addOutcome(TestOutcome.oc2)
     self.outcome1 = TestOutcome.oc1
     self.outcome2 = TestOutcome.oc2
     self.outcome3 = TestOutcome.oc3
Пример #4
0
    def setUp(self):
        self.first = Outcome('one', 17)
        self.second = Outcome('one', 17)
        self.third = Outcome('two', 32)

        self.fbin = Bin(self.first)
        self.sbin = Bin(self.second)
Пример #5
0
def first_fit(list_items, max_size):
    """ Returns list of bins with input items inside. """
    list_bins = []
    list_bins.append(Bin())  # Add first empty bin to list

    for item in list_items:
        # Go through bins and try to allocate
        alloc_flag = False

        for bin in list_bins:
            if bin.sum() + item <= max_size:
                bin.addItem(item)
                alloc_flag = True
                break

        # If item not allocated in bins in list, create new bin
        # and allocate it to it.
        if alloc_flag == False:
            newBin = Bin()
            newBin.addItem(item)
            list_bins.append(newBin)

    # Turn bins into list of items and return
    list_items = []
    for bin in list_bins:
        list_items.append(bin.show())

    return (list_items)
Пример #6
0
 def map_point_to_extBins(self, point):
     mapped_bin = self.map_point_to_bin(point)
     mapped_extBins = Bin(mapped_bin[0],
                          mapped_bin[1]).extBins_contain_bin()
     for b in mapped_extBins:
         if b not in self.extBins_dict.keys() and self._is_valid_bin(b):
             self.extBins_dict[b] = Bin(b[0], b[1]).extBin_centerd_at_bin()
     return mapped_extBins
Пример #7
0
 def apply(item, bins):
     """
     Adds the item to the very first bin that it can fit it.
     """
     b = next((b for b in bins if b.can_add_item(item)), None)
     if not b:
         b = Bin(bins[0].capacity)
         bins.append(b)
     b.add_item(item)
     return bins
Пример #8
0
 def apply(item, bins):
     """
     Adds the item to the next available bin after the last insertion.
     """
     b = bins[-1]
     if not b.add_item(item):
         b = Bin(bins[0].capacity)
         bins.append(b)
         b.add_item(item)
     return bins
Пример #9
0
def test_bin_add():
    outcome = Outcome("00", 35)
    bin = Bin( outcome)
    assert len(bin.outcomes) == 1

    #Sets are unique by hash and eq
    bin.add( Outcome("00", 35) )
    assert len(bin.outcomes) == 1

    bin.add( Outcome("0", 35) )
    assert len(bin.outcomes) == 2
Пример #10
0
def test_bin_has_outcomes():
    outcome_0 = Outcome("0", 35)
    outcome_5 = Outcome("Five", 6)
    outcome_00 = Outcome("00", 35)
    bin_0 = Bin(0)
    bin_0.add(outcome_0)
    bin_0.add(outcome_5)
    bin_00 = Bin(37)
    bin_00.add(outcome_00)
    bin_00.add(outcome_5)
    assert bin_0.outcomes == frozenset([outcome_0, outcome_5])
    assert bin_00.outcomes == frozenset([outcome_00, outcome_5])
Пример #11
0
def faseConstrutiva(itens, alpha):

    global BINS
    global ALPHA

    solucao = []
    tam_pacote = TAM_MAX_PACOTE
    lista_conflitos = []
    pacoteAtual = []
    resultado = 1

    while itens != []:

        candidatos = geraRCL(lista_conflitos, tam_pacote, pacoteAtual, itens,
                             alpha)

        if candidatos == []:
            #cria o bin com os itens do pacote atual
            BINS.append(
                Bin(
                    len(BINS) + 1, pacoteAtual, tam_pacote,
                    set(lista_conflitos), TAM_MAX_PACOTE, ALPHA))
            ALPHA = ALPHA * 0.95
            #limpaInformações atuais
            tam_pacote = TAM_MAX_PACOTE
            lista_conflitos = []
            pacoteAtual = []
            if itens != []:
                resultado += 1

        else:
            escolhido = random.choice(candidatos)
            solucao.append(escolhido)
            itens.remove(escolhido)
            tam_pacote = tam_pacote - escolhido.get_peso()
            lista_conflitos += escolhido.get_conflitos()
            pacoteAtual.append(escolhido)

    if pacoteAtual != []:
        #cria o bin com os itens do pacote atual
        BINS.append(
            Bin(
                len(BINS) + 1, pacoteAtual, tam_pacote, set(lista_conflitos),
                TAM_MAX_PACOTE, ALPHA))
        #limpaInformações atuais
        tam_pacote = TAM_MAX_PACOTE
        lista_conflitos = []
        pacoteAtual = []
        if itens != []:
            resultado += 1

    #print('Pacotes : ' + str(resultado))
    return solucao
    def findBin(self, item, capacity):
        current = self.bst.root

        _bin = self.findWorst(item)
        if _bin is None:
            _bin = Bin(capacity)
        else:
            self.bst.remove(_bin)            

        _bin.addItem(item)
        self.bst.insert(_bin)

        return _bin
Пример #13
0
 def apply(item, bins):
     """
     Adds the item to the bin for which the most amount of open space would be available after insertion.
     """
     valid_bins = (b for b in bins if b.can_add_item(item))
     sorted_bins = sorted(valid_bins, key=lambda x: x.filled_space())
     if sorted_bins:
         b = sorted_bins[0]
     else:
         b = Bin(bins[0].capacity)
         bins.append(b)
     b.add_item(item)
     return bins
Пример #14
0
 def apply(item, bins):
     """
     Adds the item to the very first bin that it can fit it.
     :param item: The item to add.
     :param bins: The bins to choose from.
     :return: The list of bins after the insertion.
     """
     b = next((b for b in bins if b.can_add_item(item)), None)
     if not b:
         b = Bin(bins[0].capacity)
         bins.append(b)
     b.add_item(item)
     return bins
Пример #15
0
 def apply(item, bins):
     """
     Adds the item to the next available bin after the last insertion.
     :param item: The item to add.
     :param bins: The bins to choose from.
     :return: The list of bins after insertion.
     """
     b = bins[-1]
     if not b.add_item(item):
         b = Bin(bins[0].capacity)
         bins.append(b)
         b.add_item(item)
     return bins
    def findBin(self, item, capacity):
        if len(self.bins) == 0:
            self.bins.append(Bin(capacity))

        bin_ = self.bins.pop()
        self.bins.append(bin_)

        if not item.fitsInto(bin_):
            bin_ = Bin(capacity)
            self.bins.append(bin_)

        bin_.addItem(item)

        return bin_
Пример #17
0
    def idIsInMyInterval(self,data):
        """recive data with id hex wanted, return 1 if the id is in my interval, else return 0"""
        ans = None
        num = Bin(data[1].decode())

        if self.idPredecessor < self.id:

            ans = self.idPredecessor < num <= self.id
        
        else:
            #el id del predecesor es mayor que mi id
            ans = self.idPredecessor < num <= self.numElements or Bin("0") <= num <= self.id

        ans = str(int(ans))
        self.listen.send(ans.encode())
Пример #18
0
    def addServerToChord(self):
        """Add in the middel to two server in the chord
            TODO 
            send all files in the new successor server and me    
        """
        #init the socket listen, that is in the __init__


        ipNewSuccessor, portNewSuccessor = self.find()
        #send to my predecessor my ip, port and id
        self.next.send_multipart([b'changeTheSuccessorInformation', self.IPListen.encode(), self.portListen.encode(), self.id.getHex().encode()])
        print(self.next.recv().decode())

        #get id of my predeccessor
        self.next.send_multipart([b'getServerID'])
        idp = self.next.recv().decode()
        self.next.disconnect(tcp + self.IPNext + ":" + self.portNext)
        print("id new predeccessor:", idp)
        self.idPredecessor = Bin(idp)

        #connect to my successor
        self.IPNext = ipNewSuccessor
        self.portNext = portNewSuccessor
        print("my successor is:", tcp + self.IPNext + ":" + self.portNext)
        self.next.connect(tcp + self.IPNext + ":" + self.portNext)
        self.next.send_multipart([b'getServerID'])
        ids = self.next.recv().decode()
        self.idSuccessor = Bin(ids)

        #tell to successor the id of his new predecessor
        self.next.send_multipart([b"updatePredecessor", self.id.getHex().encode()])
        print("update successor id",self.next.recv())

        #tell to succesor that send me hash of the my files
        msj = [b"sendAllFiles", self.idPredecessor.getHex().encode(), self.id.getHex().encode()]
        self.next.send_multipart(msj)
        filesHash = self.next.recv_multipart()
        filesHash = filesHash[1:]
        
        for fh in filesHash:
            print("Recovery files from another server")
            path = self.folder.getpath(fh.decode())
            msj = [b'download', fh]
            self.next.send_multipart(msj)
            byte = self.next.recv()
            self.filesManager.insert(fh.decode())
            with open(path, 'ab') as f :
                f.write(byte)
Пример #19
0
 def sort_in_bins(self):
     for packet in self.packets:
         if packet.sa is not None:
             if not self.bins.get(packet.sa):
                 self.bins[packet.sa] = Bin()
             self.bins[packet.sa].append(packet)
     return self.bins
Пример #20
0
 def __init__(self, rng=None):
     self.bins = tuple(Bin(i) for i in range(38))
     if rng is None:
         rng = random.Random()
     self.rng = rng
     # A map name -> Outcome
     self.all_outcomes = dict()
Пример #21
0
 def apply(item, bins):
     """
     Adds the item to the bin for which the least amount of open space would be available after insertion.
     """
     valid_bins = (b for b in bins if b.can_add_item(item))
     # Note that this method is exactly the same as for the BestFit heuristic except for the following line.
     sorted_bins = sorted(valid_bins,
                          key=lambda x: x.filled_space(),
                          reverse=True)
     if sorted_bins:
         b = sorted_bins[0]
     else:
         b = Bin(bins[0].capacity)
         bins.append(b)
     b.add_item(item)
     return bins
Пример #22
0
    def run(self):
        key = random.choice(self.BINS_DEFINITION.keys())
        outcomes = []
        for outcome_name in self.BINS_DEFINITION[key]:
            outcomes.append(self.outcome_builder.get_outcome(outcome_name))

        return Bin(outcomes)
    def findBin(self, item, capacity):
        bin_ = self.bst.select(1)

        if bin_ is not None and item.fitsInto(bin_):
            self.bst.remove(bin_)
        else:
            bin_ = self.bst.select(0)

            if bin_ is not None and item.fitsInto(bin_):
                self.bst.remove(bin_)
            else:
                bin_ = Bin(capacity)

        bin_.addItem(item)
        self.bst.insert(bin_)

        return bin_
 def __init__(self,alpha,capacity, items,t_init,t_target,iter_nb):
     self.alpha = alpha
     self.items = items
     self.capacity = capacity
     self.bins = [Bin(capacity)]
     self.t_init = t_init
     self.t_target = t_target
     self.iter_nb = iter_nb
Пример #25
0
    def __init__(self, id, IPListen, portListen, IPNext, portNext, bootstrap, k = 160):

        self.folder = Folder(id =portListen)
        self.filesManager = Trie()    

        self.IPListen = IPListen
        self.portListen = portListen
        self.IPNext = IPNext
        self.portNext = portNext
        self.k = k

        self.numElements = Bin(hex((2**k)-1)[2:])

        self.id = Bin(id)#aca va entrar la mac, debe crear una funcion que cuadre la mac como sha1
        print("my id:", self.id.getHex())

        self.listen.bind(tcp + self.IPListen + ":" + self.portListen)

        self.idPredecessor = None
        self.idSuccessor = None


        #query of disponible operations in the server's
        self.operation = {"updatePredecessor": self.updatePredecessor, 
                            "idIsInMySuccesor": self.idIsInMySuccesor,
                            "idIsInMyInterval": self.idIsInMyInterval,
                            "getSuccessor": self.getSuccessor,
                            "getServerID": self.getServerID,
                            "changeTheSuccessorInformation": self.changeTheSuccessorInformation,
                            "upload": self.upload,
                            "download": self.download,
                            "existsFileNow": self.existsFileNow,
                            "sendAllFiles": self.sendAllFiles }

        print("Server IP:", self.IPListen + ":" + self.portListen)

        if bootstrap:

            self.bootstrap()
            self.run()
        else :
            
            #self.find()
            self.addServerToChord()
            self.run()
Пример #26
0
 def __init__(self, capacity, items):
     """
     Creates an instance that can run the tabu search algorithm.
     """
     self.bin_capacity = capacity
     self.items = items
     self.fitness = 0
     self.bins = [Bin(capacity)]
     self.tabu_list = set()
Пример #27
0
 def __init__(self):
     # Create collection of empty Bins
     self.bins = list(Bin([]) for i in range(38))
     # Set pseudo-random number generator for selecting a winning Bin.
     self.rng = random.Random()
     self.rng.seed()
     self.all_outcomes = {}
     # Fill Bins with possible Outcomes.
     self._fillBins()
Пример #28
0
 def map_point_to_bin(self, point):
     mapped_bin = (math.floor(
         abs(point.x - Experiment_Setup.x_min) / self.bin_width),
                   math.floor(
                       abs(point.y - Experiment_Setup.y_min) /
                       self.bin_height))
     if mapped_bin not in self.bins_dict.keys() and self._is_valid_bin(
             mapped_bin):
         self.bins_dict[mapped_bin] = Bin(mapped_bin[0], mapped_bin[1])
     return mapped_bin
Пример #29
0
 def generate_solution(self, items):
     """
     Generates a candidate solution based on the pattern given.
     """
     solution = [Bin(self.bin_capacity)]
     pattern_length = len(self.pattern)
     for idx, item in enumerate(items):
         h = self.pattern[idx % pattern_length]
         solution = self.heuristic_map[h].apply(item, solution)
     return solution
 def __init__(self, capacity, items):
     """
     Creates an instance that can run the tabu search algorithm.
     :param capacity: The capacity of a bin.
     :param items: The items that have to be packed in bins.
     """
     self.bin_capacity = capacity
     self.items = items
     self.fitness = 0
     self.bins = [Bin(capacity)]
     self.tabu_list = set()
Пример #31
0
    def idIsInMySuccesor(self, data):
        """
            recive data with id hex wanted, return 1 if the id is in the succesor interval, else return 0
        """
        ans = None
        num = Bin(data[1].decode())
        
        #print("id:", self.id)
        #print("idSuccessor:", self.idSuccessor)
        #print("numero que busco", num)
        if self.idSuccessor > self.id :
            #print("por el if")
            ans = (self.id < num <= self.idSuccessor)

        else :
            #print("por el else")
            ans = (self.id < num <= self.numElements or Bin("0") <= num <= self.idSuccessor) # convertir esto como un string hexadecimal

        ans = str(int(ans))
        self.listen.send(ans.encode())
Пример #32
0
    def bootstrap(self):

        self.next.connect(tcp + self.IPNext + ":" + self.portNext)
        self.next.send_multipart([b"updatePredecessor", self.id.getHex().encode()])

        data = self.listen.recv_multipart()
        self.operation[data[0].decode()](data)

        self.idSuccessor = Bin(self.idPredecessor.getHex())
        
        self.next.recv()
Пример #33
0
 def testCanAddOutcomeToBin(self):
     testBin = Bin()
     self.assertEqual(len(testBin.outcomes), 0)
     testBin.add(self.output)
     self.assertEqual(len(testBin.outcomes), 1)
Пример #34
0
 def test_add(self):
     b1 = Bin()
     b1.add(o1)
     self.assertTrue(b1.outcomes == frozenset([o1]))