text
stringlengths
81
112k
Inject the request user into the kwargs passed to the form def get_form_kwargs(self): """ Inject the request user into the kwargs passed to the form """ kwargs = super(AddUpdateMixin, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs
Returns the object the view is displaying. def get_object(self, queryset=None): """ Returns the object the view is displaying. """ if queryset is None: queryset = self.get_queryset() try: return queryset.get(user__pk=self.request.user.pk) except ...
For use with user_passes_test decorator. Check if the user can manage groups. Either has the auth.group_management permission or is a leader of at least one group and is also a Member. :param user: django.contrib.auth.models.User for the request :return: bool True if user can man...
Check user has permission to manage the given group :param user: User object to test permission of :param group: Group object the user is attempting to manage :return: True if the user can manage the group def can_manage_group(cls, user, group): """ Check user has permission to ...
Creates the AuthGroup model when a group is created def create_auth_group(sender, instance, created, **kwargs): """ Creates the AuthGroup model when a group is created """ if created: AuthGroup.objects.create(group=instance)
Constructs a TS3 formatted command string Keys can have a single nested list to construct a nested parameter @param command: Command list @type command: string @param keys: Key/Value pairs @type keys: dict @param opts: Options @type opts: list def construct_comma...
Parses a TS3 command string into command/keys/opts tuple @param commandstr: Command string @type commandstr: string def parse_command(self, commandstr): """ Parses a TS3 command string into command/keys/opts tuple @param commandstr: Command string @type commandstr: strin...
Escape a value into a TS3 compatible string @param value: Value @type value: string/int def _escape_str(value): """ Escape a value into a TS3 compatible string @param value: Value @type value: string/int """ if isinstance(value, int): return ...
Unescape a TS3 compatible string into a normal string @param value: Value @type value: string/int def _unescape_str(value): """ Unescape a TS3 compatible string into a normal string @param value: Value @type value: string/int """ if isinstance(value, int...
Login to the TS3 Server @param username: Username @type username: str @param password: Password @type password: str def login(self, username, password): """ Login to the TS3 Server @param username: Username @type username: str @param password: Pas...
Use a particular Virtual Server instance @param id: Virtual Server ID @type id: int def use(self, id): """ Use a particular Virtual Server instance @param id: Virtual Server ID @type id: int """ if self._connected and id > 0: self.send_command...
Example for rendering the service control panel row You can override the default template and create a custom one if you wish. :param request: :return: def render_services_ctrl(self, request): """ Example for rendering the service control panel row You can overri...
Pseudo foreign key from alliance_id to EveAllianceInfo :raises: EveAllianceInfo.DoesNotExist :return: EveAllianceInfo or None def alliance(self) -> Union[EveAllianceInfo, None]: """ Pseudo foreign key from alliance_id to EveAllianceInfo :raises: EveAllianceInfo.DoesNotExist ...
Checks if enable was toggled on group config and deletes groups if necessary. def pre_save_config(sender, instance, *args, **kwargs): """ Checks if enable was toggled on group config and deletes groups if necessary. """ logger.debug("Received pre_save from {}".format(instance)) if not insta...
Trigger check when main character or state changes. def check_groups_on_profile_update(sender, instance, created, *args, **kwargs): """ Trigger check when main character or state changes. """ AutogroupsConfig.objects.update_groups_for_user(instance.user)
Trigger group membership update when a state is added or removed from an autogroup config. def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs): """ Trigger group membership update when a state is added or removed from an autogroup config. """ if acti...
Make a admin action for the given service :param service: services.hooks.ServicesHook :return: fn to update services groups for the selected users def make_service_hooks_update_groups_action(service): """ Make a admin action for the given service :param service: services.hooks.ServicesHook :ret...
Make a sync_nickname admin action for the given service :param service: services.hooks.ServicesHook :return: fn to sync nickname for the selected users def make_service_hooks_sync_nickname_action(service): """ Make a sync_nickname admin action for the given service :param service: services.hooks.Se...
{% renavactive request "^/a_regex" %} def renavactive(request, pattern): """ {% renavactive request "^/a_regex" %} """ if re.search(pattern, request.path): return getattr(settings, "NAVHELPER_ACTIVE_CLASS", "active") return getattr(settings, "NAVHELPER_NOT_ACTIVE_CLASS", "")
{% navactive request "view_name another_view_name" %} def navactive(request, urls): """ {% navactive request "view_name another_view_name" %} """ url_list = set(urls.split()) resolved = resolve(request.path) resolved_urls = set() if resolved.url_name: resolved_urls.add(resolved.url...
Update all the Group memberships for the users who have State :param state: State to update for :return: def update_groups_for_state(self, state: State): """ Update all the Group memberships for the users who have State :param state: State to update for :...
Update the Group memberships for the given users state :param user: User to update for :param state: State to update user for :return: def update_groups_for_user(self, user: User, state: State = None): """ Update the Group memberships for the given users state :param use...
Replace the spaces in the given name based on the config :param name: name to replace spaces in :return: name with spaces replaced with the configured character(s) or unchanged if configured def _replace_spaces(self, name: str) -> str: """ Replace the spaces in the given name based on t...
Decorator, Handles HTTP 429 "Too Many Requests" messages from the Discord API If blocking=True is specified, this function will block and retry the function up to max_retries=n times, or 3 if retries is not specified. If the API call still recieves a backoff timer this function will raise a <DiscordApiT...
Returns a random string of length string_length. def random_string(string_length=10): """Returns a random string of length string_length.""" random = str(uuid.uuid4()) # Convert UUID format to a Python string. random = random.upper() # Make all characters uppercase. random = random.replace("-", "") ...
Return the names of all imported genomes def getGenomeList() : """Return the names of all imported genomes""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(Genome_Raba) names = [] for g in f.iterRun() : names.append(g.name) return names
iterates through the codons def iterCodons(self) : """iterates through the codons""" for i in range(len(self.cDNA)/3) : yield self.getCodon(i)
removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName def removeDuplicates(inFileName, outFileName) : """removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName'""" f = open(inFileName) legend = f.readline() data = '' h = {} h[legend...
Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems def catCSVs(folder, ouputFileName, removeDups = False) : """Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems""" strCmd = r"""cat %s/*.csv > %s""" %(fold...
csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName' def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') : """csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. ...
add a filed to the legend def addField(self, field) : """add a filed to the legend""" if field.lower() in self.legend : raise ValueError("%s is already in the legend" % field.lower()) self.legend[field.lower()] = len(self.legend) if len(self.strLegend) > 0 : self.strLegend += self.separator + field el...
Loads a CSV file def parse(self, filePath, skipLines=0, separator = ',', stringSeparator = '"', lineSeparator = '\n') : """Loads a CSV file""" self.filename = filePath f = open(filePath) if lineSeparator == '\n' : lines = f.readlines() else : lines = f.read().split(lineSeparator) f.flush() f.clo...
Starts a stream to a file. Every line must be committed (l.commit()) to be appended in to the file. If keepInMemory is set to True, the parser will keep a version of the whole CSV in memory, writeRate is the number of lines that must be committed before an automatic save is triggered. def streamToFile(self, filen...
Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError def commitLine(self, line) : """Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError""" ...
Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError def closeStreamToFile(self) : """Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is onl...
Appends an empty line at the end of the CSV and returns it def newLine(self) : """Appends an empty line at the end of the CSV and returns it""" l = CSVEntry(self) if self.keepInMemory : self.lines.append(l) return l
Inserts an empty line at position i and returns it def insertLine(self, i) : """Inserts an empty line at position i and returns it""" self.data.insert(i, CSVEntry(self)) return self.lines[i]
save the CSV to a file def save(self, filePath) : """save the CSV to a file""" self.filename = filePath f = open(filePath, 'w') f.write(self.toStr()) f.flush() f.close()
returns a string version of the CSV def toStr(self) : """returns a string version of the CSV""" s = [self.strLegend] for l in self.lines : s.append(l.toStr()) return self.lineSeparator.join(s)
Returns the number of elements satisfying the query def count(self, objectType, *args, **coolArgs) : """Returns the number of elements satisfying the query""" return self._makeLoadQuery(objectType, *args, **coolArgs).count()
Raba Magic inside. This is th function that you use for querying pyGeno's DB. Usage examples: * myGenome.get("Gene", name = 'TPST2') * myGene.get(Protein, id = 'ENSID...') * myGenome.get(Transcript, {'start >' : x, 'end <' : y}) def get(self, objectType, *args, **coolArgs) : """Raba Magic i...
Same as get. But retuns the elements one by one, much more efficient for large outputs def iterGet(self, objectType, *args, **coolArgs) : """Same as get. But retuns the elements one by one, much more efficient for large outputs""" for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() : if issub...
The big wrapper, this function should detect the SNP type by the package manifest and then launch the corresponding function. Here's an example of a SNP manifest file for Casava SNPs:: [package_infos] description = Casava SNPs for testing purposes maintainer = Tariq Daouda maintainer_contact = tariq.daouda [a...
deletes a set of polymorphisms def deleteSNPs(setName) : """deletes a set of polymorphisms""" con = conf.db try : SMaster = SNPMaster(setName = setName) con.beginTransaction() SNPType = SMaster.SNPType con.delete(SNPType, 'setName = ?', (setName,)) SMaster.delete() con.endTransaction() except KeyError ...
This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno wil interpret all positions as 0 based def _importSNPs_AgnosticSNP(setName, species, genomeSource, snpsFile) : "This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno wil interpret all ...
This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based def _importSNPs_CasavaSNP(setName, species, genomeSource, snpsFile) : "This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based" printf('impor...
This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based def _importSNPs_dbSNPSNP(setName, species, genomeSource, snpsFile) : "This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based" snpData = VCFF...
Return the names of all imported snp sets def getSNPSetsList() : """Return the names of all imported snp sets""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(SNPMaster) names = [] for g in f.iterRun() : names.append(g.setName) return names
print + sys.stdout.flush() def printf(*s) : 'print + sys.stdout.flush()' for e in s[:-1] : print e, print s[-1] sys.stdout.flush()
Discrete Kullback-Leibler divergence D(P||Q) def kullback_leibler(p, q) : """Discrete Kullback-Leibler divergence D(P||Q)""" p = np.asarray(p, dtype=np.float) q = np.asarray(q, dtype=np.float) if p.shape != q.shape : raise ValueError("p and q must be of the same dimensions") return np.sum(np.where(p > 0, np....
Opens a file and parses it def parseFile(self, fil) : """Opens a file and parses it""" f = open(fil) self.parseStr(f.read()) f.close()
appends a new entry to the file def add(self, header, data) : """appends a new entry to the file""" if header[0] != '>' : self.data.append(('>'+header, data)) else : self.data.append((header, data))
returns a list of all occurances of needle in haystack def findAll(haystack, needle) : """returns a list of all occurances of needle in haystack""" h = haystack res = [] f = haystack.find(needle) offset = 0 while (f >= 0) : #print h, needle, f, offset res.append(f+offset) offset += f+len(needle) h = h[...
returns a list of complementary sequence without inversing it def complementTab(seq=[]): """returns a list of complementary sequence without inversing it""" complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M', 'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H...
returns 6 translation of sequence. One for each reading frame def translateDNA_6Frames(sequence) : """returns 6 translation of sequence. One for each reading frame""" trans = ( translateDNA(sequence, 'f1'), translateDNA(sequence, 'f2'), translateDNA(sequence, 'f3'), translateDNA(sequence, 'r1'), ...
Translates DNA code, frame : fwd1, fwd2, fwd3, rev1, rev2, rev3 def translateDNA(sequence, frame = 'f1', translTable_id='default') : """Translates DNA code, frame : fwd1, fwd2, fwd3, rev1, rev2, rev3""" protein = "" if frame == 'f1' : dna = sequence elif frame == 'f2': dna = sequence[1:] elif frame == 'f3' ...
Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) : """Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield""" if type(polymorphipolymorphicDnaSeqSeq) is ...
returns a single character encoding all nucletides of polySeq in a single character. PolySeq must have one of the following forms: ['A', 'T', 'G'], 'ATG', 'A/T/G def encodePolymorphicNucleotide(polySeq) : """returns a single character encoding all nucletides of polySeq in a single character. PolySeq must have o...
the opposite of encodePolymorphicNucleotide, from 'R' to ['A', 'G'] def decodePolymorphicNucleotide(nuc) : """the opposite of encodePolymorphicNucleotide, from 'R' to ['A', 'G']""" if nuc in polymorphicNucleotides : return polymorphicNucleotides[nuc] if nuc in nucleotides : return nuc raise ValueError('nuc: ...
Returns the entire codon of the nucleotide at pos x1 in sequence, and the position of that nocleotide in the codon in a tuple def getNucleotideCodon(sequence, x1) : """Returns the entire codon of the nucleotide at pos x1 in sequence, and the position of that nocleotide in the codon in a tuple""" if x1 < 0 or x1...
Returns a string highligthing differences between seq1 and seq2: * Matches by '-' * Differences : 'A|T' * Exceeded length : '#' def showDifferences(seq1, seq2) : """Returns a string highligthing differences between seq1 and seq2: * Matches by '-' * Differences : 'A|T' * Exceeded length : '#' """ ...
returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') : """returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop'""" seq = list(sequence) print x1, x2-1, len(seq) seq...
backup the current database version. automatically called by importGenome(). Returns the filename of the backup def backUpDB() : """backup the current database version. automatically called by importGenome(). Returns the filename of the backup""" st = time.ctime().replace(' ', '_') fn = conf.pyGeno_RABA_DB...
Removes a genome from the database def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = True try : genome = Genome_Raba(name = name, species = species.lower()) ...
Import a pyGeno genome package. A genome packages is folder or a tar.gz ball that contains at it's root: * gziped fasta files for all chromosomes, or URLs from where them must be downloaded * gziped GTF gene_set file from Ensembl, or an URL from where it must be downloaded * a manifest.ini file s...
verbose must be an int [0, 4] for various levels of verbosity def _importGenomeObjects(gtfFilePath, chroSet, genome, batchSize, verbose = 0) : """verbose must be an int [0, 4] for various levels of verbosity""" class Store(object) : def __init__(self, conf) : self.conf = conf ...
Serializes fastas into .dat files def _importSequence(chromosome, fastaFile, targetDir) : "Serializes fastas into .dat files" f = gzip.open(fastaFile) header = f.readline() strRes = f.read().upper().replace('\n', '').replace('\r', '') f.close() fn = '%s/chromosome%s.dat' % (targetDir, chromos...
Creates a default configuration file def createDefaultConfigFile() : """Creates a default configuration file""" s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION) f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w') f.write(s) f.close()
Returns the path where the settings are stored def getSettingsPath() : """Returns the path where the settings are stored""" parser = SafeConfigParser() try : parser.read(os.path.normpath(pyGeno_SETTINGS_DIR+'/config.ini')) return parser.get('pyGeno_config', 'settings_dir') except : createDefaultConfigFile() ...
This function is automatically called at launch def pyGeno_init() : """This function is automatically called at launch""" global db, dbConf global pyGeno_SETTINGS_PATH global pyGeno_RABA_DBFILE global pyGeno_DATA_PATH if not checkPythonVersion() : raise PythonVersionError("==> FATAL: pyGeno only works wi...
Returns a plucked object. Plucks the exon off the tree, set the value of self.transcript into str(self.transcript). This effectively disconnects the object and makes it much more lighter in case you'd like to pickle it def pluck(self) : """Returns a plucked object. Plucks the exon off the tree, set the value of se...
Returns the previous exon of the transcript, or None if there is none def previousExon(self) : """Returns the previous exon of the transcript, or None if there is none""" if self.number == 0 : return None try : return self.transcript.exons[self.number-1] except IndexError : return None
Parses a string def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
returns the ith entry def get(self, li) : """returns the ith entry""" i = li*4 self.__splitEntry(i) return self.data[i]
Appends an empty entry at the end of the CSV and returns it def newEntry(self, ident = "", seq = "", plus = "", qual = "") : """Appends an empty entry at the end of the CSV and returns it""" e = FastqEntry() self.data.append(e) return e
Lists all the datawraps availabe from a remote a remote location. def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """Lists all the datawraps availabe from a remote a remote location.""" loc = location + "/datawraps.json" response = urllib2.urlopen(loc) js = json.loads(response.read()) return j...
print all available datawraps from a remote location the location must have a datawraps.json in the following format:: { "Ordered": { "Reference genomes": { "Human" : ["GRCh37.75", "GRCh38.78"], "Mouse" : ["GRCm38.78"], }, "SNPs":{ } }, "Flat":{ "Reference genomes": { "G...
Import a genome available from http://pygeno.iric.ca (might work). def importRemoteGenome(name, batchSize = 100) : """Import a genome available from http://pygeno.iric.ca (might work).""" try : dw = listRemoteDatawraps()["Flat"]["Reference genomes"][name] except AttributeError : raise AttributeError("There's no...
Import a SNP set available from http://pygeno.iric.ca (might work). def importRemoteSNPs(name) : """Import a SNP set available from http://pygeno.iric.ca (might work).""" try : dw = listRemoteDatawraps()["Flat"]["SNPs"] except AttributeError : raise AttributeError("There's no remote genome datawrap by the name ...
Lists all the datawraps pyGeno comes with def listDatawraps() : """Lists all the datawraps pyGeno comes with""" l = {"Genomes" : [], "SNPs" : []} for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) : if f.find(".tar.gz") > -1 : l["Genomes"].append(f) for f in os.listdir(os.path.join(this_d...
print all available datawraps for bootstraping def printDatawraps() : """print all available datawraps for bootstraping""" l = listDatawraps() printf("Available datawraps for boostraping\n") for k, v in l.iteritems() : printf(k) printf("~"*len(k) + "|") for vv in v : printf(" "*len(k) + "|" + "~~~:> " + v...
Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. def importGenome(name, batchSize = 100) : """Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "boot...
Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. def importSNPs(name) : """Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "SNP...
logs stats about the progression, without printing anything on screen def log(self) : """logs stats about the progression, without printing anything on screen""" self.logs['epochDuration'].append(self.lastEpochDuration) self.logs['avg'].append(self.avg) self.logs['runtime'].append(self.runtime) self.logs[...
dumps logs into a nice pickle def saveLogs(self, filename) : """dumps logs into a nice pickle""" f = open(filename, 'wb') cPickle.dump(self.logs, f) f.close()
the function to be called at each iteration. Setting log = True is the same as calling log() just after update() def update(self, label = '', forceRefresh = False, log = False) : """the function to be called at each iteration. Setting log = True is the same as calling log() just after update()""" self.currEpoch +=...
The default filter mixes applied all SNPs and ignores Insertions and Deletions. def filter(self, chromosome, **kwargs) : """The default filter mixes applied all SNPs and ignores Insertions and Deletions.""" def appendAllele(alleles, sources, snp) : pos = snp.start if snp.alt[0] == '-' : pass # print ...
This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree. def aux_insertTree(childTree, parentTree): """This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree.""" if childTree.x1 != None and childTree.x2 != ...
This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1 def aux_moveTree(offset, tree): """This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1""" if tree.x1 != None and tree.x2 != None ...
Insert the segment in it's right place and returns it. If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the referedObject will be appended to the already existing list def insert(self, x1, x2, name = '', referedObject = []) : """Insert the segment in it'...
Returns a list of all segments intersected by [x1, x2] def intersect(self, x1, x2 = None) : """Returns a list of all segments intersected by [x1, x2]""" def condition(x1, x2, tree) : #print self.id, tree.x1, tree.x2, x1, x2 if (tree.x1 != None and tree.x2 != None) and (tree.x1 <= x1 and x1 < tree.x2 or tr...
Radiates down: walks self.children downward until condition is no longer verifed or there's no childrens left def __radiateDown(self, x1, x2, childId, condition) : "Radiates down: walks self.children downward until condition is no longer verifed or there's no childrens left " ret = [] i = childId while 0 <= i ...
Radiates uo: walks self.children upward until condition is no longer verifed or there's no childrens left def __radiateUp(self, x1, x2, childId, condition) : "Radiates uo: walks self.children upward until condition is no longer verifed or there's no childrens left " ret = [] i = childId while i < len(self.chil...
Remove all gaps between regions def removeGaps(self) : """Remove all gaps between regions""" for i in range(1, len(self.children)) : if self.children[i].x1 > self.children[i-1].x2: aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i])
Returns the total length of indexed regions def getIndexedLength(self) : """Returns the total length of indexed regions""" if self.x1 != None and self.x2 != None: return self.x2 - self.x1 else : if len(self.children) == 0 : return 0 else : l = self.children[0].x2 - self.children[0].x1 for i ...
returns a list of couples (x1, x2) of all the first level indexed regions def getFirstLevel(self) : """returns a list of couples (x1, x2) of all the first level indexed regions""" res = [] if len(self.children) > 0 : for c in self.children: res.append((c.x1, c.x2)) else : if self.x1 != None : re...
Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together def flatten(self) : """Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together""" if len(self.children) > 1 : children = self.children self.emptyChildren()...
Moves tree to a new starting position, updates x1s of children def move(self, newX1) : """Moves tree to a new starting position, updates x1s of children""" if self.x1 != None and self.x2 != None : offset = newX1-self.x1 aux_moveTree(offset, self) elif len(self.children) > 0 : offset = newX1-self.childre...
Returns a tuple (binary reprensentation, default sequence, polymorphisms list) def encode(self, sequence): """Returns a tuple (binary reprensentation, default sequence, polymorphisms list)""" polymorphisms = [] defaultSequence = '' binSequence = array.array(self.forma.typecode) b = 0 i = 0 trueI = 0 ...
Compares strSeq with self.sequence. If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence def findPolymorphisms(self, strSeq, strict = False): """ ...