INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
update the self rating based on the parameters. If min max is a range ( ie not equal ) then add fixed value to rating depending if current value is in range otherwise compare distance away from min/ max ( same value )
def _update_pref(self, lmin, lmax, cur): """ update the self rating based on the parameters. If min max is a range (ie not equal) then add fixed value to rating depending if current value is in range, otherwise compare distance away from min/max (same value) """ r...
this is going to be the tricky bit - probably not possible to get the exact rating for a value. Will need to do sentiment analysis of the text to see how it matches the rating. Even that sounds like it wont work - maybe a ML algorithm would do it but that requires a large body of text already matched to values - and va...
def match_value_to_text(self, text): """ this is going to be the tricky bit - probably not possible to get the 'exact' rating for a value. Will need to do sentiment analysis of the text to see how it matches the rating. Even that sounds like it wont work - maybe a ML algorithm wo...
convert a list to html using table formatting
def list2html(lst): """ convert a list to html using table formatting """ txt = '<TABLE width=100% border=0>' for l in lst: txt += '<TR>\n' if type(l) is str: txt+= '<TD>' + l + '</TD>\n' elif type(l) is list: txt+= '<TD>' for i in l: ...
builds a list of files and returns as a list
def GetFileList(rootPaths, lstXtn, shortNameOnly='Y'): """ builds a list of files and returns as a list """ numFiles = 0 opFileList = [] if type(rootPaths) == str: rootPaths = [rootPaths] for rootPath in rootPaths: for root, dirs, files in os.walk(rootPath): ...
returns the html for a simple edit form
def build_edit_form(title, id, cols, return_page): """ returns the html for a simple edit form """ txt = '<H3>' + title + '<H3>' txt += '<form action="' + return_page + '" method="POST">\n' # return_page = /agents txt += ' updating id:' + str(id) + '\n<BR>' txt += ' <input type="hidden" ...
returns the html to display a listbox
def build_html_listbox(lst, nme): """ returns the html to display a listbox """ res = '<select name="' + nme + '" multiple="multiple">\n' for l in lst: res += ' <option>' + str(l) + '</option>\n' res += '</select>\n' return res
returns the html with supplied list as a HTML listbox
def build_data_list(lst): """ returns the html with supplied list as a HTML listbox """ txt = '<H3>' + List + '<H3><UL>' for i in lst: txt += '<LI>' + i + '</LI>' txt += '<UL>' return txt
formats a standard filelist to htmk using table formats
def filelist2html(lst, fldr, hasHeader='N'): """ formats a standard filelist to htmk using table formats """ txt = '<TABLE width=100% border=0>' numRows = 1 if lst: for l in lst: if hasHeader == 'Y': if numRows == 1: td_begin = '<TH>' ...
creates a html link for a file using folder fldr
def link_file(f, fldr): """ creates a html link for a file using folder fldr """ fname = os.path.join(fldr,f) if os.path.isfile(fname): return '<a href="/aikif/data/core/' + f + '">' + f + '</a>' else: return f
converts a dictionary to a HTML table row
def dict_to_htmlrow(d): """ converts a dictionary to a HTML table row """ res = "<TR>\n" for k, v in d.items(): if type(v) == str: res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + v + '</p></TD>' else: res = res + '<TD><p>' + k + ':</p></TD><TD><p>' + str(v) ...
reads a CSV file and converts it to HTML
def read_csv_to_html_table(csvFile, hasHeader='N'): """ reads a CSV file and converts it to HTML """ txt = '<table class="as-table as-table-zebra as-table-horizontal">' with open(csvFile, "r") as f: # numRows = 1 for row in f: if hasHeader == 'Y': if num...
reads a CSV file and converts it to a HTML List
def read_csv_to_html_list(csvFile): """ reads a CSV file and converts it to a HTML List """ txt = '' with open(csvFile) as csv_file: for row in csv.reader(csv_file, delimiter=','): txt += '<div id="table_row">' for col in row: txt += " " ...
tell the agent to move to location y x Why is there another grd object in the agent? Because this is NOT the main grid rather a copy for the agent to overwrite with planning routes etc. The real grid is initialised in World. __init__ () class
def set_world(self, grd, start_y_x, y_x): """ tell the agent to move to location y,x Why is there another grd object in the agent? Because this is NOT the main grid, rather a copy for the agent to overwrite with planning routes, etc. The real grid is initialised in Worl...
the goal of the explore agent is to move to the target while avoiding blockages on the grid. This function is messy and needs to be looked at. It currently has a bug in that the backtrack oscillates so need a new method of doing this - probably checking if previously backtracked in that direction for those coords ie ke...
def do_your_job(self): """ the goal of the explore agent is to move to the target while avoiding blockages on the grid. This function is messy and needs to be looked at. It currently has a bug in that the backtrack oscillates so need a new method of doing this - probably...
wrapper for debugging print and log methods
def lg_mv(self, log_lvl, txt): """ wrapper for debugging print and log methods """ if log_lvl <= self.LOG_LEVEL: print(txt + str(self.current_y) + "," + str(self.current_x))
returns a Y X value showing which direction the agent should move in order to get to the target
def get_intended_direction(self): """ returns a Y,X value showing which direction the agent should move in order to get to the target """ x = 0 y = 0 if self.target_x == self.current_x and self.target_y == self.current_y: return y,x # target already a...
clears the cells immediately around the grid of the agent ( just to make it find to see on the screen )
def clear_surroundings(self): """ clears the cells immediately around the grid of the agent (just to make it find to see on the screen) """ cells_to_clear = self.grd.eight_neighbors(self.current_y, self.current_x) for cell in cells_to_clear: self.grd.set_tile(...
dumps the status of the agent
def show_status(self): """ dumps the status of the agent """ txt = 'Agent Status:\n' print(txt) txt += "start_x = " + str(self.start_x) + "\n" txt += "start_y = " + str(self.start_y) + "\n" txt += "target_x = " + str(self.target_x) + "\n" txt += ...
collects basic MP3 metadata Works once you use mutagenx ( buried deep in issues page ) [ Angels ] [ Red Back Fever ] [ Red Back Fever ] { album: [ Red Back Fever ] title: [ Red Back Fever ] artist: [ Angels ] }
def get_audio_metadata(fname): """ collects basic MP3 metadata Works, once you use mutagenx (buried deep in issues page) ['Angels'] ['Red Back Fever'] ['Red Back Fever'] {'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']} """ from mutagenx.easyid3 import ...
retrieve the metadata from an MP3 file
def get_audio_metadata_old(fname): """ retrieve the metadata from an MP3 file """ audio_dict = {} print("IDv2 tag info for %s:" % fname) try: audio = mutagenx.id3.ID3(fname, translate=False) except StandardError as err: print("ERROR = " + str(err)) #else: #print(audio.ppr...
Checks cytoscape version: param host: cytoscape host address default = cytoscape_host: param port: cytoscape port default = 1234: returns: cytoscape and api version
def checkCytoscapeVersion(host=cytoscape_host,port=cytoscape_port): """ Checks cytoscape version :param host: cytoscape host address, default=cytoscape_host :param port: cytoscape port, default=1234 :returns: cytoscape and api version """ URL="http://"+str(host)+":"+str(port)+...
General function for interacting with Cytoscape API.: param namespace: namespace where the request should be executed. eg. string: param commnand: command to execute. eg. protein query: param PARAMs: a dictionary with the parameters. Check your swagger normaly running on http:// localhost: 1234/ v1/ swaggerUI/ swagger ...
def cytoscape(namespace,command="",PARAMS={},host=cytoscape_host,port=cytoscape_port,method="POST",verbose=False): """ General function for interacting with Cytoscape API. :param namespace: namespace where the request should be executed. eg. "string" :param commnand: command to execute. eg. "protei...
Gets tables from cytoscape: param table: table to retrieve eg. node: param columns: columns to retrieve in list format: param namespace: namepsace default = default: param network: a network name or id default = current: param host: cytoscape host address default = cytoscape_host: param port: cytoscape port default = 1...
def getTableColumns(table, columns, namespace = "default", network = "current", host=cytoscape_host,port=cytoscape_port,verbose=False): """ Gets tables from cytoscape :param table: table to retrieve eg. node :param columns: columns to retrieve in list format :param namespace: namepsace, default...
Loads tables into cytoscape: param df: a pandas dataframe to load: param df_key: key column in df default = index: param table: target table default = node: param table_key_column: table key column default = name: param network: a network name or id default = current: param host: cytoscape host address default = cytosc...
def loadTableData(df, df_key='index',table="node", \ table_key_column = "name", network="current",\ namespace="default",\ host=cytoscape_host,port=cytoscape_port,verbose=False): """ Loads tables into cytoscape :param df: a pan...
Updates a visual style: param title: title of the visual style: param defaults: a list of dictionaries for each visualProperty: param mappings: a list of dictionaries for each visualProperty: param host: cytoscape host address default = cytoscape_host: param port: cytoscape port default = 1234: retunrs: nothing
def update_style(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port,verbose=False): """ Updates a visual style :param title: title of the visual style :param defaults: a list of dictionaries for each visualProperty :param mappings: a list of dictionaries for each visualPr...
Creates a new visual style: param title: title of the visual style: param defaults: a list of dictionaries for each visualProperty: param mappings: a list of dictionaries for each visualProperty: param host: cytoscape host address default = cytoscape_host: param port: cytoscape port default = 1234: retunrs: nothing
def create_styles(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port): """ Creates a new visual style :param title: title of the visual style :param defaults: a list of dictionaries for each visualProperty :param mappings: a list of dictionaries for each visualProperty ...
Generates a dictionary for a given visual property: param visualProperty: visualProperty: param mappingType: mappingType: param mappingColumn: mappingColumn: param lower: for continuous mappings a list of the form [ value rgb_string ]: param center: for continuous mappings a list of the form [ value rgb_string ]: param...
def mapVisualProperty(visualProperty,mappingType,mappingColumn,\ lower=None,center=None,upper=None,\ discrete=None,\ network="current",table="node",\ namespace="default",host=cytoscape_host,\ port=cytoscape_por...
Checks the current network. Note: works only on localhost: param filetype: file type default = PNG: param saveas:/ path/ to/ non/ tmp/ file. prefix: param host: cytoscape host address default = cytoscape_host: param port: cytoscape port default = 1234
def result(filetype="PNG",saveas=None, host=cytoscape_host,port=cytoscape_port): """ Checks the current network. Note: works only on localhost :param filetype: file type, default="PNG" :param saveas: /path/to/non/tmp/file.prefix :param host: cytoscape host address, default=cytoscape_h...
Plots tables from aDiff/ cuffdiff into cytoscape using String protein queries. Uses top changed genes as well as first neighbours and difusion fo generate subnetworks.: param df: df as outputed by aDiff for differential gene expression: param aging_genes: ENS gene ids to be labeled with a diagonal: param species: speci...
def aDiffCytoscape(df,aging_genes,target,species="caenorhabditis elegans",limit=None, cutoff=0.4,\ taxon=None,host=cytoscape_host,port=cytoscape_port): """ Plots tables from aDiff/cuffdiff into cytoscape using String protein queries. Uses top changed genes as well as first neighbours and ...
Find all row names and the maximum column widths.
def calculate_columns(sequence): """ Find all row names and the maximum column widths. Args: columns (dict): the keys are the column name and the value the max length. Returns: dict: column names (key) and widths (value). """ columns = {} for row in sequence: for k...
Calculate row format.
def calculate_row_format(columns, keys=None): """ Calculate row format. Args: columns (dict): the keys are the column name and the value the max length. keys (list): optional list of keys to order columns as well as to filter for them. Returns: str: format for table row """...
Print sequence as ascii table to stdout.
def pprint(sequence, keys=None): """ Print sequence as ascii table to stdout. Args: sequence (list or tuple): a sequence with a dictionary each entry. keys (list): optional list of keys to order columns as well as to filter for them. """ if len(sequence) > 0: columns = calcu...
Run pipelines in parallel.
def matrix_worker(data): """ Run pipelines in parallel. Args: data(dict): parameters for the pipeline (model, options, ...). Returns: dict: with two fields: success True/False and captured output (list of str). """ matrix = data['matrix'] Logger.get_logger(__name__ + '.worke...
Check given matrix tags to be in the given list of matric tags.
def can_process_matrix(entry, matrix_tags): """ Check given matrix tags to be in the given list of matric tags. Args: entry (dict): matrix item (in yaml). matrix_tags (list): represents --matrix-tags defined by user in command line. Returns: bool: Tru...
Running pipelines one after the other.
def run_matrix_ordered(self, process_data): """ Running pipelines one after the other. Returns dict: with two fields: success True/False and captured output (list of str). """ output = [] for entry in self.matrix: env = entry['env'].copy() ...
Running pipelines in parallel.
def run_matrix_in_parallel(self, process_data): """Running pipelines in parallel.""" worker_data = [{'matrix': entry, 'pipeline': process_data.pipeline, 'model': process_data.model, 'options': process_data.options, 'hooks': process_data.hooks} for entry in...
Process the pipeline per matrix item.
def process(self, process_data): """Process the pipeline per matrix item.""" if self.parallel and not process_data.options.dry_run: return self.run_matrix_in_parallel(process_data) return self.run_matrix_ordered(process_data)
Takes a SQL string containing 0 or more statements and returns a list of individual statements as strings. Comments and empty statements are ignored.
def _sqlfile_to_statements(sql): """ Takes a SQL string containing 0 or more statements and returns a list of individual statements as strings. Comments and empty statements are ignored. """ statements = (sqlparse.format(stmt, strip_comments=True).strip() for stmt in sqlparse.split(sql)) re...
Returns a name of a new migration. It will usually be a filename with a valid and unique name.
def generate_migration_name(self, name, suffix): """Returns a name of a new migration. It will usually be a filename with a valid and unique name. :param name: human-readable name of a migration :param suffix: file suffix (extension) - eg. 'sql' """ return os.path.join(s...
Subclasses should call this method instead of module. migrate directly to support db_config optional argument.
def _call_migrate(self, module, connection_param): """Subclasses should call this method instead of `module.migrate` directly, to support `db_config` optional argument. """ args = [connection_param] spec = inspect.getargspec(module.migrate) if len(spec.args) == 2: ...
This recognizes migration type and executes either: method: execute_python_migration or: method: execute_native_migration
def execute_migration(self, migration_file_relative): """This recognizes migration type and executes either :method:`execute_python_migration` or :method:`execute_native_migration` """ migration_file = os.path.join(self.db_config['migrations_dir'], migration_file_relative) m_type...
uses the input data which may be a string list number or file to work out how to load the data ( this can be overridden by passing the data_type on the command line
def _identify_datatype(self, input_data): """ uses the input data, which may be a string, list, number or file to work out how to load the data (this can be overridden by passing the data_type on the command line """ if isinstance(input_data, (int, float)) : ...
create a standard data object based on CSV file
def _create_from_csv(self): """ create a standard data object based on CSV file """ import aikif.dataTools.cls_datatable as cl fle = cl.DataTable(self.input_data, ',') fle.load_to_array() self.content['data'] = fle.arr lg.record_p...
create a standard data object based on CSV file
def _create_from_owl(self): """ create a standard data object based on CSV file """ self.content['data'] = 'TODO - read OWL from ' + self.input_data lg.record_process('_create_from_owl', 'read ' + self._calc_size_stats() + ' from ' + self.input_data)
create a standard data object based on CSV file
def _create_from_url(self): """ create a standard data object based on CSV file """ import aikif.toolbox.network_tools as mod_net mod_net.download_file_no_logon(self.input_data, 'temp_file.htm') with open('temp_file.htm', 'r') as f: self.content['data'] = f.re...
get the size in bytes and num records of the content
def _calc_size_stats(self): """ get the size in bytes and num records of the content """ self.total_records = 0 self.total_length = 0 self.total_nodes = 0 if type(self.content['data']) is dict: self.total_length += len(str(self.content['data'])) ...
recursively walk through a data set or json file to get the total number of nodes
def _get_size_recursive(self, dat): """ recursively walk through a data set or json file to get the total number of nodes """ self.total_records += 1 #self.total_nodes += 1 for rec in dat: if hasattr(rec, '__iter__') and type(rec) is not str: ...
Create a readable version string from version_info tuple components.
def _make_version(major, minor, micro, releaselevel, serial): """Create a readable version string from version_info tuple components.""" assert releaselevel in ['alpha', 'beta', 'candidate', 'final'] version = "%d.%d" % (major, minor) if micro: version += ".%d" % (micro,) if releaselevel != ...
Make the URL people should start at for this version of coverage. py.
def _make_url(major, minor, micro, releaselevel, serial): """Make the URL people should start at for this version of coverage.py.""" url = "https://django-pagination-bootstrap.readthedocs.io" if releaselevel != 'final': # For pre-releases, use a version-specific URL. url += "/en/" + _make_ve...
return a list of unique paths in the file list
def get_list_of_paths(self): """ return a list of unique paths in the file list """ all_paths = [] for p in self.fl_metadata: try: all_paths.append(p['path']) except: try: print('cls_filelist - ...
builds a list of files and returns as a list
def get_file_list(self, lstPaths, lstXtn, lstExcluded, VERBOSE = False): """ builds a list of files and returns as a list """ if VERBOSE: print("Generating list of Files...") print("Paths = ", lstPaths) print("Xtns = ", lstXtn) pri...
collects the files metadata - note that this will fail with strange errors if network connection drops out to shared folder but it is better to stop the program rather than do a try except otherwise you will get an incomplete set of files.
def add_file_metadata(self, fname): """ collects the files metadata - note that this will fail with strange errors if network connection drops out to shared folder, but it is better to stop the program rather than do a try except otherwise you will get an incomplete...
makes a nice display of filename for printing based on columns passed print ( {: <30 }. format ( f [ name ] ) {: }. format ( f [ size ] ))
def print_file_details_in_line(self, fname, col_headers): """ makes a nice display of filename for printing based on columns passed print('{:<30}'.format(f["name"]), '{:,}'.format(f["size"])) """ line = '' try: sze = os.path.getsize(fname) exce...
saves as csv format
def print_file_details_as_csv(self, fname, col_headers): """ saves as csv format """ line = '' qu = '"' d = ',' for fld in col_headers: if fld == "fullfilename": line = line + qu + fname + qu + d if fld == "name": l...
uses a List of files and collects meta data on them and saves to an text file as a list or with metadata depending on opFormat.
def save_filelist(self, opFile, opFormat, delim=',', qu='"'): """ uses a List of files and collects meta data on them and saves to an text file as a list or with metadata depending on opFormat. """ op_folder = os.path.dirname(opFile) if op_folder is not None: # ...
connect here - use the other classes cls_oracle cls_mysql etc otherwise this has the credentials used to access a share folder
def login(self, schema, username, password): """ connect here - use the other classes cls_oracle, cls_mysql, etc otherwise this has the credentials used to access a share folder """ self.schema = schema self.username = username self.password = password sel...
Types a collection of genes returning the most likely gene version in the collection with it s genotype
def type(self, sequence_coverage_collection, min_gene_percent_covg_threshold=99): """Types a collection of genes returning the most likely gene version in the collection with it's genotype""" best_versions = self.get_best_version( sequence_coverage_collection.values(...
collects a filelist of all. py programs
def list_all_python_programs(self): """ collects a filelist of all .py programs """ self.tot_lines = 0 self.tot_bytes = 0 self.tot_files = 0 self.tot_loc = 0 self.lstPrograms = [] fl = mod_fl.FileList([self.fldr], ['*.py'], ["__pycache__", "/venv/"...
Adds a comment to the existing program in the list logs the reference and TODO - adds core link to processes
def comment(self, nme, desc): """ Adds a comment to the existing program in the list, logs the reference and TODO - adds core link to processes """ if nme != '': program_exists = False for i in self.lstPrograms: print(i) ...
Save the list of items to AIKIF core and optionally to local file fname
def save(self, fname=''): """ Save the list of items to AIKIF core and optionally to local file fname """ if fname != '': with open(fname, 'w') as f: for i in self.lstPrograms: f.write(self.get_file_info_line(i, ',')) # sa...
gathers info on a python program in list and formats as string
def get_file_info_line(self, fname, delim): """ gathers info on a python program in list and formats as string """ txt = '' f = mod_file.File(fname[0]) txt += '"' + f.fullname + '"' + delim txt += '"' + f.name + '"' + delim txt += '"' + f.path + '"' + de...
gathers info on a python program in list and formats as string
def get_file_info_web(self, fname, delim='<BR>\n'): """ gathers info on a python program in list and formats as string """ txt = '' f = mod_file.File(fname[0]) txt += '<sup>' + f.name + '</sup>' + delim txt += '<sup>' + fname[1] + '</sup>' + delim txt +=...
gets details on the program size date list of functions and produces a Markdown file for documentation
def collect_program_info(self, fname): """ gets details on the program, size, date, list of functions and produces a Markdown file for documentation """ md = '#AIKIF Technical details\n' md += 'Autogenerated list of programs with comments and progress\n' md += '\n...
Queries the DAVID database for an enrichment analysis Check https:// david. ncifcrf. gov/ content. jsp?file = DAVID_API. html for database == type tag and categories == annot tag.
def DAVIDenrich(database, categories, user, ids, ids_bg = None, name = '', name_bg = '', verbose = False, p = 0.1, n = 2): # Modified from https://david.ncifcrf.gov/content.jsp?file=WS.html # by courtesy of HuangYi @ 20110424 """ Queries the DAVID database for an enrichment analysis Check https://d...
Given a DAVIDenrich output it converts ensembl gene ids to genes names and adds this column to the output
def id_nameDAVID(df,GTF=None,name_id=None): """ Given a DAVIDenrich output it converts ensembl gene ids to genes names and adds this column to the output :param df: a dataframe output from DAVIDenrich :param GTF: a GTF dataframe from readGTF() :param name_id: instead of a gtf dataframe a dataframe ...
Returns a list of gene names for given gene ids.
def DAVIDgetGeneAttribute(x,df,refCol="ensembl_gene_id",fieldTOretrieve="gene_name"): """ Returns a list of gene names for given gene ids. :param x: a string with the list of IDs separated by ', ' :param df: a dataframe with the reference column and a the column to retrieve :param refCol: the heade...
Queries the DAVID database for an enrichment analysis and plots CellPlots as well as SymPlots ( see plots ). Check https:// david. ncifcrf. gov/ content. jsp?file = DAVID_API. html for database == type tag and categories == annot tag.
def DAVIDplot(database, categories, user, df_ids, output, df_ids_bg = None, name = '', \ name_bg = '', verbose = False, p = 0.1, n = 2): """ Queries the DAVID database for an enrichment analysis and plots CellPlots as well as SymPlots (see plots). Check https://david.ncifcrf.gov/content.jsp?file=DAV...
Spline loc tool.
def main(**options): """Spline loc tool.""" application = Application(**options) # fails application when your defined threshold is higher than your ratio of com/loc. if not application.run(): sys.exit(1) return application
Loading configuration.
def load_configuration(self): """Loading configuration.""" filename = os.path.join(os.path.dirname(__file__), 'templates/spline-loc.yml.j2') with open(filename) as handle: return Adapter(safe_load(handle)).configuration
Verify whether to ignore a path.
def ignore_path(path): """ Verify whether to ignore a path. Args: path (str): path to check. Returns: bool: True when to ignore given path. """ ignore = False for name in ['.tox', 'dist', 'build', 'node_modules', 'htmlcov']: i...
Iterating files for given extensions.
def walk_files_for(paths, supported_extensions): """ Iterating files for given extensions. Args: supported_extensions (list): supported file extentsion for which to check loc and com. Returns: str: yield each full path and filename found. """ for...
Find out lines of code and lines of comments.
def analyse(self, path_and_filename, pattern): """ Find out lines of code and lines of comments. Args: path_and_filename (str): path and filename to parse for loc and com. pattern (str): regex to search for line commens and block comments Returns: i...
Processing the pipeline.
def run(self): """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()) configuration = self.l...
Lists BioMart datasets.
def datasetsBM(host=biomart_host): """ Lists BioMart datasets. :param host: address of the host server, default='http://www.ensembl.org/biomart' :returns: nothing """ stdout_ = sys.stdout #Keep track of the previous value. stream = StringIO() sys.stdout = stream server = Biomar...
Lists BioMart filters for a specific dataset.
def filtersBM(dataset,host=biomart_host): """ Lists BioMart filters for a specific dataset. :param dataset: dataset to list filters of. :param host: address of the host server, default='http://www.ensembl.org/biomart' :returns: nothing """ stdout_ = sys.stdout #Keep track of the previous ...
Queries BioMart.
def queryBM(query_attributes,query_dataset,query_filter=None,query_items=None,query_dic=None,host=biomart_host): """ Queries BioMart. :param query_attributes: list of attributes to recover from BioMart :param query_dataset: dataset to query :param query_filter: one BioMart filter associated with th...
Filters GO terms based on given strings using ENSEMBL s biomart homology mapping.: param names_filter: list of substrings to filter GO names on: param exclude_names: list of substrings to be used for exclusion of GO names: param defs_filter: list of substrings to filter GO defenitions on: param exclude_defs: list of su...
def FilterGOstring(names_filter=["age-", "aging", "aged", 'aging', 'aging.', 'aging,'],\ exclude_names=["packaging","voltage","cleavage-",\ "stage-1","cage-like","message-specific",\ "damage-associated","stage-specific","foraging",\ ...
Prepares the data in CSV format
def format_csv(self, delim=',', qu='"'): """ Prepares the data in CSV format """ res = qu + self.name + qu + delim if self.data: for d in self.data: res += qu + str(d) + qu + delim return res + '\n'
Prepares the data as a dictionary with column headers TODO - get variable names of data [] as strings for hdr
def format_dict(self, delim=':', qu="'"): """ Prepares the data as a dictionary with column headers TODO - get variable names of data[] as strings for hdr """ res = 'name' + delim + qu + self.name + qu + ',' for num, d in enumerate(self.data): res += 'col' + s...
return a trace of parents and children of the obect
def format_all(self): """ return a trace of parents and children of the obect """ res = '\n--- Format all : ' + str(self.name) + ' -------------\n' res += ' parent = ' + str(self.parent) + '\n' res += self._get_all_children() res += self._get_links() ...
return the list of children of a node
def _get_all_children(self,): """ return the list of children of a node """ res = '' if self.child_nodes: for c in self.child_nodes: res += ' child = ' + str(c) + '\n' if c.child_nodes: for grandchild in c.child_nod...
return the list of links of a node
def _get_links(self,): """ return the list of links of a node """ res = '' if self.links: for l in self.links: res += ' links = ' + str(l[0]) + '\n' if l[0].child_nodes: for chld in l[0].child_nodes: ...
this expands a current node by defining ALL the children for that process TODO = processes need to be recalculated
def expand(self, process, child_nodes): """ this expands a current node by defining ALL the children for that process TODO = processes need to be recalculated """ #print('TODO: process check = ', process) #print(self.name, ' expanded to ->', child_nodes) ...
this contracts the current node to its parent and then either caclulates the params and values if all child data exists OR uses the default parent data. ( In real terms it returns the parent and recalculates ) TODO = processes need to be recalculated
def contract(self, process): """ this contracts the current node to its parent and then either caclulates the params and values if all child data exists, OR uses the default parent data. (In real terms it returns the parent and recalculates) TODO = processes need to be ...
find the child object by name and return the object
def get_child_by_name(self, name): """ find the child object by name and return the object """ for c in self.child_nodes: if c.name == name: return c return None
adds a link from this thing to other thing using type ( is_a has_a uses contains part_of )
def links_to(self, other, tpe): """ adds a link from this thing to other thing using type (is_a, has_a, uses, contains, part_of) """ if self.check_type(tpe): self.links.append([other, tpe]) else: raise Exception('aikif.core_data cannot process this...
returns the filename
def get_filename(self, year): """ returns the filename """ res = self.fldr + os.sep + self.type + year + '.' + self.user return res
save table to folder in appropriate files NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE
def save(self, file_tag='2016', add_header='N'): """ save table to folder in appropriate files NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE """ fname = self.get_filename(file_tag) with open(fname, 'a') as f: if add_header == 'Y': f.writ...
Prepares the header in CSV format
def format_hdr(self, delim=',', qu='"'): """ Prepares the header in CSV format """ res = '' if self.header: for d in self.header: res += qu + str(d) + qu + delim return res + '\n'
extracts event information from core tables into diary files
def generate_diary(self): """ extracts event information from core tables into diary files """ print('Generate diary files from Event rows only') for r in self.table: print(str(type(r)) + ' = ', r)
Takes a list of VariantProbeCoverages and returns a Call for the Variant. Note in the simplest case the list will be of length one. However we may be typing the Variant on multiple backgrouds leading to multiple VariantProbes for a single Variant.
def type(self, variant_probe_coverages, variant=None): """ Takes a list of VariantProbeCoverages and returns a Call for the Variant. Note, in the simplest case the list will be of length one. However, we may be typing the Variant on multiple backgrouds leading to multiple Var...
Creator function for creating an instance of an Ansible script.
def creator(entry, config): """Creator function for creating an instance of an Ansible script.""" ansible_playbook = "ansible.playbook.dry.run.see.comment" ansible_inventory = "ansible.inventory.dry.run.see.comment" ansible_playbook_content = render(config.script, model=config.model, en...
Function that performs one step of the Game of Life
def update_gol(self): """ Function that performs one step of the Game of Life """ updated_grid = [[self.update_cell(row, col) \ for col in range(self.get_grid_width())] \ for row in range(self.get_grid_height())] ...
Function that computes the update for one cell in the Game of Life
def update_cell(self, row, col): """ Function that computes the update for one cell in the Game of Life """ # compute number of living neighbors neighbors = self.eight_neighbors(row, col) living_neighbors = 0 for neighbor in neighbors: if not self.is_e...
takes a list of bitmap points ( drawn via Life screen ) and converts to a list of full coordinates
def bitmap_pattern_to_list(self, bmp_pat): """ takes a list of bitmap points (drawn via Life screen) and converts to a list of full coordinates """ res = [] x = 1 y = 1 lines = bmp_pat.split('\n') for line in lines: y += 1 ...
offsets a pattern list generated below to a random position in the grid
def random_offset(self, lst): """ offsets a pattern list generated below to a random position in the grid """ res = [] x = random.randint(4,self.max_x - 42) y = random.randint(4,self.max_y - 10) for itm in lst: res.append([itm[0] + y, itm[1] +...
Make a Hist1D from a numpy bin_edges + histogram pair: param histogram: Initial histogram: param bin_edges: Bin edges of histogram. Must be one longer than length of histogram: param axis_names: Ignored. Sorry: - ): return:
def from_histogram(cls, histogram, bin_edges, axis_names=None): """Make a Hist1D from a numpy bin_edges + histogram pair :param histogram: Initial histogram :param bin_edges: Bin edges of histogram. Must be one longer than length of histogram :param axis_names: Ignored. Sorry :-) ...
Gives emprical PDF like np. histogram (.... density = True )
def density(self): """Gives emprical PDF, like np.histogram(...., density=True)""" h = self.histogram.astype(np.float) bindifs = np.array(np.diff(self.bin_edges), float) return h / (bindifs * self.n)
Returns random variates from the histogram. Note this assumes the histogram is an events per bin not a pdf. Inside the bins a uniform distribution is assumed.
def get_random(self, size=10): """Returns random variates from the histogram. Note this assumes the histogram is an 'events per bin', not a pdf. Inside the bins, a uniform distribution is assumed. """ bin_i = np.random.choice(np.arange(len(self.bin_centers)), size=size, p=self.no...
Estimates std of underlying data assuming each datapoint was exactly in the center of its bin.
def std(self, bessel_correction=True): """Estimates std of underlying data, assuming each datapoint was exactly in the center of its bin.""" if bessel_correction: n = self.n bc = n / (n - 1) else: bc = 1 return np.sqrt(np.average((self.bin_centers - se...