Example #1
0
	def __init__(self, speed=1):
		Sequence.__init__(
			self, [
				Row(speed, [0,0,0,0,0,0,0,0,0,0,0,0]),
			],
			1
		)
 def __init__(self,iterable=[],key=None):
     """The only additional data we maintain over a vanilla Sequence
     is a dictionary self._tag mapping sequence items to integers,
     such that an item is earlier than another iff its tag is smaller.
     """
     self._tag = {}
     Sequence.__init__(self,iterable,key=key)
 def append(self,x):
     """Add x to the end of the sequence."""
     if not self._next:  # add to empty sequence
         Sequence.append(self,x)
         self._tag[self.key(x)] = sys.maxint//2
     else:
         self.insertAfter(self._prev[self._first],x)
Example #4
0
	def __init__(self, speed=0.85):
		Sequence.__init__(
			self, [
				Row(speed, [1,0,1,0,1,0,1,0,1,0,1,0]),
				Row(speed, [0,1,0,1,0,1,0,1,0,1,0,1]),
			],
			12
		)
 def insertBefore(self,x,y):
     """Add y before x in the sequence."""
     Sequence.insertBefore(self,x,y)
     x = self.key(x)
     y = self.key(y)
     if self._first == y:
         self._tag[y] = self._tag[x]//2
         if self._tag[y] == self._tag[x]:
             self.rebalance(y)
Example #6
0
	def __init__(self, speed=0.8):
		Sequence.__init__(
			self, [
				Row(speed, [1,1,1,1,1,1,0,0,0,0,0,0]),
				Row(speed, [0,0,0,0,0,0,1,1,1,1,1,1]),
				Row(0.001, [0,0,0,0,0,0,0,0,0,0,0,0]),
			],
			99
		)
 def insertAfter(self,x,y):
     """Add y after x and compute a tag for it."""
     Sequence.insertAfter(self,x,y)
     x = self.key(x)
     y = self.key(y)
     next = self._next[y]
     if next == self._first:
         nexttag = sys.maxint
     else:
         nexttag = self._tag[next]
     xtag = self._tag[x]
     self._tag[y] = xtag + (nexttag - xtag + 1)//2
     if self._tag[y] == nexttag:
         self.rebalance(y)
def ParseXMLFile(xmlFileName):
    xmlDoc = ET.parse(xmlFileName)
    rootNode = xmlDoc.getroot()
    idSpeaker = rootNode.find('IdSpeaker').text
    idSession = rootNode.find('IdSession').text
    device = rootNode.find('Device').text
    typeSequence = rootNode.find('TypeSequence').text
    digits = rootNode.find('Digits').text
    digits = digits.split()

    digitsById = []
    for i in range(11):
        digitNode = rootNode.find('digit' + str(i + 1))
        if not digitNode:
            break
        digitName = digits[i]
        digitId = digitsByName[digitName]
        startDigit = digitNode.find('start_digit').text
        endDigit = digitNode.find('end_digit').text
        startTightDigit = digitNode.find('start_tight_digit').text
        endTightDigit = digitNode.find('end_tight_digit').text
        digit = Digit(digitId, startDigit, endDigit, startTightDigit,
                      endTightDigit, digitName)
        digitsById.append(digit)

    sequence = Sequence(idSpeaker, idSession, device, typeSequence, digitsById)
    return sequence
Example #9
0
    def __init__(self, file_list, *args, **kwargs):
        self.temp_dir = 'temp/trace_files'

        # Copy the files provided into the temp directory
        tools.copy_list_to_folder(file_list, self.temp_dir)
        self.file_list = tools.listdir_joined(self.temp_dir)

        self.trace_file, self.non_abi = tools.abi_filter(self.file_list)

        self.seq_list = []
        self.entries = []

        self.parse_failed = []
        self.exceptions = []
        self.fail_folder = os.path.join('Exceptions',
                                        str(datetime.date.today()))

        for item in self.trace_file:
            try:
                holder = Sequence(item, *args, **kwargs)
                self.seq_list.append(holder)
            except:
                self.parse_failed.append(item)
                print "Failed to parse ", item

        # Select the valid files for entry
        for seq in self.seq_list:
            if seq.record[0] is True:
                self.entries.append(seq.record)
            elif seq.record[0] is False:
                self.exceptions.append(seq.record)
                print seq.record[1], ' is not a valid file.'
Example #10
0
def Tracking(Sequence, tracker_list, visualize=False):

    if not os.path.exists('results/'):
        #创建目录
        os.mkdir("results")

    print 'generate images.txt and region.txt files...'

    with open("images.txt", "w") as f:
        while Sequence._frame < len(Sequence._images):
            #将多个文件的路径写进txt文档
            f.write(Sequence.frame() + '\n')
            Sequence._frame += 1
        Sequence._frame = 0
    with open("region.txt", "w") as f:
        f.write(
            open(os.path.join(Sequence.seqdir, 'groundtruth.txt'),
                 'r').readline())

    print 'start tracking...'

    for str in tracker_list:
        print 'tracking using: ' + str
        print(str)
        import_module(str)
        if not os.path.exists('results/' + str + '/' + Sequence.name):
            os.makedirs('results/' + str + '/' + Sequence.name)
        shutil.move("output.txt",
                    'results/' + str + '/' + Sequence.name + '/output.txt')
    #进行文件的删除
    os.remove("images.txt")
    os.remove("region.txt")

    print 'Done!!'
Example #11
0
    def __init__(self, D):
        # refine partition of states by reversed neighborhoods
        N = D.reverse()
        P = PartitionRefinement(D.states())
        P.refine([s for s in D.states() if D.isfinal(s)])
        unrefined = Sequence(P, key=id)
        while unrefined:
            part = arbitrary_item(unrefined)
            unrefined.remove(part)
            for symbol in D.alphabet:
                neighbors = set()
                for state in part:
                    neighbors |= N.transition(state, symbol)
                for new, old in P.refine(neighbors):
                    if old in unrefined or len(new) < len(old):
                        unrefined.append(new)
                    else:
                        unrefined.append(old)

        # convert partition to DFA
        P.freeze()
        self.partition = P
        self.initial = P[D.initial]
        self.alphabet = D.alphabet
        self.DFA = D
Example #12
0
 def test_minimal_sequence_visualize_tree(self):
     s = Sequence.from_file(testpath +
                            "/test_sequences/minimal_sequence.xml")
     s.resolve_references()
     tree = _Sequence_verification.Tree(sequence=s, control_values={})
     tree.build()
     tree.visualize()
Example #13
0
def yield_sequence_and_BlastHit(len_seq=500,
                                n_query=10,
                                min_len_hit=20,
                                max_len_hit=40):

    # Generate a random subject sequence
    with rand_fasta(len_seq=len_seq, n_seq=1) as subject:
        pyfasta_gen = pyfasta.Fasta(subject.fasta_path, flatten_inplace=True)
        seq_record = pyfasta_gen["seq_0"]
        sequence = Sequence(name="seq_0", seq_record=seq_record)

        seq_dict = {}
        # Generate random hits from the subject
        for i in range(n_query):
            start = ri(1, len_seq - max_len_hit)
            end = start + ri(min_len_hit, max_len_hit)
            seq_dict["query_{}:{}-{}".format(i, start,
                                             end)] = str(seq_record[start:end])
        with defined_fasta(seq_dict) as query:

            # Create Blast DB and perform a blast to generate a list of hits
            with Blastn(subject.fasta_path) as blastn:
                hit_list = blastn(
                    query.fasta_path,
                    task="blastn",
                    best_query_hit=True,
                )

            yield (sequence, hit_list)
Example #14
0
def make_sequence(path):
    sequence = Sequence()

    pitch = 48
    position = 0
    duration = Sequence.TPB
    velocity = 100

    commands = read_commands_from_file(path)
    for command in commands:
        type, value = get_type_and_value(command)
        if type == ParameterType.PITCH:
            pitch = value
            sequence.add_note(pitch, position, duration, velocity)
            position += duration
        elif type == ParameterType.POSITION:
            position = value
        elif type == ParameterType.DURATION:
            duration = value
        elif type == ParameterType.VELOCITY:
            velocity = value
        elif type == ParameterType.BPM:
            bpm = value
            sequence.set_tempo(bpm)

    return sequence
Example #15
0
def chargerFichierSequence(nom_fichier):
    res = []  # Liste où seront stocké les séquences

    # Ouverture du fichier
    fichier = open(nom_fichier, 'r')

    nomSequence = ""  # Nom de la séquence
    debut = -1  # Index de début de séquence
    fin = -1  # Index de fin de séquence
    sequence = ""  # La séquence en elle-même

    # On lit chaque ligne du fichier
    for ligne in fichier:
        ligne = ligne.strip()  # Supprime les espaces inutiles
        if (ligne[0] == '>'):  # début d'une séquence

            if (sequence != ""):  # Si la séquence n'est pas vide
                # On enregistre
                res.append(Sequence(sequence, nomSequence, debut, fin))
                # On remet tout à zero
                nomSequence = ""
                debut = -1
                fin = -1
                sequence = ""

            # On extrait les informations
            infos = ligne.split('|')
            if (len(infos) == 3):
                nomSequence = infos[1]
                debutFin = infos[2].split("-")

                if (len(debutFin) == 2):
                    debut = debutFin[0]
                    fin = debutFin[1]

            else:  # Si on a pas toutes les informations on informe qu'il y a une erreur
                raise SyntaxError("Fichier invalide (debug ligne: %s )" %
                                  ligne)

        else:  # Suite d'une séquence
            sequence += ligne.strip()

    # On oublies pas la dernière séquence (qui n'a aucune autre séquence après elle)
    if (sequence != ""):
        res.append(Sequence(sequence, nomSequence, debut, fin))

    return res
Example #16
0
 def test_detect_when_sequence_has_infinite_subloop(self):
     s = Sequence.from_file(
         testpath + "/test_sequences/minimal_sequence_with_subloop.xml")
     s.resolve_references()
     tree = _Sequence_verification.Tree(sequence=s, control_values={})
     with self.assertRaises(InvalidSequenceException):
         tree.build()
     tree.visualize()
Example #17
0
 def FromAtoms(selfClass, atoms, bonds=None, withSequence=False):
     """Constructor given a list of atoms."""
     self = selfClass()
     self.__dict__["_atoms"] = AtomContainer.FromIterable(atoms)
     self.__dict__["_connectivity"] = Connectivity.FromAtomContainer(
         self.atoms, bonds=bonds)
     if withSequence:
         self.__dict__["_sequence"] = Sequence.FromAtomContainer(self.atoms)
     return self
Example #18
0
 def loadSequence(self):
     seq = Sequence(*self.get_sequence_init_args())
     
     for _,v in self.config['sequence channels'].items():
         channelArgs = map(lambda x,y:x(y), [int, lambda x: [eval(y) for y in x], lambda x: [int(y) for y in x]],
                              [v['chNum'],v['tV_pairs'],v['V_interval_styles']])
         seq.addChannelSeq(*channelArgs)
         
     return seq
    def plain(file_name):
        """

        :param file_name: data file name
        :return: Sequence object
        """
        with open(file_name) as f:
            string = ''.join([line.strip() for line in f.readlines()])
            return [Sequence(0, string)]
Example #20
0
def calculate_average_ngram_presence(coordinates, genome, ngram):
    ngram_presence = np.zeros(len(coordinates))
    ngram_reversed = Sequence.reverse_complement(ngram)
    for idx, c in enumerate(coordinates):
        seq = genome.extract_sequence(c)
        ngram_presence[idx] = (seq.count(ngram) +
                               seq.count(ngram_reversed)) / float(len(c))

    return ngram_presence
Example #21
0
 def test_detect_when_sequence_never_terminates_at_all(self):
     s = Sequence.from_file(
         testpath + "/test_sequences/minimal_sequence_with_loop.xml")
     s.resolve_references()
     tree = _Sequence_verification.Tree(sequence=s, control_values={})
     tree.build()
     tree.visualize()
     with self.assertRaises(InvalidSequenceException):
         tree.check()
Example #22
0
    def addBlock(self, block):
        self.nbOfBlocks += 1
        self.clusters = []
        for seq in block:
            self.clusters.append(Cluster([Sequence(seq)]))

        self.buildClusters()
        self.computeRandomModel()
        self.computeEvolutionaryModel()
Example #23
0
    def getDecision(self, current_frame):
        self.log.logMessage("DECISION #%d in GAME FRAME #%d" %
                            (self.actions_performed, self.game.world_counter))
        self.log.logMessage("TRAINED ON %d FRAMES" % (self.frames_trained))

        features = self.ae_network.encodeNumpyArray(current_frame.pixels)
        #self.log.logMessage("Current frame yields features: %s" % str(features))

        if self.previous_reward != 0:
            self.log.logMessage("GOT REWARD: %d" % self.previous_reward)
        self.total_score += self.previous_reward

        # First frame of game
        if self.actions_performed == 0:
            self.actions_performed += 1
            self.previous_seq = Sequence(features)
            # print("FRAME SEQUENCE: {0}".format(self.previous_seq))
            curr_action = self.pickRandomAction()
            self.previous_seq = self.previous_seq.createNewSequence(
                curr_action)
            self.previous_action = curr_action
            # print("FIRST SEQUENCE: {0}".format(self.previous_seq))
            return

        # Should I make a random move?
        r = random.random()

        # Add on the current frame to the current sequence
        self.current_seq = self.previous_seq.createNewSequence(features)

        if r > self.epsilon or self.actions_performed < 4:  #not self.current_seq.isFull():
            curr_action = self.pickRandomAction()
        else:
            # Run the CNN and pick the max output action
            curr_action = self.pickBestAction(self.current_seq)

        # Finally, add the chosen action to the current sequence
        self.current_seq = self.current_seq.createNewSequence(curr_action)

        # Actually perform the action in the game
        self.performAction(curr_action)

        new_experience = Experience(self.previous_seq, self.previous_action,
                                    self.previous_reward, self.current_seq)
        self.replay_memory.store(new_experience)
        self.previous_seq = self.current_seq

        if self.game.world_counter > STARTING_FRAMES and self.game.world_counter % BATCH_TRAINING_FREQUENCY == 0:
            self.trainMinibatch()

        # Remember the chosen Action since it will be required for the next iteration
        self.previous_action = curr_action

        if self.epsilon < MAX_EPSILON:
            self.epsilon *= EPSILON_UPDATE
            self.log.logMessage("UPDATED EPSILON: %.5f" % self.epsilon)
Example #24
0
 def addSequenceLocation(self, sequenceLocation):
     self.sequencesLocations.append(sequenceLocation)
     seq = Sequence.loadCSVSequence(sequenceLocation, self.fields,
                                    self.observationPeriod,
                                    self.predictionPeriod)
     self.sequences.append(seq)
     if seq.getLabel() not in self.sequencesClasses:
         self.sequencesClasses[seq.getLabel()] = []
     self.sequencesClasses[seq.getLabel()].append(sequenceLocation)
     self.classes[seq.getLabel()] += 1
Example #25
0
    def __init__ (self, name, fasta, compress=True):
        """
        Create a reference object extract fasta ref if needed and create a sequence object per
        sequences found in the fasta file
        @param name     Name of the Reference
        @param fasta    Path to a fasta file (can be gzipped)
        @param compress Fasta output will be gzipped if True
        """
        print(("Create {} object".format(name)))
        # Create self variables
        self.name = name
        self.temp_dir = mkdtemp()
        self.compress = compress

        # Create a name for the fasta file to be generated
        self.modified_fasta = "{}_masked.fa{}".format(self.name, ".gz" if self.compress else "")

        try:
            # Test values
            assert self.name not in self.REFERENCE_NAMES, "Reference name <{}> is duplicated".format(self.name)
            assert is_readable_file(fasta), "{} is not a valid file".format(fasta)

            # If gziped, ungzip the reference fasta file in the temporary folder. If not compress
            # copy in the temporary folder

            if is_gziped(fasta):
                print (" * Unzip fasta file in a temporary directory")
                self.fasta = gunzip(fasta, self.temp_dir)
            else:
                print (" * Copy fasta file in a temporary directory")
                self.fasta = cp(fasta, self.temp_dir)

            # Loading the fasta sequence in a pyfasta.Fasta (seq_record is a mapping)
            print (" * Parsing the file with pyfasta")
            seq_dict = {}
            fasta_record = pyfasta.Fasta(self.fasta, flatten_inplace=True)
            print((" * Found {} sequences in {}".format (len (fasta_record), self.name)))

            for name, seq_record in list(fasta_record.items()):

                # Remove additional sequence descriptor in fasta header and create a Sequence object
                short_name = name.partition(" ")[0]
                assert short_name not in seq_dict, "Reference name <{}> is duplicated in <{}>".format(short_name,self.name)
                seq_dict[short_name] = Sequence(name=short_name, seq_record=seq_record)

            # Save to a name sorted ordered dict
            self.seq_dict = OrderedDict(sorted(list(seq_dict.items()), key=lambda x: x))

            # Add name to a class list
            self.ADD_TO_REFERENCE_NAMES(self.name)

        except Exception as E:
            self.clean()
            raise E
Example #26
0
def parse_seq(lines):
    seq_name = parse_seq_name(lines)

    seq_length = int(lines[0].split('\t', 1)[0])

    seq = ""

    for i in range(1, seq_length + 1):
        seq += lines[i].split('\t', 2)[1]

    return Sequence(seq_name, 'RNA', seq)
Example #27
0
def read_files(sequences_path, attributes_path):
    # initialize structure to store sequence object
    orig_seq_storage = []

    # append ">END" flag to fasta file
    with open(sequences_path, 'a') as f:
        f.write("\n>END")

    # open fasta file to read
    seq_file = open(sequences_path, "r")

    # read each sequence from csv and fasta files
    with open(attributes_path, "r") as attributesFile:
        reader = csv.reader(attributesFile, delimiter=",")
        for i, line in enumerate(reader):

            # create new sequence
            new_sequence = Sequence()

            # define sequence variables
            new_sequence.accession = line[0]
            new_sequence.species = line[1]
            new_sequence.length = line[2]
            new_sequence.nuc_completeness = line[3]
            new_sequence.geo_location = line[4]
            new_sequence.us_state = line[5]
            new_sequence.isolation_source = line[6]
            new_sequence.collection_date = line[7]

            # extract DNA sequence
            curr_dna_seq = []
            iterator = True
            seq_line = seq_file.readline()

            while iterator:
                seq_line = seq_file.readline()
                if seq_line[0] == ">":
                    iterator = False
                else:
                    # store sequence from fasta file into object variable, stripping whitespace
                    curr_dna_seq.append(seq_line.strip())

            # join curr_dna_seq and store to object DNASeq
            new_sequence.dna_seq = ''.join(curr_dna_seq)
            curr_dna_seq.clear()

            # append sequence to sequence storage
            orig_seq_storage.append(new_sequence)

            # print data
            new_sequence.to_string()

    return orig_seq_storage
 def FASTA(file_name):
     with open(file_name) as f:
         lines = f.readlines()
     result = []
     for line in lines:
         line = line.strip()
         if len(line) == 0: continue
         if line[0] == ">":
             id = line.split()[0][1:]
             result.append(Sequence(id, ""))
         else:
             result[-1].sequence += line
     return result
Example #29
0
class Config:
    pace = 1

    terra_wave = Action('0', 4, cd_type.Attack, 'Terra Wave')
    intense_healing = Action('1', 1, cd_type.Healing, 'Intense Healing')
    ice_strike = Action('2', 2, cd_type.Attack, 'Ice Strike')
    ice_wave = Action('8', 4, cd_type.Attack, 'Ice Wave')
    mana_heal = Action('3', 1, cd_type.Nil, 'Mana Potion')
    avalanche = Action('4', 2, cd_type.Attack, 'Avalanche')
    # mas_san = Action('F5', 2, cd_type.Attack, 'Exevo Mas San')
    # rune_area = Action('F6', 2, cd_type.Healing, '')
    # strong_mana = Action('F4', 1, cd_type.Attack, '')
    # exura_gran_san = Action('F2', 1, cd_type.Attack, '')

    seq = Sequence([ice_strike, terra_wave, ice_strike, ice_wave])
    mana_pot_seq = Sequence([mana_heal])
    intense_healing_seq = Sequence([intense_healing])
    avalanche_sequence = Sequence([avalanche])
    # sec_pally_atk = Sequence([mas_san, rune_area])
    # sec_pally_mana = Sequence([mas_san, rune_area])
    # sec_pally_heal_mana = Sequence([mas_san, rune_area])

    # Druid
    macros = {'f1': seq, 'f2': intense_healing_seq, 'f3': avalanche_sequence}
Example #30
0
    def __init__(self, f, start, dur, bars):

        self.instr = f.makeInstrument()
        self.sco = ""
        sig = choice([4, 8, 12, 16])
        seq = Sequence(sig)
        bardur = dur / bars
        notedur = bardur / sig
        for b in range(bars + 1):
            for t in range(len(seq.beats)):
                if seq.beats[t] == 1:
                    istart = start + b * bardur + t * notedur
                    n = self.instr.makeNote(istart)
                    self.sco += str(n)
            seq.mutate(1)
Example #31
0
    def from_file(case_path):
        '''
        Parse a C file into test case.
        '''
        seq = Sequence('test_syscall')
        seed = 0
        code_parser = CodeParser()
        with open(case_path, 'r') as fd:
            for line in fd:
                if 'do_' in line:
                    cmd = code_parser.parse_command(line.strip())
                    seq.push(cmd)
                elif 'srand' in line:
                    seed = re.findall(r'srand\((\d+)\)', line)[0]

        return TestCase(case_path, seq, seed)
 def GenBank(file_name):
     with open(file_name) as f:
         lines = f.readlines()
     result = []
     state = 0  #0-looking for new sequence, 1 - looking for beginning of sequence, 2 - for end of seq
     states = ["LOCUS", "ORIGIN", "//"]
     for line in lines:
         line = line.strip()
         if len(line) == 0: continue
         if line.split()[0] != states[state]:
             if state == 2:
                 result[-1].sequence += ''.join(line.split()[1:]).upper()
             continue
         if state == 0:
             id = line.split()[1]
             result.append(Sequence(id, ""))
         state = (state + 1) % 3
     return result
Example #33
0
def LexBFS(G):
    """Find lexicographic breadth-first-search traversal order of a graph.
    G should be represented in such a way that "for v in G" loops through
    the vertices, and "G[v]" produces a sequence of the neighbors of v; for
    instance, G may be a dictionary mapping each vertex to its neighbor set.
    Running time is O(n+m) and additional space usage over G is O(n).
    """
    P = PartitionRefinement(G)
    S = Sequence(P, key=id)
    while S:
        set = S[0]
        v = arbitrary_item(set)
        yield v
        P.remove(v)
        if not set:
            S.remove(set)
        for new,old in P.refine(G[v]):
            S.insertBefore(old,new)
    def FASTQ(file_name):
        """

        :param file_name: data file name
        :return: list of Sequences
        """
        with open(file_name) as f:
            lines = f.readlines()
        result = []
        current_sequence = None
        current_line = 0
        for line in lines:
            line = line.strip()
            if len(line) == 0: continue
            if line[0] == "@":
                current_line = 0
                result.append(Sequence(line[1:], ""))
            if current_line == 1:
                result[-1].sequence = line
            current_line += 1
        return result
Example #35
0
    def _make_sequences(self, alglist, te_in):
        """Convert alglist objects to sequence objects"""

        te_out = self._make_teout_name(te_in, alglist.alias)

        new_sequence = Sequence(
            te_in,
            alglist.alg_list,
            alglist.alias,  # for debugging
            te_out)

        # _update_if_diagnostic_sequence(new_sequence)
        self.sequences.append(new_sequence)

        # having appended the new sequence to the sequence list,
        # the sequence to which it is connected is attached. This
        # will be found elsewhere in the alias table.
        # Note that this code is not protected against cycles - that
        # is if the inputs do not form a tree, this procedure could go
        # into an infinite loop.
        for c in self.alias_table[alglist.alias]:
            self._make_sequences(c, te_out)
Example #36
0
 def __setstate__(self, state):
     """Set the state of the object."""
     # . Sequence is present.
     if "sequence" in state:
         sequence = Sequence.FromMapping(state["sequence"])
         atoms = sequence.GatherAtoms()
         self.__dict__["_atoms"] = AtomContainer.FromIterable(
             atoms, attributes=state.get("atoms", None))
         self.__dict__["_sequence"] = sequence
     # . Sequence is absent.
     else:
         self.__dict__["_atoms"] = AtomContainer.FromMapping(state["atoms"])
     # . Connectivity.
     self.__dict__["_connectivity"] = Connectivity.FromAtomContainer(
         self.atoms,
         bonds=state.get("bonds", None),
         ringSets=state.get("ringSets", None))
     # . Other attributes.
     for key in self.__class__.defaultAttributes:
         label = key[1:]
         if label not in ("atoms", "connectivity", "sequence"):
             value = state.get(label, None)
             if value is not None: self.__dict__[key] = value
Example #37
0
def LexBFS(G):
    """Find lexicographic breadth-first-search traversal order of a graph.
    G should be represented in such a way that "for v in G" loops through
    the vertices, and "G[v]" produces a sequence of the neighbors of v; for
    instance, G may be a dictionary mapping each vertex to its neighbor set.
    Running time is O(n+m) and additional space usage over G is O(n).
    """
    P = PartitionRefinement(G)  #một phân vùng chứa đồ thị (lọc phân vùng)
    S = Sequence(P,
                 key=id)  #một dãy, chuỗi bao gồm các giá trị vừa lọc, thêm id
    sigma = []  #mảng sigma
    while S:  #vòng lặp while đầu vào là một chuỗi
        set = S[0]  #gọi set là giá trị đầu tiên của mảng, S[0]
        v = arbitrary_item(set)  #v là 1 giá trị tùy ý

        sigma.append(v)  #nối thêm giá trị của v vào sigma

        P.remove(v)  #đồng thời remode giá trị đó ra khỏi phân vùng P
        if not set:  #thay đổi điều kiện cho đến khi nó thỏa mãn
            S.remove(set)
        for new, old in P.refine(G.neighbors(v)):
            S.insertBefore(old, new)
    return sigma
Example #38
0
	def __init__(self):
		speed = 0.083
		Sequence.__init__(
			self, [
				Row(speed, [1,0,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [0,1,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [0,0,1,0,0,0,0,0,0,0,0,0]),
				Row(speed, [0,0,0,1,0,0,0,0,0,0,0,0]),
				Row(speed, [0,0,0,0,1,0,0,0,0,0,0,0]),
				Row(speed, [0,0,0,0,0,1,0,0,0,0,0,0]),
				Row(speed, [0,0,0,0,0,0,1,0,0,0,0,0]),
				Row(speed, [0,0,0,0,0,0,0,1,0,0,0,0]),
				Row(speed, [0,0,0,0,0,0,0,0,1,0,0,0]),
				Row(speed, [0,0,0,0,0,0,0,0,0,1,0,0]),
				Row(speed, [0,0,0,0,0,0,0,0,0,0,1,0]),
				Row(speed, [0,0,0,0,0,0,0,0,0,0,0,1]),

				Row(speed, [1,0,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,1,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,0,1,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,0,0,1,0,0,0,0,0,0,0,0]),
				Row(speed, [1,0,0,0,1,0,0,0,0,0,0,0]),
				Row(speed, [1,0,0,0,0,1,0,0,0,0,0,0]),
				Row(speed, [1,0,0,0,0,0,1,0,0,0,0,0]),
				Row(speed, [1,0,0,0,0,0,0,1,0,0,0,0]),
				Row(speed, [1,0,0,0,0,0,0,0,1,0,0,0]),
				Row(speed, [1,0,0,0,0,0,0,0,0,1,0,0]),
				Row(speed, [1,0,0,0,0,0,0,0,0,0,1,0]),
				Row(speed, [1,0,0,0,0,0,0,0,0,0,0,1]),
				
				Row(speed, [0,1,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,0,0,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,1,1,0,0,0,0,0,0,0,0,0]),
				Row(speed, [1,1,0,1,0,0,0,0,0,0,0,0]),
				Row(speed, [1,1,0,0,1,0,0,0,0,0,0,0]),
				Row(speed, [1,1,0,0,0,1,0,0,0,0,0,0]),
				Row(speed, [1,1,0,0,0,0,1,0,0,0,0,0]),
				Row(speed, [1,1,0,0,0,0,0,1,0,0,0,0]),
				Row(speed, [1,1,0,0,0,0,0,0,1,0,0,0]),
				Row(speed, [1,1,0,0,0,0,0,0,0,1,0,0]),
				Row(speed, [1,1,0,0,0,0,0,0,0,0,1,0]),
				Row(speed, [1,1,0,0,0,0,0,0,0,0,0,1]),

                                Row(speed, [0,1,1,0,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,0,1,0,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,0,0,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,0,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,0,0,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,0,0,0,1,0,0,0,0]),
                                Row(speed, [1,1,1,0,0,0,0,0,1,0,0,0]),
                                Row(speed, [1,1,1,0,0,0,0,0,0,1,0,0]),
                                Row(speed, [1,1,1,0,0,0,0,0,0,0,1,0]),
                                Row(speed, [1,1,1,0,0,0,0,0,0,0,0,1]),

                                Row(speed, [0,1,1,1,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,0,1,1,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,0,1,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,1,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,0,1,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,0,0,1,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,0,0,0,1]),

                                Row(speed, [0,1,1,1,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,0,1,1,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,0,1,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,0,1,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,0,0,1,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,0,0,0,1]),

                                Row(speed, [0,1,1,1,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,0,1,1,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,0,1,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,0,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,0,0,1,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,0,0,0,1]),

                                Row(speed, [0,1,1,1,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,0,1,1,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,0,1,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,0,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,0,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,0,0,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,0,0,0,1]),

                                Row(speed, [0,1,1,1,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,0,1,1,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,0,1,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,0,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,0,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,0,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,0,0,1]),

                                Row(speed, [0,1,1,1,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,0,1,1,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,0,1,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,0,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,0,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,0,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,0,1]),

                                Row(speed, [0,1,1,1,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,0,1,1,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,0,1,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,0,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,0,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,0,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,0,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,0,1]),

                                Row(speed, [0,1,1,1,1,1,1,1,1,1,1,0]),
                                Row(speed, [1,0,1,1,1,1,1,1,1,1,1,0]),
                                Row(speed, [1,1,0,1,1,1,1,1,1,1,1,0]),
                                Row(speed, [1,1,1,0,1,1,1,1,1,1,1,0]),
                                Row(speed, [1,1,1,1,0,1,1,1,1,1,1,0]),
                                Row(speed, [1,1,1,1,1,0,1,1,1,1,1,0]),
                                Row(speed, [1,1,1,1,1,1,0,1,1,1,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,0,1,1,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,1,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,1,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,0,0]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,1,1]),

                                Row(speed, [0,1,1,1,1,1,1,1,1,1,1,1]),
                                Row(speed, [1,0,1,1,1,1,1,1,1,1,1,1]),
                                Row(speed, [1,1,0,1,1,1,1,1,1,1,1,1]),
                                Row(speed, [1,1,1,0,1,1,1,1,1,1,1,1]),
                                Row(speed, [1,1,1,1,0,1,1,1,1,1,1,1]),
                                Row(speed, [1,1,1,1,1,0,1,1,1,1,1,1]),
                                Row(speed, [1,1,1,1,1,1,0,1,1,1,1,1]),
                                Row(speed, [1,1,1,1,1,1,1,0,1,1,1,1]),
                                Row(speed, [1,1,1,1,1,1,1,1,0,1,1,1]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,0,1,1]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,0,1]),
                                Row(speed, [1,1,1,1,1,1,1,1,1,1,1,0]),

                        ]
                )
Example #39
0
	def __init__(self):		
		kitt = Kitt()
		Sequence.__init__(self, kitt.getRows())