def collipicanimal(LISTE, o, listetab, screen, bloc): if bloc.type == 6 or bloc.type == 7 or bloc.type == 3 or bloc.type == 9: LISTE.update() Tableau.initPerso(listetab[numtab], o, screen) screen.blit(listetab[numtab].background, (0, 0)) LISTE.draw(screen) screen.blit(o.image, o.pos)
class GenRegionVoronoi(GenRegion): def __init__(self, largeur, hauteur, nb=10): GenRegion.__init__(self, nb) self.tab = Tableau(largeur, hauteur) for x, y in self.tab.iterC(): self.tab[x, y] = Case(x, y) self.tab[x, y].value = -1 self.init = [] self.liste = [elt for elt in self.tab.iterB()] for i in range(nb): case = self.tab[self.liste[randrange(len(self.liste))]] case.value = i self.init.append(case) self.regions.append(Region(nb, interieur=[case])) for case in self.tab.values(): distance = self.tab.X * self.tab.Y id = -1 for init in self.init: if case.Distance(init) < distance: distance = case.Distance(init) id = init.value case.value = id voisins = [ self.tab[elt] for elt in case.Voisins() if elt in self.tab and self.tab[elt].value != -1 and self.tab[elt].value != id ] if len(voisins): self.regions[id].addFro(case) for elt in voisins: if elt in self.regions[id].interieur: self.regions[id].interieur.remove(elt) self.regions[id].addFro(elt) else: self.regions[id].addInt(case)
def e_hat(tab, star=0): """ The Young projection operator, an idempotent in the rational group algebra. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e_hat sage: e_hat([[1,2,3]]) 1/6*[1, 2, 3] + 1/6*[1, 3, 2] + 1/6*[2, 1, 3] + 1/6*[2, 3, 1] + 1/6*[3, 1, 2] + 1/6*[3, 2, 1] sage: e_hat([[1],[2]]) 1/2*[1, 2] - 1/2*[2, 1] There are differing conventions for the order of the symmetrizers and antisymmetrizers. This example illustrates our conventions:: sage: e_hat([[1,2],[3]]) 1/3*[1, 2, 3] + 1/3*[2, 1, 3] - 1/3*[3, 1, 2] - 1/3*[3, 2, 1] """ t = Tableau(tab) if star: t = t.restrict(t.size()-star) if t in ehat_cache: res = ehat_cache[t] else: res = (1/kappa(t.shape()))*e(t) return res
def prepare_auxiliar_matrix(tableau, bases): logging.debug("Preparing auxiliar matrix for operations") # Make a copy of matrix to operate over without changing the original values matrix_aux = copy.copy(tableau.matrix_tableau) # On the auxiliar matrix, the costs of initial columns are zero matrix_aux[0, :] *= 0 # Creating the aditional columuns aditional_cols = Tools.identity(tableau.restrictions) # Additional values on costs vector aditional_costs = [1] * tableau.restrictions extension_matrix = [] extension_matrix = np.insert(aditional_cols, 0, aditional_costs, 0) for col_index in range(len(extension_matrix[0, :])): matrix_aux = np.insert( matrix_aux, len(tableau.matrix_tableau[0, :]) - 1 + col_index, extension_matrix[:, col_index], 1) tmp_row = 1 for index in range( len(matrix_aux[0, :]) - len(extension_matrix[0, :]) - 1, len(matrix_aux[0, :]) - 1): Simplex.define_bases(bases, tmp_row, index) tmp_row += 1 logging.debug("The auxiliar matrix will be: ") Tableau.print_tableau(matrix_aux) return matrix_aux, bases
def pivotate(pivotal_row, cost_index, matrix_tableau, bases): value = Fraction(matrix_tableau[pivotal_row][cost_index]) logging.debug("Dividing pivotal row from A[{}][:] by {}".format( pivotal_row, value)) for n in range(len(matrix_tableau[pivotal_row, :])): if matrix_tableau[pivotal_row][n] != 0: matrix_tableau[pivotal_row][n] = Fraction( matrix_tableau[pivotal_row][n]) / Fraction(value) Tableau.print_tableau(matrix_tableau) logging.debug("Pivotating matrix over value {} on A[{}][{}]".format( value, pivotal_row, cost_index)) for row in range(len(matrix_tableau[:])): if row != pivotal_row: v = (Fraction(matrix_tableau[row, cost_index]) / Fraction(matrix_tableau[pivotal_row, cost_index])) * -1 logging.debug("Adding {} on row {} of tableau".format(v, row)) for column in range(len(matrix_tableau[0, :])): matrix_tableau[row][column] = Fraction( matrix_tableau[row][column]) + Fraction( (matrix_tableau[pivotal_row][column]) * v) Simplex.define_bases(bases, pivotal_row, cost_index) return matrix_tableau, bases
def construct(self): for x in range(4): self._freecells.append(FreeCell()) self._homecells.append(HomePile()) self._tableaux.append(Tableau()) for x in range(4): self._tableaux.append(Tableau())
def e_hat(tab, star=0): """ The Young projection operator corresponding to the Young tableau ``tab`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is an idempotent in the rational group algebra. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e_hat sage: e_hat([[1,2,3]]) 1/6*[1, 2, 3] + 1/6*[1, 3, 2] + 1/6*[2, 1, 3] + 1/6*[2, 3, 1] + 1/6*[3, 1, 2] + 1/6*[3, 2, 1] sage: e_hat([[1],[2]]) 1/2*[1, 2] - 1/2*[2, 1] There are differing conventions for the order of the symmetrizers and antisymmetrizers. This example illustrates our conventions:: sage: e_hat([[1,2],[3]]) 1/3*[1, 2, 3] + 1/3*[2, 1, 3] - 1/3*[3, 1, 2] - 1/3*[3, 2, 1] """ t = Tableau(tab) if star: t = t.restrict(t.size() - star) if t in ehat_cache: res = ehat_cache[t] else: res = (1 / kappa(t.shape())) * e(t) return res
def check_exist(self, formula, init_states): tableau = Tableau(formula, self._atomic_str) prod = tableau.product(self._model) # return False return prod.has_fair_path(tableau.initial_states & init_states, tableau.fairness_constraints)
def epsilon_ik(itab, ktab, star=0): """ EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import epsilon_ik sage: epsilon_ik([[1,2],[3]], [[1,3],[2]]) 1/4*[1, 3, 2] - 1/4*[2, 3, 1] + 1/4*[3, 1, 2] - 1/4*[3, 2, 1] sage: epsilon_ik([[1,2],[3]], [[1,3],[2]], star=1) Traceback (most recent call last): ... ValueError: the two tableaux must be of the same shape """ it = Tableau(itab) kt = Tableau(ktab) if star: it = it.restrict(it.size() - star) kt = kt.restrict(kt.size() - star) if it.shape() != kt.shape(): raise ValueError, "the two tableaux must be of the same shape" mult = permutation_options['mult'] permutation_options['mult'] = 'l2r' if kt == it: res = epsilon(itab) elif (it, kt) in epsilon_ik_cache: res = epsilon_ik_cache[(it,kt)] else: epsilon_ik_cache[(it,kt)] = epsilon(it, star+1)*e_ik(it,kt,star)*epsilon(kt, star+1) * (1/kappa(it.shape())) res = epsilon_ik_cache[(it,kt)] permutation_options['mult'] = mult return res
def e_hat(tab, star=0): """ The Young projection operator corresponding to the Young tableau ``tab`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is an idempotent in the rational group algebra. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e_hat sage: e_hat([[1,2,3]]) 1/6*[1, 2, 3] + 1/6*[1, 3, 2] + 1/6*[2, 1, 3] + 1/6*[2, 3, 1] + 1/6*[3, 1, 2] + 1/6*[3, 2, 1] sage: e_hat([[1],[2]]) 1/2*[1, 2] - 1/2*[2, 1] There are differing conventions for the order of the symmetrizers and antisymmetrizers. This example illustrates our conventions:: sage: e_hat([[1,2],[3]]) 1/3*[1, 2, 3] + 1/3*[2, 1, 3] - 1/3*[3, 1, 2] - 1/3*[3, 2, 1] """ t = Tableau(tab) if star: t = t.restrict(t.size()-star) if t in ehat_cache: res = ehat_cache[t] else: res = (1/kappa(t.shape()))*e(t) return res
def e_ik(itab, ktab, star=0): """ EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e_ik sage: e_ik([[1,2,3]], [[1,2,3]]) [1, 2, 3] + [1, 3, 2] + [2, 1, 3] + [2, 3, 1] + [3, 1, 2] + [3, 2, 1] sage: e_ik([[1,2,3]], [[1,2,3]], star=1) [1, 2] + [2, 1] """ it = Tableau(itab) kt = Tableau(ktab) if star: it = it.restrict(it.size() - star) kt = kt.restrict(kt.size() - star) if it.shape() != kt.shape(): raise ValueError, "the two tableaux must be of the same shape" mult = permutation_options['mult'] permutation_options['mult'] = 'l2r' if kt == it: res = e(it) elif (it, kt) in e_ik_cache: res = e_ik_cache[(it,kt)] else: pi = pi_ik(it,kt) e_ik_cache[(it,kt)] = e(it)*pi res = e_ik_cache[(it,kt)] permutation_options['mult'] = mult return res
def b(tableau, star=0): r""" The column projection operator corresponding to the Young tableau ``tableau`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is the signed sum (in the group algebra of the relevant symmetric group over `\QQ`) of all the permutations which preserve the column of ``tableau`` (where the signs are the usual signs of the permutations). It is called `b_{\text{tableau}}` in [EtRT]_, Section 4.2. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import b sage: b([[1,2]]) [1, 2] sage: b([[1],[2]]) [1, 2] - [2, 1] sage: b([]) [] sage: b([[1, 2, 4], [5, 3]]) [1, 2, 3, 4, 5] - [1, 3, 2, 4, 5] - [5, 2, 3, 4, 1] + [5, 3, 2, 4, 1] With the `l2r` setting for multiplication, the unnormalized Young symmetrizer ``e(tableau)`` should be the product ``b(tableau) * a(tableau)`` for every ``tableau``. Let us check this on the standard tableaux of size 5:: sage: from sage.combinat.symmetric_group_algebra import a, b, e sage: all( e(t) == b(t) * a(t) for t in StandardTableaux(5) ) True """ t = Tableau(tableau) if star: t = t.restrict(t.size()-star) cs = t.column_stabilizer().list() n = t.size() # This all should be over ZZ, not over QQ, but symmetric group # algebras don't seem to preserve coercion (the one over ZZ # doesn't coerce into the one over QQ even for the same n), # and the QQ version of this method is more important, so let # me stay with QQ. # TODO: Fix this. sgalg = SymmetricGroupAlgebra(QQ, n) one = QQ.one() P = permutation.Permutation # Ugly hack for the case of an empty tableau, due to the # annoyance of Permutation(Tableau([]).row_stabilizer()[0]) # being [1] rather than [] (which seems to have its origins in # permutation group code). # TODO: Fix this. if len(tableau) == 0: return sgalg.one() cd = dict((P(v), v.sign()*one) for v in cs) return sgalg._from_dict(cd)
def __init__(self, strategy, visual=False, screen=None): S = getattr(strategies, strategy) strategy = S() self.tableau = Tableau() self.redeals = 2 self.strategy = strategy self.visual = visual self.screen = screen
def a(tableau, star=0): r""" The row projection operator corresponding to the Young tableau ``tableau`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is the sum (in the group algebra of the relevant symmetric group over `\QQ`) of all the permutations which preserve the rows of ``tableau``. It is called `a_{\text{tableau}}` in [EtRT]_, Section 4.2. REFERENCES: .. [EtRT] Pavel Etingof, Oleg Golberg, Sebastian Hensel, Tiankai Liu, Alex Schwendner, Dmitry Vaintrob, Elena Yudovina, "Introduction to representation theory", :arXiv:`0901.0827v5`. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import a sage: a([[1,2]]) [1, 2] + [2, 1] sage: a([[1],[2]]) [1, 2] sage: a([]) [] sage: a([[1, 5], [2, 3], [4]]) [1, 2, 3, 4, 5] + [1, 3, 2, 4, 5] + [5, 2, 3, 4, 1] + [5, 3, 2, 4, 1] """ t = Tableau(tableau) if star: t = t.restrict(t.size()-star) rs = t.row_stabilizer().list() n = t.size() # This all should be over ZZ, not over QQ, but symmetric group # algebras don't seem to preserve coercion (the one over ZZ # doesn't coerce into the one over QQ even for the same n), # and the QQ version of this method is more important, so let # me stay with QQ. # TODO: Fix this. sgalg = SymmetricGroupAlgebra(QQ, n) one = QQ.one() P = permutation.Permutation # Ugly hack for the case of an empty tableau, due to the # annoyance of Permutation(Tableau([]).row_stabilizer()[0]) # being [1] rather than [] (which seems to have its origins in # permutation group code). # TODO: Fix this. if len(tableau) == 0: return sgalg.one() rd = dict((P(h), one) for h in rs) return sgalg._from_dict(rd)
def setUp(self): # variables pre_var = [(0, True), (0, False), (0, False), (0, True), (0, True)] self.vars = [Variable(*v) for v in pre_var] # row lines pre_row = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, -1, 0, 0], [2, -1, 0, -1, 0], [-1, 2, 0, 0, -1]] self.rows = [RowLine(r) for r in pre_row] # tableau self.table = Tableau(self.vars, self.rows)
class Seed: def __init__(self,largeur,hauteur,noeud = {"type" : "plaque"},minValue = 0,maxValue = 255, value = 0): self.function = {"rand" : self.rand, "degrade" : self.degrade, "plaque" : self.plaque} self.maxValue = maxValue self.minValue = minValue self.X = largeur self.Y = hauteur self.tab = Tableau(self.X,self.Y) if "args" in noeud: self.function[noeud["type"]](noeud["args"]) else : self.function[noeud["type"]]() def degrade(self,args = {"direction":"Y","evolution":"increase"}): if args["direction"] == "Y": c = self.Y current = lambda x,y : y else: c = self.X current = lambda x,y : x - self.ligne(y) if args["evolution"] == "increase": fun = lambda x,y : self.maxValue * current(x,y) // c elif args["evolution"] == "decrease": fun = lambda x,y : self.maxValue * (c - (1 + current(x,y))) // c elif args["evolution"] == "center": fun = lambda x,y : min(self.maxValue * current(x,y) // c,self.maxValue * (c - (1 + current(x,y))) //c) * 2 elif args["evolution"] == "border": fun = lambda x,y : max(self.maxValue * current(x,y) // c,self.maxValue * (c - (1 + current(x,y))) //c) - ( self.maxValue // 2) * 2 for(x,y) in self.tab.iterC(): self.tab[x,y] = Case(x,y) self.tab[x,y].value = fun(x,y) def rand(self,args = {}): for(x,y) in self.tab.iterC(): self.tab[x,y] = Case(x,y) self.tab[x,y].value = randint(self.minValue,self.maxValue) def plaque(self,args = {"nombre" : 5, "plaques" : 8}): for x,y in self.tab.iterC(): self.tab[x,y] = Case(x,y) self.tab[x,y].value = 0 liste = [ elt for elt in self.tab.iterB(1) ] nombre = args["nombre"] plaque = args["plaques"] plaques = GenRegionPasse(self.tab,None,plaque,5) plaques.finalisation() liste_plaque = [ (elt.interieur,elt.frontiere) for elt in plaques.regions] for i in range(nombre): li,lf = liste_plaque[randrange(len(liste_plaque))] liste_plaque.remove((li,lf)) for elt in [ (elt.u,elt.v) for elt in li if (elt.u,elt.v) in liste]: #self.tab[elt].value = randint((self.minValue + self.maxValue) * 3 // 4 , self.maxValue ) self.tab[elt].value = int(((plaques.iteration - self.tab[elt].nb + 1) / plaques.iteration)* self.maxValue)
def define_initial_bases(tableau): logging.debug( '\n =================================== \n = DEFINING INITIAL BASES = \n ===================================' ) # If B vector has all values greater than zero, because the entry format is always <=, # the base will be the matrix formed by gap_vars. is_b_positive = True if any(n < 0 for n in tableau.matrix_tableau.T[len(tableau.matrix_tableau.T) - 1]): is_b_positive = False bases = [] alternative_certificate = [] if is_b_positive: logging.debug("B vector has only positive values") count = 1 for x in range( int((len(tableau.matrix_tableau.T) - 1) / 3) + int( (len(tableau.matrix_tableau.T) - 1) / 3), len(tableau.matrix_tableau.T) - 1): t = (count, x) bases.append(t) count += 1 logging.debug("Initial bases: {}".format(bases)) else: logging.debug("B vector has at least one negative value") logging.debug( "Corverting b entry to positive by multiplying row by -1") while any(n < 0 for n in Simplex.get_tableau_b_vector_whithout_optm( tableau.matrix_tableau)): for entry_index, b_entry in enumerate( Simplex.get_tableau_b_vector_whithout_optm( tableau.matrix_tableau)): if b_entry < 0: tableau.matrix_tableau[entry_index, :] *= -1 Tableau.print_tableau(tableau.matrix_tableau) matrix_aux, bases = Simplex.prepare_auxiliar_matrix(tableau, bases) alternative_certificate = Simplex.run_auxiliar_matrix_operations( matrix_aux, bases, tableau.restrictions) return bases, alternative_certificate
def run_auxiliar_matrix_operations(matrix_aux, bases, restrictions): logging.debug("Running auxiliar matrix operations") max_iterations = len(bases) - 1 for i, base in enumerate(bases): Simplex.pivotate(base[0], base[1], matrix_aux, bases) if i >= max_iterations: break logging.debug("All operations over auxiliar are done!") Tableau.print_tableau(matrix_aux) return Simplex.get_certificate(matrix_aux)
def get_exists_nodes(self, formula): tableau = Tableau(formula, self._atomic_str) prod = tableau.product(self._model) print('#relations', prod.count_relations()) print( '#reachable states', prod.count_reachable_states(tableau.initial_states & self._model.atomic)) states = prod.find_fair_nodes(tableau.initial_states, tableau.fairness_constraints) states = bdd_utils.only_consider_prims(states, self._model.msb) bdd_utils.print_debug_bdd('states', states) return states
def creation_tableau_joueur(dimension: int, nom_joueur: str): """ Fonction servant a creer un objet Tableau et un objet Joueur et attribuer a Joueur le tableau PRE: - dimension = int - nom_joueur = str POST : - création objet plateau_joueur de classe Tableau(dimension) - creation d'un tableau dans l'objet plateau_joueur - creation d'un objet Joueur possedant un nom et un objet Tableau - retourne l'objet de classe Joueur """ plateau_joueur = Tableau(dimension) plateau_joueur.creation_tableau() return Joueur(nom_joueur, plateau_joueur)
def epsilon(tab, star=0): """ EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import epsilon sage: epsilon([[1,2]]) 1/2*[1, 2] + 1/2*[2, 1] sage: epsilon([[1],[2]]) 1/2*[1, 2] - 1/2*[2, 1] """ t = Tableau(tab) if star: t = t.restrict(t.size() - star) mult = permutation_options['mult'] permutation_options['mult'] = 'l2r' if t in epsilon_cache: res = epsilon_cache[t] else: if t.size() == 2: epsilon_cache[t] = e(t)*(1/kappa(t.shape())) res = epsilon_cache[t] elif t == Tableau([[1]]): epsilon_cache[t] = e(t) res = epsilon_cache[t] else: epsilon_cache[t] = epsilon(t, 1)*e(t)*epsilon(t,1)*( 1 / kappa(t.shape())) res = epsilon_cache[t] permutation_options['mult'] = mult return res
def run_game(): # Create deck, hand, tableau. deck = Deck() hand = Hand(deck) tableau = Tableau(tableau_limit) trade = Trade() game_end = False # Main game loop. while game_end is False: # Choose action. # phase = gf.choose_action() # Play phases. for phase in range(0, 5): gf.play_phase(phase, deck, hand, tableau, trade) # Check hand limit hand.hand_limit(deck) # Check for game end. game_end = gf.end_check(tableau, scoreboard) return scoreboard.get_vp_total(tableau)
def collipicanimal(LISTE, o, listetab, screen, bloc): if bloc.type == 6 or bloc.type == 7 or bloc.type == 3 or bloc.type == 9: o.score-=75 LISTE.update() Tableau.initPerso(listetab[numtab], o, screen) screen.blit(listetab[numtab].background , (0,0)) LISTE.draw(screen) screen.blit(o.image, o.pos) piece = pygame.image.load('image/piece.png') piece = pygame.transform.scale(piece, (20, 20)) smallText = pygame.font.Font("freesansbold.ttf",15) nbpiece = smallText.render((" x " + str(o.compteurpiece)),1,(210, 210, 210)) screen.blit(piece,(0,5)) screen.blit(nbpiece,(20,10)) scA = smallText.render(("Score:"+str(o.score)),1,(210, 210, 210)) screen.blit(scA,(870,35)) screen.blit(timer(horloge,o),(870,10))
class Game(object): def __init__(self, strategy, visual=False, screen=None): S = getattr(strategies, strategy) strategy = S() self.tableau = Tableau() self.redeals = 2 self.strategy = strategy self.visual = visual self.screen = screen def play(self): while True: while self.tableau.has_moves(): if self.visual and self.screen: self.screen.addstr(1,0,self.tableau.dump().encode("utf_8")) self.screen.refresh() self.strategy.apply_strategy(self.tableau) if self.visual and self.screen: self.screen.getch() if not self.tableau.is_complete() and self.redeals > 0: self.tableau.redeal() self.redeals -= 1 else: break def in_progress(self): return self.tableau.has_moves() def game_won(self): return self.tableau.is_complete()
class Game(object): def __init__(self, strategy, visual=False, screen=None): S = getattr(strategies, strategy) strategy = S() self.tableau = Tableau() self.redeals = 2 self.strategy = strategy self.visual = visual self.screen = screen def play(self): while True: while self.tableau.has_moves(): if self.visual and self.screen: self.screen.addstr(1, 0, self.tableau.dump().encode("utf_8")) self.screen.refresh() self.strategy.apply_strategy(self.tableau) if self.visual and self.screen: self.screen.getch() if not self.tableau.is_complete() and self.redeals > 0: self.tableau.redeal() self.redeals -= 1 else: break def in_progress(self): return self.tableau.has_moves() def game_won(self): return self.tableau.is_complete()
def pi_ik(itab, ktab): """ EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import pi_ik sage: pi_ik([[1,3],[2]], [[1,2],[3]]) [1, 3, 2] """ it = Tableau(itab) kt = Tableau(ktab) p = [None]*kt.size() for i in range(len(kt)): for j in range(len(kt[i])): p[ it[i][j] -1 ] = kt[i][j] QSn = SymmetricGroupAlgebra(QQ, it.size()) p = permutation.Permutation(p) return QSn(p)
def _build_tableau(self): ncons = self.lp.A_fpi.shape[0] opmat = np.vstack((np.zeros((1, ncons)), np.identity(ncons))) opmat = np.asmatrix(opmat, np.float64) lpmat = np.vstack((np.hstack((self.lp.c_fpi.T * (-1), [[0.0]])), np.hstack((self.lp.A_fpi, self.lp.b_fpi)))) tableau = np.asmatrix(np.hstack((opmat, lpmat))) return Tableau(tableau)
def epsilon_ik(self, itab, ktab, star=0): """ Returns the seminormal basis element of self corresponding to the pair of tableaux itab and ktab. EXAMPLES:: sage: QS3 = SymmetricGroupAlgebra(QQ, 3) sage: a = QS3.epsilon_ik([[1,2,3]], [[1,2,3]]); a 1/6*[1, 2, 3] + 1/6*[1, 3, 2] + 1/6*[2, 1, 3] + 1/6*[2, 3, 1] + 1/6*[3, 1, 2] + 1/6*[3, 2, 1] sage: QS3.dft()*vector(a) (1, 0, 0, 0, 0, 0) sage: a = QS3.epsilon_ik([[1,2],[3]], [[1,2],[3]]); a 1/3*[1, 2, 3] - 1/6*[1, 3, 2] + 1/3*[2, 1, 3] - 1/6*[2, 3, 1] - 1/6*[3, 1, 2] - 1/6*[3, 2, 1] sage: QS3.dft()*vector(a) (0, 0, 0, 0, 1, 0) """ it = Tableau(itab) kt = Tableau(ktab) stn = StandardTableaux_n(self.n) if it not in stn: raise TypeError, "it must be a standard tableaux of size %s"%self.n if kt not in stn: raise TypeError, "kt must be a standard tableaux of size %s"%self.n if it.shape() != kt.shape(): raise ValueError, "it and kt must be of the same shape" BR = self.base_ring() z_elts = {} epik = epsilon_ik(it, kt, star=star) for m,c in epik._monomial_coefficients.iteritems(): z_elts[m] = BR(c) z = self._from_dict(z_elts) if permutation.PermutationOptions()['mult'] == 'l2r': return z else: return z.map_support(lambda x: x.inverse())
def print_full_typology(rankings): """Print the full set of results: ranking, winner, and winner type.""" for ranking in rankings: constraint_ranking = ConstraintSet(ranking) print("----------------------------------") print(constraint_ranking) print("----------------------------------") for inputs in gen.inputs(): tableau = Tableau(inputs, constraint_ranking, gen.candidates(inputs)) print(inputs, tableau.winners, tableau.typology)
def __init__(self, largeur, hauteur, modele): # X,Y,Liste_Coeff self.X = largeur self.Y = hauteur self.MAXVALUE = 256 self.tab = Tableau(self.X, self.Y) self.modele = Modele("patron.xml") self.seed = [(key, Seed(self.X, self.Y, elt["seed"])) for key, elt in self.modele.racine["couche"].items()] for x, y in self.tab.iterC(): self.tab[x, y] = Case(x, y) for key, s in self.seed: self.tab[x, y].biome.set(key, s.tab[x, y].value)
def __init__(self,largeur,hauteur,noeud = {"type" : "plaque"},minValue = 0,maxValue = 255, value = 0): self.function = {"rand" : self.rand, "degrade" : self.degrade, "plaque" : self.plaque} self.maxValue = maxValue self.minValue = minValue self.X = largeur self.Y = hauteur self.tab = Tableau(self.X,self.Y) if "args" in noeud: self.function[noeud["type"]](noeud["args"]) else : self.function[noeud["type"]]()
def main(): logging.debug( '\n ======================== \n = Reading Data = \n ========================' ) vars_and_restrictions = input() vars_and_restrictions = vars_and_restrictions.split() r = int(vars_and_restrictions[0]) v = int(vars_and_restrictions[1]) logging.debug("Number of restrictions: {}".format(r)) logging.debug("Number of variables: {}".format(v)) c_input = input() c_list = list(c_input.split()) c = [] for i in range(len(c_list)): c.append(float(c_list[i])) logging.debug("Costs vector: {}".format(c)) a = [] b = [] for i in range(r): line = input().split() a_row = [] for j in range(len(line)): if j < v: a_row.append(float(line[j])) else: b.append(float(line[j])) a.append(a_row) logging.debug("Matrix A[]: {}".format(a)) logging.debug("Vector B[]: {}".format(b)) tableau = Tableau(r, v, c, a, b) Tableau.print_tableau(tableau.matrix_tableau) Simplex.do_simplex(tableau)
class Test(unittest.TestCase): def setUp(self): # variables pre_var = [(0, True), (0, False), (0, False), (0, True), (0, True)] self.vars = [Variable(*v) for v in pre_var] # row lines pre_row = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, -1, 0, 0], [2, -1, 0, -1, 0], [-1, 2, 0, 0, -1]] self.rows = [RowLine(r) for r in pre_row] # tableau self.table = Tableau(self.vars, self.rows) def tearDown(self): pass # tests about operators to help Gaussian elimination def test_row_subtraction(self): t_sub = self.rows[3] - self.rows[2] self.assertListEqual(t_sub.coef, [1, -2, 1, -1, 0]) def test_row_multiplication(self): t_mul = self.rows[4] * 3 self.assertListEqual(t_mul.coef, [-3, 6, 0, 0, -3]) def test_row_division(self): t_div = self.rows[2] / 5 self.assertListEqual(t_div.coef, [0.2, 0.2, -0.2, 0, 0]) def test_getitem(self): # originally, this operation should be written self.rows[2].coef[0] # RowLine has __getitem__ method, so this abbreviation is able self.assertEqual(self.rows[2][0], 1) # main test def test_gaussian_elimination(self): self.table.gaussian_elimination(2, 0) coef = [r.coef for r in self.table.rows] self.assertListEqual(coef, [[-1, -1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, -1, 0, 0], [0, -3, 2, -1, 0], [0, 3, -1, 0, -1]])
def b(tableau, star=0): r""" The column projection operator corresponding to the Young tableau ``tableau`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is the signed sum (in the group algebra of the relevant symmetric group over `\QQ`) of all the permutations which preserve the column of ``tableau`` (where the signs are the usual signs of the permutations). It is called `b_{\text{tableau}}` in [EtRT]_, Section 4.2. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import b sage: b([[1,2]]) [1, 2] sage: b([[1],[2]]) [1, 2] - [2, 1] sage: b([]) [] sage: b([[1, 2, 4], [5, 3]]) [1, 2, 3, 4, 5] - [1, 3, 2, 4, 5] - [5, 2, 3, 4, 1] + [5, 3, 2, 4, 1] With the `l2r` setting for multiplication, the unnormalized Young symmetrizer ``e(tableau)`` should be the product ``b(tableau) * a(tableau)`` for every ``tableau``. Let us check this on the standard tableaux of size 5:: sage: from sage.combinat.symmetric_group_algebra import a, b, e sage: all( e(t) == b(t) * a(t) for t in StandardTableaux(5) ) True """ t = Tableau(tableau) if star: t = t.restrict(t.size() - star) cs = t.column_stabilizer().list() n = t.size() # This all should be over ZZ, not over QQ, but symmetric group # algebras don't seem to preserve coercion (the one over ZZ # doesn't coerce into the one over QQ even for the same n), # and the QQ version of this method is more important, so let # me stay with QQ. # TODO: Fix this. sgalg = SymmetricGroupAlgebra(QQ, n) one = QQ.one() P = permutation.Permutation # Ugly hack for the case of an empty tableau, due to the # annoyance of Permutation(Tableau([]).row_stabilizer()[0]) # being [1] rather than [] (which seems to have its origins in # permutation group code). # TODO: Fix this. if len(tableau) == 0: return sgalg.one() cd = dict((P(v), v.sign() * one) for v in cs) return sgalg._from_dict(cd)
class Test(unittest.TestCase): def setUp(self): # variables pre_var = [(0, True), (0, False), (0, False), (0, True), (0, True)] self.vars = [Variable(*v) for v in pre_var] # row lines pre_row = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, -1, 0, 0], [2, -1, 0, -1, 0], [-1, 2, 0, 0, -1]] self.rows = [RowLine(r) for r in pre_row] # tableau self.table = Tableau(self.vars, self.rows) def tearDown(self): pass # tests about operators to help Gaussian elimination def test_row_subtraction(self): t_sub = self.rows[3] - self.rows[2] self.assertListEqual(t_sub.coef, [1, -2, 1, -1, 0]) def test_row_multiplication(self): t_mul = self.rows[4] * 3 self.assertListEqual(t_mul.coef, [-3, 6, 0, 0, -3]) def test_row_division(self): t_div = self.rows[2] / 5 self.assertListEqual(t_div.coef, [0.2, 0.2, -0.2, 0, 0]) def test_getitem(self): # originally, this operation should be written self.rows[2].coef[0] # RowLine has __getitem__ method, so this abbreviation is able self.assertEqual(self.rows[2][0], 1) # main test def test_gaussian_elimination(self): self.table.gaussian_elimination(2, 0) coef = [r.coef for r in self.table.rows] self.assertListEqual( coef, [[-1, -1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, -1, 0, 0], [0, -3, 2, -1, 0], [0, 3, -1, 0, -1]])
def a(tableau, star=0): r""" The row projection operator corresponding to the Young tableau ``tableau`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). This is the sum (in the group algebra of the relevant symmetric group over `\QQ`) of all the permutations which preserve the rows of ``tableau``. It is called `a_{\text{tableau}}` in [EtRT]_, Section 4.2. REFERENCES: .. [EtRT] Pavel Etingof, Oleg Golberg, Sebastian Hensel, Tiankai Liu, Alex Schwendner, Dmitry Vaintrob, Elena Yudovina, "Introduction to representation theory", :arXiv:`0901.0827v5`. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import a sage: a([[1,2]]) [1, 2] + [2, 1] sage: a([[1],[2]]) [1, 2] sage: a([]) [] sage: a([[1, 5], [2, 3], [4]]) [1, 2, 3, 4, 5] + [1, 3, 2, 4, 5] + [5, 2, 3, 4, 1] + [5, 3, 2, 4, 1] """ t = Tableau(tableau) if star: t = t.restrict(t.size() - star) rs = t.row_stabilizer().list() n = t.size() # This all should be over ZZ, not over QQ, but symmetric group # algebras don't seem to preserve coercion (the one over ZZ # doesn't coerce into the one over QQ even for the same n), # and the QQ version of this method is more important, so let # me stay with QQ. # TODO: Fix this. sgalg = SymmetricGroupAlgebra(QQ, n) one = QQ.one() P = permutation.Permutation # Ugly hack for the case of an empty tableau, due to the # annoyance of Permutation(Tableau([]).row_stabilizer()[0]) # being [1] rather than [] (which seems to have its origins in # permutation group code). # TODO: Fix this. if len(tableau) == 0: return sgalg.one() rd = dict((P(h), one) for h in rs) return sgalg._from_dict(rd)
def solve(self, verbose = False): if verbose: print("The input linear program is:\n") print("Maximize %s" % vect_vars(self.c)) print("Such that:") for k, row in enumerate(self.A): print("\t%s <= %s" % (vect_vars(row), str(self.b[k]))) print("\t" + ", ".join(["x%i" % (i + 1) for i in range(self.n)]) + " are non-negative\n") T = self.T = Tableau(self.c, self.A, self.b, self.pivot) phase_one_objective = T.initialize_basis() # PHASE 1 if T.nb_additional_vars > 0: if verbose: print("=== PHASE 1 ===") print("Added %i new positive variables." % T.nb_additional_vars) print("Now trying to maximize: %s" % vect_vars(phase_one_objective)) T.set_objective_vector(phase_one_objective) T.phase(verbose) if T.opt != 0: print("This linear program is INFEASIBLE.") self.log() return else: T.remove_additional_vars() if verbose: print("Found a basic feasible solution.: %s" % T.get_solution()) print("Removed additional variables from the tableau.\n") print("=== PHASE 2 ===") # PHASE 2 T.set_objective_vector(self.c) R = T.phase(verbose) if R == FeasibleResult.BOUNDED: print("This linear problem is FEASIBLE and BOUNDED.") print("One optimal solution is: %s" % T.get_solution()) print("The value of the objective for this solution is: %s" % str(-T.opt)) else: print("This linear problem is FEASIBLE but UNBOUNDED.") self.log()
def e(tableau, star=0): """ The unnormalized Young projection operator. EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e sage: e([[1,2]]) [1, 2] + [2, 1] sage: e([[1],[2]]) [1, 2] - [2, 1] There are differing conventions for the order of the symmetrizers and antisymmetrizers. This example illustrates our conventions:: sage: e([[1,2],[3]]) [1, 2, 3] + [2, 1, 3] - [3, 1, 2] - [3, 2, 1] """ t = Tableau(tableau) if star: t = t.restrict(t.size()-star) mult = permutation_options['mult'] permutation_options['mult'] = 'l2r' if t in e_cache: res = e_cache[t] else: rs = t.row_stabilizer().list() cs = t.column_stabilizer().list() n = t.size() QSn = SymmetricGroupAlgebra(QQ, n) one = QQ(1) P = permutation.Permutation rd = dict((P(h), one) for h in rs) sym = QSn._from_dict(rd) cd = dict((P(v), v.sign()*one) for v in cs) antisym = QSn._from_dict(cd) res = antisym*sym e_cache[t] = res permutation_options['mult'] = mult return res
def _build_aux_tableau(self): num_cons = self._tableau.A.shape[0] aux_c = np.zeros_like(self._tableau.ct) aux_c = np.asmatrix( np.hstack((np.zeros((1, num_cons)), aux_c, np.ones( (1, num_cons)))), np.float64) b_neglines = np.where(float_comp(self._tableau.b, 0.0, less=True))[0] opmat = np.asmatrix(np.identity(num_cons), np.float64) aux_opA = np.hstack((opmat, self._tableau.A)) aux_opA[b_neglines, :] = aux_opA[b_neglines, :] * (-1) aux_opA = np.hstack((aux_opA, np.identity(aux_opA.shape[0]))) aux_b = np.copy(self._tableau.b) aux_b[b_neglines, :] = aux_b[b_neglines, :] * (-1) aux_tab_mat = np.vstack((np.hstack( (aux_c, [[0.0]])), np.hstack((aux_opA, aux_b)))) aux_tab = Tableau(aux_tab_mat) return aux_tab
def test1(): print 'Test 1' r1 = [2, 1, -2, '<', 8] r2 = [4, -1, 2, '>', 2] r3 = [2, 3, -1, '>', 4] r = list() r.append(r1) r.append(r2) r.append(r3) f = [-2, 1, -1] tableau = Tableau(f, r) simplex = Simplex(tableau) simplex.execute() print 'Solution: ' + str(simplex.solution)
def input1(): print '' r1 = [1, 1, '>=', 2] r2 = [1, 2, '>=', 5] # r3 = [5,3,'<=',15] r = list() r.append(r1) r.append(r2) # r.append(r3) f = [-1, -1] tableau = Tableau(f, r) simplex = Simplex(tableau) simplex.execute() print 'Solution: ' + str(simplex.solution) print simplex.tableau
curses.endwin() # convert the input to simplex tableau print exit_mes print buf # do simplex method if input_ok: # split buffers to formulas formulas = [b.split() for b in buf] # formulas[var_num] is ineq # make variables var_list = [] for vi in range(var_num): var_list.append(Variable(0, False)) for fe in formulas: var_list.append(Variable(0, True, float(fe[var_num + 1]), fe[var_num])) # ineq type # make coefficient tableau row_list = [] for ri in range(var_num): row_list.append(RowLine([0] * (var_num + for_num))) for i, fe in enumerate(formulas): tmp_f = [float(e) for e in fe[:var_num]] tmp_zeros = [0] * for_num tmp_zeros[i] = -1 row_list.append(RowLine(tmp_f + tmp_zeros)) # simplex tableau table = Tableau(var_list, row_list) # do simplex method table.simplex_method()
def e(tableau, star=0): """ The unnormalized Young projection operator corresponding to the Young tableau ``tableau`` (which is supposed to contain every integer from `1` to its size precisely once, but may and may not be standard). EXAMPLES:: sage: from sage.combinat.symmetric_group_algebra import e sage: e([[1,2]]) [1, 2] + [2, 1] sage: e([[1],[2]]) [1, 2] - [2, 1] sage: e([]) [] There are differing conventions for the order of the symmetrizers and antisymmetrizers. This example illustrates our conventions:: sage: e([[1,2],[3]]) [1, 2, 3] + [2, 1, 3] - [3, 1, 2] - [3, 2, 1] """ t = Tableau(tableau) if star: t = t.restrict(t.size()-star) mult = permutation_options['mult'] permutation_options['mult'] = 'l2r' if t in e_cache: res = e_cache[t] else: rs = t.row_stabilizer().list() cs = t.column_stabilizer().list() n = t.size() QSn = SymmetricGroupAlgebra(QQ, n) one = QQ.one() P = permutation.Permutation rd = dict((P(h), one) for h in rs) sym = QSn._from_dict(rd) cd = dict((P(v), v.sign()*one) for v in cs) antisym = QSn._from_dict(cd) res = antisym*sym # Ugly hack for the case of an empty tableau, due to the # annoyance of Permutation(Tableau([]).row_stabilizer()[0]) # being [1] rather than [] (which seems to have its origins in # permutation group code). # TODO: Fix this. if len(tableau) == 0: res = QSn.one() e_cache[t] = res permutation_options['mult'] = mult return res
class MapGen: def __init__(self, largeur, hauteur, modele): # X,Y,Liste_Coeff self.X = largeur self.Y = hauteur self.MAXVALUE = 256 self.tab = Tableau(self.X, self.Y) self.modele = Modele("patron.xml") self.seed = [(key, Seed(self.X, self.Y, elt["seed"])) for key, elt in self.modele.racine["couche"].items()] for x, y in self.tab.iterC(): self.tab[x, y] = Case(x, y) for key, s in self.seed: self.tab[x, y].biome.set(key, s.tab[x, y].value) def cycle(self, duree): for i in range(duree): self.Division() self.Egalisation() self.Finalisation() def Division(self, mod=2): aux = Tableau(self.tab.X * 2, self.tab.Y * 2) for y in range(self.Y): init = self.tab.ligne(y) offset = 0 if init * 2 > y: offset = 1 for x in range(init, self.X + init): for y2 in range(mod): init2 = self.tab.ligne(y2) for x2 in range(init2, mod + init2): aux[(x) * mod + x2 - offset, y * mod + y2] = Case((x) * mod + x2 - offset, y * mod + y2) aux[(x) * mod + x2 - offset, y * mod + y2].biome.copy(self.tab[x, y].biome) self.tab = aux self.Y *= 2 self.X *= 2 def Egalisation(self): self.aux = Tableau(self.tab.X, self.tab.Y) self.tab.iter(self._egalisation) self.tab = self.aux def _egalisation(self, x, y): biome = self.Moyenne(x, y) self.aux[x, y] = Case(x, y) self.aux[x, y].biome = biome def Moyenne(self, x, y): aux = [] biome = Biome() compteur = 0 for elt in self.modele.hierarchie: biome.set(elt, 0) for elt in self.tab[x, y].Voisins(): if elt in self.tab: for elt1 in self.modele.hierarchie: biome.add(elt1, self.tab[elt].biome.dict[elt1]) aux.append(elt) compteur = compteur + 1 x1, y1 = aux[randrange(len(aux))] for elt in biome.dict.keys(): div = 0 biome.div(elt, compteur) biome.mult(elt, self.modele.argsRand[elt]["moyenne"]) div += self.modele.argsRand[elt]["moyenne"] biome.add(elt, self.tab[x, y].biome.dict[elt] * self.modele.argsRand[elt]["centre"]) div += self.modele.argsRand[elt]["centre"] biome.add(elt, self.tab[x1, y1].biome.dict[elt] * self.modele.argsRand[elt]["rand"]) div += self.modele.argsRand[elt]["rand"] biome.div(elt, div) return biome def Finalisation(self): aux = {} self.niveaux = {} for i in range(self.MAXVALUE): for elt in self.modele.hierarchie: aux[elt, i] = 0 for case in self.tab.values(): for elt in self.modele.hierarchie: aux[elt, case.biome.dict[elt]] += 1 for elt in self.modele.hierarchie: self.niveaux[elt] = [] i = 0 buffer_ = 1 for valeur in self.modele.pourcents[elt]: valeur = float(valeur) while i < self.MAXVALUE and buffer_ * 100 / (self.X * self.Y) <= valeur: buffer_ += aux[elt, i] i += 1 self.niveaux[elt].append(i) for case in self.tab.values(): for elt in self.modele.hierarchie: i = 0 while i < len(self.niveaux[elt]) and case.biome.dict[elt] > self.niveaux[elt][i]: i += 1 case.biome.dict[elt] = i self.modele.determine(case.biome) def getSurface(self): w = sf.RenderTexture(hexagone.l * self.X + hexagone.l // 2, (hexagone.L * 1.5) * (self.Y // 2 + 1)) w.clear() return w def getTexture(self, w): for elt in self.tab.values(): w.draw(elt.sprite()) w.display() return w def save(self, name): w = self.getTexture() image = w.texture.to_image() image.to_file(name)