INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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.
:param database: A string for the database to query, e.g. 'WORMBASE_GENE_ID'
:param categories: A comma separated string with data... | 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
:param df: a dataframe output from DAVIDenrich
:param GTF: a GTF dataframe from readGTF()
:param name_id: instead of a gtf dataframe a dataframe with the columns 'gene_name' and 'gene_id' can be given ... | 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.
: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 header of the column containing the identifiers
:param fieldTOretrieve: the field to retrieve from ... | 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.
:param database: a string for the database to query, e.g. 'WORMBASE_GENE_ID'
... | 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.
Args:
path (str): path to check.
Returns:
bool: True when to ignore given 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.
Args:
supported_extensions (list): supported file extentsion for which to check loc and com.
Returns:
str: yield each full path and filename found. | 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.
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:
int, int: loc and com for given file. | 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.
:param host: address of the host server, default='http://www.ensembl.org/biomart'
:returns: nothing | 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.
:param dataset: dataset to list filters of.
:param host: address of the host server, default='http://www.ensembl.org/biomart'
:returns: nothing | 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.
:param query_attributes: list of attributes to recover from BioMart
:param query_dataset: dataset to query
:param query_filter: 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_... | 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 exc... | 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... |
Plots the histogram with Poisson (sqrt(n)) error bars
- scale_errors_by multiplies the error bars by its argument
- scale_histogram_by multiplies the histogram AND the error bars by its argument
- plt thing to call .errorbar on (pylab, figure, axes, whatever the matplotlib guys come up wit... | def plot(self, normed=False, scale_errors_by=1.0, scale_histogram_by=1.0, plt=plt, errors=False, **kwargs):
"""Plots the histogram with Poisson (sqrt(n)) error bars
- scale_errors_by multiplies the error bars by its argument
- scale_histogram_by multiplies the histogram AND the error bars by... |
Return bin center nearest to percentile | def percentile(self, percentile):
"""Return bin center nearest to percentile"""
return self.bin_centers[np.argmin(np.abs(self.cumulative_density * 100 - percentile))] |
Lookup values at coordinates.
coordinates: arraylike of coordinates.
Clips if out of range!! TODO: option to throw exception instead.
TODO: Needs tests!! | def lookup(self, coordinates):
"""Lookup values at coordinates.
coordinates: arraylike of coordinates.
Clips if out of range!! TODO: option to throw exception instead.
TODO: Needs tests!!
"""
# Convert coordinates to indices
index_array = np.clip(np.searchsorted(... |
Make a HistdD from numpy histogram + bin edges
:param histogram: Initial histogram
:param bin_edges: x bin edges of histogram, y bin edges, ...
:return: Histnd instance | def from_histogram(cls, histogram, bin_edges, axis_names=None):
"""Make a HistdD from numpy histogram + bin edges
:param histogram: Initial histogram
:param bin_edges: x bin edges of histogram, y bin edges, ...
:return: Histnd instance
"""
bin_edges = np.array(bin_edges)
... |
Return bin_edges, histogram array | def _data_to_hist(self, data, **kwargs):
"""Return bin_edges, histogram array"""
if hasattr(self, 'bin_edges'):
kwargs.setdefault('bins', self.bin_edges)
if len(data) == 1 and isinstance(data[0], COLUMNAR_DATA_SOURCES):
data = data[0]
if self.axis_names is N... |
Return axis names without axis, or None if axis_names is None | def axis_names_without(self, axis):
"""Return axis names without axis, or None if axis_names is None"""
if self.axis_names is None:
return None
return itemgetter(*self.other_axes(axis))(self.axis_names) |
Return bin centers along an axis, or if axis=None, list of bin_centers along each axis | def bin_centers(self, axis=None):
"""Return bin centers along an axis, or if axis=None, list of bin_centers along each axis"""
if axis is None:
return np.array([self.bin_centers(axis=i) for i in range(self.dimensions)])
axis = self.get_axis_number(axis)
return 0.5 * (self.bin... |
Returns index along axis of bin in histogram which contains value
Inclusive on both endpoints | def get_axis_bin_index(self, value, axis):
"""Returns index along axis of bin in histogram which contains value
Inclusive on both endpoints
"""
axis = self.get_axis_number(axis)
bin_edges = self.bin_edges[axis]
# The right bin edge of np.histogram is inclusive:
if... |
Returns index tuple in histogram of bin which contains value | def get_bin_indices(self, values):
"""Returns index tuple in histogram of bin which contains value"""
return tuple([self.get_axis_bin_index(values[ax_i], ax_i)
for ax_i in range(self.dimensions)]) |
Return ndarray of same shape as histogram containing bin center value along axis at each point | def all_axis_bin_centers(self, axis):
"""Return ndarray of same shape as histogram containing bin center value along axis at each point"""
# Arcane hack that seems to work, at least in 3d... hope
axis = self.get_axis_number(axis)
return np.meshgrid(*self.bin_centers(), indexing='ij')[axi... |
Sums all data along axis, returns d-1 dimensional histogram | def sum(self, axis):
"""Sums all data along axis, returns d-1 dimensional histogram"""
axis = self.get_axis_number(axis)
if self.dimensions == 2:
new_hist = Hist1d
else:
new_hist = Histdd
return new_hist.from_histogram(np.sum(self.histogram, axis=axis),
... |
Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop
(both inclusive). Returns d dimensional histogram. | def slice(self, start, stop=None, axis=0):
"""Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop
(both inclusive). Returns d dimensional histogram."""
if stop is None:
# Make a 1=bin slice
stop = start
axis = self.... |
Slices the histogram along axis, then sums over that slice, returning a d-1 dimensional histogram | def slicesum(self, start, stop=None, axis=0):
"""Slices the histogram along axis, then sums over that slice, returning a d-1 dimensional histogram"""
return self.slice(start, stop, axis).sum(axis) |
Sums all data along all other axes, then return Hist1D | def projection(self, axis):
"""Sums all data along all other axes, then return Hist1D"""
axis = self.get_axis_number(axis)
projected_hist = np.sum(self.histogram, axis=self.other_axes(axis))
return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis]) |
Returns new histogram with all data cumulated along axis. | def cumulate(self, axis):
"""Returns new histogram with all data cumulated along axis."""
axis = self.get_axis_number(axis)
return Histdd.from_histogram(np.cumsum(self.histogram, axis=axis),
bin_edges=self.bin_edges,
axis_... |
Returns new histogram where all values along axis (in one bin of the other axes) sum to 1 | def normalize(self, axis):
"""Returns new histogram where all values along axis (in one bin of the other axes) sum to 1"""
axis = self.get_axis_number(axis)
sum_along_axis = np.sum(self.histogram, axis=axis)
# Don't do anything for subspaces without any entries -- this avoids nans everyw... |
Returns new histogram with all values replaced by their central likelihoods along axis. | def central_likelihood(self, axis):
"""Returns new histogram with all values replaced by their central likelihoods along axis."""
result = self.cumulative_density(axis)
result.histogram = 1 - 2 * np.abs(result.histogram - 0.5)
return result |
Returns d-1 dimensional histogram containing percentile of values along axis
if inclusive=True, will report bin center of first bin for which percentile% of data lies in or below the bin
=False, ... data lies strictly below the bin
10% percentile is calculated as: value at least 10% ... | def percentile(self, percentile, axis, inclusive=True):
"""Returns d-1 dimensional histogram containing percentile of values along axis
if inclusive=True, will report bin center of first bin for which percentile% of data lies in or below the bin
=False, ... data lies strictly below t... |
Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!! | def average(self, axis):
"""Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!!
"""
axis = self.get_axis_number(axis)
avg_hist = np.ma.average(self.all_axis_bin_centers(axis),
... |
Returns d-1 dimensional histogram of (estimated) std value along axis
NB this is very different from just std of the histogram values (which describe bin counts) | def std(self, axis):
"""Returns d-1 dimensional histogram of (estimated) std value along axis
NB this is very different from just std of the histogram values (which describe bin counts)
"""
def weighted_std(values, weights, axis):
# Stolen from http://stackoverflow.com/questi... |
Return a new histogram that is 'rebinned' (zoomed) by factors (tuple of floats) along each dimensions
factors: tuple with zoom factors along each axis. e.g. 2 = double number of bins, 0.5 = halve them.
order: Order for spline interpolation in scipy.ndimage.zoom. Defaults to linear interpolation (or... | def rebin(self, *factors, **kwargs):
"""Return a new histogram that is 'rebinned' (zoomed) by factors (tuple of floats) along each dimensions
factors: tuple with zoom factors along each axis. e.g. 2 = double number of bins, 0.5 = halve them.
order: Order for spline interpolation in scipy.ndi... |
Returns (size, n_dim) array of random variates from the histogram.
Inside the bins, a uniform distribution is assumed
Note this assumes the histogram is an 'events per bin', not a pdf.
TODO: test more. | def get_random(self, size=10):
"""Returns (size, n_dim) array of random variates from the histogram.
Inside the bins, a uniform distribution is assumed
Note this assumes the histogram is an 'events per bin', not a pdf.
TODO: test more.
"""
# Sample random bin centers
... |
Lookup values at specific points.
coordinate_arrays: numpy arrays of coordinates, one for each dimension
e.g. lookup(np.array([0, 2]), np.array([1, 3])) looks up (x=0, y=1) and (x=2, y3).
Clips if out of range!! TODO: option to throw exception instead.
TODO: Needs tests!!
TODO: ... | def lookup(self, *coordinate_arrays):
"""Lookup values at specific points.
coordinate_arrays: numpy arrays of coordinates, one for each dimension
e.g. lookup(np.array([0, 2]), np.array([1, 3])) looks up (x=0, y=1) and (x=2, y3).
Clips if out of range!! TODO: option to throw exception in... |
Return histogram within binning of Histdd mh, with values looked up in this histogram.
This is not rebinning: no interpolation /renormalization is performed.
It's just a lookup. | def lookup_hist(self, mh):
"""Return histogram within binning of Histdd mh, with values looked up in this histogram.
This is not rebinning: no interpolation /renormalization is performed.
It's just a lookup.
"""
result = mh.similar_blank_histogram()
points = np.stack([mh... |
takes a dictionary read from a yaml file and converts
it to the roadmap documentation | def create_roadmap_doc(dat, opFile):
"""
takes a dictionary read from a yaml file and converts
it to the roadmap documentation
"""
op = format_title('Roadmap for AIKIF')
for h1 in dat['projects']:
op += format_h1(h1)
if dat[h1] is None:
op += '(No details)\n'
... |
Reset the game so the grid is zeros (or default items) | def reset(self):
"""
Reset the game so the grid is zeros (or default items)
"""
self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in range(self.grid_height)] |
Clears grid to be EMPTY | def clear(self):
"""
Clears grid to be EMPTY
"""
self.grid = [[EMPTY for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)] |
saves a grid to file as ASCII text | def save(self, fname):
""" saves a grid to file as ASCII text """
try:
with open(fname, "w") as f:
f.write(str(self))
except Exception as ex:
print('ERROR = cant save grid results to ' + fname + str(ex)) |
loads a ASCII text file grid to self | def load(self, fname):
""" loads a ASCII text file grid to self """
# get height and width of grid from file
self.grid_width = 4
self.grid_height = 4
# re-read the file and load it
self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in ra... |
get column number 'col' | def extract_col(self, col):
"""
get column number 'col'
"""
new_col = [row[col] for row in self.grid]
return new_col |
get row number 'row' | def extract_row(self, row):
"""
get row number 'row'
"""
new_row = []
for col in range(self.get_grid_width()):
new_row.append(self.get_tile(row, col))
return new_row |
replace a grids row at index 'ndx' with 'line' | def replace_row(self, line, ndx):
"""
replace a grids row at index 'ndx' with 'line'
"""
for col in range(len(line)):
self.set_tile(ndx, col, line[col]) |
replace a grids column at index 'ndx' with 'line' | def replace_col(self, line, ndx):
"""
replace a grids column at index 'ndx' with 'line'
"""
for row in range(len(line)):
self.set_tile(row, ndx, line[row]) |
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time. | def new_tile(self, num=1):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
for _ in range(num):
if random.random() > .5:
new_tile = self.pieces[0]
... |
return a count of blank cells | def count_blank_positions(self):
"""
return a count of blank cells
"""
blanks = 0
for row_ndx in range(self.grid_height - 0):
for col_ndx in range(self.grid_width - 0):
if self.get_tile(row_ndx, col_ndx) == EMPTY:
blanks += 1
... |
return a count of blank cells | def count_filled_positions(self):
"""
return a count of blank cells
"""
filled = 0
for row_ndx in range(self.grid_height - 0):
for col_ndx in range(self.grid_width - 0):
if self.get_tile(row_ndx, col_ndx) != EMPTY:
filled += 1
... |
Set the tile at position row, col to have the given value. | def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
#print('set_tile: y=', row, 'x=', col)
if col < 0:
print("ERROR - x less than zero", col)
col = 0
#return
if col > s... |
Returns horiz/vert neighbors of cell (row, col) | def four_neighbors(self, row, col):
"""
Returns horiz/vert neighbors of cell (row, col)
"""
ans = []
if row > 0:
ans.append((row - 1, col))
if row < self.grid_height - 1:
ans.append((row + 1, col))
if col > 0:
ans.append((row, c... |
Returns horiz/vert neighbors of cell (row, col) as well as
diagonal neighbors | def eight_neighbors(self, row, col):
"""
Returns horiz/vert neighbors of cell (row, col) as well as
diagonal neighbors
"""
ans = []
if row > 0:
ans.append((row - 1, col))
if row < self.grid_height - 1:
ans.append((row + 1, col))
if ... |
replace all cells in current grid with updated grid | def replace_grid(self, updated_grid):
"""
replace all cells in current grid with updated grid
"""
for col in range(self.get_grid_width()):
for row in range(self.get_grid_height()):
if updated_grid[row][col] == EMPTY:
self.set_empty(row, col... |
finds a place on the grid which is clear on all sides
to avoid starting in the middle of a blockage | def find_safe_starting_point(self):
"""
finds a place on the grid which is clear on all sides
to avoid starting in the middle of a blockage
"""
y = random.randint(2,self.grid_height-4)
x = random.randint(2,self.grid_width-4)
return y, x |
takes a screenshot of the users desktop (Currently Win only) | def screenshot(fname):
"""
takes a screenshot of the users desktop (Currently Win only)
"""
try:
im = ImageGrab.grab()
im.save(fname)
except Exception as ex:
print('image_tools.screenshot:cant create screenshot ' + str(ex)) |
resize an image to basewidth | def resize(fname, basewidth, opFilename):
""" resize an image to basewidth """
if basewidth == 0:
basewidth = 300
img = Image.open(fname)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
i... |
prints stats, remember that img should already have been loaded | def print_stats(img):
""" prints stats, remember that img should already have been loaded """
stat = ImageStat.Stat(img)
print("extrema : ", stat.extrema)
print("count : ", stat.count)
print("sum : ", stat.sum)
print("sum2 : ", stat.sum2)
print("mean : ", stat.mean... |
high level that prints all as long list | def print_all_metadata(fname):
""" high level that prints all as long list """
print("Filename :", fname )
print("Basename :", os.path.basename(fname))
print("Path :", os.path.dirname(fname))
print("Size :", os.path.getsize(fname))
img = Image.open(fname)
# get the image's wi... |
Gets all metadata and puts into dictionary | def get_metadata_as_dict(fname):
""" Gets all metadata and puts into dictionary """
imgdict = {}
try:
imgdict['filename'] = fname
imgdict['size'] = str(os.path.getsize(fname))
imgdict['basename'] = os.path.basename(fname)
imgdict['path'] = os.path.dirname(fname)
img ... |
Gets all metadata and puts into CSV format | def get_metadata_as_csv(fname):
""" Gets all metadata and puts into CSV format """
q = chr(34)
d = ","
res = q + fname + q + d
res = res + q + os.path.basename(fname) + q + d
res = res + q + os.path.dirname(fname) + q + d
try:
res = res + q + str(os.path.getsize(fname)) + q + d
... |
convert an image by adding text | def add_text_to_image(fname, txt, opFilename):
""" convert an image by adding text """
ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil")
#wh = ft.getsize(txt)
print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename)
im = Image.open(fname)
draw = ImageD... |
convert an image by adding a cross hair | def add_crosshair_to_image(fname, opFilename):
""" convert an image by adding a cross hair """
im = Image.open(fname)
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=(255, 255, 255))
draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255))
del draw
im.save(opFilename) |
convert an image by applying a contour | def filter_contour(imageFile, opFile):
""" convert an image by applying a contour """
im = Image.open(imageFile)
im1 = im.filter(ImageFilter.CONTOUR)
im1.save(opFile) |
Checking Images for duplicates (despite resizing, colours, etc) | def check_image_duplicates(file_list):
""" Checking Images for duplicates (despite resizing, colours, etc) """
master_hash = ''
ham_dist = 0
results = []
print("Checking Images for duplicates (despite resizing, colours, etc) " )
for ndx, fname in enumerate(file_list):
#img = Image.open(f... |
Return the Hamming distance between equal-length sequences
(http://en.wikipedia.org/wiki/Hamming_distance ) | def hamming_distance(s1, s2):
"""
Return the Hamming distance between equal-length sequences
(http://en.wikipedia.org/wiki/Hamming_distance )
"""
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) |
Grayscale and shrink the image in one step | def get_img_hash(image, hash_size = 8):
""" Grayscale and shrink the image in one step """
image = image.resize((hash_size + 1, hash_size), Image.ANTIALIAS, )
pixels = list(image.getdata())
#print('get_img_hash: pixels=', pixels)
# Compare adjacent pixels.
difference = []
for row in range... |
read an image from file - PIL doesnt close nicely | def load_image(fname):
""" read an image from file - PIL doesnt close nicely """
with open(fname, "rb") as f:
i = Image.open(fname)
#i.load()
return i |
output the image as text | def dump_img(fname):
""" output the image as text """
img = Image.open(fname)
width, _ = img.size
txt = ''
pixels = list(img.getdata())
for col in range(width):
txt += str(pixels[col:col+width])
return txt |
Python implementation of the CellPlot from the CellPlot package for R.
-inf or inf enrichments will come out as min found float or max found float, respectively.
:param df: pandas dataframe with the following columns - 'Enrichment', 'Term', and 'log2fc'.
For log2fc each cell must contain a comma... | def CellPlot(df, output_file=None, gene_expression="log2FC", figure_title="CellPlot", pvalCol="elimFisher", lowerLimit=None, upperLimit=None, colorBarType='Spectral'):
"""
Python implementation of the CellPlot from the CellPlot package for R.
-inf or inf enrichments will come out as min found float or max f... |
Python implementation of the SymPlot from the CellPlot package for R.
-inf or inf enrichments will come out as min found float or max found float, respectively.
:param df: pandas dataframe with the following columns - 'Enrichment', 'Significant', 'Annotated', 'Term', and 'log2fc'.
'Annotated'i s... | def SymPlot(df,output_file=None,figure_title="SymPlot",pvalCol="elimFisher"):
"""
Python implementation of the SymPlot from the CellPlot package for R.
-inf or inf enrichments will come out as min found float or max found float, respectively.
:param df: pandas dataframe with the following columns - 'En... |
Normalizes intensities of a gene in two samples
:param df: dataframe output of GetData()
:param sampleA: column header of sample A
:param sampleB: column header of sample B
:returns: normalized intensities | def NormInt(df,sampleA,sampleB):
"""
Normalizes intensities of a gene in two samples
:param df: dataframe output of GetData()
:param sampleA: column header of sample A
:param sampleB: column header of sample B
:returns: normalized intensities
"""
c1=df[sampleA]
c2=df[sampleB]
... |
Plots an MA like plot GetData() outputs.
:param df: dataframe output of GetData()
:param title: plot title, 'Genes' or 'Transcripts'
:param figName: /path/to/saved/figure/prefix
:param c: pair of samples to be plotted in list format
:param daType: data type, ie. 'counts' or 'FPKM'
:param nbins:... | def MA(df,title,figName,c, daType="counts",nbins=10,perc=.5,deg=3,eq=True,splines=True,spec=None,Targets=None,ylim=None,sizeRed=8):
"""
Plots an MA like plot GetData() outputs.
:param df: dataframe output of GetData()
:param title: plot title, 'Genes' or 'Transcripts'
:param figName: /path/to/saved... |
Testing given number to be a prime.
>>> [n for n in range(100+1) if is_prime(n)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] | def is_prime(number):
"""
Testing given number to be a prime.
>>> [n for n in range(100+1) if is_prime(n)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
if number < 2:
return False
if number % 2 == 0:
return number == 2
... |
Return array of valid flows (i.e. excluding rejected years etc)
:param catchment: gauged catchment with amax_records set
:type catchment: :class:`floodestimation.entities.Catchment`
:return: 1D array of flow values
:rtype: :class:`numpy.ndarray` | def valid_flows_array(catchment):
"""
Return array of valid flows (i.e. excluding rejected years etc)
:param catchment: gauged catchment with amax_records set
:type catchment: :class:`floodestimation.entities.Catchment`
:return: 1D array of flow values
:rtype: :class:`numpy.ndarray`
"""
... |
Return QMED estimate using best available methodology depending on what catchment attributes are available.
The preferred/best order of methods is defined by :attr:`qmed_methods`. Alternatively, a method can be supplied
e.g. `method='descriptors_1999'` to force the use of a particular method.
... | def qmed(self, method='best', **method_options):
"""
Return QMED estimate using best available methodology depending on what catchment attributes are available.
The preferred/best order of methods is defined by :attr:`qmed_methods`. Alternatively, a method can be supplied
e.g. `method='... |
Returns a dict of QMED methods using all available methods.
Available methods are defined in :attr:`qmed_methods`. The returned dict keys contain the method name, e.g.
`amax_record` with value representing the corresponding QMED estimate in m³/s.
:return: dict of QMED estimates
:rtype:... | def qmed_all_methods(self):
"""
Returns a dict of QMED methods using all available methods.
Available methods are defined in :attr:`qmed_methods`. The returned dict keys contain the method name, e.g.
`amax_record` with value representing the corresponding QMED estimate in m³/s.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.