INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case)
def add_case(self, case_obj): """Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case) """ for ind_obj in case_obj.individuals: self._add_individual(ind_obj) logger.debug("Adding case {0} to plugin...
Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object
def case(self, case_id=None): """Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object """ cases = self.cases() if case_id: for case ...
Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual)
def individual(self, ind_id=None): """Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual) """ for ind_obj in self.individuals: if ind_obj.ind_id == ...
Computes distance between 2D points using chebyshev metric :param point1: 1st point :type point1: list :param point2: 2nd point :type point2: list :returns: Distance between point1 and point2 :rtype: float
def chebyshev(point1, point2): """Computes distance between 2D points using chebyshev metric :param point1: 1st point :type point1: list :param point2: 2nd point :type point2: list :returns: Distance between point1 and point2 :rtype: float """ return max(abs(point1[0] - point2[0]),...
Rotates and flips a quadrant appropriately for the Hilbert scan generator. See https://en.wikipedia.org/wiki/Hilbert_curve.
def hilbertrot(n, x, y, rx, ry): """Rotates and flips a quadrant appropriately for the Hilbert scan generator. See https://en.wikipedia.org/wiki/Hilbert_curve. """ if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x return x, y
Scan pixels in a circle pattern around a center point :param x0: Center x-coordinate :type x0: float :param y0: Center y-coordinate :type y0: float :param r1: Initial radius :type r1: float :param r2: Final radius :type r2: float :returns: Coordinate generator :rtype: function
def circlescan(x0, y0, r1, r2): """Scan pixels in a circle pattern around a center point :param x0: Center x-coordinate :type x0: float :param y0: Center y-coordinate :type y0: float :param r1: Initial radius :type r1: float :param r2: Final radius :type r2: float :returns: Coor...
Scan pixels in a grid pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: int :param stepx: Step size in x-coo...
def gridscan(xi, yi, xf, yf, stepx=1, stepy=1): """Scan pixels in a grid pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate...
Scan pixels in a Hilbert curve pattern in the first quadrant. Modified algorithm from https://en.wikipedia.org/wiki/Hilbert_curve. :param size: Size of enclosing square :type size: int :param distance: Distance along curve (Must be smaller than size**2 - 1) :type distance: int :returns: Coordi...
def hilbertscan(size, distance): """Scan pixels in a Hilbert curve pattern in the first quadrant. Modified algorithm from https://en.wikipedia.org/wiki/Hilbert_curve. :param size: Size of enclosing square :type size: int :param distance: Distance along curve (Must be smaller than size**2 - 1) ...
Scan pixels in a ring pattern around a center point clockwise :param x0: Center x-coordinate :type x0: int :param y0: Center y-coordinate :type y0: int :param r1: Initial radius :type r1: int :param r2: Final radius :type r2: int :param metric: Distance metric :type metric: func...
def ringscan(x0, y0, r1, r2, metric=chebyshev): """Scan pixels in a ring pattern around a center point clockwise :param x0: Center x-coordinate :type x0: int :param y0: Center y-coordinate :type y0: int :param r1: Initial radius :type r1: int :param r2: Final radius :type r2: int ...
Scan pixels in a snake pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: int :returns: Coordinate generator ...
def snakescan(xi, yi, xf, yf): """Scan pixels in a snake pattern along the x-coordinate then y-coordinate :param xi: Initial x-coordinate :type xi: int :param yi: Initial y-coordinate :type yi: int :param xf: Final x-coordinate :type xf: int :param yf: Final y-coordinate :type yf: i...
Scan pixels in a random walk pattern with given step probabilities. The random walk will continue indefinitely unless a skip transformation is used with the 'stop' parameter set or a clip transformation is used with the 'abort' parameter set to True. The probabilities are normalized to sum to 1. :param...
def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25): """Scan pixels in a random walk pattern with given step probabilities. The random walk will continue indefinitely unless a skip transformation is used with the 'stop' parameter set or a clip transformation is used with the 'abort' parameter set t...
Next point in iteration
def next(self): """Next point in iteration """ while True: x, y = next(self.scan) if self.predicate is not None and not self.predicate(x,y): if self.abort: raise StopIteration("Boundary crossed!") elif (x < self.minx or x > self...
Next point in iteration
def next(self): """Next point in iteration """ x, y = next(self.scan) xr = -x if self.rx else x yr = -y if self.ry else y return xr, yr
Next point in iteration
def next(self): """Next point in iteration """ if self.count < len(self.reservoir): self.count += 1 return self.reservoir[self.count-1] raise StopIteration("Reservoir exhausted")
Next point in iteration
def next(self): """Next point in iteration """ x, y = next(self.scan) ca, sa = math.cos(self.angle), math.sin(self.angle) xr = ca * x - sa * y yr = sa * x + ca * y return xr, yr
Next point in iteration
def next(self): """Next point in iteration """ if self.probability == 1: x, y = next(self.scan) else: while True: x, y = next(self.scan) if random.random() <= self.probability: break return x, y
Next point in iteration
def next(self): """Next point in iteration """ x, y = next(self.scan) xr = self.sx * x yr = self.sy * y return xr, yr
Next point in iteration
def next(self): """Next point in iteration """ while True: x, y = next(self.scan) self.index += 1 if (self.index < self.start): continue if (self.index > self.stop): raise StopIteration("skip stopping") if ((self.index-self.start) % sel...
Next point in iteration
def next(self): """Next point in iteration """ x, y = next(self.scan) xs = int(round(x)) ys = int(round(y)) return xs, ys
Next point in iteration
def next(self): """Next point in iteration """ x, y = next(self.scan) xr = x + self.tx yr = y + self.ty return xr, yr
Validates whether a configuration is valid. :rtype: bool :raises ConfigurationError: if no ``access_token`` provided. :raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters. :raises ConfigurationError: if provided ``access_token`` is invalid...
def validate(self): """Validates whether a configuration is valid. :rtype: bool :raises ConfigurationError: if no ``access_token`` provided. :raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters. :raises ConfigurationError: if provi...
Start synchronization flow Starts a new synchronization session. This is the first endpoint to call, in order to start a new synchronization session. :calls: ``post /sync/start`` :param string device_uuid: Device's UUID for which to perform synchronization. :return: Dictionary ...
def start(self, device_uuid): """ Start synchronization flow Starts a new synchronization session. This is the first endpoint to call, in order to start a new synchronization session. :calls: ``post /sync/start`` :param string device_uuid: Device's UUID for which to per...
Get data from queue Fetch fresh data from the named queue. Using session identifier you call continously the `#fetch` method to drain the named queue. :calls: ``get /sync/{session_id}/queues/main`` :param string device_uuid: Device's UUID for which to perform synchronization. :...
def fetch(self, device_uuid, session_id): """ Get data from queue Fetch fresh data from the named queue. Using session identifier you call continously the `#fetch` method to drain the named queue. :calls: ``get /sync/{session_id}/queues/main`` :param string device_uuid:...
Acknowledge received data Send acknowledgement keys to let know the Sync service which data you have. As you fetch new data, you need to send acknowledgement keys. :calls: ``post /sync/ack`` :param string device_uuid: Device's UUID for which to perform synchronization. :param l...
def ack(self, device_uuid, ack_keys): """ Acknowledge received data Send acknowledgement keys to let know the Sync service which data you have. As you fetch new data, you need to send acknowledgement keys. :calls: ``post /sync/ack`` :param string device_uuid: Device's U...
Perform a full synchronization flow. .. code-block:: python :linenos: >>> client = basecrm.Client(access_token='<YOUR_PERSONAL_ACCESS_TOKEN>') >>> sync = basecrm.Sync(client=client, device_uuid='<YOUR_DEVICES_UUID>') >>> sync.fetch(lambda meta, data: basecrm.Syn...
def fetch(self, callback): """ Perform a full synchronization flow. .. code-block:: python :linenos: >>> client = basecrm.Client(access_token='<YOUR_PERSONAL_ACCESS_TOKEN>') >>> sync = basecrm.Sync(client=client, device_uuid='<YOUR_DEVICES_UUID>') ...
Calculate the weighted mean of a list.
def weighted_mean(data, weights=None): """Calculate the weighted mean of a list.""" if weights is None: return mean(data) total_weight = float(sum(weights)) weights = [weight / total_weight for weight in weights] w_mean = 0 for i, weight in enumerate(weights): w_mean += weight * ...
Calculate the weighted mean of an array/list using numpy.
def numpy_weighted_mean(data, weights=None): """Calculate the weighted mean of an array/list using numpy.""" import numpy as np weights = np.array(weights).flatten() / float(sum(weights)) return np.dot(np.array(data), weights)
Calculate the median of a list.
def median(data): """Calculate the median of a list.""" data.sort() num_values = len(data) half = num_values // 2 if num_values % 2: return data[half] return 0.5 * (data[half-1] + data[half])
Calculate the weighted median of a list.
def weighted_median(data, weights=None): """Calculate the weighted median of a list.""" if weights is None: return median(data) midpoint = 0.5 * sum(weights) if any([j > midpoint for j in weights]): return data[weights.index(max(weights))] if any([j > 0 for j in weights]): so...
Calculate the weighted median of an array/list using numpy.
def numpy_weighted_median(data, weights=None): """Calculate the weighted median of an array/list using numpy.""" import numpy as np if weights is None: return np.median(np.array(data).flatten()) data, weights = np.array(data).flatten(), np.array(weights).flatten() if any(weights > 0): ...
Parses the supplied Redis URL and returns a dict with the parsed/split data. For ambiguous URLs like redis://localhost and redis://my_socket_file this function will prioritize network URLs over socket URLs. redis://my_socket_file will be interpreted as a network URL, with the Redis server having a hostname of ...
def parse_url(url): """Parses the supplied Redis URL and returns a dict with the parsed/split data. For ambiguous URLs like redis://localhost and redis://my_socket_file this function will prioritize network URLs over socket URLs. redis://my_socket_file will be interpreted as a network URL, with the Redis s...
Return a StrictRedis.__init__() compatible dictionary from data in the Flask config. Generate a dictionary compatible with StrictRedis.__init__() keyword arguments from data in the Flask application's configuration values relevant to Redis. This is where REDIS_URL (or whatever prefix used) is parsed, by c...
def read_config(config, prefix): """Return a StrictRedis.__init__() compatible dictionary from data in the Flask config. Generate a dictionary compatible with StrictRedis.__init__() keyword arguments from data in the Flask application's configuration values relevant to Redis. This is where REDIS_URL (...
Actual method to read Redis settings from app configuration and initialize the StrictRedis instance. Positional arguments: app -- Flask application instance. config_prefix -- Prefix used in config key names in the Flask app's configuration. Useful for applications which interface wi...
def init_app(self, app, config_prefix=None): """Actual method to read Redis settings from app configuration and initialize the StrictRedis instance. Positional arguments: app -- Flask application instance. config_prefix -- Prefix used in config key names in the Flask app's configuration...
.. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we do, following the behavior of GNU ``realpath(1)``!
def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we do, following the behavior of GNU ``realpath(1)``! """ real = Path.root() for segment in path.segments: current = real / segment seen ...
A recursive, non-atomic directory removal.
def _recursive_remove(fs, path): """ A recursive, non-atomic directory removal. """ if not fs.is_link(path=path) and fs.is_dir(path=path): for child in fs.children(path=path): _recursive_remove(fs=fs, path=child) fs.remove_empty_directory(path=path) else: fs.remov...
Create a new kind of filesystem.
def create( name, create_file, open_file, remove_file, create_directory, list_directory, remove_empty_directory, temporary_directory, stat, lstat, link, readlink, realpath=_realpath, remove=_recursive_remove, ): """ Create a new kind of filesystem. ...
Check that the given path exists on the filesystem. Note that unlike `os.path.exists`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up.
def _exists(fs, path): """ Check that the given path exists on the filesystem. Note that unlike `os.path.exists`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ ...
Check that the given path is a directory. Note that unlike `os.path.isdir`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up.
def _is_dir(fs, path): """ Check that the given path is a directory. Note that unlike `os.path.isdir`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ try: ...
Check that the given path is a file. Note that unlike `os.path.isfile`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up.
def _is_file(fs, path): """ Check that the given path is a file. Note that unlike `os.path.isfile`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ try: ...
Check that the given path is a symbolic link. Note that unlike `os.path.islink`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up.
def _is_link(fs, path): """ Check that the given path is a symbolic link. Note that unlike `os.path.islink`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ try...
:param page_number: The page number to fetch (1-indexed) :return: The requested page fetched from the API for the query
def get_page(self, page_number): """ :param page_number: The page number to fetch (1-indexed) :return: The requested page fetched from the API for the query """ if page_number: kwargs = dict(self._list_kwargs) kwargs['limit'] = self.limit kwar...
Fetch a list of resources from the API. :param kwargs: Parameters for the request (see from and below https://api.ghost.org/docs/limit) :return: The list of items returned by the API wrapped as `Model` objects with pagination by `ModelList`
def list(self, **kwargs): """ Fetch a list of resources from the API. :param kwargs: Parameters for the request (see from and below https://api.ghost.org/docs/limit) :return: The list of items returned by the API wrapped as `Model` objects with pagination by `Mod...
Fetch a resource from the API. Either the `id` or the `slug` has to be present. :param id: The ID of the resource :param slug: The slug of the resource :param kwargs: Parameters for the request (see from and below https://api.ghost.org/docs/limit) :return: The item r...
def get(self, id=None, slug=None, **kwargs): """ Fetch a resource from the API. Either the `id` or the `slug` has to be present. :param id: The ID of the resource :param slug: The slug of the resource :param kwargs: Parameters for the request (see from and be...
Creates a new resource. :param kwargs: The properties of the resource :return: The created item returned by the API wrapped as a `Model` object
def create(self, **kwargs): """ Creates a new resource. :param kwargs: The properties of the resource :return: The created item returned by the API wrapped as a `Model` object """ response = self.ghost.execute_post('%s/' % self._type_name, json={ ...
Updates an existing resource. :param id: The ID of the resource :param kwargs: The properties of the resource to change :return: The updated item returned by the API wrapped as a `Model` object
def update(self, id, **kwargs): """ Updates an existing resource. :param id: The ID of the resource :param kwargs: The properties of the resource to change :return: The updated item returned by the API wrapped as a `Model` object """ response = self....
Creates a new post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param kwargs: The properties of the post :return: The created `Post` object
def create(self, **kwargs): """ Creates a new post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param kwargs: The properties of the post :return: The created `Post` object """ return ...
Updates an existing post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param id: The ID of the existing post :param kwargs: The properties of the post to change :return: The updated `Post` object
def update(self, id, **kwargs): """ Updates an existing post. When the `markdown` property is present, it will be automatically converted to `mobiledoc` on v1.+ of the server. :param id: The ID of the existing post :param kwargs: The properties of the post to change ...
This function measures the residence time of all residues within the cutoff distance from the ligand. Takes: * cutoff * - cutoff distance in angstroms Output: * self.residue_counts * - dictionary of all residues that have made contact with the ligand (i.e. hav...
def measure_residence_time(self, cutoff = 3.5): """ This function measures the residence time of all residues within the cutoff distance from the ligand. Takes: * cutoff * - cutoff distance in angstroms Output: * self.residue_counts * - dictionary of all r...
Since plotting all residues that have made contact with the ligand over a lenghty simulation is not always feasible or desirable. Therefore, only the residues that have been in contact with ligand for a long amount of time will be plotted in the final image. The function first determine...
def define_residues_for_plotting_traj(self, analysis_cutoff): """ Since plotting all residues that have made contact with the ligand over a lenghty simulation is not always feasible or desirable. Therefore, only the residues that have been in contact with ligand for a long amount of time...
Make numpy array from timeseries data.
def make_table(self): """Make numpy array from timeseries data.""" num_records = np.sum([1 for frame in self.timeseries]) dtype = [("frame",float),("time",float),("ligand atom id",int), ("ligand atom name","|U4"),("cutoff",float), ("protein atom names",list),("pro...
Using rdkit to detect aromatic rings in ligand - size 4-6 atoms and all atoms are part of the ring. Saves this data in self.ligrings.
def detect_aromatic_rings_in_ligand(self): """Using rdkit to detect aromatic rings in ligand - size 4-6 atoms and all atoms are part of the ring. Saves this data in self.ligrings.""" self.ligrings = {} try: ring_info = self.topology_data.mol.GetRingInfo() self.ligand_ring...
Use rdkit to detect aromatic rings in protein. A (relatively) simpler case, since only 4 of 20 aa have rings. Since different forcefields can have different atom names, each of 4 aromatic residues is extracted as PDB file and the aromatic rings are detected for each. The case is trickier with TRP, since...
def detect_aromatic_rings_in_protein(self): """Use rdkit to detect aromatic rings in protein. A (relatively) simpler case, since only 4 of 20 aa have rings. Since different forcefields can have different atom names, each of 4 aromatic residues is extracted as PDB file and the aromatic rings are ...
Make MDAnalysis atom selections for rings in protein residues that will be plotted in the final figure - since they are the only ones that should be analysed. Saves the rings in self.protein_rings dictionary.
def define_all_protein_rings(self): """Make MDAnalysis atom selections for rings in protein residues that will be plotted in the final figure - since they are the only ones that should be analysed. Saves the rings in self.protein_rings dictionary. """ self.protein_rings = {} ...
Main analysis function. Analyses each frame in the trajectory in search for pi-pi interactions between previously defined rings on protein residues and ligand molecule.
def find_all_pistacking_pairs(self): """Main analysis function. Analyses each frame in the trajectory in search for pi-pi interactions between previously defined rings on protein residues and ligand molecule. """ data = namedtuple("pistacking","frame time proteinring ligandring distance angle of...
Make numpy array from timeseries data.
def make_table(self): """Make numpy array from timeseries data.""" num_records = int(np.sum([1 for frame in self.timeseries])) dtype = [ ("frame",float),("time",float),("proteinring",list), ("ligand_ring_ids",list),("distance",float),("angle",float), ...
Count how many times each individual pi-pi interaction occured throughout the simulation. Returns numpy array.
def count_by_type(self): """Count how many times each individual pi-pi interaction occured throughout the simulation. Returns numpy array.""" pistack = defaultdict(int) for contact in self.timeseries: #count by residue name not by proteinring pkey = (contact.ligan...
MDAnalysis atom selections of aromatic rings present in the ligand molecule. Takes: * ring * - index in self.ligrings dictionary Output: * ring_selection * - MDAnalysis Atom group
def get_ligand_ring_selection(self,ring): """MDAnalysis atom selections of aromatic rings present in the ligand molecule. Takes: * ring * - index in self.ligrings dictionary Output: * ring_selection * - MDAnalysis Atom group""" ring_names = "" for atom in ...
Calculates the frequency of pi-pi interactions throughout simulations. If the frequency exceeds the analysis cutoff, this interaction will be plotted in the final figure. Takes: * analysis_cutoff * - fraction of simulation time a feature has to be present for to be plotted Output: ...
def get_pistacking_frequency(self,analysis_cutoff): """Calculates the frequency of pi-pi interactions throughout simulations. If the frequency exceeds the analysis cutoff, this interaction will be plotted in the final figure. Takes: * analysis_cutoff * - fraction of simulation time a...
The total hydrogen bond count per frame is provided as CSV output file. Each trajectory has a separate file.
def write_output_files(self,traj): """ The total hydrogen bond count per frame is provided as CSV output file. Each trajectory has a separate file. """ try: os.chdir("analysis") except Exception as e: os.mkdir("analysis") os.chdir("anal...
获得给定的时间字符串,获得相应的时间戳 :param time_string: 时间字符串 :param fmt: :return:
def get_timestamp(cls, time_string: str, fmt: str): """ 获得给定的时间字符串,获得相应的时间戳 :param time_string: 时间字符串 :param fmt: :return: """ return int(time.mktime(time.strptime(time_string, fmt)))
解析给定的时间戳,获得相应的时间字符串 :param timestamp: :param fmt: :return:
def get_formatted_datetime_string(cls, timestamp: int, fmt="%Y-%m-%d %H:%M:%S"): """ 解析给定的时间戳,获得相应的时间字符串 :param timestamp: :param fmt: :return: """ return time.strftime(fmt, time.localtime(timestamp))
Puzzle: manage DNA variant resources.
def base(ctx, verbose, config): """Puzzle: manage DNA variant resources.""" # configure root logger to print to STDERR loglevel = LEVELS.get(min(verbose, 3)) configure_stream(level=loglevel) ctx.obj = {} if config and os.path.exists(config): ctx.obj = yaml.load(open(config, 'r')) or {} ...
Database replication subscriber. The function will subscribe to the event sourcing pk stream, retrive rows from master based pk and then update the slave.
def repl_db_sub(master_dsn, slave_dsn, tables): """Database replication subscriber. The function will subscribe to the event sourcing pk stream, retrive rows from master based pk and then update the slave. """ logger = logging.getLogger("meepo.sub.replicate_sub") # sqlalchemy reflection lo...
Return height / width ratio of the given Axes object. The ratio is calculated in 'display coordinate', defined in matplotlib document on transformation. Thus, the calculated ratio is what one would feels when the Axes is displayed to the her/him.
def get_axes_ratio(ax): """Return height / width ratio of the given Axes object. The ratio is calculated in 'display coordinate', defined in matplotlib document on transformation. Thus, the calculated ratio is what one would feels when the Axes is displayed to the her/him. """ ax_bbox_p...
DB Replication app. This script will replicate data from mysql master to other databases( including mysql, postgres, sqlite). This script only support a very limited replication: 1. data only. The script only replicates data, so you have to make sure the tables already exists in slave db. 2. ...
def main(master_dsn, slave_dsn, tables, blocking=False): """DB Replication app. This script will replicate data from mysql master to other databases( including mysql, postgres, sqlite). This script only support a very limited replication: 1. data only. The script only replicates data, so you have ...
Return text position corresponding to given 'pos'. The text alignment in the bounding box should be set accordingly in order to have a good-looking layout. This corresponding text alignment can be obtained by 'get_text_alignment' or 'get_text_position_and_inner_alignment' function.
def get_text_position_in_ax_coord(ax, pos, scale=default_text_relative_padding): """Return text position corresponding to given 'pos'. The text alignment in the bounding box should be set accordingly in order to have a good-looking layout. This corresponding text alignment can be obtained by 'get_text_...
Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position)
def get_text_alignment(pos): """Return 'verticalalignment'('va') and 'horizontalalignment'('ha') for given 'pos' (position)""" pos = pos.lower() # to make it case insensitive va, ha = None, None if pos == 'nw': va, ha = 'top', 'left' elif pos == 'ne': va, ha = 'top', 'right' elif pos == 'sw': v...
Return text position and its alignment in its bounding box. The returned position is given in Axes coordinate, as defined in matplotlib documentation on transformation. The returned alignment is given in dictionary, which can be put as a fontdict to text-relavent method.
def get_text_position_and_inner_alignment(ax, pos, scale=default_text_relative_padding, with_transAxes_kwargs=True): """Return text position and its alignment in its bounding box. The returned position is given in Axes coordinate, as defined in matplotlib documentation on transformation. The retur...
Return text position inside of the given axis
def get_text_position(fig, ax, ha='left', va='top', pad_scale=1.0): """Return text position inside of the given axis""" ## Check and preprocess input arguments try: pad_scale = float(pad_scale) except: raise TypeError("'pad_scale should be of type 'float'") for arg in [va, ha]: ass...
Flask app factory function. Args: config (Optional[path]): path to a Python module config file config_obj (Optional[class]): Python config object
def create_app(config=None, config_obj=None): """Flask app factory function. Args: config (Optional[path]): path to a Python module config file config_obj (Optional[class]): Python config object """ app = Flask(__name__) # configure application from external configs configure_ap...
Configure application instance. Args: app (Flask): initialized Flask app instance config (Optional[path]): path to a Python module config file config_obj (Optional[class]): Python config object
def configure_app(app, config=None, config_obj=None): """Configure application instance. Args: app (Flask): initialized Flask app instance config (Optional[path]): path to a Python module config file config_obj (Optional[class]): Python config object """ app.config.from_object(c...
Configure extensions. Args: app (Flask): initialized Flask app instance
def bind_extensions(app): """Configure extensions. Args: app (Flask): initialized Flask app instance """ # bind plugin to app object app.db = app.config['PUZZLE_BACKEND'] app.db.init_app(app) # bind bootstrap blueprints bootstrap.init_app(app) markdown(app) @app.templa...
Since MDAnalysis a pre-set list for acceptor and donor atoms for proteins and solvents from specific forcefields, it is necessary to find donor and acceptor atoms for the ligand molecule. This function uses RDKit and searches through ligand atoms to find matches for pre-set list of possible dono...
def find_donors_and_acceptors_in_ligand(self): """ Since MDAnalysis a pre-set list for acceptor and donor atoms for proteins and solvents from specific forcefields, it is necessary to find donor and acceptor atoms for the ligand molecule. This function uses RDKit and searches through lig...
MDAnalysis.analysis.hbonds module is used to analyse hydrogen bonds formed between protein and ligand for each submitted trajectory. The hydrogen bonds are then counted by total value per frame (count_by_time), as well as obtaining the frequency of each individual hydrogen bond (count_by_type). ...
def analyse_hydrogen_bonds_traj(self,distance=3): """ MDAnalysis.analysis.hbonds module is used to analyse hydrogen bonds formed between protein and ligand for each submitted trajectory. The hydrogen bonds are then counted by total value per frame (count_by_time), as well as obtaining th...
Count how many times each individual hydrogen bonds occured throughout the simulation. Returns numpy array.
def count_by_type(self,table,timesteps): """Count how many times each individual hydrogen bonds occured throughout the simulation. Returns numpy array.""" hbonds = defaultdict(int) for contact in table: #count by residue name not by proteinring pkey = (contact.don...
MDAnalysis.analysis.hbonds module is used to analyse hydrogen bonds formed between protein and ligand for each submitted trajectory. The hydrogen bonds are then counted by total value per frame (count_by_time), as well as obtaining the frequency of each individual hydrogen bond (count_by_type). ...
def analyse_hydrogen_bonds_topology(self,distance=3): """ MDAnalysis.analysis.hbonds module is used to analyse hydrogen bonds formed between protein and ligand for each submitted trajectory. The hydrogen bonds are then counted by total value per frame (count_by_time), as well as obtainin...
Since plotting all hydrogen bonds could lead to a messy plot, a cutoff has to be imple- mented. In this function the frequency of each hydrogen bond is summated and the total compared against analysis cutoff - a fraction multiplied by trajectory count. Those hydrogen bonds that are present for l...
def determine_hbonds_for_drawing(self, analysis_cutoff): """ Since plotting all hydrogen bonds could lead to a messy plot, a cutoff has to be imple- mented. In this function the frequency of each hydrogen bond is summated and the total compared against analysis cutoff - a fraction multip...
The total hydrogen bond count per frame is provided as CSV output file. Each trajectory has a separate file.
def write_output_files(self): """ The total hydrogen bond count per frame is provided as CSV output file. Each trajectory has a separate file. """ os.mkdir("analysis") os.chdir("analysis") os.mkdir("hydrogen_bonds") os.chdir("hydrogen_bonds") for t...
Converts `value` type from python to dbus according signature. :param value: value to convert to dbus object :param str signature: dbus type signature. :returns: value in dbus type.
def convert2dbus(value, signature): """Converts `value` type from python to dbus according signature. :param value: value to convert to dbus object :param str signature: dbus type signature. :returns: value in dbus type. """ if len(signature) == 2 and signature.startswith('a'): return d...
Converts dbus_obj from dbus type to python type. :param dbus_obj: dbus object. :returns: dbus_obj in python type.
def convert(dbus_obj): """Converts dbus_obj from dbus type to python type. :param dbus_obj: dbus object. :returns: dbus_obj in python type. """ _isinstance = partial(isinstance, dbus_obj) ConvertType = namedtuple('ConvertType', 'pytype dbustypes') pyint = ConvertType(int, (dbus.Byte, dbus....
Decorator to convert value from dbus type to python type.
def converter(f): """Decorator to convert value from dbus type to python type.""" @wraps(f) def wrapper(*args, **kwds): return convert(f(*args, **kwds)) return wrapper
Decorator to convert dbus exception to pympris exception.
def exception_wrapper(f): """Decorator to convert dbus exception to pympris exception.""" @wraps(f) def wrapper(*args, **kwds): try: return f(*args, **kwds) except dbus.exceptions.DBusException as err: _args = err.args raise PyMPRISException(*_args) re...
Searchs and returns set of unique names of objects which implements MPRIS2 interfaces. :returns: set of unique names. :type: set
def available_players(): """Searchs and returns set of unique names of objects which implements MPRIS2 interfaces. :returns: set of unique names. :type: set """ bus = dbus.SessionBus() players = set() for name in filter(lambda item: item.startswith(MPRIS_NAME_PREFIX), ...
Decorator converts function's arguments from dbus types to python.
def signal_wrapper(f): """Decorator converts function's arguments from dbus types to python.""" @wraps(f) def wrapper(*args, **kwds): args = map(convert, args) kwds = {convert(k): convert(v) for k, v in kwds.items()} return f(*args, **kwds) return wrapper
Filters signals by iface name. :param function f: function to wrap. :param str signal_iface_name: interface name.
def filter_properties_signals(f, signal_iface_name): """Filters signals by iface name. :param function f: function to wrap. :param str signal_iface_name: interface name. """ @wraps(f) def wrapper(iface, changed_props, invalidated_props, *args, **kwargs): if iface == signal_iface_name: ...
Returns pairs of matching indices from l1 and l2.
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]): """Returns pairs of matching indices from l1 and l2.""" common = [] # We will keep track of the global index in the source list as we # will successively reduce their sizes. l1 = list(enumerate(l1)) l2 = list(enumerate(l2)) ...
Matches elements in l1 and l2 using normalization functions. Splits the elements in each list into buckets given by the normalization function. If the same normalization value points to a bucket from the first list and a bucket from the second list, both with a single element we consider the elements i...
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh): """Matches elements in l1 and l2 using normalization functions. Splits the elements in each list into buckets given by the normalization function. If the same normalization value points to a bucket from the first list and a bucket from the seco...
Matches two lists using the Munkres algorithm. Returns pairs of matching indices from the two lists by minimizing the sum of the distance between the linked elements and taking only the elements which have the distance between them less (or equal) than the threshold.
def _match_munkres(l1, l2, dist_matrix, thresh): """Matches two lists using the Munkres algorithm. Returns pairs of matching indices from the two lists by minimizing the sum of the distance between the linked elements and taking only the elements which have the distance between them less (or equal) tha...
Link a suspect to a case.
def add_suspect(self, case_obj, variant_obj): """Link a suspect to a case.""" new_suspect = Suspect(case=case_obj, variant_id=variant_obj.variant_id, name=variant_obj.display_name) self.session.add(new_suspect) self.save() return new_suspect
De-link a suspect from a case.
def delete_suspect(self, suspect_id): """De-link a suspect from a case.""" suspect_obj = self.suspect(suspect_id) logger.debug("Deleting suspect {0}".format(suspect_obj.name)) self.session.delete(suspect_obj) self.save()
Visualize DNA variant resources. 1. Look for variant source(s) to visualize and inst. the right plugin
def view(ctx, host, port, debug, pattern, family_file, family_type, variant_source, root, no_browser, phenomizer): """Visualize DNA variant resources. 1. Look for variant source(s) to visualize and inst. the right plugin """ main_loop = (not debug) or (os.environ.get('WERKZEUG_RUN_MAIN') == 't...
Configure root logger using a standard stream handler. Args: level (string, optional): lowest level to log to the console Returns: logging.RootLogger: root logger instance with attached handler
def configure_stream(level='WARNING'): """Configure root logger using a standard stream handler. Args: level (string, optional): lowest level to log to the console Returns: logging.RootLogger: root logger instance with attached handler """ # get the root logger root_logger = lo...
Function used to exclude defined fields from object collect. :param obj: the object we are collecting :param fields: every field related to this object (direct or reverse one) :param get_field_fn: function used to get accessor for each field :param exclude_list: model/fields we have defi...
def clean_by_fields(self, obj, fields, get_field_fn, exclude_list): """ Function used to exclude defined fields from object collect. :param obj: the object we are collecting :param fields: every field related to this object (direct or reverse one) :param get_field_fn: function us...
Testing if we try to collect an object of the same type as root. This is not really a good sign, because it means that we are going to collect a whole new tree, that will maybe collect a new tree, that will...
def _is_same_type_as_root(self, obj): """ Testing if we try to collect an object of the same type as root. This is not really a good sign, because it means that we are going to collect a whole new tree, that will maybe collect a new tree, that will... """ if not self.ALLO...
If the field we are currently working on has too many objects related to it, we want to restrict it depending on a settings-driven threshold. :param objects: The objects we want to filter :param current_obj: The current collected instance :param field_name: The current field name ...
def filter_by_threshold(self, objects, current_instance, field_name): """ If the field we are currently working on has too many objects related to it, we want to restrict it depending on a settings-driven threshold. :param objects: The objects we want to filter :param current_obj...
We want to manage the side-effect of not collecting other items of the same type as root model. If for example, you run the collect on a specific user that is linked to a model "A" linked (ForeignKey) to ANOTHER user. Then the collect won't collect this other user, but the collected model "A" wi...
def post_collect(self, obj): """ We want to manage the side-effect of not collecting other items of the same type as root model. If for example, you run the collect on a specific user that is linked to a model "A" linked (ForeignKey) to ANOTHER user. Then the collect won't collec...
initialize variable from loaded data
def initialize(self, data): """ initialize variable from loaded data """ for item in data: if hasattr(self, item): setattr(self, item, data[item])
Parse contents of the README.
def parse_readme(): """Parse contents of the README.""" # Get the long description from the relevant file here = os.path.abspath(os.path.dirname(__file__)) readme_path = os.path.join(here, 'README.md') with codecs.open(readme_path, encoding='utf-8') as handle: long_description = handle.read(...
Return all transcripts sound in the vcf file
def _add_transcripts(self, variant_obj, info_dict): """Return all transcripts sound in the vcf file""" vep_string = info_dict.get('CSQ') #Check if snpeff annotation: snpeff_string = info_dict.get('ANN') # We check one of these. # VEP has presedence over snpeff ...
Create a transcript based on the snpeff annotation Args: transcript_info (dict): A dict with snpeff info Returns: transcript (puzzle.models.Transcript): A Transcripts
def _get_snpeff_transcript(self, transcript_info): """Create a transcript based on the snpeff annotation Args: transcript_info (dict): A dict with snpeff info Returns: transcript (puzzle.models.Transcript): A Transcripts """ transcript = ...