code
stringlengths
1
18.2k
def add_colors(self, system, colors): """Add color definition to a given color system. You may add to already existing color system. Previously existing color definitions of the same (normalized) name will be overwritten, regardless of the color system. Args: system (string): The color system the colors should be added...
def match_name(self, in_string, fuzzy=False): """Match a color to a sRGB value. The matching will be based purely on the input string and the color names in the registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method will never fail to return a sRGB value, but depending on the score, it m...
matching if no exact match was found. Defaults to ``False``. Returns: A named tuple with the members `hex_code` and `score`. Raises: ValueError: If ``fuzzy`` is ``False`` and no match is found Examples: >>> tint_registry = TintRegistry() >>> tint_registry.match_name("rather white", fuzzy=True) MatchResult(hex_code=u'ff...
n in key_union) color_name, score = sorted(counter, key=operator.itemgetter(1))[-1] return MatchResult(self._hex_by_color[color_name], score / 2)
def find_nearest(self, hex_code, system, filter_set=None): """Find a color name that's most similar to a given sRGB hex code. In normalization terms, this method implements "normalize an arbitrary sRGB value to a well-defined color name". Args: system (string): The color system. Currently, `"en"`` is the only default s...
in self._colors_by_system_hex: raise ValueError( "%r is not a registered color system. Try one of %r" % (system, self._colors_by_system_hex.keys()) ) hex_code = hex_code.lower().strip() # Try direct hit (fast path) if hex_code in self._colors_by_system_hex[system]: color_name = self._colors_by_system_hex[system][hex_co...
def SessionAuthSourceInitializer( value_key='sanity.' ): """ An authentication source that uses the current session """ value_key = value_key + 'value' @implementer(IAuthSourceService) class SessionAuthSource(object): vary = [] def __init__(self, context, request): self.request = request self.session = request.session ...
def CookieAuthSourceInitializer( secret, cookie_name='auth', secure=False, max_age=None, httponly=False, path="/", domains=None, debug=False, hashalg='sha512', ): """ An authentication source that uses a unique cookie. """ @implementer(IAuthSourceService) class CookieAuthSource(object): vary = ['Cookie'] def __init__(s...
def HeaderAuthSourceInitializer( secret, salt='sanity.header.' ): """ An authentication source that uses the Authorization header. """ @implementer(IAuthSourceService) class HeaderAuthSource(object): vary = ['Authorization'] def __init__(self, context, request): self.request = request self.cur_val = None serializer = J...
def apply(self, collection, ops, resource=None, **kwargs): """Filter given collection.""" mfield = self.mfield or resource.meta.model._meta.fields.get(self.field.attribute) if mfield: collection = collection.where(*[op(mfield, val) for op, val in ops]) return collection
def get_one(self, request, **kwargs): """Load a resource.""" resource = request.match_info.get(self.name) if not resource: return None try: return self.collection.where(self.meta.model_pk == resource).get() except Exception: raise RESTNotFound(reason='Resource not found.')
def sort(self, *sorting, **kwargs): """Sort resources.""" sorting_ = [] for name, desc in sorting: field = self.meta.model._meta.fields.get(name) if field is None: continue if desc: field = field.desc() sorting_.append(field) if sorting_: return self.collection.order_by(*sorting_) return self.collection
def paginate(self, request, offset=0, limit=None): """Paginate queryset.""" return self.collection.offset(offset).limit(limit), self.collection.count()
def save(self, request, resource=None, **kwargs): """Create a resource.""" resources = resource if isinstance(resource, list) else [resource] for obj in resources: obj.save() return resource
async def delete(self, request, resource=None, **kwargs): """Delete a resource. Supports batch delete. """ if resource: resources = [resource] else: data = await self.parse(request) if data: resources = list(self.collection.where(self.meta.model_pk << data)) if not resources: raise RESTNotFound(reason='Resource not fou...
def get_sub_accounts_of_account(self, account_id, recursive=None): """ Get the sub-accounts of an account. List accounts that are sub-accounts of the given account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - recursive """If true, the entire a...
def list_active_courses_in_account(self, account_id, by_subaccounts=None, by_teachers=None, completed=None, enrollment_term_id=None, enrollment_type=None, hide_enrollmentless_courses=None, include=None, published=None, search_term=None, state=None, with_enrollments=None): """ List active courses in an account. Retrieve...
= enrollment_type # OPTIONAL - published """If true, include only published courses. If false, exclude published courses. If not present, do not filter on published status.""" if published is not None: params["published"] = published # OPTIONAL - completed """If true, include only completed courses (these may be in sta...
subaccounts.""" if by_subaccounts is not None: params["by_subaccounts"] = by_subaccounts # OPTIONAL - hide_enrollmentless_courses """If present, only return courses that have at least one enrollment. Equivalent to 'with_enrollments=true'; retained for compatibility.""" if hide_enrollmentless_courses is not None: params...
params["search_term"] = search_term # OPTIONAL - include """- All explanations can be seen in the {api:CoursesController#index Course API index documentation} - "sections", "needs_grading_count" and "total_scores" are not valid options at the account level""" if include is not None: self._validate_enum(include, ["sylla...
def update_account(self, id, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_time_zone=None, account_default_user_storage_quota_mb=None, account_name=None, account_services=None, account_settings_lock_all_announcements_locked=None, account_settings_lock_all_announceme...
quota to be used, if not otherwise specified.""" if account_default_user_storage_quota_mb is not None: data["account[default_user_storage_quota_mb]"] = account_default_user_storage_quota_mb # OPTIONAL - account[default_group_storage_quota_mb] """The default group storage quota to be used, if not otherwise specified."""...
is not None: data["account[settings][lock_all_announcements][value]"] = account_settings_lock_all_announcements_value # OPTIONAL - account[settings][lock_all_announcements][locked] """Lock this setting for sub-accounts and courses""" if account_settings_lock_all_announcements_locked is not None: data["account[settings]...
def create_new_sub_account(self, account_id, account_name, account_default_group_storage_quota_mb=None, account_default_storage_quota_mb=None, account_default_user_storage_quota_mb=None, account_sis_account_id=None): """ Create a new sub-account. Add a new sub-account to a given account. """ path = {} data = {} params ...
group storage quota to be used, if not otherwise specified.""" if account_default_group_storage_quota_mb is not None: data["account[default_group_storage_quota_mb]"] = account_default_group_storage_quota_mb self.logger.debug("POST /api/v1/accounts/{account_id}/sub_accounts with query params: {params} and form data: {da...
def delete(self, table, where=None): """Delete existing rows from a table.""" if where: where_key, where_val = where query = "DELETE FROM {0} WHERE {1}='{2}'".format(wrap(table), where_key, where_val) else: query = 'DELETE FROM {0}'.format(wrap(table)) self.execute(query) return True
def coloured_network(network, setup, filename): """ Plots a coloured (hyper-)graph to a dot file Parameters ---------- network : object An object implementing a method `__plot__` which must return the `networkx.MultiDiGraph`_ instance to be coloured. Typically, it will be an instance of either :class:`caspo.core.graph....
-1 : {'color': 'red', 'arrowhead': 'tee'} } graph = network.__plot__() for node in graph.nodes(): _type = 'DEFAULT' for attr, value in NODES_ATTR[_type].items(): graph.node[node][attr] = value if 'gate' in graph.node[node]: _type = 'GATE' elif node in setup.stimuli: _type = 'STIMULI' elif node in setup.readouts and nod...
def networks_distribution(df, filepath=None): """ Generates two alternative plots describing the distribution of variables `mse` and `size`. It is intended to be used over a list of logical networks. Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `mse` and `size` filepath: str Absolute path to a f...
plt.figure() counts = df[["size", "mse"]].reset_index(level=0).groupby(["size", "mse"], as_index=False).count() cp = counts.pivot("size", "mse", "index").sort_index() ax = sns.heatmap(cp, annot=True, fmt=".0f", linewidths=.5) ax.set_xlabel("MSE") ax.set_ylabel("Size") if filepath: plt.savefig(os.path.join(filepath, 'ne...
def mappings_frequency(df, filepath=None): """ Plots the frequency of logical conjunction mappings Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `frequency` and `mapping` filepath: str Absolute path to a folder where to write the plot Returns ------- plot Generated plot .. _pandas.DataFrame: http...
def behaviors_distribution(df, filepath=None): """ Plots the distribution of logical networks across input-output behaviors. Optionally, input-output behaviors can be grouped by MSE. Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `networks` and optionally `mse` filepath: str Absolute path to a fol...
def experimental_designs(df, filepath=None): """ For each experimental design it plot all the corresponding experimental conditions in a different plot Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `id` and starting with `TR:` filepath: str Absolute path to a folder where to write the plot Return...
def differences_distribution(df, filepath=None): """ For each experimental design it plot all the corresponding generated differences in different plots Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `id`, `pairs`, and starting with `DIF:` filepath: str Absolute path to a folder where to write the...
def predictions_variance(df, filepath=None): """ Plots the mean variance prediction for each readout Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `VAR:` filepath: str Absolute path to a folder where to write the plots Returns ------- plot Generated plot .. _pandas.DataFrame: http:/...
def intervention_strategies(df, filepath=None): """ Plots all intervention strategies Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `TR:` filepath: str Absolute path to a folder where to write the plot Returns ------- plot Generated plot .. _pandas.DataFrame: http://pandas.pydata.or...
'strategies.pdf')) return ax
def interventions_frequency(df, filepath=None): """ Plots the frequency of occurrence for each intervention Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns `frequency` and `intervention` filepath: str Absolute path to a folder where to write the plot Returns ------- plot Generated plot .. _pandas.D...
def add_graph( self, y, x_label=None, y_label="", title="", x_run=None, y_run=None, svg_size_px=None, key_position="bottom right", ): """ Add a new graph to the overlap report. Args: y (str): Value plotted on y-axis. x_label (str): Label on x-axis. y_label (str): Label on y-axis. title (str): Title of the plot. x_run (...
def clean(self): """Remove all temporary files.""" rnftools.utils.shell('rm -fR "{}" "{}"'.format(self.report_dir, self._html_fn))
def create_html(self): """Create HTML report.""" html_table = "" columns = [panel.get_html_column() for panel in self.panels] trs = len(columns[0]) html_table += os.linesep.join( [ "<tr>{}</tr>".format("".join(["<td>{}</td>".format(columns[col][row]) for col in range(len(columns))])) for row in range(trs) ] ) with open...
def get_current_traceback(show_hidden_frames=False, skip=0, context=None, exc_info=None): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the functio...
def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.rstrip() + '\n' file_mode = getattr(logfile, 'mode', None) if file_mode is not None: if 'b' in file_mode: tb = tb.encode('utf-8') logfile.write(tb)
def paste(self): """Create a paste and return the paste id.""" data = json.dumps({ 'description': 'Backlash Internal Server Error', 'public': False, 'files': { 'traceback.txt': { 'content': self.plaintext } } }).encode('utf-8') rv = urlopen('https://api.github.com/gists', data=data) resp = json.loads(rv.read().decode('...
def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' description = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error: title = text_('Syntax Error') else: title = text_('Trac...
def generate_plaintext_traceback(self): """Like the plaintext attribute but returns a generator""" yield text_('Traceback (most recent call last):') for frame in self.frames: yield text_(' File "%s", line %s, in %s' % ( frame.filename, frame.lineno, frame.function_name )) yield text_(' ' + frame.current_line.strip()) y...
def render_source(self): """Render the sourcecode.""" return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in self.get_annotated_lines()))
def recode_dwgsim_reads( dwgsim_prefix, fastq_rnf_fo, fai_fo, genome_id, estimate_unknown_values, number_of_read_tuples=10**9, ): """Convert DwgSim FASTQ file to RNF FASTQ file. Args: dwgsim_prefix (str): DwgSim prefix of the simulation (see its commandline parameters). fastq_rnf_fo (file): File object of RNF FASTQ. fa...
- reverse) # 6) random read end 1 (0 - from the mutated reference, 1 - random) # 7) random read end 2 (0 - from the mutated reference, 1 - random) # 8) number of sequencing errors end 1 (color errors for colorspace) # 9) number of SNPs end 1 # 10) number of indels end 1 # 11) number of sequencing errors end 2 (color er...
with open(old_fq, "r+") as f1: for line in f1: if i % 4 == 0: read_tuple_name = line[1:].strip() if read_tuple_name != last_read_tuple_name: new_tuple = True if last_read_tuple_name is not None: read_tuple_id += 1 else: new_tuple = False last_read_tuple_name = read_tuple_name m = dwgsim_pattern.search(line) if m is Non...
fai_index.dict_chr_ids != {} else "0" elif i % 4 == 1: bases = line.strip() if new_tuple: segment = rnftools.rnfformat.Segment( genome_id=genome_id, chr_id=chr_id, direction=direction_1, left=start_1, right=start_1 + len(bases) - 1 if estimate_unknown_values else 0, ) else: segment = rnftools.rnfformat.Segment( genome_...
def sleep(seconds=0): """Yield control to another eligible coroutine until at least *seconds* have elapsed. *seconds* may be specified as an integer, or a float if fractional seconds are desired. """ loop = evergreen.current.loop current = Fiber.current() assert loop.task is not current timer = loop.call_later(seconds,...
def spawn(func, *args, **kwargs): """Create a task to run ``func(*args, **kwargs)``. Returns a :class:`Task` objec. Execution control returns immediately to the caller; the created task is merely scheduled to be run at the next available opportunity. Use :func:`spawn_later` to arrange for tasks to be spawned after a fi...
def task(func): """Decorator to run the decorated function as a Task """ def task_wrapper(*args, **kwargs): return spawn(func, *args, **kwargs) return task_wrapper
def join(self, timeout=None): """Wait for this Task to end. If a timeout is given, after the time expires the function will return anyway.""" if not self._started: raise RuntimeError('cannot join task before it is started') return self._exit_event.wait(timeout)
def kill(self, typ=TaskExit, value=None, tb=None): """Terminates the current task by raising an exception into it. Whatever that task might be doing; be it waiting for I/O or another primitive, it sees an exception as soon as it yields control. By default, this exception is TaskExit, but a specific exception may be spe...
def from_csv(cls, filename): """ Creates a list of logical networks from a CSV file. Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored except for a column named `networks` which (if present) is interpreted as the number of logical networks having the same input-output behavior. Paramete...
def from_hypergraph(cls, hypergraph, networks=None): """ Creates a list of logical networks from a given hypergraph and an optional list of :class:`caspo.core.logicalnetwork.LogicalNetwork` object instances Parameters ---------- hypegraph : :class:`caspo.core.hypergraph.HyperGraph` Underlying hypergraph for this logica...
def mappings(self): """ :class:`caspo.core.mapping.MappingList`: the list of mappings present in at least one logical network in this list """ return self.hg.mappings[np.unique(np.where(self.__matrix == 1)[1])]
def reset(self): """ Drop all networks in the list """ self.__matrix = np.array([]) self.__networks = np.array([])
def split(self, indices): """ Splits logical networks according to given indices Parameters ---------- indices : list 1-D array of sorted integers, the entries indicate where the array is split Returns ------- list List of :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instances .. seealso:: `numpy.split ...
def concat(self, other): """ Returns the concatenation with another :class:`caspo.core.logicalnetwork.LogicalNetworkList` object instance. It is assumed (not checked) that both have the same underlying hypergraph. Parameters ---------- other : :class:`caspo.core.logicalnetwork.LogicalNetworkList` The list to concatenat...
def append(self, network): """ Append a :class:`caspo.core.logicalnetwork.LogicalNetwork` to the list Parameters ---------- network : :class:`caspo.core.logicalnetwork.LogicalNetwork` The network to append """ arr = network.to_array(self.hg.mappings) if len(self.__matrix): self.__matrix = np.append(self.__matrix, [arr]...
def to_funset(self): """ Converts the list of logical networks to a set of `gringo.Fun`_ instances Returns ------- set Representation of all networks as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set((gringo.Fun("variable", [var]) for var in self.hg.nodes))...
def to_dataframe(self, networks=False, dataset=None, size=False, n_jobs=-1): """ Converts the list of logical networks to a `pandas.DataFrame`_ object instance Parameters ---------- networks : boolean If True, a column with number of networks having the same behavior is included in the DataFrame dataset: Optional[:clas...
is not None: clampings = dataset.clampings readouts = dataset.readouts.columns observations = dataset.readouts.values pos = ~np.isnan(observations) mse = Parallel(n_jobs=n_jobs)(delayed(__parallel_mse__)(n, clampings, readouts, observations[pos], pos) for n in self) df = pd.concat([df, pd.DataFrame({'mse': mse})], axis...
def to_csv(self, filename, networks=False, dataset=None, size=False, n_jobs=-1): """ Writes the list of logical networks to a CSV file Parameters ---------- filename : str Absolute path where to write the CSV file networks : boolean If True, a column with number of networks having the same behavior is included in the f...
def frequencies_iter(self): """ Iterates over all non-zero frequencies of logical conjunction mappings in this list Yields ------ tuple[caspo.core.mapping.Mapping, float] The next pair (mapping,frequency) """ f = self.__matrix.mean(axis=0) for i, m in self.mappings.iteritems(): yield m, f[i]
def frequency(self, mapping): """ Returns frequency of a given :class:`caspo.core.mapping.Mapping` Parameters ---------- mapping : :class:`caspo.core.mapping.Mapping` A logical conjuntion mapping Returns ------- float Frequency of the given mapping over all logical networks Raises ------ ValueError If the given mapping...
def combinatorics(self): """ Returns mutually exclusive/inclusive mappings Returns ------- (dict,dict) A tuple of 2 dictionaries. For each mapping key, the first dict has as value the set of mutually exclusive mappings while the second dict has as value the set of mutually inclusive mappings. """ f = self.__matrix.mean...
def predictions(self, setup, n_jobs=-1): """ Returns a `pandas.DataFrame`_ with the weighted average predictions and variance of all readouts for each possible clampings in the given experimental setup. For each logical network the weight corresponds to the number of networks having the same behavior. Parameters ------...
axis=0, weights=self.__networks) var = np.average((predictions[:, :, nc:]-avg)**2, axis=0, weights=self.__networks) rcues = ["TR:%s" % c for c in setup.cues(True)] cols = np.concatenate([rcues, ["AVG:%s" % r for r in readouts], ["VAR:%s" % r for r in readouts]]) #use the first network predictions to extract all clampin...
def weighted_mse(self, dataset, n_jobs=-1): """ Returns the weighted MSE over all logical networks with respect to the given :class:`caspo.core.dataset.Dataset` object instance. For each logical network the weight corresponds to the number of networks having the same behavior. Parameters ---------- dataset: :class:`cas...
def from_hypertuples(cls, hg, tuples): """ Creates a logical network from an iterable of integer tuples matching mappings in the given :class:`caspo.core.hypergraph.HyperGraph` Parameters ---------- hg : :class:`caspo.core.hypergraph.HyperGraph` Underlying hypergraph tuples : (int,int) tuples matching mappings in the g...
def to_graph(self): """ Converts the logical network to its underlying interaction graph Returns ------- caspo.core.graph.Graph The underlying interaction graph """ edges = set() for clause, target in self.edges_iter(): for source, signature in clause: edges.add((source, target, signature)) return Graph.from_tuples(edg...
def step(self, state, clamping): """ Performs a simulation step from the given state and with respect to the given clamping Parameters ---------- state : dict The key-value mapping describing the current state of the logical network clamping : caspo.core.clamping.Clamping A clamping over variables in the logical networ...
def fixpoint(self, clamping, steps=0): """ Computes the fixpoint with respect to a given :class:`caspo.core.clamping.Clamping` Parameters ---------- clamping : :class:`caspo.core.clamping.Clamping` The clamping with respect to the fixpoint is computed steps : int If greater than zero, a maximum number of steps is perfo...
def predictions(self, clampings, readouts, stimuli=None, inhibitors=None, nclampings=-1): """ Computes network predictions for the given iterable of clampings Parameters ---------- clampings : iterable Iterable over clampings readouts : list[str] List of readouts names stimuli : Optional[list[str]] List of stimuli name...
> 0 else len(clampings), nc+len(readouts)), dtype=np.int8) for i, clamping in enumerate(clampings): if nc > 0: arr = clamping.to_array(cues) arr[np.where(arr[:ns] == -1)[0]] = 0 arr[ns + np.where(arr[ns:] == -1)[0]] = 1 predictions[i, :nc] = arr fixpoint = self.fixpoint(clamping) for j, readout in enumerate(readouts): ...
def mse(self, dataset): """ Returns the Mean Squared Error with respect to the given :class:`caspo.core.dataset.Dataset` object Parameters ---------- dataset : :class:`caspo.core.dataset.Dataset` Dataset to compute MSE Returns ------- float Computed mean squared error """ clampings = dataset.clampings readouts = datase...
def variables(self): """ Returns variables in the logical network Returns ------- set[str] Unique variables names """ variables = set() for v in self.nodes_iter(): if isinstance(v, Clause): for l in v: variables.add(l.variable) else: variables.add(v) return variables
def formulas_iter(self): """ Iterates over all variable-clauses in the logical network Yields ------ tuple[str,frozenset[caspo.core.clause.Clause]] The next tuple of the form (variable, set of clauses) in the logical network. """ for var in it.ifilter(self.has_node, self.variables()): yield var, frozenset(self.predeces...
def to_array(self, mappings): """ Converts the logical network to a binary array with respect to the given mappings from a :class:`caspo.core.hypergraph.HyperGraph` object instance. Parameters ---------- mappings : :class:`caspo.core.mapping.MappingList` Mappings to create the binary array Returns ------- `numpy.ndarra...
def answering_questions(self, attempt, validation_token, quiz_submission_id, access_code=None, quiz_questions=None): """ Answering questions. Provide or update an answer to one or more QuizQuestions. """ path = {} data = {} params = {} # REQUIRED - PATH - quiz_submission_id """ID""" path["quiz_submission_id"] = quiz_su...
Formats} for the accepted answer formats for each question type.""" if quiz_questions is not None: data["quiz_questions"] = quiz_questions self.logger.debug("POST /api/v1/quiz_submissions/{quiz_submission_id}/questions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return s...
def unflagging_question(self, id, attempt, validation_token, quiz_submission_id, access_code=None): """ Unflagging a question. Remove the flag that you previously set on a quiz question after you've returned to it. """ path = {} data = {} params = {} # REQUIRED - PATH - quiz_submission_id """ID""" path["quiz_submission...
access_code self.logger.debug("PUT /api/v1/quiz_submissions/{quiz_submission_id}/questions/{id}/unflag with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/quiz_submissions/{quiz_submission_id}/questions/{id}/unflag".format(**path), dat...
def to_funset(self, lname="clamping", cname="clamped"): """ Converts the list of clampings to a set of `gringo.Fun`_ instances Parameters ---------- lname : str Predicate name for the clamping id cname : str Predicate name for the clamped variable Returns ------- set Representation of all clampings as a set of `gringo....
def to_dataframe(self, stimuli=None, inhibitors=None, prepend=""): """ Converts the list of clampigns to a `pandas.DataFrame`_ object instance Parameters ---------- stimuli : Optional[list[str]] List of stimuli names. If given, stimuli are converted to {0,1} instead of {-1,1}. inhibitors : Optional[list[str]] List of i...
= 0 arr[ns + np.where(arr[ns:] == -1)[0]] = 1 if len(matrix): matrix = np.append(matrix, [arr], axis=0) else: matrix = np.array([arr]) return pd.DataFrame(matrix, columns=[prepend + "%s" % c for c in (stimuli + [i+'i' for i in inhibitors] if nc > 0 else variables)])
def to_csv(self, filename, stimuli=None, inhibitors=None, prepend=""): """ Writes the list of clampings to a CSV file Parameters ---------- filename : str Absolute path where to write the CSV file stimuli : Optional[list[str]] List of stimuli names. If given, stimuli are converted to {0,1} instead of {-1,1}. inhibitors...
def from_dataframe(cls, df, inhibitors=None): """ Creates a list of clampings from a `pandas.DataFrame`_ object instance. Column names are expected to be of the form `TR:species_name` Parameters ---------- df : `pandas.DataFrame`_ Columns and rows correspond to species names and individual clampings, respectively. inhi...
ni = len(inhibitors) for _, row in df.iterrows(): if ni > 0: literals = [] for v, s in row.iteritems(): if v.endswith('i') and v[3:-1] in inhibitors: if s == 1: literals.append(Literal(v[3:-1], -1)) else: literals.append(Literal(v[3:], 1 if s == 1 else -1)) clampings.append(Clamping(literals)) else: clampings.append(Cl...
def from_csv(cls, filename, inhibitors=None): """ Creates a list of clampings from a CSV file. Column names are expected to be of the form `TR:species_name` Parameters ---------- filename : str Absolute path to a CSV file to be loaded with `pandas.read_csv`_. The resulting DataFrame is passed to :func:`from_dataframe`....
pd.read_csv(filename) return cls.from_dataframe(df, inhibitors)
def frequencies_iter(self): """ Iterates over the frequencies of all clamped variables Yields ------ tuple[ caspo.core.literal.Literal, float ] The next tuple of the form (literal, frequency) """ df = self.to_dataframe() n = float(len(self)) for var, sign in it.product(df.columns, [-1, 1]): f = len(df[df[var] == sign])...
def frequency(self, literal): """ Returns the frequency of a clamped variable Parameters ---------- literal : :class:`caspo.core.literal.Literal` The clamped variable Returns ------- float The frequency of the given literal Raises ------ ValueError If the variable is not present in any of the clampings """ df = self.to...
def combinatorics(self): """ Returns mutually exclusive/inclusive clampings Returns ------- (dict,dict) A tuple of 2 dictionaries. For each literal key, the first dict has as value the set of mutually exclusive clampings while the second dict has as value the set of mutually inclusive clampings. """ df = self.to_datafr...
def differences(self, networks, readouts, prepend=""): """ Returns the total number of pairwise differences over the given readouts for the given networks Parameters ---------- networks : iterable[:class:`caspo.core.logicalnetwork.LogicalNetwork`] Iterable of logical networks to compute pairwise differences readouts : ...
def drop_literals(self, literals): """ Returns a new list of clampings without the given literals Parameters ---------- literals : iterable[:class:`caspo.core.literal.Literal`] Iterable of literals to be removed from each clamping Returns ------- caspo.core.clamping.ClampingList The new list of clampings """ clampings ...