def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Cargo): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if service.Fit.getInstance().serviceFittingOptions["rackLabels"]: if stuff.slot == Slot.MODE: return u'─ Tactical Mode ─' else: return u'─ {} Slots ─'.format(Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name else: item = getattr(stuff, "item", stuff) if service.Fit.getInstance().serviceFittingOptions["showMarketShortcuts"]: marketShortcut = getattr(item, "marketShortcut", None) if marketShortcut: # use unicode subscript to display shortcut value shortcut = unichr(marketShortcut+8320)+u" " return shortcut+item.name return item.name
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Cargo): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if service.Fit.getInstance().serviceFittingOptions["rackLabels"]: if stuff.slot == Slot.MODE: return u'─ Tactical Mode ─' else: return u'─ {} Slots ─'.format( Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name else: item = getattr(stuff, "item", stuff) if service.Fit.getInstance( ).serviceFittingOptions["showMarketShortcuts"]: marketShortcut = getattr(item, "marketShortcut", None) if marketShortcut: # use unicode subscript to display shortcut value shortcut = unichr(marketShortcut + 8320) + u" " return shortcut + item.name return item.name
def refresh(self, stuff): ''' Displays fitting Sends data to d.Display.refresh where the rows and columns are set up, then does a bit of post-processing (colors) ''' self.Freeze() d.Display.refresh(self, stuff) sFit = service.Fit.getInstance() fit = sFit.getFit(self.activeFitID) slotMap = {} # test for too many modules (happens with t3s / CCP change in slot layout) for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 font = (self.GetClassDefaultAttributes()).font for i, mod in enumerate(self.mods): self.SetItemBackgroundColour(i, self.GetBackgroundColour()) # only consider changing color if we're dealing with a Module if type(mod) is Module: if slotMap[mod.slot]: # Color too many modules as red self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51)) elif sFit.serviceFittingOptions[ "colorFitBySlot"]: # Color by slot it enabled self.SetItemBackgroundColour(i, self.slotColour(mod.slot)) # Set rack face to bold if isinstance(mod, Rack) and \ sFit.serviceFittingOptions["rackSlots"] and \ sFit.serviceFittingOptions["rackLabels"]: font.SetWeight(wx.FONTWEIGHT_BOLD) self.SetItemFont(i, font) else: font.SetWeight(wx.FONTWEIGHT_NORMAL) self.SetItemFont(i, font) self.Thaw() self.itemCount = self.GetItemCount() self.itemRect = self.GetItemRect(0) if 'wxMac' in wx.PlatformInfo: try: self.MakeSnapshot() except: pass
def refresh(self, stuff): ''' Displays fitting Sends data to d.Display.refresh where the rows and columns are set up, then does a bit of post-processing (colors) ''' self.Freeze() d.Display.refresh(self, stuff) sFit = service.Fit.getInstance() fit = sFit.getFit(self.activeFitID) slotMap = {} # test for too many modules (happens with t3s / CCP change in slot layout) for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 font = (self.GetClassDefaultAttributes()).font for i, mod in enumerate(self.mods): self.SetItemBackgroundColour(i, self.GetBackgroundColour()) # only consider changing color if we're dealing with a Module if type(mod) is Module: if slotMap[mod.slot]: # Color too many modules as red self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51)) elif sFit.serviceFittingOptions["colorFitBySlot"]: # Color by slot it enabled self.SetItemBackgroundColour(i, self.slotColour(mod.slot)) # Set rack face to bold if isinstance(mod, Rack) and \ sFit.serviceFittingOptions["rackSlots"] and \ sFit.serviceFittingOptions["rackLabels"]: font.SetWeight(wx.FONTWEIGHT_BOLD) self.SetItemFont(i, font) else: font.SetWeight(wx.FONTWEIGHT_NORMAL) self.SetItemFont(i, font) self.Thaw() self.itemCount = self.GetItemCount() self.itemRect = self.GetItemRect(0) if 'wxMac' in wx.PlatformInfo: try: self.MakeSnapshot() except: pass
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) if isinstance(stuff, Fighter): return "%d/%d %s" % ( stuff.amountActive, stuff.getModifiedItemAttr("fighterSquadronMaxSize"), stuff.item.name) elif isinstance(stuff, Cargo): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): if self.projectedView: # we need a little more information for the projected view fitID = self.mainFrame.getActiveFit() return "%dx %s (%s)" % (stuff.getProjectionInfo(fitID).amount, stuff.name, stuff.ship.item.name) else: return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if service.Fit.getInstance().serviceFittingOptions["rackLabels"]: if stuff.slot == Slot.MODE: return u'─ Tactical Mode ─' else: return u'─ {} Slots ─'.format( Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name elif isinstance(stuff, Implant): return stuff.item.name else: item = getattr(stuff, "item", stuff) if service.Fit.getInstance( ).serviceFittingOptions["showMarketShortcuts"]: marketShortcut = getattr(item, "marketShortcut", None) if marketShortcut: # use unicode subscript to display shortcut value shortcut = unichr(marketShortcut + 8320) + u" " del item.marketShortcut return shortcut + item.name return item.name
def _exportEftBase(fit): offineSuffix = " /OFFLINE" export = "[%s, %s]\n" % (fit.ship.item.name, fit.name) stuff = {} sFit = service.Fit.getInstance() for module in fit.modules: slot = module.slot if not slot in stuff: stuff[slot] = [] curr = module.item.name if module.item else ("[Empty %s slot]" % Slot.getName(slot).capitalize() if slot is not None else "") if module.charge and sFit.serviceFittingOptions["exportCharges"]: curr += ", %s" % module.charge.name if module.state == State.OFFLINE: curr += offineSuffix curr += "\n" stuff[slot].append(curr) for slotType in EFT_SLOT_ORDER: data = stuff.get(slotType) if data is not None: export += "\n" for curr in data: export += curr if len(fit.drones) > 0: export += "\n\n" for drone in fit.drones: export += "%s x%s\n" % (drone.item.name, drone.amount) if export[-1] == "\n": export = export[:-1] return export
def refresh(self, stuff): d.Display.refresh(self, stuff) sFit = service.Fit.getInstance() fit = sFit.getFit(self.activeFitID) slotMap = {} for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 bkcolor = self.GetBackgroundColour() for i, mod in enumerate(self.mods): if slotMap[mod.slot]: self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51)) else: icolor = self.GetItemBackgroundColour(i) if icolor != bkcolor: self.SetItemBackgroundColour(i, bkcolor)
def exportXml(cls, *fits): doc = xml.dom.minidom.Document() fittings = doc.createElement("fittings") doc.appendChild(fittings) for fit in fits: fitting = doc.createElement("fitting") fitting.setAttribute("name", fit.name) fittings.appendChild(fitting) description = doc.createElement("description") description.setAttribute("value", "") fitting.appendChild(description) shipType = doc.createElement("shipType") shipType.setAttribute("value", fit.ship.item.name) fitting.appendChild(shipType) charges = {} slotNum = {} for module in fit.modules: if module.isEmpty: continue slot = module.slot if not slot in slotNum: slotNum[slot] = 0 slotId = slotNum[slot] slotNum[slot] += 1 hardware = doc.createElement("hardware") hardware.setAttribute("type", module.item.name) slotName = Slot.getName(slot).lower() slotName = slotName if slotName != "high" else "hi" hardware.setAttribute("slot", "%s slot %d" % (slotName, slotId)) fitting.appendChild(hardware) if module.charge: if not module.charge.name in charges: charges[module.charge.name] = 0 # `or 1` because some charges (ie scripts) are without qty charges[module.charge.name] += module.numShots or 1 for drone in fit.drones: hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % drone.amount) hardware.setAttribute("slot", "drone bay") hardware.setAttribute("type", drone.item.name) fitting.appendChild(hardware) for cargo in fit.cargo: if not cargo.item.name in charges: charges[cargo.item.name] = 0 charges[cargo.item.name] += cargo.amount for name, qty in charges.items(): hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % qty) hardware.setAttribute("slot", "cargo") hardware.setAttribute("type", name) fitting.appendChild(hardware) return doc.toprettyxml()
def exportEft(self): offineSuffix = " /OFFLINE" export = "[%s, %s]\n" % (self.ship.item.name, self.name) stuff = {} for module in self.modules: slot = module.slot if not slot in stuff: stuff[slot] = [] curr = module.item.name if module.item else ("[Empty %s slot]" % Slot.getName(slot).capitalize() if slot is not None else "") if module.charge: curr += ", %s" % module.charge.name if module.state == State.OFFLINE: curr += offineSuffix curr += "\n" stuff[slot].append(curr) for slotType in self.EXPORT_ORDER_EFT: data = stuff.get(slotType) if data is not None: export += "\n" for curr in data: export += curr if len(self.drones) > 0: export += "\n\n" for drone in self.drones: export += "%s x%s\n" % (drone.item.name, drone.amount) if export[-1] == "\n": export = export[:-1] return export
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if service.Fit.getInstance().serviceFittingOptions["rackLabels"]: return u'─ {} Slots ─'.format(Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name else: item = getattr(stuff, "item", stuff) return item.name
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fighter): return "%d/%d %s" % \ (stuff.amountActive, stuff.getModifiedItemAttr("fighterSquadronMaxSize"), stuff.item.name) elif isinstance(stuff, Cargo): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): if self.projectedView: # we need a little more information for the projected view fitID = self.mainFrame.getActiveFit() return "%dx %s (%s)" % (stuff.getProjectionInfo(fitID).amount, stuff.name, stuff.ship.item.name) else: return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if Fit.getInstance().serviceFittingOptions["rackLabels"]: if stuff.slot == Slot.MODE: return u'─ Tactical Mode ─' else: return u'─ {} Slots ─'.format(Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name elif isinstance(stuff, Implant): return stuff.item.name else: item = getattr(stuff, "item", stuff) if Fit.getInstance().serviceFittingOptions["showMarketShortcuts"]: marketShortcut = getattr(item, "marketShortcut", None) if marketShortcut: # use unicode subscript to display shortcut value shortcut = unichr(marketShortcut + 8320) + u" " del item.marketShortcut return shortcut + item.name return item.name
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Cargo): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Rack): if service.Fit.getInstance().serviceFittingOptions["rackLabels"]: return u'─ {} Slots ─'.format(Slot.getName(stuff.slot).capitalize()) else: return "" elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name else: item = getattr(stuff, "item", stuff) return item.name
def refresh(self, stuff): d.Display.refresh(self, stuff) sFit = service.Fit.getInstance() fit = sFit.getFit(self.activeFitID) slotMap = {} for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 for i, mod in enumerate(self.mods): if slotMap[mod.slot]: self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51)) elif sFit.serviceFittingOptions["colorFitBySlot"]: self.SetItemBackgroundColour(i, self.slotColour(mod.slot)) else: self.SetItemBackgroundColour(i, self.GetBackgroundColour()) self.itemCount = self.GetItemCount() self.itemRect = self.GetItemRect(0) if 'wxMac' in wx.PlatformInfo: self.MakeSnapshot()
def getText(self, stuff): if isinstance(stuff, Drone): return "%dx %s" % (stuff.amount, stuff.item.name) elif isinstance(stuff, Fit): return "%s (%s)" % (stuff.name, stuff.ship.item.name) elif isinstance(stuff, Module): if stuff.isEmpty: return "%s Slot" % Slot.getName(stuff.slot).capitalize() else: return stuff.item.name else: item = getattr(stuff, "item", stuff) return item.name
def getImageId(self, stuff): if isinstance(stuff, Drone): return -1 if isinstance(stuff, Fit): return self.shipImage if isinstance(stuff, Module): if stuff.isEmpty: return self.fittingView.imageList.GetImageIndex("slot_%s_small" % Slot.getName(stuff.slot).lower(), "icons") else: return self.loadIconFile(stuff.item.icon.iconFile if stuff.item.icon else "") item = getattr(stuff, "item", stuff) return self.loadIconFile(item.icon.iconFile if item.icon else "")
def getImageId(self, stuff): if isinstance(stuff, Drone): return -1 if isinstance(stuff, Fit): return self.shipImage if isinstance(stuff, Module): if stuff.isEmpty: return self.fittingView.imageList.GetImageIndex( "slot_%s_small" % Slot.getName(stuff.slot).lower(), "icons") else: return self.loadIconFile( stuff.item.icon.iconFile if stuff.item.icon else "") item = getattr(stuff, "item", stuff) return self.loadIconFile(item.icon.iconFile if item.icon else "")
def exportXml(cls, *fits): doc = xml.dom.minidom.Document() fittings = doc.createElement("fittings") doc.appendChild(fittings) for fit in fits: fitting = doc.createElement("fitting") fitting.setAttribute("name", fit.name) fittings.appendChild(fitting) description = doc.createElement("description") description.setAttribute("value", "") fitting.appendChild(description) shipType = doc.createElement("shipType") shipType.setAttribute("value", fit.ship.item.name) fitting.appendChild(shipType) slotNum = {} for module in fit.modules: if module.isEmpty: continue slot = module.slot if not slot in slotNum: slotNum[slot] = 0 slotId = slotNum[slot] slotNum[slot] += 1 hardware = doc.createElement("hardware") hardware.setAttribute("type", module.item.name) slotName = Slot.getName(slot).lower() slotName = slotName if slotName != "high" else "hi" hardware.setAttribute("slot", "%s slot %d" % (slotName, slotId)) fitting.appendChild(hardware) for drone in fit.drones: hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % drone.amount) hardware.setAttribute("slot", "drone bay") hardware.setAttribute("type", drone.item.name) fitting.appendChild(hardware) return doc.toprettyxml()
def getImageId(self, stuff): if isinstance(stuff, Drone): return -1 elif isinstance(stuff, Fit): return self.shipImage elif isinstance(stuff, Rack): return -1 elif isinstance(stuff, Implant): if stuff.character: # if it has a character as it's parent return self.fittingView.imageList.GetImageIndex("character_small", "gui") else: return self.shipImage elif isinstance(stuff, Module): if stuff.isEmpty: return self.fittingView.imageList.GetImageIndex("slot_%s_small" % Slot.getName(stuff.slot).lower(), "gui") else: return self.loadIconFile(stuff.item.icon.iconFile if stuff.item.icon else "") item = getattr(stuff, "item", stuff) return self.loadIconFile(item.icon.iconFile if item.icon else "")
def getImageId(self, stuff): if isinstance(stuff, Drone): return -1 if isinstance(stuff, Fit): return self.shipImage if isinstance(stuff, Rack): return -1 if isinstance(stuff, Implant): if stuff.character: # if it has a character as it's parent return self.fittingView.imageList.GetImageIndex( "character_small", "gui") else: return self.shipImage if isinstance(stuff, Module): if stuff.isEmpty: return self.fittingView.imageList.GetImageIndex( "slot_%s_small" % Slot.getName(stuff.slot).lower(), "gui") else: return self.loadIconFile( stuff.item.icon.iconFile if stuff.item.icon else "") item = getattr(stuff, "item", stuff) return self.loadIconFile(item.icon.iconFile if item.icon else "")
def exportXml(cls, callback=None, *fits): doc = xml.dom.minidom.Document() fittings = doc.createElement("fittings") doc.appendChild(fittings) sFit = service.Fit.getInstance() for i, fit in enumerate(fits): try: fitting = doc.createElement("fitting") fitting.setAttribute("name", fit.name) fittings.appendChild(fitting) description = doc.createElement("description") description.setAttribute("value", "") fitting.appendChild(description) shipType = doc.createElement("shipType") shipType.setAttribute("value", fit.ship.item.name) fitting.appendChild(shipType) charges = {} slotNum = {} for module in fit.modules: if module.isEmpty: continue slot = module.slot if slot == Slot.SUBSYSTEM: # Order of subsystem matters based on this attr. See GH issue #130 slotId = module.getModifiedItemAttr("subSystemSlot") - 124 else: if not slot in slotNum: slotNum[slot] = 0 slotId = slotNum[slot] slotNum[slot] += 1 hardware = doc.createElement("hardware") hardware.setAttribute("type", module.item.name) slotName = Slot.getName(slot).lower() slotName = slotName if slotName != "high" else "hi" hardware.setAttribute("slot", "%s slot %d" % (slotName, slotId)) fitting.appendChild(hardware) if module.charge and sFit.serviceFittingOptions["exportCharges"]: if not module.charge.name in charges: charges[module.charge.name] = 0 # `or 1` because some charges (ie scripts) are without qty charges[module.charge.name] += module.numCharges or 1 for drone in fit.drones: hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % drone.amount) hardware.setAttribute("slot", "drone bay") hardware.setAttribute("type", drone.item.name) fitting.appendChild(hardware) for cargo in fit.cargo: if not cargo.item.name in charges: charges[cargo.item.name] = 0 charges[cargo.item.name] += cargo.amount for name, qty in charges.items(): hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % qty) hardware.setAttribute("slot", "cargo") hardware.setAttribute("type", name) fitting.appendChild(hardware) except: print "Failed on fitID: %d"%fit.ID continue finally: if callback: wx.CallAfter(callback, i) return doc.toprettyxml()
def run(self, elite=0.05, crossoverChance=0.8, slotMutationChance=0.5, typeMutationChance=0.5): #Use a copy of the original for all our calcs. We don't want to damage it fit = copy.deepcopy(self.original) fit.unfill() #First of all, lets check the number of slots we got to play with chromLength = -1 slotAmounts = {} for type in Slot.getTypes(): slot = Slot.getValue(type) amount = fit.getSlotsFree(slot) if amount > 0: slotAmounts[slot] = amount chromLength += amount if not slotAmounts: #Nothing to do, joy return slotModules = {} metaModules = {} for slotType in slotAmounts: slotModules[slotType] = modules = [] for module in self.modules: #Store the variations of each base for ease and speed metaParent = self.__getMetaParent(module.item) metaList = metaModules.get(metaParent) if metaList is None: metaList = metaModules[metaParent] = [] metaList.append(module) #Sort stuff by slotType for ease and speed slot = module.slot if slot in slotModules: slotModules[slot].append(module) for slotType, modules in slotModules.iteritems(): if len(modules) == 0: chromLength -= slotAmounts[slotType] del slotAmounts[slotType] #Now, we need an initial set, first thing to do is decide how big that set will be setSize = 10 #Grab some variables locally for performance improvements rchoice = random.choice rrandom = random.random rrandint = random.randint bbisect = bisect.bisect ccopy = copy.copy #Get our list for storage of our chromosomes chromosomes = [] # Helpers weigher = lambda chromosome: (self.fitness(fit, chromosome), chromosome ) keyer = lambda info: info[0] eliteCutout = int(math.floor(setSize * (1 - elite))) lastEl = setSize - 1 #Generate our initial set entirely randomly #Subtelies to take in mind: # * modules of the same slotType are kept together for easy cross-overing state = self.state for _ in xrange(setSize): chrom = [] for type, amount in slotAmounts.iteritems(): for _ in xrange(amount): chrom.append(rchoice(slotModules[type])) chromosomes.append(weigher(chrom)) #Sort our initial set chromosomes.sort(key=keyer) currentGeneration = chromosomes #Yield the best result from our initial set, this is gonna be pretty bad yield currentGeneration[lastEl] #Setup's done, now we can actualy apply our genetic algorithm to optimize all this while True: moo = time.time() #First thing we do, we're gonna be elitair #Grab the top x%, we'll put em in the next generation nextGeneration = [] for i in xrange(lastEl, eliteCutout - 1, -1): nextGeneration.append(currentGeneration[i]) #Figure out our ratios to do our roulette wheel fitnessList = map(keyer, currentGeneration) totalFitness = float(sum(fitnessList)) curr = 0 ratios = [] for fitness in fitnessList: curr += fitness ratios.append(curr / (totalFitness or 1)) t = 0 #Do our pairing for _ in xrange(0, eliteCutout): # Crossover chance mother = currentGeneration[bbisect(ratios, rrandom())][1] father = currentGeneration[bbisect(ratios, rrandom())][1] if rrandom() <= crossoverChance: crosspoint = rrandint(0, chromLength) luke = mother[:crosspoint] + father[crosspoint:] else: luke = father #Chance for slot mutation if rrandom() <= slotMutationChance: target = rrandint(0, chromLength) mod = luke[target] luke[target] = rchoice(slotModules[mod.slot]) if rrandom() <= typeMutationChance: #Mutation of an item to another one of the same type target = rrandint(0, chromLength) mod = luke[target] vars = metaModules[self.__getMetaParent(mod.item)] luke[target] = rchoice(vars) tt = time.time() nextGeneration.append(weigher(luke)) t += time.time() - tt print "time spent weighing: ", t nextGeneration.sort(key=keyer) currentGeneration = nextGeneration print "total time spent this iteration:", time.time() - moo yield currentGeneration[lastEl]
def run(self, elite = 0.05, crossoverChance = 0.8, slotMutationChance = 0.5, typeMutationChance = 0.5): #Use a copy of the original for all our calcs. We don't want to damage it fit = copy.deepcopy(self.original) fit.unfill() #First of all, lets check the number of slots we got to play with chromLength = -1 slotAmounts = {} for type in Slot.getTypes(): slot = Slot.getValue(type) amount = fit.getSlotsFree(slot) if amount > 0: slotAmounts[slot] = amount chromLength += amount if not slotAmounts: #Nothing to do, joy return slotModules = {} metaModules = {} for slotType in slotAmounts: slotModules[slotType] = modules = [] for module in self.modules: #Store the variations of each base for ease and speed metaParent = self.__getMetaParent(module.item) metaList = metaModules.get(metaParent) if metaList is None: metaList = metaModules[metaParent] = [] metaList.append(module) #Sort stuff by slotType for ease and speed slot = module.slot if slot in slotModules: slotModules[slot].append(module) for slotType, modules in slotModules.iteritems(): if len(modules) == 0: chromLength -= slotAmounts[slotType] del slotAmounts[slotType] #Now, we need an initial set, first thing to do is decide how big that set will be setSize = 10 #Grab some variables locally for performance improvements rchoice = random.choice rrandom = random.random rrandint = random.randint bbisect = bisect.bisect ccopy = copy.copy #Get our list for storage of our chromosomes chromosomes = [] # Helpers weigher = lambda chromosome: (self.fitness(fit, chromosome), chromosome) keyer = lambda info: info[0] eliteCutout = int(math.floor(setSize * (1 - elite))) lastEl = setSize - 1 #Generate our initial set entirely randomly #Subtelies to take in mind: # * modules of the same slotType are kept together for easy cross-overing state = self.state for _ in xrange(setSize): chrom = [] for type, amount in slotAmounts.iteritems(): for _ in xrange(amount): chrom.append(rchoice(slotModules[type])) chromosomes.append(weigher(chrom)) #Sort our initial set chromosomes.sort(key=keyer) currentGeneration = chromosomes #Yield the best result from our initial set, this is gonna be pretty bad yield currentGeneration[lastEl] #Setup's done, now we can actualy apply our genetic algorithm to optimize all this while True: moo = time.time() #First thing we do, we're gonna be elitair #Grab the top x%, we'll put em in the next generation nextGeneration = [] for i in xrange(lastEl, eliteCutout - 1, -1): nextGeneration.append(currentGeneration[i]) #Figure out our ratios to do our roulette wheel fitnessList = map(keyer, currentGeneration) totalFitness = float(sum(fitnessList)) curr = 0 ratios = [] for fitness in fitnessList: curr += fitness ratios.append(curr / (totalFitness or 1)) t = 0 #Do our pairing for _ in xrange(0, eliteCutout): # Crossover chance mother = currentGeneration[bbisect(ratios, rrandom())][1] father = currentGeneration[bbisect(ratios, rrandom())][1] if rrandom() <= crossoverChance: crosspoint = rrandint(0, chromLength) luke = mother[:crosspoint] + father[crosspoint:] else: luke = father #Chance for slot mutation if rrandom() <= slotMutationChance: target = rrandint(0, chromLength) mod = luke[target] luke[target] = rchoice(slotModules[mod.slot]) if rrandom() <= typeMutationChance: #Mutation of an item to another one of the same type target = rrandint(0, chromLength) mod = luke[target] vars = metaModules[self.__getMetaParent(mod.item)] luke[target] = rchoice(vars) tt = time.time() nextGeneration.append(weigher(luke)) t += time.time() - tt print "time spent weighing: ", t nextGeneration.sort(key=keyer) currentGeneration = nextGeneration print "total time spent this iteration:", time.time() - moo yield currentGeneration[lastEl]
def MakeSnapshot(self, maxColumns = 1337): if self.FVsnapshot: del self.FVsnapshot tbmp = wx.EmptyBitmap(16,16) tdc = wx.MemoryDC() tdc.SelectObject(tbmp) font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) tdc.SetFont(font) columnsWidths = [] for i in xrange(len(self.DEFAULT_COLS)): columnsWidths.append(0) sFit = service.Fit.getInstance() try: fit = sFit.getFit(self.activeFitID) except: return if fit is None: return slotMap = {} for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 padding = 2 isize = 16 headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2 maxWidth = 0 maxRowHeight = isize rows = 0 for id,st in enumerate(self.mods): for i, col in enumerate(self.activeColumns): if i>maxColumns: break name = col.getText(st) if not isinstance(name, basestring): name = "" nx,ny = tdc.GetTextExtent(name) imgId = col.getImageId(st) cw = 0 if imgId != -1: cw += isize + padding if name != "": cw += nx + 4*padding if imgId == -1 and name == "": cw += isize +padding maxRowHeight = max(ny, maxRowHeight) columnsWidths[i] = max(columnsWidths[i], cw) rows += 1 render = wx.RendererNative.Get() #Fix column widths (use biggest between header or items) for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, basestring): name = "" opts = wx.HeaderButtonParams() if name != "": opts.m_labelText = name if imgId != -1: opts.m_labelBitmap = wx.EmptyBitmap(isize,isize) width = render.DrawHeaderButton(self, tdc, (0, 0, 16, 16), sortArrow = wx.HDR_SORT_ICON_NONE, params = opts) columnsWidths[i] = max(columnsWidths[i], width) tdc.SelectObject(wx.NullBitmap) maxWidth = padding * 2 for i in xrange(len(self.DEFAULT_COLS)): if i > maxColumns: break maxWidth += columnsWidths[i] mdc = wx.MemoryDC() mbmp = wx.EmptyBitmap(maxWidth, (maxRowHeight) * rows + padding*4 + headerSize) mdc.SelectObject(mbmp) mdc.SetBackground(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))) mdc.Clear() mdc.SetFont(font) mdc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)) cx = padding for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, basestring): name = "" opts = wx.HeaderButtonParams() opts.m_labelAlignment = wx.ALIGN_LEFT if name != "": opts.m_labelText = name if imgId != -1: bmp = col.bitmap opts.m_labelBitmap = bmp width = render.DrawHeaderButton (self, mdc, (cx, padding, columnsWidths[i], headerSize), wx.CONTROL_CURRENT, sortArrow = wx.HDR_SORT_ICON_NONE, params = opts) cx += columnsWidths[i] brush = wx.Brush(wx.Colour(224, 51, 51)) pen = wx.Pen(wx.Colour(224, 51, 51)) mdc.SetPen(pen) mdc.SetBrush(brush) cy = padding*2 + headerSize for id,st in enumerate(self.mods): cx = padding if slotMap[st.slot]: mdc.DrawRectangle(cx,cy,maxWidth - cx,maxRowHeight) for i, col in enumerate(self.activeColumns): if i>maxColumns: break name = col.getText(st) if not isinstance(name, basestring): name = "" imgId = col.getImageId(st) tcx = cx if imgId != -1: self.imageList.Draw(imgId,mdc,cx,cy,wx.IMAGELIST_DRAW_TRANSPARENT,False) tcx += isize + padding if name != "": nx,ny = mdc.GetTextExtent(name) rect = wx.Rect() rect.top = cy rect.left = cx + 2*padding rect.width = nx rect.height = maxRowHeight + padding mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL) tcx += nx + padding cx += columnsWidths[i] cy += maxRowHeight mdc.SelectObject(wx.NullBitmap) self.FVsnapshot = mbmp
def exportXml(cls, callback=None, *fits): doc = xml.dom.minidom.Document() fittings = doc.createElement("fittings") doc.appendChild(fittings) sFit = service.Fit.getInstance() for i, fit in enumerate(fits): try: fitting = doc.createElement("fitting") fitting.setAttribute("name", fit.name) fittings.appendChild(fitting) description = doc.createElement("description") description.setAttribute("value", "") fitting.appendChild(description) shipType = doc.createElement("shipType") shipType.setAttribute("value", fit.ship.item.name) fitting.appendChild(shipType) charges = {} slotNum = {} for module in fit.modules: if module.isEmpty: continue slot = module.slot if slot == Slot.SUBSYSTEM: # Order of subsystem matters based on this attr. See GH issue #130 slotId = module.getModifiedItemAttr("subSystemSlot") - 125 else: if not slot in slotNum: slotNum[slot] = 0 slotId = slotNum[slot] slotNum[slot] += 1 hardware = doc.createElement("hardware") hardware.setAttribute("type", module.item.name) slotName = Slot.getName(slot).lower() slotName = slotName if slotName != "high" else "hi" hardware.setAttribute("slot", "%s slot %d" % (slotName, slotId)) fitting.appendChild(hardware) if module.charge and sFit.serviceFittingOptions["exportCharges"]: if not module.charge.name in charges: charges[module.charge.name] = 0 # `or 1` because some charges (ie scripts) are without qty charges[module.charge.name] += module.numCharges or 1 for drone in fit.drones: hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % drone.amount) hardware.setAttribute("slot", "drone bay") hardware.setAttribute("type", drone.item.name) fitting.appendChild(hardware) for cargo in fit.cargo: if not cargo.item.name in charges: charges[cargo.item.name] = 0 charges[cargo.item.name] += cargo.amount for name, qty in charges.items(): hardware = doc.createElement("hardware") hardware.setAttribute("qty", "%d" % qty) hardware.setAttribute("slot", "cargo") hardware.setAttribute("type", name) fitting.appendChild(hardware) except: print "Failed on fitID: %d"%fit.ID continue finally: if callback: wx.CallAfter(callback, i) return doc.toprettyxml()
def MakeSnapshot(self, maxColumns=1337): if self.FVsnapshot: del self.FVsnapshot tbmp = wx.EmptyBitmap(16, 16) tdc = wx.MemoryDC() tdc.SelectObject(tbmp) font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) tdc.SetFont(font) columnsWidths = [] for i in xrange(len(self.DEFAULT_COLS)): columnsWidths.append(0) sFit = service.Fit.getInstance() try: fit = sFit.getFit(self.activeFitID) except: return if fit is None: return slotMap = {} for slotType in Slot.getTypes(): slot = Slot.getValue(slotType) slotMap[slot] = fit.getSlotsFree(slot) < 0 padding = 2 isize = 16 headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2 maxWidth = 0 maxRowHeight = isize rows = 0 for id, st in enumerate(self.mods): for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.getText(st) if not isinstance(name, basestring): name = "" nx, ny = tdc.GetTextExtent(name) imgId = col.getImageId(st) cw = 0 if imgId != -1: cw += isize + padding if name != "": cw += nx + 4 * padding if imgId == -1 and name == "": cw += isize + padding maxRowHeight = max(ny, maxRowHeight) columnsWidths[i] = max(columnsWidths[i], cw) rows += 1 render = wx.RendererNative.Get() #Fix column widths (use biggest between header or items) for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, basestring): name = "" opts = wx.HeaderButtonParams() if name != "": opts.m_labelText = name if imgId != -1: opts.m_labelBitmap = wx.EmptyBitmap(isize, isize) width = render.DrawHeaderButton(self, tdc, (0, 0, 16, 16), sortArrow=wx.HDR_SORT_ICON_NONE, params=opts) columnsWidths[i] = max(columnsWidths[i], width) tdc.SelectObject(wx.NullBitmap) maxWidth = padding * 2 for i in xrange(len(self.DEFAULT_COLS)): if i > maxColumns: break maxWidth += columnsWidths[i] mdc = wx.MemoryDC() mbmp = wx.EmptyBitmap(maxWidth, (maxRowHeight) * rows + padding * 4 + headerSize) mdc.SelectObject(mbmp) mdc.SetBackground( wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))) mdc.Clear() mdc.SetFont(font) mdc.SetTextForeground( wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)) cx = padding for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, basestring): name = "" opts = wx.HeaderButtonParams() opts.m_labelAlignment = wx.ALIGN_LEFT if name != "": opts.m_labelText = name if imgId != -1: bmp = col.bitmap opts.m_labelBitmap = bmp width = render.DrawHeaderButton( self, mdc, (cx, padding, columnsWidths[i], headerSize), wx.CONTROL_CURRENT, sortArrow=wx.HDR_SORT_ICON_NONE, params=opts) cx += columnsWidths[i] brush = wx.Brush(wx.Colour(224, 51, 51)) pen = wx.Pen(wx.Colour(224, 51, 51)) mdc.SetPen(pen) mdc.SetBrush(brush) cy = padding * 2 + headerSize for id, st in enumerate(self.mods): cx = padding if slotMap[st.slot]: mdc.DrawRectangle(cx, cy, maxWidth - cx, maxRowHeight) for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.getText(st) if not isinstance(name, basestring): name = "" imgId = col.getImageId(st) tcx = cx if imgId != -1: self.imageList.Draw(imgId, mdc, cx, cy, wx.IMAGELIST_DRAW_TRANSPARENT, False) tcx += isize + padding if name != "": nx, ny = mdc.GetTextExtent(name) rect = wx.Rect() rect.top = cy rect.left = cx + 2 * padding rect.width = nx rect.height = maxRowHeight + padding mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL) tcx += nx + padding cx += columnsWidths[i] cy += maxRowHeight mdc.SelectObject(wx.NullBitmap) self.FVsnapshot = mbmp