def default_initial_partition(g): partitions = [] already_in_partition = set() for s in g.states: s_edge_labels = set([oedge[0] for oedge in s.outedges]) # print("Current state: {}\n\tOutedges: {}".format(s.name, s.outedges))# if not partitions: prt = pt.Partition(s) # print("\tCreating initial partition with s")# partitions.append(prt) already_in_partition.add(s) else: # Removed fail_count for p in partitions: # Solved bug with p.outedges (it was a list, so we must index position) p_edge_labels = set([oedge[0] for oedge in p.outedges[0]]) # print("\tCurrent partition: {}\n\t\tOutedges: {}".format(p.name, p.outedges))# if (p_edge_labels == s_edge_labels): # print("\t\t s added to partition") p.add_to_partition(s) already_in_partition.add(s) if s not in already_in_partition: # print("\t\tCreating new partition with s") prt = pt.Partition(s) partitions.append(prt) already_in_partition.add(s) # print() # print() return ps.PartitionSet(partitions)
def viterbi(self, l): """Compute the Partitions with Lexique l, using Viterbi algorithm, on the already stored data. """ for x in self: x[1] = partition.Partition() x[1].viterbi(x[0], l)
def SemistandardMultiSkewTableaux(shape, weight): """ Returns the combinatorial class of semistandard multi skew tableaux. A multi skew tableau is a k-tuple of skew tableaux of givens shape with a specified total weight. EXAMPLES:: sage: s = SemistandardMultiSkewTableaux([ [[2,1],[]], [[2,2],[1]] ], [2,2,2]); s Semistandard multi skew tableaux of shape [[[2, 1], []], [[2, 2], [1]]] and weight [2, 2, 2] sage: s.list() [[[[1, 1], [2]], [[None, 2], [3, 3]]], [[[1, 2], [2]], [[None, 1], [3, 3]]], [[[1, 3], [2]], [[None, 2], [1, 3]]], [[[1, 3], [2]], [[None, 1], [2, 3]]], [[[1, 1], [3]], [[None, 2], [2, 3]]], [[[1, 2], [3]], [[None, 2], [1, 3]]], [[[1, 2], [3]], [[None, 1], [2, 3]]], [[[2, 2], [3]], [[None, 1], [1, 3]]], [[[1, 3], [3]], [[None, 1], [2, 2]]], [[[2, 3], [3]], [[None, 1], [1, 2]]]] """ shape = [skew_partition.SkewPartition(x) for x in shape] weight = partition.Partition(weight) if sum(weight) != sum(s.size() for s in shape): raise ValueError, "the sum of weight must be the sum of the sizes of shape" return SemistandardMultiSkewTtableaux_shapeweight(shape, weight)
def KL_MC(self, lp2, nb=100, lg=1000): """Compute Kullback-Leibler divergence to Lproportion lp2 with Monte Carlo simulation on nb=100 Sequence of length lg=1000. """ if nb <= 0: print "Too few sequences" return if lg <= 1: print "Too short sequences" return lx1 = lexique.Lexique() lx1.read_Lprop(self) lx2 = lexique.Lexique() lx2.read_Lprop(lp2) g = sequence.Sequence() p = partition.Partition() v = 0.0 for i in range(nb): print i, '\r', sys.stdout.flush() g.read_Lprop(self, long=lg) p.viterbi(g, lx1) v += p.val() p.viterbi(g, lx2) v -= p.val() v /= nb return v / (lg - 1)
def mpp(self, l, i): """Compute maximally predictive i-Partition with Lexique l, on the already stored data. """ for x in self: p = partition.Partition() p.mpp(x[0], l, i) x[1] = p
def intersection(p1, p2): inter = [] for a in p1.name: idx = 0 for idx2,b in enumerate(p2.name): if a == b: inter.append(st.State(b, p2.outedges[idx], p2.state_probs[idx2])) break idx += 1 if inter: p = pt.Partition(inter.pop(0)) for i in inter: p.add_to_partition(i) else: p = pt.Partition(None) return p
def __init__(self, context, prev, next, install): Gtk.VBox.__init__(self) self.prev = prev self.next = next self.install = install self.context = context intro_card = intro.Intro(self.context) device_card = device.Device(self.context) partition_card = partition.Partition(self.context) timezone_card = timezone.Timezone(self.context) locale_card = locale.Locale(self.context) user_card = user.User(self.context) root_card = root.Root(self.context) finalinfo_card = finalinfo.FinalInfo(self.context) status_card = status.Status(self.context) self.card_names = [ 'intro_card', 'device_card', 'partition_card', 'timezone_card', 'locale_card', 'user_card', 'root_card', 'finalinfo_card', 'status_card' ] self.cards = [ intro_card, device_card, partition_card, timezone_card, locale_card, user_card, root_card, finalinfo_card, status_card ] self.the_stack = Gtk.Stack() self.the_stack.set_hexpand(True) self.the_stack.set_vexpand(True) self.context['the_stack'] = self.the_stack self.pack_start(self.the_stack, True, True, 0) self.set_name('stack') # add the cards to the stack self.the_stack.add_titled(intro_card, 'intro_card', 'Introduction') self.the_stack.add_titled(device_card, 'device_card', 'Device') self.the_stack.add_titled(partition_card, 'partition_card', 'Partition') self.the_stack.add_titled(timezone_card, 'timezone_card', 'Timezone') self.the_stack.add_titled(locale_card, 'locale_card', 'Locale') self.the_stack.add_titled(user_card, 'user_card', 'User') self.the_stack.add_titled(root_card, 'root_card', 'Root') self.the_stack.add_titled(finalinfo_card, 'finalinfo_card', 'Confirmation') self.the_stack.add_titled(status_card, 'status_card', 'Status') self.prev.connect('clicked', self.nav_prev) self.next.connect('clicked', self.nav_next) self.current_card = self.card_names[0] self.current_index = 0 self.prev.set_sensitive(False) self.install.set_sensitive(False)
def partition(self): problem = Problem(self.g, self.k, max_steps=self.max_steps) state = search.annealing(problem, working_dir=self.working_dir) final_partition = [] for gid in state.get_partitions(): final_partition.append(state.get_nodes(gid)) p = partition.Partition(groups=final_partition) self.partition = p return p
def define_partition(self, text, loc, part_def): """We have everything we need here to make a partition""" try: # Creation adds it to set p = partition.Partition(self.cfg, part_def.name, *tuple(part_def.parts)) except partition.PartitionError: raise ParserError(text, loc, "Error in '%s' can be found" % part_def.name)
def scene(self): self.menu_frame = tk.Frame(self.root) self.menu_frame.pack(side=tk.TOP, expand=True, fill=tk.X, anchor="n") self.menu_fichier = tk.Menubutton(self.menu_frame, text="File", underline=0, relief="raised") self.deroul_fichier = tk.Menu(self.menu_fichier, tearoff=False) self.deroul_fichier.add_command(label="New (Ctrl + N)", command=self.newPartition) self.deroul_fichier.add_command(label="Open (Ctrl + O)", command=self.openPartition) self.deroul_fichier.add_command(label="Save (Ctrl + S)", command=self.savePartition) self.deroul_fichier.add_separator() self.deroul_fichier.add_command(label="Quit (Alt + F4)", command=self.quit) cframe = tk.Frame(self.root) cframe.rowconfigure(0, weight=1) cframe.columnconfigure(0, weight=1) cframe.pack(expand=1, fill="both", padx=5, pady=5) self.canv = tk.Canvas(cframe, width=1000, height=200, bg="white") self.canv.create_oval(28, 18, 33, 23, fill='red', outline='red', tag="visu") self.Partition = partition.Partition(self.canv) hbar = tk.Scrollbar(cframe, orient="horizontal") self.canv.configure( xscrollcommand=hbar.set, scrollregion=(0, 0, 20000, 600), ) hbar.configure(command=self.canv.xview) hbar.pack(side="bottom") self.canv.bind("<Motion>", self.visualisation) self.canv.bind("<Button-1>", self.addNote) self.root.protocol("WM_DELETE_WINDOW", self.quit) self.root.bind("<Control-n>", self.newPartition) self.root.bind("<Control-o>", self.openPartition) self.root.bind("<Control-s>", self.savePartition) self.root.bind("<Control-z>", self.cancel) self.menu_fichier.config(menu=self.deroul_fichier) self.menu_fichier.pack(side=tk.LEFT) self.canv.pack()
def polymorphismsWithIdentities(A, B, equations, idempotent=False): """ Each equation is of the form (args1, args2) where args1,args2 are tuples whose entries are single letter variables. Example: An equation ('xyx','yxx') talks about a ternary function that satisfies forall x,y, f(x,y,x) = f(y,x,x). All these equations must have the same arity. """ logging.debug('polymorphismsWithIdentities:') if len(equations) == 0: return None # Check that all equations have the same arity arity = len(equations[0][0]) for p in equations: if len(p[0]) != arity or len(p[1]) != arity: logging.error( 'equations::hasPolymorphism: LHS has {:d} and RHS has {:d} variables' .format(len(p[0]), len(p[1]))) raise Exception An = A.power(arity) logging.debug('polymorphismsWithIdentities:Computed Power') indicatorPartition = partition.Partition(An.domain) for p in equations: variables = list(set(p[0]) | set(p[1])) for instanciations in product(A.domain, repeat=len(variables)): tuple1 = tuple(instanciations[variables.index(p[0][i])] for i in range(0, arity)) tuple2 = tuple(instanciations[variables.index(p[1][i])] for i in range(0, arity)) indicatorPartition.union(tuple1, tuple2) logging.debug('polymorphismsWithIdentities:Computed Partition') Factor = An.quotient(indicatorPartition) logging.debug('polymorphismsWithIdentities:Computed Factor Structure') L = {} # The 'idempotent' flag only makes sense if A.domain is a subset of B.domain # If set to True, we impose that for every tuple (x,...,x) in the domain of An, L[x/Theta] := x if idempotent == True and (set(A.domain) & set(B.domain) == set(A.domain)): for x in A.domain: representative = An.domain[indicatorPartition.representative( tuple(x for i in range(0, arity)))] L[representative] = {x} # For all the tuples a for which L[a/Theta] is not yet created, we allow all # possible values and set L[a/Theta] := B.domain for a in product(A.domain, repeat=arity): representative = An.domain[indicatorPartition.representative(a)] if representative not in L: L[representative] = set(B.domain) logging.debug('polymorphismsWithIdentities:Finished preparing the factor') yield from homomorphisms(Factor, B, L)
def fb(self, l): """Compute the Partitions with Lexique l, using forward-backward algorithm, on the already stored data. On each position, the first best descriptor is kept. """ m = matrice.Matrice() for x in self: x[1] = partition.Partition() m.fb(x[0], l) x[1].read_Matrice(m)
def partition(self): nodes = self.g.nodes() random.shuffle(nodes) part = [] while len(nodes) >= 2 * self.k: part.append(nodes[:self.k]) del nodes[:self.k] part.append(nodes) self.partition = partition.Partition(part) return self.partition
def splitting(partition, letter, states): p1 = pt.Partition(None) p2 = pt.Partition(None) for s in states: edge_labels = [edge[0] for edge in s.outedges] if letter in edge_labels: next_state = [state for state in states if (state.name == s.next_state_from_edge(letter))][0] if next_state: if next_state.name in partition.name: p1.add_to_partition(s) else: p2.add_to_partition(s) else: p2.add_to_partition(s) else: p1.add_to_partition(s) p2.add_to_partition(s) r = [x for x in [p1, p2] if x.size > 0] return r
def outer_shape(self): """ Returns the outer shape of the tableau. EXAMPLES:: sage: SkewTableau([[None,1,2],[None,3],[4]]).outer_shape() [3, 2, 1] """ return partition.Partition([len(row) for row in self])
def build_random(self, lg, np): """Build a random (uniform distribution) np-partitioning on data-length lg. """ if lg <= 0 or np <= 0 or np >= lg: return self.__init__() for i in range(np): p = partition.Partition() p.build_random(lg, i + 1) self.__tab.append(p)
def newPartition(self): self.canv.delete("all") self.Partition = partition.Partition(self.canv) self.DICO.clear() self.POS_LIST = [] self.canv.create_oval(28, 18, 33, 23, fill='red', outline='red', tag="visu")
def inner_shape(self): """ Returns the inner shape of the tableau. EXAMPLES:: sage: SkewTableau([[None,1,2],[None,3],[4]]).inner_shape() [1, 1] """ return partition.Partition( filter(lambda x: x != 0, [len(filter(lambda x: x is None, row)) for row in self]))
def simplemoore(pset, graph): partition = pset.partitions while True: old_partition = partition s0 = graph.state_named(partition[0].name[0]) ed = [] for e in s0.outedges: for p in partition: if e[1]: if e[1].name in p.name: ed.append([e[0], p]) break p0 = [[[s0], ed]] for p in partition[1:]: for nm in p.name: s = graph.state_named(nm) fail = True for q in p0: for e in s.outedges: for d in q[1]: if e[0] == d[0]: if e[1]: if e[1].name in d[1].name: q[0].append(s) fail = False break if fail: ed = [] for e in s.outedges: for o in partition: if e[1]: if e[1].name in o.name: ed.append([e[0], o]) p0.append([[s], ed]) partition = [] for p in p0: for i in range(len(p[0])): if i == 0: eq_class = pt.Partition(p[0][i]) else: eq_class.add_to_partition(p[0][i]) partition.append(eq_class) if len(partition) == len(old_partition): return partition
def RibbonTableaux(shape, weight, length): """ Returns the combinatorial class of ribbon tableaux of skew shape shape and weight weight tiled by ribbons of length length. EXAMPLES:: sage: RibbonTableaux([[2,1],[]],[1,1,1],1) Ribbon tableaux of shape [[2, 1], []] and weight [1, 1, 1] with 1-ribbons """ if shape in partition.Partitions(): shape = partition.Partition(shape) shape = skew_partition.SkewPartition([shape, shape.core(length)]) else: shape = skew_partition.SkewPartition(shape) if shape.size() != length * sum(weight): raise ValueError weight = [i for i in weight if i != 0] return RibbonTableaux_shapeweightlength(shape, weight, length)
def spin_polynomial_square(part, weight, length): """ Returns the spin polynomial associated with part, weight, and length, with the substitution t -> t^2 made. EXAMPLES:: sage: from sage.combinat.ribbon_tableau import spin_polynomial_square sage: spin_polynomial_square([6,6,6],[4,2],3) t^12 + t^10 + 2*t^8 + t^6 + t^4 sage: spin_polynomial_square([6,6,6],[4,1,1],3) t^12 + 2*t^10 + 3*t^8 + 2*t^6 + t^4 sage: spin_polynomial_square([3,3,3,2,1], [2,2], 3) t^7 + t^5 sage: spin_polynomial_square([3,3,3,2,1], [2,1,1], 3) 2*t^7 + 2*t^5 + t^3 sage: spin_polynomial_square([3,3,3,2,1], [1,1,1,1], 3) 3*t^7 + 5*t^5 + 3*t^3 + t sage: spin_polynomial_square([5,4,3,2,1,1,1], [2,2,1], 3) 2*t^9 + 6*t^7 + 2*t^5 sage: spin_polynomial_square([[6]*6, [3,3]], [4,4,2], 3) 3*t^18 + 5*t^16 + 9*t^14 + 6*t^12 + 3*t^10 """ R = ZZ['t'] t = R.gen() if part in partition.Partitions(): part = skew_partition.SkewPartition([part, partition.Partition([])]) elif part in skew_partition.SkewPartitions(): part = skew_partition.SkewPartition(part) if part == [[], []] and weight == []: return t.parent()(1) return R( graph_implementation_rec(part, weight, length, functools.partial(spin_rec, t))[0])
def mpp(self, d, l, i): """Compute a maximal predictive i-partitioning on data d with Lexique l. Each new k-Partition gets its length k as name. """ if l.is_empty(): return self.__init__() p = Cparti_simp() if isinstance(d, matrice._Matr): p.lisse(d._Matr__c_elem(), l._Lexique__c_elem(), i) elif isinstance(d, sequence._Seq): p.lisse(d._Seq__c_elem(), l._Lexique__c_elem(), i) j = 1 x = p[j] while x != "": q = partition.Partition() q.read_str(x) self.__tab.append(q) q.s_name(len(q)) j += 1 x = p[j] self.__nbmax = p.np_max() self.__valmax = p.val_max()
def read_Lprop(self, lprop, **kw): """Build from a Lproportion lprop. Return the Partition of the descriptors. Keyword argument: deb -- change only after position deb (>=0) included; fin -- change only before position fin (<len()) included; long -- create a lg-length Sequence. In that case, deb and fin are not read; etat_init -- begin with descriptor number etat_init if it is valid. Otherwise, starts with a random descriptor of lprop. """ al = lprop.alph() if al == [] or al == ["^"]: print "Empty Lproportion" self.__init__() return p = partition.Partition() e = kw.get('etat_init', -1) if kw.has_key('long'): if not isinstance(self, Sequence): print "impossible generation of virtual sequence" return p fin = kw['long'] if fin <= 0: return p self.generate(fin) fin -= 1 deb = 0 else: self.__gen.termine(self.__gen.vtaille() - 1) fin = kw.get('fin', len(self) - 1) fin = min(fin, len(self)) deb = kw.get('deb', 0) if deb < 0 or deb > fin: return p lik = lprop.num() if lik == []: return p if deb != 0: p += Segment(deb=0, fin=deb - 1) def sum(x, y): return x + y # dicos des transitions entre etats ltrans = {} llik = len(lik) for b in lik: sb = reduce(sum, [lprop.inter(b, x) for x in lik]) ltrans[b] = {} if sb == 0: for x in lik: ltrans[b][x] = 1.0 / llik else: for x in lik: ltrans[b][x] = float(lprop.inter(b, x)) / sb ## Demarrage avec choix uniforme de l'etat initial ou bien e if e in lik: etat = e else: etat = random.choice(lik) tab = lprop[etat] dseg = deb ilal = 1.0 / len(al) asuiv = [[x, ilal] for x in al] for i in range(deb, fin): ##choix de la lettre j = i - 1 s = "" while j >= 0: s = self.__gen[j] + s if not tab.has_prefix(s): s = s[1:] break else: j -= 1 suiv = tab.next(s) if suiv == []: suiv = asuiv y = reduce(sum, [t[1] for t in suiv]) x = random.random() * y lsuiv = len(suiv) while x >= 0 and lsuiv > 0: lsuiv -= 1 x -= suiv[lsuiv][1] if len(suiv[lsuiv][0]) != 1: print "Bad proportion after " + sq[1:] self.__init__() return a = suiv[lsuiv][0][0] if a == "^": for j in range(i, fin + 1): self.__gen[j] = "\0" self.__gen.termine(i - 1) if dseg < i: p += Segment(deb=dseg, fin=i - 1, num=[etat]) return p else: self.__gen[i] = a ##choix de l'etat suivant llik = len(lik) x = random.random() while x >= 0 and llik > 0: llik -= 1 x -= ltrans[etat][lik[llik]] if etat != lik[llik]: p += Segment(deb=dseg, fin=i, num=[etat]) dseg = i + 1 etat = lik[llik] tab = lprop[etat] ##choix de la lettre finale j = fin - 1 s = '' while j >= 0: s = self.__gen[j] + s if not tab.has_prefix(s): s = s[1:] break else: j -= 1 suiv = tab.next(s) if suiv == []: suiv = asuiv y = reduce(lambda x, y: x + y, [t[1] for t in suiv]) x = random.random() * y lsuiv = len(suiv) while x >= 0 and lsuiv > 0: lsuiv -= 1 x -= suiv[lsuiv][1] a = suiv[lsuiv][0][0] if a == "^": self.__gen.termine(fin - 1) self.__gen[fin] = "\0" if dseg < fin: p += Segment(deb=dseg, fin=fin - 1, num=[etat]) return p else: self.__gen[fin] = a p += Segment(deb=dseg, fin=fin, num=[etat]) if fin < len(self) - 1: p += Segment(deb=fin + 1, fin=len(self) - 1) return p
def build_random(self, l): "Create random l-Partition on the data-list." for x in self: p = partition.Partition() p.build_random(len(x[0]), l) x[1] = p
def graph_implementation_rec(skp, weight, length, function): """ TESTS:: sage: from sage.combinat.ribbon_tableau import graph_implementation_rec, list_rec sage: graph_implementation_rec(SkewPartition([[1], []]), [1], 1, list_rec) [[[], [[1]]]] sage: graph_implementation_rec(SkewPartition([[2, 1], []]), [1, 2], 1, list_rec) [[[], [[2], [1, 2]]]] sage: graph_implementation_rec(SkewPartition([[], []]), [0], 1, list_rec) [[[], []]] """ inn = "graph_implementation_rec(%s, %s, %s, %s)" % (skp, weight, length, function) #print "!!!", inn if sum(weight) == 0: weight = [] partp = skp[0].conjugate() ## Some tests in order to know if the shape and the weight are compatible. if weight != [] and weight[-1] <= len(partp): perms = permutation.Permutations([0] * (len(partp) - weight[-1]) + [length] * (weight[-1])).list() else: return function([], [], skp, weight, length) selection = [] for j in range(len(perms)): retire = [(partp[i] + len(partp) - (i + 1) - perms[j][i]) for i in range(len(partp))] retire.sort(reverse=True) retire = [retire[i] - len(partp) + (i + 1) for i in range(len(retire))] if retire[-1] >= 0 and retire == [i for i in reversed(sorted(retire))]: retire = partition.Partition(filter(lambda x: x != 0, retire)).conjugate() # Cutting branches if the retired partition has a line strictly included into the inner one append = True padded_retire = retire + [0] * (len(skp[1]) - len(retire)) for k in range(len(skp[1])): if padded_retire[k] - skp[1][k] < 0: append = False break if append: selection.append([retire, perms[j]]) #selection contains the list of current nodes #print "selection", selection if len(weight) == 1: return function([], selection, skp, weight, length) else: #The recursive calls permit us to construct the list of the sons #of all current nodes in selection a = [ graph_implementation_rec([p[0], skp[1]], weight[:-1], length, function) for p in selection ] #print "a", a return function(a, selection, skp, weight, length)
def insertion_tableau(skp, perm, evaluation, tableau, length): """ INPUT: - ``skp`` - skew partitions - ``perm, evaluation`` - non-negative integers - ``tableau`` - skew tableau - ``length`` - integer TESTS:: sage: from sage.combinat.ribbon_tableau import insertion_tableau sage: insertion_tableau([[1], []], [1], 1, [[], []], 1) [[], [[1]]] sage: insertion_tableau([[2, 1], []], [1, 1], 2, [[], [[1]]], 1) [[], [[2], [1, 2]]] sage: insertion_tableau([[2, 1], []], [0, 0], 3, [[], [[2], [1, 2]]], 1) [[], [[2], [1, 2]]] sage: insertion_tableau([[1, 1], []], [1], 2, [[], [[1]]], 1) [[], [[2], [1]]] sage: insertion_tableau([[2], []], [0, 1], 2, [[], [[1]]], 1) [[], [[1, 2]]] sage: insertion_tableau([[2, 1], []], [0, 1], 3, [[], [[2], [1]]], 1) [[], [[2], [1, 3]]] sage: insertion_tableau([[1, 1], []], [2], 1, [[], []], 2) [[], [[1], [0]]] sage: insertion_tableau([[2], []], [2, 0], 1, [[], []], 2) [[], [[1, 0]]] sage: insertion_tableau([[2, 2], []], [0, 2], 2, [[], [[1], [0]]], 2) [[], [[1, 2], [0, 0]]] sage: insertion_tableau([[2, 2], []], [2, 0], 2, [[], [[1, 0]]], 2) [[], [[2, 0], [1, 0]]] sage: insertion_tableau([[2, 2], [1]], [3, 0], 1, [[], []], 3) [[1], [[1, 0], [0]]] """ psave = partition.Partition(skp[1]) partc = skp[1] + [0] * (len(skp[0]) - len(skp[1])) tableau = skew_tableau.SkewTableau(expr=tableau).to_expr()[1] for k in range(len(tableau)): tableau[-(k + 1)] += [0] * (skp[0][k] - partc[k] - len(tableau[-(k + 1)])) ## We construct a tableau from the southwest corner to the northeast one tableau = [[0] * (skp[0][k] - partc[k]) for k in reversed(range(len(tableau), len(skp[0])))] + tableau tableau = skew_tableau.from_expr([skp[1], tableau]).conjugate() tableau = tableau.to_expr()[1] skp = skew_partition.SkewPartition(skp).conjugate().to_list() skp[1].extend([0] * (len(skp[0]) - len(skp[1]))) if len(perm) > len(skp[0]): return None for k in range(len(perm)): if perm[-(k + 1)] != 0: tableau[len(tableau) - len(perm) + k][skp[0][len(perm) - (k + 1)] - skp[1][len(perm) - (k + 1)] - 1] = evaluation return skew_tableau.SkewTableau( expr=[psave.conjugate(), tableau]).conjugate().to_expr()
bootdrv = drv.get_path() drvdisk = drv.disk_open() if drvdisk is not None: partlist = drvdisk.get_part_list() isdata = 0 for part in partlist: if part.get_type() != parted.PARTITION_FREESPACE: isdata = 1 drvdisk.close() for drv in drvinstlist: print "Partitioning drive %s..." % drv.get_path() drvobj = partition.Partition(drv) drvsectors = drv.get_length() drvobj.create_partition_table() partabssect = 0 # for reference, partcfg at this point looks like: # [['ext2', '80%', '/', ['primary']], ['swap', '256M', 'swap', ['primary']]] for partinfo in partcfg: if partinfo[2] == "/": rootpart = partinfo partsizetype = string.upper(partinfo[1][-1]) if partsizetype == "M": partsize = string.atoi(partinfo[1][:-1]) partsect = int( float(partsize) * 1024 * 1024 / parted.SECTOR_SIZE) partabssect = partabssect + partsect
def run_trial(params, out_dir): # model input and output sizes input_size = params['points'].shape[1] output_size = params['num_labels'] column_name = 'point' the_partition = partition.Partition(params['points'], params['num_labels'], np.zeros(input_size), params['temp'], params['conv']) part = the_partition.partition points = the_partition.points train_split = 0.75 train_bins = { label: part[label][:int(train_split * len(part[label]))] for label in part } test_bins = { label: part[label][int(train_split * len(part[label])):] for label in part } # oversample from all but biggest bins # note: partition.labelled_pts will no longer be true labels for training # data, only for test max_train_bin = max(len(train_bins[label]) for label in train_bins) train_bins = { label: np.random.choice(train_bins[label], max_train_bin, replace=True) if 0 < len(train_bins[label]) < max_train_bin else train_bins[label] for label in train_bins } def from_bins_to_xy(bins): x = np.vstack([points[bins[label]] for label in bins]) # TODO: why does this sometimes return floats, and therefore require # the astype(int)? y = np.concatenate([[label] * len(bins[label]) for label in bins]).astype(int) return x, y train_x, train_y = from_bins_to_xy(train_bins) train_input_fn = tf.estimator.inputs.numpy_input_fn( x={column_name: train_x}, y=train_y, batch_size=32, num_epochs=params['num_epochs'], shuffle=True) test_x, test_y = from_bins_to_xy(test_bins) test_input_fn = tf.estimator.inputs.numpy_input_fn(x={column_name: test_x}, y=test_y, num_epochs=1, batch_size=len(test_x), shuffle=False) total_x, total_y = from_bins_to_xy(part) total_input_train = tf.estimator.inputs.numpy_input_fn( x={column_name: total_x}, y=total_y, batch_size=32, num_epochs=params['num_epochs'], shuffle=True) total_input_test = tf.estimator.inputs.numpy_input_fn( x={column_name: total_x}, y=total_y, batch_size=len(total_x), num_epochs=1, shuffle=False) # main network training network_params = { 'hidden_units': [32, 32], 'activation': tf.nn.relu, 'optimizer': tf.train.AdamOptimizer(), 'model_dir': out_dir } point_column = tf.feature_column.numeric_column(column_name, shape=(input_size, )) estimator = tf.estimator.DNNClassifier( hidden_units=network_params['hidden_units'], feature_columns=[point_column], # model_dir=network_params['model_dir'] n_classes=output_size, activation_fn=network_params['activation'], optimizer=network_params['optimizer']) estimator.train(train_input_fn) # linear model for measuring degree of separability linear_model = tf.estimator.LinearClassifier( feature_columns=[point_column], n_classes=output_size) linear_model.train(total_input_train) linear_results = linear_model.evaluate(total_input_test) linear_results = { 'linear_' + key: linear_results[key] for key in linear_results } trial_results = dict(params) del trial_results['points'] # TODO: record all info desired! trial_results['degree_of_convexity'] = the_partition.degree_of_convexity() trial_results.update(estimator.evaluate(test_input_fn)) trial_results.update( {'cell{}_size'.format(label): len(part[label]) for label in part}) trial_results.update(linear_results) print(trial_results) trial_results.update( {'cell_{}'.format(label): part[label] for label in part}) return trial_results
except IOError, e: print "Unknown file: ", nf else: self.__init__() s = f.readline() while s: s.strip() if (s.find("MAX", 0, 3) == 0): pat = 'MAX\((?P<nm>\d*)\)\s*--->\s*(?P<val>-?\d+\.?\d*)' r = re.compile(pat) g = r.match(s) if g: self.__nbmax = eval(g.group('nm')) self.__valmax = float(g.group('val')) else: p = partition.Partition() if p.read_str(s): self.__tab.append(p) if p.name() == "": p.s_name(str(len(self.__tab))) s = f.readline() f.close() def build_random(self, lg, np): """Build a random (uniform distribution) np-partitioning on data-length lg. """ if lg <= 0 or np <= 0 or np >= lg: return self.__init__() for i in range(np):
lx.g_inter(i, j, (1 - lamb) / (numMod)) #lx.g_inter(0,0,lamb) #lx.g_inter(0,1,(1-lamb)/2) #lx.g_inter(0,2,(1-lamb)/2) #lx.g_inter(1,1,lamb) #lx.g_inter(1,0,(1-lamb)/2) #lx.g_inter(1,2,(1-lamb)/2) #lx.g_inter(2,2,lamb) #lx.g_inter(2,0,(1-lamb)/2) #lx.g_inter(2,1,(1-lamb)/2) #print m[:10] #print lx p_vit = partition.Partition() p_vit.viterbi(m, lx) print("\n\nViterbi : ") #print len(p_vit) #print p_vit.len_don() print(p_vit) p_vit.draw_nf(outvit, num=1) # FOR PDF OUTPUT, UNCOMMENT THE NEXT LINE #os.system("ps2pdf "+outvit) m_fb = matrice.Matrice() m_fb.fb(m, lx) p_fb = partition.Partition() p_fb.read_Matrice(m_fb) p_fb.draw_nf(outfb, num=1)