Esempio n. 1
0
    def run(self):
        pprint("OPT calculating initial population...", BLUE, self.printing)
        population = self.initialPopulation()

        for i in range(self.iterations):
            pprint("OPT iteration number %s" % (i + 1), BLUE, self.printing)
            population = self.mutatePopulation(population)
        print bestSolution(population)
Esempio n. 2
0
    def run(self, initialPopulation=None):
        pprint("OPT calculating initial population...", BLUE, self.printing)
        if initialPopulation == None:
            population = self.initialPopulation()
        else:
            for p in initialPopulation:
                self.calcIndividualFitness(p)
            population = self.mutatePopulation(initialPopulation)

        for i in range(self.iterations):
            pprint("OPT iteration number %s" % (i + 1), BLUE, self.printing)
            population = self.mutatePopulation(population)
        return population
Esempio n. 3
0
    def start(self, endMarginLimit=10, machineMarginLimit=10):
        pprint("SCHED Started...", BLUE, self.printing)
        self.endMargin = 1
        while self.endMargin <= endMarginLimit:
            self.machineMargin = 1
            while self.machineMargin <= machineMarginLimit:
                try:
                    pprint("SCHED End Margin: %d, Machine Margin: %d" % \
                     (self.endMargin, self.machineMargin), YELLOW, self.printing)
                    self.problem.reset()
                    solutions, numberOfSolutions = self.run()
                    if numberOfSolutions > 0:
                        return solutions
                except Exception as e:
                    pprint("SCHED Exception " + str(e), RED)
                    pprint("SCHED Trying new value for End Margin.", RED)
                    endMarginLimit += 1

                self.machineMargin += 1
            self.endMargin += 1
        pprint("SCHED No solutions found.", RED, self.printing)
        return None
Esempio n. 4
0
    def run(self):
        """
		Runs the main Scheduler logic.
		"""
        for machine in self.plant.machines:
            var = self.createMachineQuantityVarName(machine)
            self.problem.addVariable(var, [machine.quantity])

        for machine in self.plant.machines:
            for order in self.orderList.orders:
                var = self.createTimeAtMachineVarName(order, machine)
                self.problem.addVariable(var, [order.recipe[machine.name]])

        for machineIndex, machine in enumerate(self.plant.machines):
            for order in self.orderList.orders:
                self.addOrderEnterTimeAtMachineVar(order, machine.name,
                                                   machineIndex)

        for machineIndex, machine in enumerate(self.plant.machines):
            if machine.precedence == True and \
               machineIndex != len(self.plant.machines) - 1:
                self.addCapacityConstraint(machine, machineIndex)
            self.addMachineQuantityConstraint(machine)

        for machineIndex, machine in enumerate(self.plant.machines):
            if len(machine.setOfBreaks()) != 0:
                for order in self.orderList.orders:
                    enterVar = self.createEnterTimeVarName(order, machine)
                    self.problem.addConstraint(
                        MachineBreaksConstraint(order, machine), [enterVar])

        for order in self.orderList.orders:
            self.addFinishTimeVar(order)

        pprint("SCHED Computing solutions...", BLUE, self.printing)
        solutions = self.problem.getSolutions()
        return solutions, len(solutions)
Esempio n. 5
0
	def initialPopulation(self):
		population = []
		initIndiv = self.initialIndividual()
		population.append(initIndiv)
		
		for i in range(self.populationSize):
			pprint("OPT generating new initial individual...", BLUE, self.printing)
			mutatedIndiv = self.mutateIndividual(initIndiv)
			while self.isIndividualInPopulation(mutatedIndiv, population) == True:
				mutatedIndiv = self.mutateIndividual(initIndiv)
			pprint("OPT calculating fitness of individual...", BLUE, self.printing)
			self.calcIndividualFitness(mutatedIndiv)
			pprint("OPT Done.", BLUE, self.printing)
			population.append(mutatedIndiv)
		self.sortPopulation(population)
		return population
Esempio n. 6
0
    "schedule": (schedule, ["plant-name", "order-list-name"],
                 "Compute a schedule for an order list on a plant"),
    "optimize": (optimize, ["plant-name", "order-list-name"],
                 "Optimize a schedule for an order list on a plant")
}


def showHelp():
    """
	Shows help data from the commands dict.
	"""
    print "Plant Maker\nUsage:\n"
    for c in commands:
        print c,

        for a in commands[c][1]:
            print "<" + a + ">",

        print "-- " + commands[c][2]


if __name__ == '__main__':
    if len(sys.argv) < 3:
        showHelp()
    else:
        arguments = sys.argv[2:]
        try:
            commands[sys.argv[1]][0](arguments)
        except KeyboardInterrupt:
            pprint("Operation cancelled by user.", GREEN)
Esempio n. 7
0
    def simulate(self, inSchedule):
        pprint("SIM Starting new simulation...", CYAN, self.printing)

        assert type(inSchedule) == Schedule
        assert len(inSchedule.schedule) == 0
        assert len(inSchedule.finishTimes) == 0

        schedule = inSchedule.startTimes[:]
        schedule.sort(lambda a, b: cmp(a[2], b[2]))

        t = schedule[0][2]
        delay = 0

        numOfOrdersFinished = 0
        numOfTotalOrders = len(schedule)

        while numOfOrdersFinished < numOfTotalOrders:
            for i, s in enumerate(schedule):
                if s == None:
                    continue

                if s[2] <= t:
                    entered = False
                    currentMachineIndex = 0
                    currentMachine = s[0].currentMachine
                    if currentMachine != "":
                        currentMachineIndex = self.machineIndexInGraph(
                            currentMachine)
                    machine = self.graph[currentMachineIndex][0].machine
                    if [
                            z in machine.setOfBreaks()
                            for z in range(t, t + s[0].recipe[machine.name])
                    ].count(True) == 0:
                        for n in self.graph[currentMachineIndex]:
                            if n.currentOrder == None:
                                n.currentOrder = [
                                    s[0], s[0].recipe[n.machine.name]
                                ]
                                schedule[i] = None
                                entered = True
                                pprint(
                                    "SIM %10s %20s %15s at time %5s." %
                                    (n.currentOrder[0], "entered", n.machine,
                                     t), YELLOW, self.printing)
                                inSchedule.schedule.append([
                                    n.currentOrder[0],
                                    str(n.machine.name), t
                                ])
                                break

                        if entered == False:
                            pprint(
                                "SIM %10s %20s %15s at time %5s." %
                                (n.currentOrder[0], "could not enter",
                                 n.machine, t), RED, self.printing)
                            s[2] += 1
                            delay += 1
                    else:
                        pprint(
                            "SIM %10s %20s %15s at time %5s because of machine break."
                            % (s[0], "could not enter", machine, t), RED,
                            self.printing)
                        s[2] += 1
                        delay += 1

            for i, n in enumerate(self.graph):
                if type(n) == list:
                    for m in n:
                        if m.currentOrder != None:
                            if m.currentOrder[1] != 0:
                                m.currentOrder[1] -= 1
                            else:
                                if n == self.graph[-1]:
                                    pprint(
                                        "SIM %10s %20s at time %5s." %
                                        (m.currentOrder[0], "finished", t),
                                        GREEN, self.printing)
                                    inSchedule.finishTimes.append(
                                        [m.currentOrder[0], t])
                                    m.currentOrder = None
                                    numOfOrdersFinished += 1
                                else:
                                    self.graph[i + 1].orders.append([
                                        m.currentOrder[0],
                                        self.plant.craneMoveTime
                                    ])
                                    pprint(
                                        "SIM %10s %20s %15s at time %5s." %
                                        (m.currentOrder[0], "left", m.machine,
                                         t), YELLOW, self.printing)
                                    m.currentOrder = None
                else:
                    for j, o in enumerate(n.orders):
                        if o == None:
                            continue

                        if o[1] > 0:
                            o[1] -= 1
                        else:
                            machine = self.graph[i + 1][0].machine
                            if [
                                    z in machine.setOfBreaks() for z in range(
                                        t, t + o[0].recipe[machine.name])
                            ].count(True) == 0:
                                for m in self.graph[i + 1]:
                                    if m.currentOrder == None:
                                        if m.machine.precedence == False:
                                            m.currentOrder = [
                                                o[0],
                                                o[0].recipe[m.machine.name]
                                            ]
                                            pprint(
                                                "SIM %10s %20s %15s at time %5s."
                                                % (o[0], "entered", m.machine,
                                                   t), YELLOW, self.printing)
                                        else:
                                            time = max(
                                                self.minTimeFinish(
                                                    self.graph[i + 1]),
                                                o[0].recipe[m.machine.name])
                                            m.currentOrder = [o[0], time]
                                            if time != o[0].recipe[
                                                    m.machine.name]:
                                                pprint(
                                                    "SIM %10s %20s %15s at time %5s with overtime %5s."
                                                    %
                                                    (o[0], "entered",
                                                     m.machine, t, time - o[0].
                                                     recipe[m.machine.name]),
                                                    RED, self.printing)
                                            else:
                                                pprint(
                                                    "SIM %10s %20s %15s at time %5s."
                                                    % (o[0], "entered",
                                                       m.machine, t), YELLOW,
                                                    self.printing)
                                        inSchedule.schedule.append([
                                            m.currentOrder[0],
                                            str(m.machine.name), t
                                        ])

                                        if o[1] < 0:
                                            pprint(
                                                "SIM %10s before %15s was delayed %5s."
                                                % (o[0], m.machine, o[1]), RED,
                                                self.printing)
                                            delay += 1
                                        n.orders[j] = None
                                        break
                            else:
                                pprint(
                                    "SIM %10s %20s %15s at time %5s because of machine break."
                                    % (o[0], "could not enter", machine, t),
                                    RED, self.printing)
                                delay += 1
            t += 1
        pprint(
            "SIM --------------------------------------------------------------",
            CYAN, self.printing)
Esempio n. 8
0
 def nymaim_parse_blob(self, blob):
     """
     decrypt and interpret config (uses hardcoded hashes)
     """
     parsed = {'domains': [], 'urls': [], 'dns': [], 'type': 'nymaim'}
     for hash, raw in NymCfgStream(blob):
         try:
             pprint("<{:08x}>: {}".format(
                 hash,
                 raw.encode('hex') if len(raw) == 4 else raw))
             if hash == self.CFG_URL:  # '48c2026b':
                 parsed['urls'] += [{
                     'url': append_http(raw[20:].rstrip(';'))
                 }]
             elif hash == self.CFG_DGA_HASH:  # 'd9aea02a':
                 parsed['dga_hash'] = [uint32(h) for h in chunks(raw, 4)]
             elif hash == self.CFG_DOMAINS:  # '095d4b1d':
                 parsed['domains'] += [{
                     'cnc':
                     append_http(raw[4:].rstrip(';'))
                 }]
             elif hash == self.CFG_ENC_KEY:  # '510be622':
                 parsed['encryption_key'] = raw
             elif hash == self.CFG_RSA_KEY:  # 'fb7f122f':
                 bits = uint32(raw[:4])
                 bytes = bits / 8
                 d = raw[4:4 + bytes].encode('hex')
                 e = raw[4 + bytes:4 + bytes + bytes].encode('hex')
                 parsed['public_key'] = {
                     'n': str(int(d, 16)),
                     'e': int(e, 16),
                 }
             elif hash == self.CFG_TTL:  # '8de8f7e6':
                 if len(raw) == 12:
                     year, month, day = uint32(raw[-4:]), uint32(
                         raw[4:-4]), uint32(raw[:4])
                     parsed['time_restriction'] = '{}-{:02}-{:02}'.format(
                         year, month, day)
                 else:
                     parsed['time_restriction'] = [raw.encode('hex')]
             elif hash == self.CFG_DNS:
                 parsed['dns'] += raw.split(';')
             elif hash == self.CTG_32BIT_TMPL_1:
                 parsed['template_32bit_1'] = raw
             elif hash == self.CTG_32BIT_TMPL_2:
                 parsed['template_32bit_2'] = raw
             elif hash == self.CTG_64BIT_TMPL:
                 parsed['template_64bit_2'] = raw
             elif hash == self.CFT_NOTEPAD_TMPL:  # notepad template
                 parsed['notepad_template'] = raw
             elif hash == self.CFG_FAKE_ERROR_MSG:  # fake error message, shown to user on startup
                 parsed['fake_error_message'] = raw
             elif hash == self.CFG_PEER_DOMAINS:
                 parsed['domains'] += [{
                     'cnc': x
                 } for x in raw.split(';') if x]
             elif (all(c in string.printable
                       for c in raw) and len(raw) > 3) or len(
                           [c for c in raw if c in string.printable]) > 10:
                 if 'other_strings' not in parsed:
                     parsed['other_strings'] = {}
                 parsed['other_strings'][hex(hash)] = raw.encode('hex')
         except RuntimeError:
             # error during parsing...
             if 'errored_on' not in parsed:
                 parsed['errored_on'] = []
             parsed['errored_on'] += [{
                 'hash': hash,
                 'raw': raw.encode('hex')
             }]
     return parsed