Example #1
0
 def getEntity(self):
     activeObject = self.getActiveObject()
     activeEntity = Machine.getEntity(self)  #run the default code
     # read the processing time from the corresponding remainingRoute entry
     processingTime = activeEntity.remainingRoute[0].get(
         'processingTime', {})
     processingTime = self.getOperationTime(processingTime)
     self.rng = RandomNumberGenerator(self, processingTime)
     self.procTime = self.rng.generateNumber()
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Processing', entity=activeEntity)
     # read the setup time from the corresponding remainingRoute entry
     setupTime = activeEntity.remainingRoute[0].get('setupTime', {})
     setupTime = self.getOperationTime(setupTime)
     self.stpRng = RandomNumberGenerator(self, setupTime)
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Setup', entity=activeEntity)
     activeEntity.currentStep = activeEntity.remainingRoute.pop(
         0)  #remove data from the remaining route of the entity
     if activeEntity.currentStep:
         # update the task_id of the currentStep dict within the schedule
         try:
             activeEntity.schedule[-1][
                 "task_id"] = activeEntity.currentStep["task_id"]
             # if there is currentOperator then update the taskId of corresponding step of their schedule according to the task_id of the currentStep
             if self.currentOperator:
                 self.currentOperator.schedule[-1][
                     "task_id"] = activeEntity.currentStep["task_id"]
         except KeyError:
             pass
     return activeEntity
Example #2
0
 def __init__(self, id='',name='',victim=None, distribution=None, index=0, repairman=None,**kw):
     ObjectInterruption.__init__(self,id,name,victim=victim)
     self.rngTTF=RandomNumberGenerator(self, distribution.get('TTF',{'Fixed':{'mean':100}}))
     self.rngTTR=RandomNumberGenerator(self, distribution.get('TTR',{'Fixed':{'mean':10}}))
     self.name="F"+str(index)
     self.repairman=repairman        # the resource that may be needed to fix the failure
                                     # if now resource is needed this will be "None" 
     self.type="PeriodicMaintenance"
Example #3
0
 def calculateInitialOperationTimes(self):
     # read the setup/processing time from the first entry of the full route
     activeEntity = self.getActiveObjectQueue()[0]
     #if the entity has its route defined in the BOM then remainingProcessing/SetupTime is provided
     # XX consider moving setupUPtime update to checkForManualOperationTypes as Setup is performed before Processing
     if activeEntity.routeInBOM:
         processingTime = self.getOperationTime(
             activeEntity.remainingProcessingTime)
         setupTime = self.getOperationTime(activeEntity.remainingSetupTime)
     else:  # other wise these should be read from the route
         processingTime = activeEntity.route[0].get('processingTime', {})
         processingTime = self.getOperationTime(processingTime)
         setupTime = activeEntity.route[0].get('setupTime', {})
         setupTime = self.getOperationTime(setupTime)
     self.rng = RandomNumberGenerator(self, processingTime)
     self.stpRng = RandomNumberGenerator(self, setupTime)
    def __init__(self, id, name, capacity=1, \
                 processingTime=None, repairman='None',\
                 scrapQuantity={},
                 operatorPool='None',operationType='None',\
                 setupTime=None, loadTime=None,
                 canDeliverOnInterruption=False,
                 **kw):
        if not processingTime:
            processingTime = {'distributionType': 'Fixed', 'mean': 1}
        # initialize using the default method of the object
        Machine.__init__(self,id=id,name=name,\
                                    capacity=capacity,\
                                    processingTime=processingTime,
                                    repairman=repairman,
                                    canDeliverOnInterruption=canDeliverOnInterruption,
                                    operatorPool=operatorPool,operationType=operationType,\
                                    setupTime=setupTime, loadTime=loadTime,
                                    )

        # set the attributes of the scrap quantity distribution
        if not scrapQuantity:
            scrapQuantity = {'Fixed': {'mean': 0}}

        self.scrapRng = RandomNumberGenerator(self, scrapQuantity)
        from Globals import G
        G.BatchScrapMachineList.append(self)
Example #5
0
    def __init__(self,
                 id,
                 name,
                 numberOfSubBatches=1,
                 processingTime=None,
                 operator='None',
                 outputResults=False,
                 **kw):
        CoreObject.__init__(self, id, name)
        self.type = "BatchRassembly"  #String that shows the type of object
        if not processingTime:
            processingTime = {'Fixed': {'mean': 0}}
        if 'Normal' in processingTime.keys() and\
                processingTime['Normal'].get('max', None) is None:
            processingTime['Normal']['max'] = float(
                processingTime['Normal']['mean']) + 5 * float(
                    processingTime['Normal']['stdev'])

        # holds the capacity of the object
        self.numberOfSubBatches = numberOfSubBatches
        # sets the operator resource of the Machine
        self.operator = operator
        # Sets the attributes of the processing (and failure) time(s)
        self.rng = RandomNumberGenerator(self, processingTime)
        from Globals import G
        G.BatchReassemblyList.append(self)
        # flag to show if the objects outputs results
        self.outputResults = bool(int(outputResults))
class Main:
    generator = RandomNumberGenerator()
    observer1 = DigitObserver()
    observer2 = GraphObserver()
    generator.addObserver(observer1)
    generator.addObserver(observer2)
    generator.execute()
Example #7
0
    def __init__(self,
                 id,
                 name,
                 interArrivalTime=None,
                 entity='Dream.Part',
                 **kw):
        # Default values
        if not interArrivalTime:
            interArrivalTime = {'Fixed': {'mean': 1}}
        if 'Normal' in interArrivalTime.keys() and\
              interArrivalTime['Normal'].get('max', None) is None:
            interArrivalTime['Normal']['max'] = interArrivalTime['Normal'][
                'mean'] + 5 * interArrivalTime['Normal']['stdev']

        CoreObject.__init__(self, id, name)
        # properties used for statistics
        self.totalinterArrivalTime = 0  # the total interarrival time
        self.numberOfArrivals = 0  # the number of entities that were created

        self.type = "Source"  #String that shows the type of object
        self.rng = RandomNumberGenerator(self, interArrivalTime)

        self.item = Globals.getClassFromName(
            entity)  #the type of object that the Source will generate

        self.scheduledEntities = [
        ]  # list of creations that are scheduled. pattern is [timeOfCreation, EntityCounter]
        from Globals import G
        G.SourceList.append(self)
    def __init__(self,
                 id,
                 name,
                 processingTime=None,
                 numberOfSubBatches=1,
                 operator='None',
                 **kw):
        CoreObject.__init__(self, id, name)
        self.type = "BatchDecomposition"  #String that shows the type of object

        if not processingTime:
            processingTime = {'Fixed': {'mean': 0}}
        if 'Normal' in processingTime.keys() and\
                processingTime['Normal'].get('max', None) is None:
            processingTime['Normal']['max'] = float(
                processingTime['Normal']['mean']) + 5 * float(
                    processingTime['Normal']['stdev'])

        # holds the capacity of the object
        self.numberOfSubBatches = int(numberOfSubBatches)
        # sets the operator resource of the Machine
        self.operator = operator
        # Sets the attributes of the processing (and failure) time(s)
        self.rng = RandomNumberGenerator(self, processingTime)
        from Globals import G
        G.BatchDecompositionList.append(self)
Example #9
0
 def readLoadTime(self,callerObject=None):
     assert callerObject!=None, 'the caller of readLoadTime cannot be None'
     thecaller=callerObject
     thecaller.sortEntities()
     activeEntity=thecaller.Res.users[0]
     # read the load time from the corresponding remainingRoute entry
     loadTime=activeEntity.remainingRoute[0].get('loadTime',{})
     loadTime=self.getOperationTime(loadTime)
     self.loadRng=RandomNumberGenerator(self, loadTime)
Example #10
0
 def getEntity(self):
     activeObject=self.getActiveObject()
     activeEntity=Machine.getEntity(self)     #run the default code
     # read the processing time from the corresponding remainingRoute entry
     processingTime=activeEntity.remainingRoute[0].get('processingTime',{})
     processingTime=self.getOperationTime(processingTime)
     self.rng=RandomNumberGenerator(self, processingTime)
     self.procTime=self.rng.generateNumber()
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Processing',entity=activeEntity)
     # read the setup time from the corresponding remainingRoute entry
     setupTime=activeEntity.remainingRoute[0].get('setupTime',{})
     setupTime=self.getOperationTime(setupTime)
     self.stpRng=RandomNumberGenerator(self, setupTime)
     # check if there is a need for manual processing
     self.checkForManualOperation(type='Setup',entity=activeEntity)
     removedStep = activeEntity.remainingRoute.pop(0)      #remove data from the remaining route of the entity
     return activeEntity
Example #11
0
 def __generate_instance(self, seed):
     RNG = RandomNumberGenerator(seed)
     task_queue = []
     for J in range(0, self.size):
         task_queue.append({'j': J + 1})
         for M in range(1, self.machines + 1):
             task_queue[J].update({f'p{M}': RNG.nextInt(1, MAX_VALUE)})
             task_queue[J].update({f'S{M}': 0})
             task_queue[J].update({f'C{M}': 0})
     return task_queue
Example #12
0
 def calculateProcessingTime(self):
     # this is only for processing of the initial wip
     if self.isProcessingInitialWIP:
         activeEntity=self.getActiveObjectQueue()[0]
         if activeEntity.remainingProcessingTime:
             remainingProcessingTime=activeEntity.remainingProcessingTime
             from RandomNumberGenerator import RandomNumberGenerator
             initialWIPrng=RandomNumberGenerator(self, remainingProcessingTime)
             return initialWIPrng.generateNumber()
     return self.rng.generateNumber()           # this is if we have a default processing time for all the entities
Example #13
0
def instanceGenerator(Z, size):
    generator = RandomNumberGenerator(Z)
    d = [[0 for i in range(size)] for j in range(size)]

    for i in range(size):
        for j in range(size):
            if (i > j):
                d[i][j] = generator.nextInt(1, 50)
                d[j][i] = generator.nextInt(1, 50)

    return d
Example #14
0
def defineScrapQuantities():
    process = G.CMSDData.getElementsByTagName('Process')

    #loop through the processes
    for proc in process:
        try:
            #read the scrap quantity
            Property = proc.getElementsByTagName('Property')
            for prop in Property:
                name = prop.getElementsByTagName('Name')
                name = name[0].toxml().replace('<Name>',
                                               '').replace('</Name>', '')
                if name == 'ScrapQuantity':
                    scrap = Property[0].getElementsByTagName('Distribution')
                    scrapName = scrap[0].getElementsByTagName('Name')
                    scrapName = scrapName[0].toxml().replace('<Name>',
                                                             '').replace(
                                                                 '</Name>', '')

                    distrParA = scrap[0].getElementsByTagName(
                        'DistributionParameterA')
                    parAName = distrParA[0].getElementsByTagName('Name')
                    parAName = parAName[0].toxml().replace('<Name>',
                                                           '').replace(
                                                               '</Name>', '')
                    parAValue = distrParA[0].getElementsByTagName('Value')
                    parAValue = parAValue[0].toxml().replace(
                        '<Value>', '').replace('</Value>', '')

                else:
                    continue

                #read the id of the station resource
                ResourcesRequired = proc.getElementsByTagName(
                    'ResourcesRequired')
                for res in ResourcesRequired:
                    Resource = res.getElementsByTagName('Resource')
                    ResourceIdentifier = Resource[0].getElementsByTagName(
                        'ResourceIdentifier')
                    ResourceIdentifier = ResourceIdentifier[0].toxml().replace(
                        '<ResourceIdentifier>',
                        '').replace('</ResourceIdentifier>', '')

                    #loop through the stations and for the one with the id set the scrap
                    distributionDict = {
                        str(scrapName): {
                            str(parAName): parAValue
                        }
                    }
                for obj in G.ObjList:
                    if obj.id == ResourceIdentifier:
                        obj.rng = RandomNumberGenerator(obj, distributionDict)
        except IndexError:
            continue
Example #15
0
 def __init__(self, id='',name='',victim=None, distribution={}, index=0, repairman=None, offshift=False,
              deteriorationType='constant',
              waitOnTie=False,**kw):
     ObjectInterruption.__init__(self,id,name,victim=victim)
     self.rngTTF=RandomNumberGenerator(self, distribution.get('TTF',{'Fixed':{'mean':100}}))
     self.rngTTR=RandomNumberGenerator(self, distribution.get('TTR',{'Fixed':{'mean':10}}))
     self.name="F"+str(index)
     self.repairman=repairman        # the resource that may be needed to fix the failure
                                     # if now resource is needed this will be "None" 
     self.type="Failure"
     
     # shows how the time to failure is measured
     # 'constant' means it counts not matter the state of the victim
     # 'onShift' counts only if the victim is onShift
     # 'working' counts only working time
     self.deteriorationType=deteriorationType
     # flag used to identify if the time between failures should be counted while the victim is off-shift
     self.offshift=offshift
     # flag to show if the failure will wait on tie with other events before interrupting the victim
     self.waitOnTie=waitOnTie
Example #16
0
 def __init__(self,
              id='',
              name='',
              victim=None,
              distribution={},
              endUnfinished=True,
              offShiftAnticipation=0,
              **kw):
     ObjectInterruption.__init__(self, id, name, victim=victim)
     self.rngTTB = RandomNumberGenerator(
         self, distribution.get('TTB', {'Fixed': {
             'mean': 100
         }}))
     self.rngTTR = RandomNumberGenerator(
         self, distribution.get('TTR', {'Fixed': {
             'mean': 10
         }}))
     self.type = "Break"
     # end current wip before going to break
     self.endUnfinished = endUnfinished
     # if the break is close to end of shift below a limit it will be suspended
     self.offShiftAnticipation = offShiftAnticipation
Example #17
0
def defineProcessingTimes():
    process = G.CMSDData.getElementsByTagName('Process')

    #loop through the processes
    for proc in process:
        try:
            #read the mean processing time a the unit
            OperationTime = proc.getElementsByTagName('OperationTime')
            distr = OperationTime[0].getElementsByTagName('Distribution')
            distrName = distr[0].getElementsByTagName('Name')
            distrName = distrName[0].toxml().replace('<Name>', '').replace(
                '</Name>', '')

            distrParA = distr[0].getElementsByTagName('DistributionParameterA')
            parAName = distrParA[0].getElementsByTagName('Name')
            parAName = parAName[0].toxml().replace('<Name>',
                                                   '').replace('</Name>', '')
            parAValue = distrParA[0].getElementsByTagName('Value')
            parAValue = parAValue[0].toxml().replace('<Value>', '').replace(
                '</Value>', '')

            distrParB = distr[0].getElementsByTagName('DistributionParameterB')
            parBName = distrParB[0].getElementsByTagName('Name')
            parBName = parBName[0].toxml().replace('<Name>',
                                                   '').replace('</Name>', '')
            parBValue = distrParB[0].getElementsByTagName('Value')
            parBValue = parBValue[0].toxml().replace('<Value>', '').replace(
                '</Value>', '')

            #read the id of the station resource
            ResourcesRequired = proc.getElementsByTagName('ResourcesRequired')
            for res in ResourcesRequired:
                Resource = res.getElementsByTagName('Resource')
                ResourceIdentifier = Resource[0].getElementsByTagName(
                    'ResourceIdentifier')
                ResourceIdentifier = ResourceIdentifier[0].toxml().replace(
                    '<ResourceIdentifier>',
                    '').replace('</ResourceIdentifier>', '')

                #loop through the stations and for the one with the id set the processing time
                distributionDict = {
                    str(distrName): {
                        str(parAName): parAValue,
                        str(parBName): parBValue
                    }
                }
                for obj in G.ObjList:
                    if obj.id == ResourceIdentifier:
                        obj.rng = RandomNumberGenerator(obj, distributionDict)
        except IndexError:
            continue
def main():
    seed = int(input("Wprowadź Z: "))
    generator = RandomNumberGenerator(seed)
    taskNumber = int(input("Wprowadź liczbę zadań: "))
    tasks = range(1, taskNumber + 1)
    machineNumber = int(input("Wprowadź liczbę maszyn: "))
    machines = range(1, machineNumber + 1)

    #lista wszystkich zadan na konkretnych maszynach
    p_ij = []
    # permutacja zadan
    pi = []
    # wyswietlenie rozwiazania po wykonaniu algorytmu optymalizacji
    solution = []
    #lista zadan przydzielonych do jednej maszyny
    pj = []

    for task in tasks:
        for machine in machines:
            pj.append(generator.nextInt(1, 29))
        p_ij.append(pj.copy())
        pj.clear()
        pi.append(task)

    print(p_ij)
    print("Permutacj naturalna: ")
    print("pi: ", pi)
    Cj, Cmax = calculate(p_ij, taskNumber, machineNumber)
    print("C:", Cj)
    print("Cmax:", Cmax)

    for task in tasks:
        solution.append([pi[task - 1], p_ij[task - 1]])

    pi = Johnson(tasks, p_ij.copy())
    print("Johnson: ")
    print("pi: ", pi)

    sort = {x: i for i, x in enumerate(pi)}
    solution.sort(key=lambda x: sort[x[0]])
    Cj, Cmax = calculate([row[1] for row in solution], taskNumber,
                         machineNumber)
    print("C", Cj)
    print("Cmax:", Cmax)
Example #19
0
def main():
    seed = int(input("Wprowadź Z: "))
    generator = RandomNumberGenerator(seed)
    taskNumber = int(input("Wprowadź rozmiar problemu: "))
    tasks = range(1, taskNumber + 1)
    nr = []
    pj = []  #czas wykonania
    wj = []  #waga/współczynnik kary
    dj = []  #żądany termin zakończenia

    for task in tasks:
        nr.append(task)
        pj.append(generator.nextInt(1, 29))

    A = 0
    for number in pj:
        A += number

    for task in tasks:
        wj.append(generator.nextInt(1, 9))
    X = 29
    #X=A
    for task in tasks:
        dj.append(generator.nextInt(1, X))

    print("\nnr:", nr)
    print("pj: ", pj)
    print("wj ", wj)
    print("dj", dj)

    witi_start = target_fun(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla początkowego = {witi_start[0]}')
    print(f'C: {witi_start[2]}')
    print(f'T: {witi_start[1]}')

    witi_greedy = greedy(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla Greedy algorithm = {witi_greedy[0]}')
    print(f'C: {witi_greedy[2]}')
    print(f'T: {witi_greedy[1]}')

    witi_brute_force = brute_force(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla Brute Force = {witi_brute_force[0]}')
    print(f'C: {witi_brute_force[2]}')
    print(f'T: {witi_brute_force[1]}')
Example #20
0
    def __init__(self, size, seed):
        self.size = size
        self.last_permutation = []
        RNG = RandomNumberGenerator(seed)
        p_list = []
        w_list = []
        d_list = []
        p_sum = 0
        self.queue = []
        for J in range(0, self.size):
            p_list.append(RNG.nextInt(1, MAX_VALUE))
            p_sum += p_list[-1]

        for J in range(0, self.size):
            w_list.append(RNG.nextInt(1, 9))

        for J in range(0, self.size):
            d_list.append(RNG.nextInt(1, MAX_D))

        for J in range(0, self.size):
            self.queue.append(task(J + 1, p_list[J], w_list[J], d_list[J]))
            self.last_permutation.append(J + 1)
Example #21
0
    def __init__(self,
                 id='',
                 name='',
                 processingTime=None,
                 inputsDict=None,
                 **kw):
        self.type = "Assembly"  #String that shows the type of object
        self.next = []  #list with the next objects in the flow
        self.previous = []  #list with the previous objects in the flow
        self.previousPart = []  #list with the previous objects that send parts
        self.previousFrame = [
        ]  #list with the previous objects that send frames
        self.nextIds = []  #list with the ids of the next objects in the flow
        self.previousIds = [
        ]  #list with the ids of the previous objects in the flow

        #lists to hold statistics of multiple runs
        self.Waiting = []
        self.Working = []
        self.Blockage = []

        if not processingTime:
            processingTime = {'Fixed': {'mean': 0}}
        if 'Normal' in processingTime.keys() and\
                processingTime['Normal'].get('max', None) is None:
            processingTime['Normal']['max'] = float(
                processingTime['Normal']['mean']) + 5 * float(
                    processingTime['Normal']['stdev'])

        CoreObject.__init__(self, id, name)
        self.rng = RandomNumberGenerator(self, processingTime)

        # ============================== variable that is used for the loading of machines =============
        self.exitAssignedToReceiver = False  # by default the objects are not blocked
        # when the entities have to be loaded to operatedMachines
        # then the giverObjects have to be blocked for the time
        # that the machine is being loaded
        from Globals import G
        G.AssemblyList.append(self)
Example #22
0
def simulatedAnnealing(tasks):
    RNG = RandomNumberGenerator(123)
    t = copy.deepcopy(tasks)
    T = 1550.0  #temperatura zarzenia na bialo rozgrzanej stali :)
    Tend = 1E-10  # cokolwiek większe od zera
    it = 0
    L = 10
    pi = []
    pi_new = []
    pi_best = []

    #natural perm
    for perm in range(1, t.size + 1):
        pi.append(perm)
        pi_best.append(perm)

    while T > Tend:
        for k in range(L):
            i = RNG.nextInt(0, t.size) - 1
            j = RNG.nextInt(0, t.size) - 1
            pi_new = copy.deepcopy(pi)
            swap_value = pi_new[i]
            pi_new[i] = pi_new[j]
            pi_new[j] = swap_value
            cmax_new = t.calculate_Cmax(pi_new)
            cmax_old = t.calculate_Cmax(pi)
            if cmax_new > cmax_old:
                r = RNG.nextFloat(0, 1)
                dCmax = cmax_old - cmax_new
                if r >= math.exp(dCmax / T):
                    pi_new = copy.deepcopy(pi)
            pi = copy.deepcopy(pi_new)
            if t.calculate_Cmax(pi_best) > t.calculate_Cmax(pi):
                pi_best = copy.deepcopy(pi)
        it += 1
        T = T / math.log(it + 1)  #ln(it+1)
    return pi_best
Example #23
0
    def parseInputs(self, inputsDict):
        CoreObject.parseInputs(self, inputsDict)
        processingTime = inputsDict.get('processingTime', {})
        if not processingTime:
            processingTime = {
                'distributionType': 'Fixed',
                'mean': 0,
                'stdev': 0,
                'min': 0,
            }
        if processingTime['distributionType'] == 'Normal' and\
              processingTime.get('max', None) is None:
            processingTime['max'] = float(
                processingTime['mean']) + 5 * float(processingTime['stdev'])

        self.rng = RandomNumberGenerator(self, **processingTime)

        # ============================== variable that is used for the loading of machines =============
        self.exitAssignedToReceiver = False  # by default the objects are not blocked
        # when the entities have to be loaded to operatedMachines
        # then the giverObjects have to be blocked for the time
        # that the machine is being loaded
        from Globals import G
        G.AssemblyList.append(self)
def main():
    seed = int(input("Wprowadź Z: "))
    generator = RandomNumberGenerator(seed)
    taskNumber = int(input("Wprowadź liczbę zadań: "))
    tasks = range(1, taskNumber + 1)
    machineNumber = int(input("Wprowadź liczbę maszyn: "))
    machines = range(1, machineNumber + 1)

    Pi = []  #Permutacja po uszeregowaniu
    P = []  # Macierz czas wykonania
    Nr = []  # Lista zadań do wykonania
    P_Copy = []  #Macierz czasów wykonania
    Nr_Copy = []  # Lista zadań do wykonania
    C = []  # Macierz czasów zakończenia zadań
    S = []  # Macierz czasów trwania zadań

    for i in range(1, taskNumber + 1):
        Pi.append(i)

    for i in range(0, taskNumber):
        z = [None] * machineNumber
        C.append(z)

    for i in range(0, taskNumber):
        x = [None] * machineNumber
        S.append(x)

    for i in range(0, taskNumber):
        p = []
        for j in range(0, machineNumber):
            p.append(generator.nextInt(1, 29))
        P.append(p)
        P_Copy.append(p)

    for i in range(1, taskNumber + 1):
        Nr.append(i)
        Nr_Copy.append(i)

    print("\n")
    print("Tabu Calculate:")
    tabu_calculate(taskNumber, machineNumber, C, P, Pi, S)

    print(f"Pi: {Pi}")
    print(f"P: {P}")
    print(f"C: {C}")
    print(f"Cmax: {calculate_cmax(machineNumber,Pi,P)}")

    tabu_time_start = datetime.datetime.now()
    newPi = tabuSearch(taskNumber, machineNumber, P, Pi)
    tabu_time_end = datetime.datetime.now() - tabu_time_start

    newP = []

    for i in range(0, taskNumber):
        newP.append(P[newPi[i] - 1])

    tabu_calculate(taskNumber, machineNumber, C, newP, newPi, S)
    C, Cmax = calculate_neh(newP, taskNumber, machineNumber)
    print(f"Tabu search czas: {tabu_time_end}")
    print(f"Tabu search po sortowaniu: ")
    print(f"Pi: {newPi}")
    print(f"C: {C}")
    print(f"Cmax: {Cmax}")

    #lista wszystkich zadan na konkretnych maszynach
    p_ij_neh = P
    # permutacja zadan
    pi_neh = Nr
    p_kj = []

    print("\n")
    print("NEH:")
    print("p", p_ij_neh)
    print("Permutacj naturalna: ")
    print("pi: ", pi_neh)
    Cj, Cmax = calculate_neh(p_ij_neh, taskNumber, machineNumber)
    print("C:", Cj)
    print("Cmax:", Cmax)

    neh_time_start = datetime.datetime.now()
    p_kj = NEH(p_ij_neh.copy(), taskNumber, machineNumber)
    neh_time_end = datetime.datetime.now() - neh_time_start

    print(f"NEH czas: {neh_time_end}")
    print("NEH po sortowaniu: ")
    print("pkj: ", p_kj)
    Cj, Cmax = calculate_neh(p_kj, taskNumber, machineNumber)
    print("C:", Cj)
    print("Cmax:", Cmax)

    #lista wszystkich zadan na konkretnych maszynach
    p_ij_johnson = P
    # permutacja zadan
    pi_johnson = Nr
    # wyswietlenie rozwiazania po wykonaniu algorytmu optymalizacji
    solution = []

    print("\n")
    print("Johnson:")
    print(p_ij_johnson)
    print("Permutacj naturalna: ")
    print("pi: ", pi_johnson)
    Cj, Cmax = calculate_johnson(p_ij_johnson, taskNumber, machineNumber)
    print("C:", Cj)
    print("Cmax:", Cmax)

    for task in tasks:
        solution.append([pi_johnson[task - 1], p_ij_johnson[task - 1]])

    johson_time_start = datetime.datetime.now()
    pi = Johnson(tasks, p_ij_johnson.copy())
    johson_time_end = datetime.datetime.now() - johson_time_start
    print(f"Johson czas: {johson_time_end}")
    print("Johnson po sortowaniu: ")
    print("pi: ", pi)

    sort = {x: i for i, x in enumerate(pi)}
    solution.sort(key=lambda x: sort[x[0]])
    Cj, Cmax = calculate_johnson([row[1] for row in solution], taskNumber,
                                 machineNumber)
    print("C", Cj)
    print("Cmax:", Cmax)
def main():
    seed = int(input("Wprowadź Z:"))
    generator = RandomNumberGenerator(seed)
    taskNumber = int(input("Wprtowadź liczbe zadań:"))
    tasks = range(1, taskNumber + 1)

    nr = []  #wektor kolejnych zadan
    r = []  #czas przygotowania kolejnych zadań
    p = []  #czas wykonania kolejnych zadan
    q = []  #czas dostarczenia/stygnięcia kolejnych zadań

    #generowanie danych do zadania
    for task in tasks:
        nr.append(task)
        p.append(generator.nextInt(1, 29))

    pi = nr.copy()  #inicjalizacja permutacji zadań

    A = 0
    # X = 29
    for number in p:
        A += number

    for task in tasks:
        r.append(generator.nextInt(1, A))

    for task in tasks:
        q.append(generator.nextInt(1, 29))

    print("\nnr:", nr)
    print("r: ", r)
    print("p: ", p)
    print("q: ", q)
    print("\n")

    S, C, Cq, Cmax = calculate(r, p, q, taskNumber)
    print(f'pi: {pi}')
    print("S: ", S)
    print("C: ", C)
    print(f"Cq: {Cq}")
    print("Cmax", Cmax)
    print("\n")

    #inicjalizacja permutacji zadań
    # pi = nr.copy()

    #strutktura skladajaca sie z
    solution = []
    for task in tasks:
        solution.append([pi[task - 1], r[task - 1], p[task - 1], q[task - 1]])

    #Schrage
    print("Po sortowaniu:")
    pi = schragePmtn(r, p, q, tasks)
    sort = {x: i for i, x in enumerate(pi)}
    solution.sort(key=lambda x: sort[x[0]])

    rjSchrage = []
    pjSchrage = []
    qjSchrage = []

    for task in tasks:
        rjSchrage.append(solution[task - 1][1])
        pjSchrage.append(solution[task - 1][2])
        qjSchrage.append(solution[task - 1][3])

    SSchrage, CSchrage, CqSchrage, CmaxSchrager = calculate(
        rjSchrage, pjSchrage, qjSchrage, taskNumber)
    print("pi:", pi)
    print("S: ", SSchrage)
    print("C: ", CSchrage)
    print(f"Cq: {CqSchrage}")
    print("Cmax", CmaxSchrager)
Example #26
0
from RandomNumberGenerator import RandomNumberGenerator
from DigitObserver import DigitObserver
from GraphObserver import GraphObserver

if __name__ == '__main__':
    generator = RandomNumberGenerator()
    observer1 = DigitObserver()
    observer2 = GraphObserver()
    generator.addObserver(observer1)
    generator.addObserver(observer2)
    generator.execute()
Example #27
0
 def createMould(self, component):
     #read attributes from the json or from the orderToBeDecomposed
     id = component.get('id', 'not found')
     name = component.get('name', 'not found')
     try:
         # dummy variable that holds the routes of the jobs the route from the JSON file is a sequence of dictionaries
         JSONRoute = component.get('route', [])
         # variable that holds the argument used in the Job initiation hold None for each entry in the 'route' list
         route = [x for x in JSONRoute]  #    copy JSONRoute
         # assert that the assembler is in the moulds route and update the initial step of the mould's route
         firstStep = route.pop(0)
         assert (self.id in firstStep.get('stationIdsList',[])),\
                      'the assembler must be in the mould-to-be-created route\' initial step'
         # normal processing operation
         processingTime = firstStep['processingTime']
         processingTime = self.getOperationTime(processingTime)
         self.rng = RandomNumberGenerator(self, processingTime)
         self.procTime = self.rng.generateNumber()
         # update the activeObject's processing time according to the readings in the mould's route
         processDistType = processingTime.keys()[0]
         procTime = float(processingTime[processDistType].get('mean', 0))
         processOpType = firstStep.get('operationType', {}).get(
             'Processing', 'not found')  # can be manual/automatic
         # task_id
         task_id = firstStep.get('task_id', None)
         # sequence
         sequence = firstStep.get('sequence', None)
         # operator
         operator = firstStep.get('operator', {})
         # technology
         technology = firstStep.get('technology', None)
         # quantity
         quantity = firstStep.get('quantity', None)
         # setup operation
         setupTime = firstStep.get('setupTime', None)
         if setupTime:
             setupTime = self.getOperationTime(setupTime)
             self.stpRng = RandomNumberGenerator(self, setupTime)
             # update the activeObject's processing time according to the readings in the mould's route
             setupDistType = setupTime.keys()[0]
             setTime = float(setupTime[setupDistType].get('mean', 0))
             setupOpType = firstStep.get('operationType', {}).get(
                 'Setup', 'not found')  # can be manual/automatic
             # update the first step of the route with the activeObjects id as sole element of the stationIdsList
             route.insert(0, {'stationIdsList':[str(self.id)],
                              'processingTime':{str(processDistType):{'mean':str(procTime)}},\
                              'setupTime':{str(setupDistType):{'mean':str(setupTime)}},
                              'operationType':{'Processing':processOpType,'Setup':setupOpType}})
         else:
             # update the first step of the route with the activeObjects id as sole element of the stationIdsList
             route.insert(
                 0, {
                     'stationIdsList': [str(self.id)],
                     'processingTime': {
                         str(processDistType): {
                             'mean': str(procTime)
                         }
                     },
                     'operationType': {
                         'Processing': processOpType
                     }
                 })
         # if there is task_id then add it to the route
         if task_id:
             route[0]["task_id"] = task_id
         # if there is sequence then add it to the route
         if sequence:
             route[0]["sequence"] = sequence
         # if there is operator then add it to the route
         if operator:
             route[0]["operator"] = operator
         # if there is technology then add it to the route
         if technology:
             route[0]["technology"] = technology
         # if there is quantity then add it to the route
         if quantity != None:
             route[0]["quantity"] = quantity
         #Below it is to assign an exit if it was not assigned in JSON
         #have to talk about it with NEX
         exitAssigned = False
         for element in route:
             elementIds = element.get('stationIdsList', [])
             for obj in G.ObjList:
                 for elementId in elementIds:
                     if obj.id == elementId and obj.type == 'Exit':
                         exitAssigned = True
         # assign an exit to the route of the mould
         if not exitAssigned:
             exitId = None
             for obj in G.ObjList:
                 if obj.type == 'Exit':
                     exitId = obj.id
                     break
             if exitId:
                 route.append({
                     'stationIdsList': [str(exitId)],
                     'processingTime': {}
                 })
         # keep a reference of all extra properties passed to the job
         extraPropertyDict = {}
         for key, value in component.items():
             if key not in ('_class', 'id'):
                 extraPropertyDict[key] = value
         # create and initiate the OrderComponent
         from Mould import Mould
         M=Mould(id, name, route, \
                           priority=self.mouldParent.priority, \
                           order=self.mouldParent,\
                           dueDate=self.mouldParent.dueDate, \
                           orderDate=self.mouldParent.orderDate, \
                           extraPropertyDict=extraPropertyDict,\
                           isCritical=self.mouldParent.isCritical)
         # update the mouldToBeCreated
         self.mouldToBeCreated = M
         G.JobList.append(M)
         G.WipList.append(M)
         G.EntityList.append(M)
         G.MouldList.append(M)
         #initialize the component
         M.initialize()
     except:
         # added for testing
         print 'the mould to be created', component.get(
             'name', 'not found'), 'cannot be created', 'time', self.env.now
         raise
Example #28
0
                                           key,
                                           algorithm,
                                           use_custom_rc4=USE_CUSTOM_RC4)
                else:
                    print("Invalid parameters. \n" + help_message)
            except Exception as e:
                print(e)
                print("Invalid parameters. \n" + help_message)

        elif method_id == "2":  # random number
            key = sys.argv[0]
            test_randomness = False
            if nb_args == 3:
                test_randomness = True if sys.argv[1] == "True" else False

            rdm_generator = RandomNumberGenerator(key,
                                                  use_custom=USE_CUSTOM_RC4)
            print(f"Your random number: {rdm_generator.generate()}")
            if test_randomness:
                rdm_generator.display_random_image()
                rdm_generator.verify_randomness()
                rdm_generator.plot_random_and_semi_random()

        elif method_id == "3":  # full cipher/decipher pipeline
            filename = sys.argv[0]
            algorithm = sys.argv[
                1] if sys.argv[1] == "rc4" or sys.argv[1] == "rc5" else None
            key = sys.argv[2]

            WAV_file_demo = False
            if nb_args == 5:
                WAV_file_demo = True if sys.argv[3] == "True" else False