INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Dispatches an event to any subscribed listeners
def emit(self, name, *args, **kwargs): """Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :clas...
Retrieves an Event object by name
def get_dispatcher_event(self, name): """Retrieves an Event object by name Args: name (str): The name of the :class:`Event` or :class:`~pydispatch.properties.Property` object to retrieve Returns: The :class:`Event` instance for the event or property defi...
Holds emission of events and dispatches the last event on release
def emission_lock(self, name): """Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: ...
Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later
def TEST(fname): """ Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later """ #fname = os.path.join(os.getcwd(), '..','..', # os.path.join(os.path.getcwd(), ' m = MapObject(fname, os.p...
describes various contents of data table
def describe_contents(self): """ describes various contents of data table """ print('======================================================================') print(self) print('Table = ', str(len(self.header)) + ' cols x ' + str(len(self.arr)) + ' rows') print('HEADER = ', self...
returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case.
def get_distinct_values_from_cols(self, l_col_list): """ returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case. ...
selects rows from the array where col_list == val_list
def select_where(self, where_col_list, where_value_list, col_name=''): """ selects rows from the array where col_list == val_list """ res = [] # list of rows to be returned col_ids = [] # ids of the columns to check #print('select_where : arr = ', len(self.ar...
updates the array to set cell = value where col_list == val_list
def update_where(self, col, value, where_col_list, where_value_list): """ updates the array to set cell = value where col_list == val_list """ if type(col) is str: col_ndx = self.get_col_by_name(col) else: col_ndx = col #print('col_ndx = ', col_nd...
calculates the percentiles of col_name WHERE [ where_col_list ] = [ where_value_list ]
def calc_percentiles(self, col_name, where_col_list, where_value_list): """ calculates the percentiles of col_name WHERE [where_col_list] = [where_value_list] """ #col_data = self.get_col_data_by_name(col_name) col_data = self.select_where(where_col_list, where_value_li...
calculates the num percentile of the items in the list
def percentile(self, lst_data, percent , key=lambda x:x): """ calculates the 'num' percentile of the items in the list """ new_list = sorted(lst_data) #print('new list = ' , new_list) #n = float(len(lst_data)) k = (len(new_list)-1) * percent f = math.floor(k) c = ...
default is to save a file from list of lines
def save(self, filename, content): """ default is to save a file from list of lines """ with open(filename, "w") as f: if hasattr(content, '__iter__'): f.write('\n'.join([row for row in content])) else: print('WRINGI CONTWETESWREWR'...
save the default array as a CSV file
def save_csv(self, filename, write_header_separately=True): """ save the default array as a CSV file """ txt = '' #print("SAVING arr = ", self.arr) with open(filename, "w") as f: if write_header_separately: f.write(','.join([c for c in...
drop the table view or delete the file
def drop(self, fname): """ drop the table, view or delete the file """ if self.dataset_type == 'file': import os try: os.remove(fname) except Exception as ex: print('cant drop file "' + fname + '" : ' + str(ex))
returns the values of col_name according to where
def get_col_data_by_name(self, col_name, WHERE_Clause=''): """ returns the values of col_name according to where """ #print('get_col_data_by_name: col_name = ', col_name, ' WHERE = ', WHERE_Clause) col_key = self.get_col_by_name(col_name) if col_key is None: print('get_col_da...
return table in RST format
def format_rst(self): """ return table in RST format """ res = '' num_cols = len(self.header) col_width = 25 for _ in range(num_cols): res += ''.join(['=' for _ in range(col_width - 1)]) + ' ' res += '\n' for c in self.header: ...
Read perseus network collection folder format >>> network_table networks = read_networks ( folder ): param folder: Path to network collection: returns: Network table and dictionary with name edge_table and node_table keys.
def read_networks(folder): """ Read perseus network collection folder format >>> network_table, networks = read_networks(folder) :param folder: Path to network collection :returns: Network table and dictionary with 'name', 'edge_table', and 'node_table' keys. """ network_table = re...
Create networkx graph from network tables >>> from perseuspy import read_networks nx >>> network_table networks = read_networks ( folder ) >>> graphs = nx. from_perseus ( network_table networks )
def from_perseus(network_table, networks): """ Create networkx graph from network tables >>> from perseuspy import read_networks, nx >>> network_table, networks = read_networks(folder) >>> graphs = nx.from_perseus(network_table, networks) """ graphs = [] for guid, graph_attr in zip(...
Create a network table and the network dictionary for export to Perseus.: param graphs: Collection of networkx graphs
def to_perseus(graphs): """ Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks = nx.to_perseus([G]) """ ...
Writing networkTable nodes and edges to Perseus readable format.: param folder: Path to output directory.: param network_table: Network table.: param networks: Dictionary with node and edge tables indexed by network guid.
def write_networks(folder, network_table, networks): """ Writing networkTable, nodes and edges to Perseus readable format. :param folder: Path to output directory. :param network_table: Network table. :param networks: Dictionary with node and edge tables, indexed by network guid. """ ma...
Returns NBCI s Homolog Gene tables.
def getHomoloGene(taxfile="build_inputs/taxid_taxname",\ genefile="homologene.data",\ proteinsfile="build_inputs/all_proteins.data",\ proteinsclusterfile="build_inputs/proteins_for_clustering.data",\ baseURL="http://ftp.ncbi.nih.gov/pub/HomoloGene/...
Retrieves a sequence from an opened multifasta file
def getFasta(opened_file, sequence_name): """ Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1...
Writes a fasta sequence into a file.
def writeFasta(sequence, sequence_name, output_file): """ Writes a fasta sequence into a file. :param sequence: a string with the sequence to be written :param sequence_name: name of the the fasta sequence :param output_file: /path/to/file.fa to be written :returns: nothing """ i=0 ...
Rewrites a specific sequence in a multifasta file while keeping the sequence header.
def rewriteFasta(sequence, sequence_name, fasta_in, fasta_out): """ Rewrites a specific sequence in a multifasta file while keeping the sequence header. :param sequence: a string with the sequence to be written :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome ch...
get a string representation of the tool
def _get_tool_str(self, tool): """ get a string representation of the tool """ res = tool['file'] try: res += '.' + tool['function'] except Exception as ex: print('Warning - no function defined for tool ' + str(tool)) res += '\n' r...
get the tool object by name or file
def get_tool_by_name(self, nme): """ get the tool object by name or file """ for t in self.lstTools: if 'name' in t: if t['name'] == nme: return t if 'file' in t: if t['file'] == nme: return t...
Adds a Tool to the list logs the reference and TODO
def add(self, tool): """ Adds a Tool to the list, logs the reference and TODO """ self.lstTools.append(tool) self.lg.record_process(self._get_tool_str(tool))
Save the list of tools to AIKIF core and optionally to local file fname
def save(self, fname=''): """ Save the list of tools to AIKIF core and optionally to local file fname """ if fname != '': with open(fname, 'w') as f: for t in self.lstTools: self.verify(t) f.write(self.tool_as_string(t))
check that the tool exists
def verify(self, tool): """ check that the tool exists """ if os.path.isfile(tool['file']): print('Toolbox: program exists = TOK :: ' + tool['file']) return True else: print('Toolbox: program exists = FAIL :: ' + tool['file']) retu...
import the tool and call the function passing the args.
def run(self, tool, args, new_import_path=''): """ import the tool and call the function, passing the args. """ if new_import_path != '': #print('APPENDING PATH = ', new_import_path) sys.path.append(new_import_path) #if silent == 'N': prin...
The Pipeline tool.
def main(**kwargs): """The Pipeline tool.""" options = ApplicationOptions(**kwargs) Event.configure(is_logging_enabled=options.event_logging) application = Application(options) application.run(options.definition)
Setup of application logging.
def setup_logging(self): """Setup of application logging.""" is_custom_logging = len(self.options.logging_config) > 0 is_custom_logging = is_custom_logging and os.path.isfile(self.options.logging_config) is_custom_logging = is_custom_logging and not self.options.dry_run if is_cu...
Validate given pipeline document.
def validate_document(self, definition): """ Validate given pipeline document. The method is trying to load, parse and validate the spline document. The validator verifies the Python structure B{not} the file format. Args: definition (str): path and filename of a ya...
Running pipeline via a matrix.
def run_matrix(self, matrix_definition, document): """ Running pipeline via a matrix. Args: matrix_definition (dict): one concrete matrix item. document (dict): spline document (complete) as loaded from yaml file. """ matrix = Matrix(matrix_definition, 'm...
Shutdown of the application.
def shutdown(self, collector, success): """Shutdown of the application.""" self.event.delegate(success) if collector is not None: collector.queue.put(None) collector.join() if not success: sys.exit(1)
Processing the pipeline.
def run(self, definition): """Processing the pipeline.""" self.logger.info("Running with Python %s", sys.version.replace("\n", "")) self.logger.info("Running on platform %s", platform.platform()) self.logger.info("Current cpu count is %d", multiprocessing.cpu_count()) self.logger...
When configured trying to ensure that path does exist.
def provide_temporary_scripts_path(self): """When configured trying to ensure that path does exist.""" if len(self.options.temporary_scripts_path) > 0: if os.path.isfile(self.options.temporary_scripts_path): self.logger.error("Error: configured script path seems to be a file!...
Create and run collector process for report data.
def create_and_run_collector(document, options): """Create and run collector process for report data.""" collector = None if not options.report == 'off': collector = Collector() collector.store.configure(document) Event.configure(collector_queue=collector.queu...
Use Jinja2 rendering for given text an key key/ values.
def render(value, **kwargs): """ Use Jinja2 rendering for given text an key key/values. Args: value (str): the template to be rendered. kwargs (dict): named parameters representing available variables inside the template. >>> model = {"message": "hello world 1!"}...
Transform dictionary of environment variables into Docker - e parameters.
def docker_environment(env): """ Transform dictionary of environment variables into Docker -e parameters. >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'}) >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"'] True """ return ' '.join( ...
Find ** stages ** in document.
def find_stages(document): """ Find **stages** in document. Args: document (dict): validated spline document loaded from a yaml file. Returns: list: stages as a part of the spline document or an empty list if not given. >>> find_stages({'pipeline': [{'stage(Prepare)':1}, {'stage(...
Retrieves download location for FEH data zip file from hosted json configuration file.
def _retrieve_download_url(): """ Retrieves download location for FEH data zip file from hosted json configuration file. :return: URL for FEH data file :rtype: str """ try: # Try to obtain the url from the Open Hydrology json config file. with urlopen(config['nrfa']['oh_json_url...
Check whether updated NRFA data is available.
def update_available(after_days=1): """ Check whether updated NRFA data is available. :param after_days: Only check if not checked previously since a certain number of days ago :type after_days: float :return: `True` if update available, `False` if not, `None` if remote location cannot be reached. ...
Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache folder.
def download_data(): """ Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache folder. """ with urlopen(_retrieve_download_url()) as f: with open(os.path.join(CACHE_FOLDER, CACHE_ZIP), "wb") as local_file: local_file.write(...
Save NRFA metadata to local config file using retrieved config data
def _update_nrfa_metadata(remote_config): """ Save NRFA metadata to local config file using retrieved config data :param remote_config: Downloaded JSON data, not a ConfigParser object! """ config['nrfa']['oh_json_url'] = remote_config['nrfa_oh_json_url'] config['nrfa']['version'] = remote_confi...
Return metadata on the NRFA data.
def nrfa_metadata(): """ Return metadata on the NRFA data. Returned metadata is a dict with the following elements: - `url`: string with NRFA data download URL - `version`: string with NRFA version number, e.g. '3.3.4' - `published_on`: datetime of data release/publication (only month and year...
Extract all files from downloaded FEH data zip file.
def unzip_data(): """ Extract all files from downloaded FEH data zip file. """ with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), 'r') as zf: zf.extractall(path=CACHE_FOLDER)
Return all annual maximum flow ( *. am ) files in cache folder and sub folders.
def amax_files(): """ Return all annual maximum flow (`*.am`) files in cache folder and sub folders. :return: List of file paths :rtype: list """ return [os.path.join(dp, f) for dp, dn, filenames in os.walk(CACHE_FOLDER) for f in filenames if os.path.splitext(f)[1].lower() == '.am']
return a dictionary of statistics about an XML file including size in bytes num lines number of elements count by elements
def get_xml_stats(fname): """ return a dictionary of statistics about an XML file including size in bytes, num lines, number of elements, count by elements """ f = mod_file.TextFile(fname) res = {} res['shortname'] = f.name res['folder'] = f.path res['filesize'] = str(f.size) + ...
makes a random xml file mainly for testing the xml_split
def make_random_xml_file(fname, num_elements=200, depth=3): """ makes a random xml file mainly for testing the xml_split """ with open(fname, 'w') as f: f.write('<?xml version="1.0" ?>\n<random>\n') for dep_num, _ in enumerate(range(1,depth)): f.write(' <depth>\n <content>\n...
returns ( 511 35082 ) for ANC__WhereToHongKong. xml
def count_elements(fname, element): """ returns (511, 35082) for ANC__WhereToHongKong.xml """ num = 0 tot = 0 for event, elem in iterparse(fname): tot += 1 if elem.text != '': #print(' tag = ', elem.tag) #print(' event = ', event # always end ...
Lists all organisms present in the KEGG database.
def organismsKEGG(): """ Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row. """ organisms=urlopen("http://rest.kegg.jp/list/organism").read() organisms=organisms.split("\n") #for o in organisms: # print o # sys.stdout.flus...
Finds KEGG database identifiers for a respective organism given example ensembl ids.
def databasesKEGG(organism,ens_ids): """ Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a...
Looks up KEGG mappings of KEGG ids to ensembl ids
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism
def ecs_idsKEGG(organism): """ Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism :param organism: an organisms as listed in organismsKEGG() :returns: a Pandas dataframe of with 'ec' and 'KEGGid'. """ kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read...
Uses KEGG to retrieve all ids for a given KEGG organism
def idsKEGG(organism): """ Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'. """ ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") ...
Retrieves all pathways for a given organism.: param organism: an organism as listed in organismsKEGG (): returns df: a Pandas dataframe with the columns KEGGid pathIDs and pathName.: returns df_: a Pandas dataframe with a columns for KEGGid and one column for each pathway with the corresponding gene ids below
def pathwaysKEGG(organism): """ Retrieves all pathways for a given organism. :param organism: an organism as listed in organismsKEGG() :returns df: a Pandas dataframe with the columns 'KEGGid','pathIDs', and 'pathName'. :returns df_: a Pandas dataframe with a columns for 'KEGGid', and one column for...
Transforms a pandas dataframe with the columns ensembl_gene_id kegg_enzyme to dataframe ready for use in...
def biomaRtTOkegg(df): """ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_ge...
Gets all KEGG pathways for an organism
def expKEGG(organism,names_KEGGids): """ Gets all KEGG pathways for an organism :param organism: an organism as listed in organismsKEGG() :param names_KEGGids: a Pandas dataframe with the columns 'gene_name': and 'KEGGid' as reported from idsKEGG(organism) (or a subset of it). :returns df: a Pand...
Looks for all KEGG annotatios of an organism in biomart and the respective pathways in KEGG. It can also retrieve links to pathways figures with red labeled genes provided in a dataframe.
def KEGGmatrix(organism, dataset, query_attributes=['ensembl_gene_id','kegg_enzyme'], host=biomart_host,links=True,dfexp=None,kegg_db=None, database=None ): """ Looks for all KEGG annotatios of an organism in biomart and the respective pathways in KEGG. It can also retrieve links to pathways figures with red la...
Lists BioMart databases through a RPY2 connection.
def RdatabasesBM(host=rbiomart_host): """ Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") print(biomaRt.listMarts(host=host))
Lists BioMart datasets through a RPY2 connection.
def RdatasetsBM(database,host=rbiomart_host): """ Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") ensemblMart=bi...
Lists BioMart filters through a RPY2 connection.
def RfiltersBM(dataset,database,host=rbiomart_host): """ Lists BioMart filters through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing ...
Lists BioMart attributes through a RPY2 connection.
def RattributesBM(dataset,database,host=rbiomart_host): """ Lists BioMart attributes through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: no...
Queries BioMart.
def RqueryBM(query_filter,query_items,query_attributes,dataset,database,host=rbiomart_host): """ Queries BioMart. :param query_filtery: one BioMart filter associated with the items being queried :param query_items: list of items to be queried (must assoiate with given filter) :param query_attribute...
Example of self documenting ( of sorts ) code via aikif. Simply call functions like below to build an overview which has metadata automatically updated.
def main(): """ Example of self documenting (of sorts) code, via aikif. Simply call functions like below to build an overview which has metadata automatically updated. """ fldr = mod_cfg.fldrs['program_path'] p = mod_prg.Programs('AIKIF Programs', fldr) document_core_programs(p) do...
Document a subset of core programs with purpose ( and intent )
def document_core_programs(p): """ Document a subset of core programs with purpose (and intent) """ p.comment('programs.py', 'collects list of aikif programs to show progress and allows comments to be added to each file') p.comment('cls_file_mapping.py', 'uses ontology to get list of files to s...
Document example programs with purpose ( and intent )
def document_examples(p): """ Document example programs with purpose (and intent) """ p.comment('maths_ml_algorithms.py', 'machine learning algorithms for toolbox in AIKIF') p.comment('algebra.py', 'toolbox module for based evaluation of maths problems') p.comment('crypt_utils.py', 'scripts to e...
Document agents in AIKIF ( purpose and intent )
def document_agents(p): """ Document agents in AIKIF (purpose and intent) """ p.comment('agent.py', 'base agent class') p.comment('run_agents.py', 'Top level function to run the agents') p.comment('agent_image_metadata.py', 'agent to collect file picture metadata') p.comment('agent_lear...
Get list of applications
def get_list_of_applications(): """ Get list of applications """ apps = mod_prg.Programs('Applications', 'C:\\apps') fl = mod_fl.FileList(['C:\\apps'], ['*.exe'], ["\\bk\\"]) for f in fl.get_list(): apps.add(f, 'autogenerated list') apps.list() apps.save()
base function for extracting a simple parameter value.: param tree: the parameters tree.: param kind: the xml - tag name of the parameter.: param name: the name of the parameter.: returns value: the content of the parameter Value as string.
def _simple_string_value(tree, kind, name): """ base function for extracting a simple parameter value. :param tree: the parameters tree. :param kind: the xml-tag name of the parameter. :param name: the name of the parameter. :returns value: the content of the parameter 'Value' as string.""" quer...
boolean parameter value.: param parameters: the parameters tree.: param name: the name of the parameter.
def boolParam(parameters, name): """ boolean parameter value. :param parameters: the parameters tree. :param name: the name of the parameter. """ value = _simple_string_value(parameters, 'BoolParam', name) if value not in {'true', 'false'}: raise ValueError('BoolParam Value has to be either...
single choice parameter value. Returns - 1 if no value was chosen.: param parameters: the parameters tree.: param name: the name of the parameter.: param type_converter: function to convert the chosen value to a different type ( e. g. str float int ). default = str
def singleChoiceParam(parameters, name, type_converter = str): """ single choice parameter value. Returns -1 if no value was chosen. :param parameters: the parameters tree. :param name: the name of the parameter. :param type_converter: function to convert the chosen value to a different type (e.g. str, ...
multi choice parameter values.: param parameters: the parameters tree.: param name: the name of the parameter.: param type_converter: function to convert the chosen value to a different type ( e. g. str float int ). default = str: returns dictionary: value - > values
def multiChoiceParam(parameters, name, type_converter = str): """ multi choice parameter values. :param parameters: the parameters tree. :param name: the name of the parameter. :param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str' :re...
single choice with sub parameters value and chosen subparameters. Returns - 1 and None if no value was chosen.: param parameters: the parameters tree.: param name: the name of the parameter.
def boolWithSubParams(parameters, name): """ single choice with sub parameters value and chosen subparameters. Returns -1 and None if no value was chosen. :param parameters: the parameters tree. :param name: the name of the parameter. """ param = parameters.find(".//BoolWithSubParams[@Name='{name}']...
Add the field to the internal configuration dictionary.
def add_field(self, name, label, field_type, *args, **kwargs): """ Add the field to the internal configuration dictionary. """ if name in self._dyn_fields: raise AttributeError('Field already added to the form.') else: self._dyn_fields[name] = {'label': label, 'type': fie...
Add the validator to the internal configuration dictionary.
def add_validator(self, name, validator, *args, **kwargs): """ Add the validator to the internal configuration dictionary. :param name: The field machine name to apply the validator on :param validator: The WTForms validator object The rest are optional arguments...
Process the given WTForm Form object.
def process(self, form, post): """ Process the given WTForm Form object. Itterate over the POST values and check each field against the configuration that was made. For each field that is valid, check all the validator parameters for possible %field% replacement, then bind ...
Reads a gz compressed BED narrow peak file from a web address or local file
def GetBEDnarrowPeakgz(URL_or_PATH_TO_file): """ Reads a gz compressed BED narrow peak file from a web address or local file :param URL_or_PATH_TO_file: web address of path to local file :returns: a Pandas dataframe """ if os.path.isfile(URL_or_PATH_TO_file): response=open(URL_or_PATH...
Transforms a pandas dataframe into a bedtool
def dfTObedtool(df): """ Transforms a pandas dataframe into a bedtool :param df: Pandas dataframe :returns: a bedtool """ df=df.astype(str) df=df.drop_duplicates() df=df.values.tolist() df=["\t".join(s) for s in df ] df="\n".join(df) df=BedTool(df, from_string=True) re...
Annotates a bedtool BED narrow peak
def GetPeaksExons(bed,parsedGTF): """ Annotates a bedtool, BED narrow peak :param bed: a pandas dataframe in bed format :param parsedGTF: a parsed GTF file as outputed by parseGTF() with the following columns :returns: a Pandas dataframe """ bedtool_AB=dfTObedtool(bed) exonsGTF=parse...
Annotates a bed file.
def AnnotateBED(bed, GTF, genome_file, bedcols=None, promoter=[1000,200]): """ Annotates a bed file. :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols. :param GTF: /path/to/file.gtf :param genome_file: /path/to/file.genome - a tab separate...
Global configuration for event handling.
def configure(**kwargs): """Global configuration for event handling.""" for key in kwargs: if key == 'is_logging_enabled': Event.is_logging_enabled = kwargs[key] elif key == 'collector_queue': Event.collector_queue = kwargs[key] else: ...
Delegate success/ failure to the right method.
def delegate(self, success, **kwargs): """Delegate success/failure to the right method.""" if success: self.succeeded(**kwargs) else: self.failed(**kwargs)
Finish event as failed with optional additional information.
def failed(self, **kwargs): """Finish event as failed with optional additional information.""" self.finished = datetime.now() self.status = 'failed' self.information.update(kwargs) self.logger.info("Failed - took %f seconds.", self.duration()) self.update_report_collector...
Updating report collector for pipeline details.
def update_report_collector(self, timestamp): """Updating report collector for pipeline details.""" report_enabled = 'report' in self.information and self.information['report'] == 'html' report_enabled = report_enabled and 'stage' in self.information report_enabled = report_enabled and E...
This function collects GO annotation from http:// geneontology. org/ page/ download - annotations.
def getGeneAssociation(URL_or_file): """ This function collects GO annotation from http://geneontology.org/page/download-annotations. :param URL_or_file: either a link to a file on geneontology.org eg. http://geneontology.org/gene-associations/gene_association.fb.gz or the path for the respective downlode...
test function.
def count_lines_in_file(src_file ): """ test function. """ tot = 0 res = '' try: with open(src_file, 'r') as f: for line in f: tot += 1 res = str(tot) + ' recs read' except: res = 'ERROR -couldnt open file' return res
creates a SQL loader script to load a text file into a database and then executes it. Note that src_file is
def load_txt_to_sql(tbl_name, src_file_and_path, src_file, op_folder): """ creates a SQL loader script to load a text file into a database and then executes it. Note that src_file is """ if op_folder == '': pth = '' else: pth = op_folder + os.sep fname_create_script...
create_CTL ( fname_control_file tbl_name src_file cols TRUNCATE )
def create_CTL(fname, tbl_name, col_list, TRUNC_OR_APPEND, delim=','): """ create_CTL(fname_control_file, tbl_name, src_file, cols, 'TRUNCATE') """ with open(fname, 'w') as ct: ct.write('LOAD DATA\n') ct.write(TRUNC_OR_APPEND + '\n') ct.write('into table ' + tbl_name + '\n') ...
Return an iterator object.
async def aiter(*args): """Return an iterator object. Args: obj: An object that implements the __iter__ or __aiter__ method. sentinel: An optional sentinel value to look for while iterator. Return: iterable: Some iterable that provides a __anext__ method. Raises: TypeE...
Return the next item from an async iterator.
async def anext(*args): """Return the next item from an async iterator. Args: iterable: An async iterable. default: An optional default value to return if the iterable is empty. Return: The next value of the iterable. Raises: TypeError: The iterable given is not async....
Make an iterator that returns object over and over again.
def repeat(obj, times=None): """Make an iterator that returns object over and over again.""" if times is None: return AsyncIterWrapper(sync_itertools.repeat(obj)) return AsyncIterWrapper(sync_itertools.repeat(obj, times))
Ensure the callable is an async def.
def _async_callable(func): """Ensure the callable is an async def.""" if isinstance(func, types.CoroutineType): return func @functools.wraps(func) async def _async_def_wrapper(*args, **kwargs): """Wrap a a sync callable in an async def.""" return func(*args, **kwargs) retu...
Return n independent iterators from a single iterable.
def tee(iterable, n=2): """Return n independent iterators from a single iterable. Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. This itertool may require significant auxiliary ...
Called internally to emit changes from the instance object
def _on_change(self, obj, old, value, **kwargs): """Called internally to emit changes from the instance object The keyword arguments here will be passed to callbacks through the instance object's :meth:`~pydispatch.dispatch.Dispatcher.emit` method. Keyword Args: property: T...
Parse string and return relevant object
def parse_str(self, s): """ Parse string and return relevant object :param s: string to parse :type s: str :return: Parsed object """ self.object = self.parsed_class() in_section = None # Holds name of FEH file section while traversing through file. ...
Parse entire file and return relevant object.
def parse(self, file_name): """ Parse entire file and return relevant object. :param file_name: File path :type file_name: str :return: Parsed object """ self.object = self.parsed_class() with open(file_name, encoding='utf-8') as f: self.parse...
Parse entire file and return a: class: Catchment object.
def parse(self, file_name): """ Parse entire file and return a :class:`Catchment` object. :param file_name: File path :type file_name: str :return: Parsed object :rtype: :class:`Catchment` """ root = ET.parse(file_name).getroot() return self._pars...
Parse entire file and return a: class: Catchment object.
def parse_str(self, s): """ Parse entire file and return a :class:`Catchment` object. :param file_name: File path :type file_name: str :return: Parsed object :rtype: :class:`Catchment` """ root = ET.fromstring(s) return self._parse(root)
Returns a Page object for the given 1 - based page number.
def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page page_items = self.object_list[bottom:top] # check moved from v...