def loadFile(self, filename): self._filename = filename with open(filename, "r") as f: lines = f.readlines() self._modulesNumber = int(lines[0]) temp = list( map( lambda x: list(filter(lambda a: a != '', x)), list( map(lambda x: x[:-1].split(" "), lines[1:self._modulesNumber + 1])))) temp = list(map(lambda x: list(map(lambda a: int(a), x)), temp)) self._weights = np.array(temp[:]) temp = list( map( lambda x: list(filter(lambda a: a != '', x)), list( map(lambda x: x[:-1].split(" "), lines[self._modulesNumber + 2:])))) temp = list(map(lambda x: list(map(lambda a: int(a), x)), temp)) self._distances = np.array(temp[:-1]) self.loadHashMap() self._perm = Permutation(modulesNumber=self._modulesNumber) self._perm.shuffle()
def __init__(self): self._weights = [] self._distances = [] self._perm = Permutation(0) self._modulesNumber = 0 self._hashMap = {} self._access = 0 self._filename = ""
def encodePermutation(self, perm): """ugh""" encode = Per(perm) cipherText = encode.encode(self.planeText) if (self.verbose == 1): print(cipherText) return (cipherText)
def decodePermutation(self, perm): """ugh""" decode = Per(perm) planeText = decode.decode(self.cipherText) if (self.verbose == 1): print(planeText) return (planeText)
class Taixxa: def __init__(self): self._weights = [] self._distances = [] self._perm = Permutation(0) self._modulesNumber = 0 self._hashMap = {} self._access = 0 self._filename = "" def loadFile(self, filename): self._filename = filename with open(filename, "r") as f: lines = f.readlines() self._modulesNumber = int(lines[0]) temp = list( map( lambda x: list(filter(lambda a: a != '', x)), list( map(lambda x: x[:-1].split(" "), lines[1:self._modulesNumber + 1])))) temp = list(map(lambda x: list(map(lambda a: int(a), x)), temp)) self._weights = np.array(temp[:]) temp = list( map( lambda x: list(filter(lambda a: a != '', x)), list( map(lambda x: x[:-1].split(" "), lines[self._modulesNumber + 2:])))) temp = list(map(lambda x: list(map(lambda a: int(a), x)), temp)) self._distances = np.array(temp[:-1]) self.loadHashMap() self._perm = Permutation(modulesNumber=self._modulesNumber) self._perm.shuffle() def addHash(self, hashed, cost): self._hashMap[hashed] = cost def getCost(self, hashed): self._access += 1 return self._hashMap[hashed] def saveHashMap(self): with open(self._filename + '.hash', 'wb') as f: pickle.dump(self._hashMap, f) def loadHashMap(self): try: with open(self._filename + '.hash', 'rb') as f: self._hashMap = pickle.load(f) except FileNotFoundError: print("file hash not yet created think about saving for next time")
def encode(self, S): enc = Perm(self.perm) st = enc.encode(S) new = "" num_rows = len(st) / len(self.perm) for i in range(len(self.perm)): for j in range(int(num_rows)): new += st[len(self.perm) * j + i] return new
def pickGenes(self, main, second, nbPermutations): size = len(main._perm) childGenes = [None] * size permCrossed = list() indexes = random.sample(range(0, size - 1), nbPermutations) for i in indexes: childGenes[i] = second[i] permCrossed.append((childGenes[i], main[i])) for i in range(size): if childGenes[i] is None: if main[i] in [e[0] for e in permCrossed]: for tup in permCrossed: if main[i] == tup[0] and tup[1] not in childGenes: childGenes[i] = tup[1] else: childGenes[i] = main[i] left = self.find_missing(childGenes, len(childGenes)) for gene in childGenes: if gene is None: childGenes[childGenes.index(gene)] = left[0] left.pop(0) return Permutation(size, childGenes)
def decode(self, S): dec = Perm(self.perm) st = "" num_rows = int(len(S) / len(self.perm)) for i in range((num_rows)): for j in range(len(self.perm)): st += S[num_rows * j + i] new = dec.decode(st) return(new)
class TabuSearch: def __init__(self,taixxa): self._perm = Permutation(taixxa._modulesNumber) self._data = taixxa def solve(self, maxIter, lenList): self._perm.shuffle() fitness = [] xmin = self._perm fmin = self._perm.computeCost(self._data) T = [] for i in range(maxIter): Txi = list(map(lambda x: self._perm.permute(x[0],x[1]), T)) C = [x for x in self._perm.getNeighbours() if x not in Txi] fC = list(map(lambda x: x.computeCost(self._data), C)) xnext = C[fC.index(min(fC))] variationF = xnext.computeCost(self._data) - self._perm.computeCost(self._data) if variationF >= 0: if T.count(xnext.reversePerm(self._perm)) == 0: T.append(xnext.reversePerm(self._perm)) if len(T) > lenList: T.pop(0) fnext = xnext.computeCost(self._data) if fnext < fmin: xmin = xnext fmin = fnext self._perm = xnext fitness.append(self._perm.computeCost(self._data)) return xmin, fitness
def symmetric(cls, n: int) -> Group_Type: """ Creates the symmetric group of the all permutations of n elements :param n: :return: """ element_list = [p for p in Permutation.generator(n)] return Group.from_definition(operation=Permutation.__add__, element_set=element_list, name='S_{}'.format(n))
def semi_direct_product(cls, group_g: Group_Type, group_h: Group_Type, phi: Permutation_Type = Permutation()) -> Group_Type: """ :param group_g: :param group_h: :param phi: :return: """ gl, hl = group_g.order, group_h.order if len(phi) > gl: raise ValueError('Invalid phi permutation on group G') logger.debug('G Element set = {}'.format(list(group_g.element_set))) logger.debug('H Element set = {}'.format(list(group_h.element_set))) logger.debug('phi = {}'.format(phi)) logger.debug('|G x. H| = |G|x.|H| = {} x. {} = {}'.format(gl, hl, gl * hl)) def product_element(gx: int, hx: int) -> int: return gx + hx * gl def product_element_pair(prod_element: int): return prod_element % gl, prod_element // gl def semi_direct_multiply(el_x: int, el_y: int) -> int: x1, x2 = product_element_pair(el_x) y1, y2 = product_element_pair(el_y) logger.debug('{}*{}=({},{})*({},{})'.format(el_x, el_y, x1, y1, x2, y2)) logger.debug('\t=({}*phi[{}], {}*{})'.format(x1, y1, x2, y2)) logger.debug('\t=({}*{}, {}*{})'.format(x1, phi[y1], x2, y2)) z1 = group_g.multiply(x1, phi[y1]) z2 = group_h.multiply(x2, y2) n = product_element(z1, z2) logger.debug('\t=({},{})={}'.format(z1, z2, n)) return n prod_lables = [] for prod_n in range(gl * hl): logger.debug('Getting label of {}'.format(prod_n)) x, y = product_element_pair(prod_n) logger.debug('{}=>({},{})'.format(prod_n, x, y)) x_label = group_g.labels[x] logger.debug('x = {} => {}'.format(x, x_label)) y_label = group_h.labels[y] logger.debug('y = {} => {}'.format(y, y_label)) logger.debug('Label of {} => ({},{})\n'.format(prod_n, x_label, y_label)) prod_lables.append('({},{})'.format(x_label, y_label)) def prod_element_label(n: int) -> str: return prod_lables[n] return Group.from_definition(semi_direct_multiply, list(range(gl * hl)), prod_element_label)
def is_homomorphic(self, group_h: Group_Type) -> Tuple[bool, str]: if group_h.order < self.order: return group_h.is_homomorphic(self) elif group_h.order % self.order == 0: # logger.debug('Determining if g and h is a homomorphism') for phi in Permutation.generator(group_h.order): print('phi = {}'.format(phi)) for a, b in itr.product(self.element_set, repeat=2): if phi[self.multiply(a, b)] != group_h.multiply(phi[a], phi[b]): break else: return True, str(phi) return False, '' else: return False, ''
def automorphism(self) -> Group_Type: """ Group automorphism is the homomorphism of the Group to it self. As in all the rewiring of the group that keep the result multiplication table consistent. :return: automorphism Group """ if self._automorphism is None: automorphism_elements = list() # logger.debug('Getting automorphism of group G') for phi in Permutation.generator(self.order): for a, b in itr.product(self.element_set, repeat=2): if self.multiply(phi[a], phi[b]) != phi[self.multiply(a, b)]: break else: automorphism_elements.append(phi) logger.debug('Added {}'.format(phi)) logger.debug('AutomorphismGroup elements are \n{}'.format([str(i) for i in automorphism_elements])) return Group.from_definition(Permutation.__add__, automorphism_elements) else: return self._automorphism
def __init__(self, n: int, subgroup=False, elements=list()): self.n = n # the size of the symmetric group self.elements = set([]) # the elements of the group if subgroup: for elmnt in elements: self.elements.add(elmnt) p = choice(list(self.elements)) self.id = ~p * p return # Generate the permutations perms = list(permutations([i + 1 for i in range(n)])) for perm in perms: d = {} for i in range(n): d[i + 1] = perm[i] self.elements.add(Permutation(d)) p = choice(list(self.elements)) self.id = ~p * p
class SimulatedAnnealing: def __init__(self,taixxa): self._perm = Permutation(taixxa._modulesNumber) self._data = taixxa def solve(self, t0, mu, n1, n2, f): self._perm.shuffle() fitness = [] i = 0 xmin = self._perm xnext = 0 temp = t0 temps =[t0] fmin = self._perm.computeCost(self._data) fitness.append(fmin) for k in range(n1): neighbours = self._perm.getNeighbours() # print(neighbours) for l in range(1, n2): y = rd.choice(neighbours) variationF = y.computeCost(self._data) - self._perm.computeCost(self._data) if variationF <= 0: xnext = y fnext = xnext.computeCost(self._data) if fnext < fmin: xmin = xnext fmin = fnext else: p = rd.uniform(0, 1) if p <= np.exp(-variationF / temp): xnext = y else: xnext = self._perm self._perm = xnext fitness.append(self._perm.computeCost(self._data)) i = i+1 temp = f(t0,i) temps.append(temp) return copy.deepcopy(xmin), np.array(fitness), np.array(temps)
def __init__(self, constraints: Constraints) -> None: self.constraints: Constraints = constraints self.permutation: Permutation = Permutation(constraints)
class methods: def __init__(self, fps, clockObject, surface, font, bars, windowsize): self.fps = fps self.clock = clockObject self.surface = surface self.font = font self.bars = bars self.windowsize = windowsize def get_array(self, length, mode=0): arr = list(range(length)) if not mode: random.shuffle(arr) elif mode == 2: arr = arr[::-1] elif mode == 3: for i in range(length - 1): if random.randint(0, 10) < 8: tmp = random.randint(4, 15) try: arr[i], arr[i + tmp] = arr[i + tmp], arr[i] except: pass return arr def setup(self, length, mode=0): self.array = self.get_array(length, mode) self.display = Display(self.windowsize[0] / length, self.windowsize, self.surface, self.font) self.accesses = 0 self.comparisons = 0 setattr(self.display, "bars", self.bars) bubble = lambda self: Bubble(self.array, self.display, self.clock, self.fps ).main() quicksort = lambda self: Quicksort(self.array, self.display, self.clock, self.fps).main() selection = lambda self: Selection(self.array, self.display, self.clock, self.fps).main() cocktail = lambda self: Cocktail(self.array, self.display, self.clock, self .fps).main() bogo = lambda self: Bogo(self.array, self.display, self.clock, self.fps ).main() oddeven = lambda self: Oddeven(self.array, self.display, self.clock, self. fps).main() shell = lambda self: Shell(self.array, self.display, self.clock, self.fps ).main() comb = lambda self: Comb(self.array, self.display, self.clock, self.fps ).main() insertion = lambda self: Insertion(self.array, self.display, self.clock, self.fps).main() mergetd = lambda self: MergeTD(self.array, self.display, self.clock, self. fps).main() radixlsd = lambda self: RadixLSD(self.array, self.display, self.clock, self .fps).main() counting = lambda self: Counting(self.array, self.display, self.clock, self .fps).main() cycle = lambda self: Cycle(self.array, self.display, self.clock, self.fps ).main() heap = lambda self: Heap(self.array, self.display, self.clock, self.fps ).main() circle = lambda self: Circle(self.array, self.display, self.clock, self.fps ).main() gnome = lambda self: Gnome(self.array, self.display, self.clock, self.fps ).main() binaryinsertion = lambda self: BinaryInsertion( self.array, self.display, self.clock, self.fps).main() pancake = lambda self: Pancake(self.array, self.display, self.clock, self. fps).main() permutation = lambda self: Permutation(self.array, self.display, self. clock, self.fps).main() strand = lambda self: Strand(self.array, self.display, self.clock, self.fps ).main() bucket = lambda self: Bucket(self.array, self.display, self.clock, self.fps ).main() minmax = lambda self: MinMax(self.array, self.display, self.clock, self.fps ).main() mergebu = lambda self: MergeBU(self.array, self.display, self.clock, self. fps).main() bitonic = lambda self: Bitonic(self.array, self.display, self.clock, self. fps).main() stooge = lambda self: Stooge(self.array, self.display, self.clock, self.fps ).main() smooth = lambda self: Smooth(self.array, self.display, self.clock, self.fps ).main() quick3 = lambda self: Quick3(self.array, self.display, self.clock, self.fps ).main()
2: 3, 3: 1 }, { 2: 3, 3: 4, 4: 2 }, ] # Generate subgroup old_perms = [] perms = [] for m in maps: try: perms.append(Permutation(m)) except IllegalActionException: print("Illegal Action: ", str(m)) G = SymmetricGroup.generate(*perms) print(G) # Results show that G is the alternating group A_4 def display_cosets(cosets): for coset in cosets: print(str(coset)) # Calculate H1=<(123)> H1 = SymmetricGroup.generate(perms[0])
from Permutation import Permutation from SymmetricGroup import SymmetricGroup from random import choice generators = [ Permutation({ 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 1 }), Permutation({ 1: 2, 2: 1, 3: 6, 4: 5, 5: 4, 6: 3 }) ] # Generates the group G=<(123456),(12)(36)(45)> G = SymmetricGroup.generate(*generators) print(G) # Generate the hom-set Hom([6],[2]), with functions represented as hash maps funcs = [] for a in range(2): for b in range(2):
def __init__(self,taixxa): self._perm = Permutation(taixxa._modulesNumber) self._data = taixxa