code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
axes = []
bw = matplotlib.colors.ListedColormap(['white', 'black'])
cols = df.columns
for i, dd in df.groupby("id"):
cues = dd.drop([c for c in cols if not c.startswith("TR:")] + ["id"], axis=1).reset_index(drop=True)
cues.columns = [c[3:] for c in cues.columns]
plt.figure... | 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
Returns
... | 3.762046 | 3.533412 | 1.064706 |
axes = []
cols = df.columns
for i, dd in df.groupby("id"):
palette = sns.color_palette("Set1", len(dd))
plt.figure()
readouts = dd.drop([c for c in cols if not c.startswith("DIF:")] + ["id"], axis=1).reset_index(drop=True)
readouts.columns = [c[4:] for c in readouts.co... | 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 plots
Re... | 3.174411 | 2.795556 | 1.13552 |
df = df.filter(regex="^VAR:")
by_readout = df.mean(axis=0).reset_index(level=0)
by_readout.columns = ['Readout', 'Prediction variance (mean)']
by_readout['Readout'] = by_readout.Readout.map(lambda n: n[4:])
g1 = sns.factorplot(x='Readout', y='Prediction variance (mean)', data=by_readout, ki... | 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.Data... | 2.986804 | 2.654597 | 1.125144 |
logger = logging.getLogger("caspo")
LIMIT = 50
if len(df) > LIMIT:
msg = "Too many intervention strategies to visualize. A sample of %s strategies will be considered." % LIMIT
logger.warning(msg)
df = df.sample(LIMIT)
values = np.unique(df.values.flatten())
if len(valu... | 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... | 3.070617 | 3.053611 | 1.005569 |
df = df.sort_values('frequency')
df['conf'] = df.frequency.map(lambda f: 0 if f < 0.2 else 1 if f < 0.8 else 2)
g = sns.factorplot(x="intervention", y="frequency", data=df, aspect=3, hue='conf', legend=False)
for tick in g.ax.get_xticklabels():
tick.set_rotation(90)
_ = [t.set_color(... | 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
..... | 2.497908 | 2.484432 | 1.005424 |
if x_run is None:
x_run = self.default_x_run
if y_run is None:
y_run = self.default_y_run
if svg_size_px is None:
svg_size_px = self.default_svg_size_px
for panel in self.panels:
x_run = self._load_x_run(x_run)
y_run ... | 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 ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_po... | 1.525579 | 1.611033 | 0.946957 |
rnftools.utils.shell('rm -fR "{}" "{}"'.format(self.report_dir, self._html_fn)) | def clean(self) | Remove all temporary files. | 21.957151 | 16.318518 | 1.345536 |
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))]))
... | def create_html(self) | Create HTML report. | 3.562325 | 3.460087 | 1.029548 |
if exc_info is None:
exc_info = sys.exc_info()
exc_type, exc_value, tb = exc_info
for x in range(skip):
if tb.tb_next is None:
break
tb = tb.tb_next
tb = Traceback(exc_type, exc_value, tb, context=context)
if not show_hidden_frames:
tb.filter_hidden_... | 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 function as first parameter. | 1.949133 | 1.939914 | 1.004752 |
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 log(self, logfile=None) | Log the ASCII traceback into a file object. | 3.388574 | 2.80084 | 1.209842 |
data = json.dumps({
'description': 'Backlash Internal Server Error',
'public': False,
'files': {
'traceback.txt': {
'content': self.plaintext
}
}
}).encode('utf-8')
rv = urlopen('https:/... | def paste(self) | Create a paste and return the paste id. | 3.68823 | 3.461721 | 1.065432 |
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:
... | def render_summary(self, include_title=True) | Render the traceback for the interactive console. | 3.402863 | 3.297785 | 1.031863 |
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.curre... | def generate_plaintext_traceback(self) | Like the plaintext attribute but returns a generator | 3.182608 | 3.074124 | 1.035289 |
return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in
self.get_annotated_lines())) | def render_source(self) | Render the sourcecode. | 20.99579 | 18.72077 | 1.121524 |
loop = evergreen.current.loop
current = Fiber.current()
assert loop.task is not current
timer = loop.call_later(seconds, current.switch)
try:
loop.switch()
finally:
timer.cancel() | 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. | 8.80382 | 9.28667 | 0.948006 |
t = Task(target=func, args=args, kwargs=kwargs)
t.start()
return t | 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 finite delay. | 3.042209 | 5.138829 | 0.592004 |
def task_wrapper(*args, **kwargs):
return spawn(func, *args, **kwargs)
return task_wrapper | def task(func) | Decorator to run the decorated function as a Task | 3.021157 | 2.890487 | 1.045207 |
if not self._started:
raise RuntimeError('cannot join task before it is started')
return self._exit_event.wait(timeout) | 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. | 6.095533 | 5.084466 | 1.198854 |
if not self.is_alive():
return
if not value:
value = typ()
if not self._running:
# task hasn't started yet and therefore throw won't work
def just_raise():
six.reraise(typ, value, tb)
self.run = just_raise
... | 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 specified. | 6.424397 | 6.583119 | 0.975889 |
df = pd.read_csv(filename)
edges = set()
mappings = []
cols = []
for m in df.columns:
try:
ct = Mapping.from_str(m)
mappings.append(ct)
cols.append(m)
for source, sign in ct.clause:
... | 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... | 4.089202 | 4.054382 | 1.008588 |
matrix = None
nnet = None
if networks:
matrix = np.array([networks[0].to_array(hypergraph.mappings)])
nnet = [networks[0].networks]
for network in networks[1:]:
matrix = np.append(matrix, [network.to_array(hypergraph.mappings)], axis=0... | 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 logical network li... | 2.995776 | 3.538813 | 0.846548 |
return self.hg.mappings[np.unique(np.where(self.__matrix == 1)[1])] | def mappings(self) | :class:`caspo.core.mapping.MappingList`: the list of mappings present in at least one logical network in this list | 18.296886 | 17.095829 | 1.070254 |
self.__matrix = np.array([])
self.__networks = np.array([]) | def reset(self) | Drop all networks in the list | 16.763983 | 9.086627 | 1.844907 |
return [LogicalNetworkList(self.hg, part) for part in np.split(self.__matrix, indices)] | 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`... | 23.73801 | 15.063087 | 1.575906 |
if len(other) == 0:
return self
elif len(self) == 0:
return other
else:
return LogicalNetworkList(self.hg, np.append(self.__matrix, other.__matrix, axis=0), np.concatenate([self.__networks, other.__networks])) | 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 li... | 5.148489 | 3.396935 | 1.515627 |
arr = network.to_array(self.hg.mappings)
if len(self.__matrix):
self.__matrix = np.append(self.__matrix, [arr], axis=0)
self.__networks = np.append(self.__networks, network.networks)
else:
self.__matrix = np.array([arr])
self.__networks = ... | 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 | 3.894856 | 4.190951 | 0.929349 |
fs = set((gringo.Fun("variable", [var]) for var in self.hg.nodes))
formulas = set()
for network in self:
formulas = formulas.union(it.imap(lambda (_, f): f, network.formulas_iter()))
formulas = pd.Series(list(formulas))
for i, network in enumerate(self):
... | 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 | 4.367533 | 4.172206 | 1.046816 |
length = len(self)
df = pd.DataFrame(self.__matrix, columns=map(str, self.hg.mappings))
if networks:
df = pd.concat([df, pd.DataFrame({'networks': self.__networks})], axis=1)
if dataset is not None:
clampings = dataset.clampings
readouts = d... | 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[:class:`caspo.core.dataset.Dataset`]
... | 4.051032 | 4.071556 | 0.994959 |
self.to_dataframe(networks, dataset, size, n_jobs).to_csv(filename, index=False) | 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 file
dataset: Optio... | 2.817376 | 3.958964 | 0.711645 |
f = self.__matrix.mean(axis=0)
for i, m in self.mappings.iteritems():
yield m, f[i] | 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) | 8.855659 | 10.150479 | 0.872438 |
return self.__matrix[:, self.hg.mappings[mapping]].mean() | 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
... | 77.951569 | 99.323624 | 0.784824 |
f = self.__matrix.mean(axis=0)
candidates = np.where((f < 1) & (f > 0))[0]
exclusive, inclusive = defaultdict(set), defaultdict(set)
for i, j in it.combinations(candidates, 2):
xor = np.logical_xor(self.__matrix[:, i], self.__matrix[:, j])
if xor.all():
... | 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 mapp... | 2.699919 | 2.485827 | 1.086125 |
stimuli, inhibitors, readouts = setup.stimuli, setup.inhibitors, setup.readouts
nc = len(setup.cues())
predictions = np.zeros((len(self), 2**nc, len(setup)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, list(setup.clampings_iter(setup.cues(... | 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
----------
... | 4.905085 | 4.721682 | 1.038843 |
predictions = np.zeros((len(self), len(dataset.clampings), len(dataset.setup.readouts)))
predictions[:, :, :] = Parallel(n_jobs=n_jobs)(delayed(__parallel_predictions__)(n, dataset.clampings, dataset.setup.readouts) for n in self)
for i, _ in enumerate(self):
predictions[i, ... | 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:`caspo.core.dataset... | 5.529798 | 5.689668 | 0.971902 |
return cls([(hg.clauses[j], hg.variable(i)) for i, j in tuples], networks=1) | 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 mat... | 19.591961 | 22.640388 | 0.865354 |
edges = set()
for clause, target in self.edges_iter():
for source, signature in clause:
edges.add((source, target, signature))
return Graph.from_tuples(edges) | def to_graph(self) | Converts the logical network to its underlying interaction graph
Returns
-------
caspo.core.graph.Graph
The underlying interaction graph | 6.911912 | 8.511345 | 0.812082 |
ns = state.copy()
for var in state:
if clamping.has_variable(var):
ns[var] = int(clamping.bool(var))
else:
or_value = 0
for clause, _ in self.in_edges_iter(var):
or_value = or_value or clause.bool(state)... | 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 ... | 4.647375 | 4.199468 | 1.106658 |
current = dict.fromkeys(self.variables(), 0)
updated = self.step(current, clamping)
steps -= 1
while current != updated and steps != 0:
current = updated
updated = self.step(current, clamping)
return current | 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... | 4.465714 | 6.126229 | 0.72895 |
stimuli, inhibitors = stimuli or [], inhibitors or []
cues = stimuli + inhibitors
nc = len(cues)
ns = len(stimuli)
predictions = np.zeros((nclampings if nclampings > 0 else len(clampings), nc+len(readouts)), dtype=np.int8)
for i, clamping in enumerate(clampings):... | 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 names
inhi... | 3.032238 | 3.123364 | 0.970825 |
clampings = dataset.clampings
readouts = dataset.readouts.columns
observations = dataset.readouts.values
pos = ~np.isnan(observations)
return mean_squared_error(observations, (self.predictions(clampings, readouts).values)[pos]) | 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 | 9.947626 | 10.717863 | 0.928135 |
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 variables(self) | Returns variables in the logical network
Returns
-------
set[str]
Unique variables names | 3.652485 | 4.21008 | 0.867557 |
for var in it.ifilter(self.has_node, self.variables()):
yield var, frozenset(self.predecessors(var)) | 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. | 8.434394 | 6.721385 | 1.254859 |
arr = np.zeros(len(mappings), np.int8)
for i, (clause, target) in enumerate(mappings):
if self.has_edge(clause, target):
arr[i] = 1
return arr | 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
... | 3.986554 | 4.249499 | 0.938123 |
def answering_questions(self, attempt, validation_token, quiz_submission_id, access_code=None, quiz_questions=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - quiz_submission_id
path["quiz_submission_id"] = quiz_submission_id
# REQU... | Answering questions.
Provide or update an answer to one or more QuizQuestions. | null | null | null | |
def unflagging_question(self, id, attempt, validation_token, quiz_submission_id, access_code=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - quiz_submission_id
path["quiz_submission_id"] = quiz_submission_id
# REQUIRED - PATH - id
... | Unflagging a question.
Remove the flag that you previously set on a quiz question after you've
returned to it. | null | null | null | |
fs = set()
for i, clamping in enumerate(self):
fs.add(gringo.Fun(lname, [i]))
fs = fs.union(clamping.to_funset(i, cname))
return fs | 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... | 6.779721 | 4.461997 | 1.519437 |
stimuli, inhibitors = stimuli or [], inhibitors or []
cues = stimuli + inhibitors
nc = len(cues)
ns = len(stimuli)
variables = cues or np.array(list(set((v for (v, s) in it.chain.from_iterable(self)))))
matrix = np.array([])
for clamping in self:
... | 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 inhibitors nam... | 3.900253 | 3.983143 | 0.97919 |
self.to_dataframe(stimuli, inhibitors, prepend).to_csv(filename, index=False) | 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 : Optio... | 3.363779 | 4.565103 | 0.736846 |
inhibitors = inhibitors or []
clampings = []
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:
... | 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.
... | 3.255377 | 2.978795 | 1.09285 |
df = pd.read_csv(filename)
return cls.from_dataframe(df, inhibitors) | 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`.
inh... | 2.780518 | 3.885125 | 0.715683 |
df = self.to_dataframe()
n = float(len(self))
for var, sign in it.product(df.columns, [-1, 1]):
f = len(df[df[var] == sign]) / n
if f > 0:
yield Literal(var, sign), f | 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) | 4.960438 | 4.514582 | 1.098759 |
df = self.to_dataframe()
if literal.variable in df.columns:
return len(df[df[literal.variable] == literal.signature]) / float(len(self))
else:
raise ValueError("Variable not found: %s" % literal.variable) | 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
... | 4.032288 | 4.098612 | 0.983818 |
df = self.to_dataframe()
literals = set((l for l in it.chain.from_iterable(self)))
exclusive, inclusive = defaultdict(set), defaultdict(set)
for l1, l2 in it.combinations(it.ifilter(lambda l: self.frequency(l) < 1., literals), 2):
a1, a2 = df[l1.variable] == l1.sign... | 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 cl... | 3.457232 | 3.057272 | 1.130822 |
z, p = np.zeros((len(self), len(readouts)), dtype=int), np.zeros(len(self), dtype=int)
for n1, n2 in it.combinations(networks, 2):
r, c = np.where(n1.predictions(self, readouts) != n2.predictions(self, readouts))
z[r, c] += 1
p[r] += 1
df = pd.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 : list[str]
... | 2.987845 | 3.072372 | 0.972488 |
clampings = []
for clamping in self:
c = clamping.drop_literals(literals)
if len(c) > 0:
clampings.append(c)
return ClampingList(clampings) | 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 ... | 4.073865 | 3.525623 | 1.155502 |
return cls(it.imap(lambda (v, s): Literal(v, s), tuples)) | def from_tuples(cls, tuples) | Creates a clamping from tuples of the form (variable, sign)
Parameters
----------
tuples : iterable[(str,int)]
An iterable of tuples describing clamped variables
Returns
-------
caspo.core.clamping.Clamping
Created object instance | 11.150616 | 14.702361 | 0.758423 |
fs = set()
for var, sign in self:
fs.add(gringo.Fun(name, [index, var, sign]))
return fs | def to_funset(self, index, name="clamped") | Converts the clamping to a set of `gringo.Fun`_ object instances
Parameters
----------
index : int
An external identifier to associate several clampings together in ASP
name : str
A function name for the clamping
Returns
-------
set
... | 10.091932 | 7.970571 | 1.266149 |
arr = np.zeros(len(variables), np.int8)
dc = dict(self)
for i, var in enumerate(variables):
arr[i] = dc.get(var, arr[i])
return arr | def to_array(self, variables) | Converts the clamping to a 1-D array with respect to the given variables
Parameters
----------
variables : list[str]
List of variables names
Returns
-------
`numpy.ndarray`_
1-D array where position `i` correspond to the sign of the clamped vari... | 4.142733 | 4.789941 | 0.864882 |
def create_custom_gradebook_column(self, course_id, column_title, column_hidden=None, column_position=None, column_teacher_notes=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - c... | Create a custom gradebook column.
Create a custom gradebook column | null | null | null | |
def update_column_data(self, id, user_id, course_id, column_data_content):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - id
path["id"] = id
# REQU... | Update column data.
Set the content of a custom column | null | null | null | |
if not os.path.isfile(file_path):
return elements.error("Output Log", "Could not open file: " + file_path.split(os.sep)[-1])
headers = ["Converged Iterations",
"Avg. Iterations to Converge",
"Processor Count",
"Dycore Type"]
with open(file_path, 'r... | def parse_log(file_path) | Parse a CISM output log and extract some information.
Args:
file_path: absolute path to the log file
Return:
A dictionary created by the elements object corresponding to
the results of the bit for bit testing | 3.648037 | 3.575873 | 1.020181 |
if not os.path.isfile(file_path):
return {}
parser = ConfigParser()
parser.read(file_path)
# Strip out inline comments
for s in parser._sections:
for v in six.iterkeys(parser._sections[s]):
parser._sections[s][v] = parser._sections[s][v].split("#")[0].strip()
ret... | def parse_config(file_path) | Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file | 2.665743 | 3.030603 | 0.879608 |
# TODO - figure out what happens if no repo is selected
selectedModelIndexes = \
self.reposTableWidget.selectionModel().selectedRows()
for index in selectedModelIndexes:
return index.row() | def _selectedRepoRow(self) | Return the currently select repo | 6.569446 | 6.229075 | 1.054642 |
'''
Updates objective function for given measured metabolites.
:param dict measured_metabolites: dict in which keys are metabolite names
and values are float numbers represent fold changes in metabolites.
'''
self.clean_objective()
for k, v in measured_meta... | def set_objective(self, measured_metabolites) | Updates objective function for given measured metabolites.
:param dict measured_metabolites: dict in which keys are metabolite names
and values are float numbers represent fold changes in metabolites. | 5.281733 | 3.256664 | 1.621823 |
_sharing_id, _mode = tuple(share.split(":"))
_router_cls = ROUTERS.get(typ)
class _Handler(handler):
mode=_mode
sharing_id=_sharing_id
router_cls=_router_cls
return _Handler | def Routers(typ, share, handler=RoutersHandler) | Pass the result of this function to the handler argument
in your attribute declaration | 5.949103 | 6.476558 | 0.918559 |
def list_migration_issues_accounts(self, account_id, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - PATH - content_migration_id
path["conte... | List migration issues.
Returns paginated migration issues | null | null | null | |
def list_migration_issues_courses(self, course_id, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - content_migration_id
path["content_mi... | List migration issues.
Returns paginated migration issues | null | null | null | |
def list_migration_issues_groups(self, group_id, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - PATH - content_migration_id
path["content_migrati... | List migration issues.
Returns paginated migration issues | null | null | null | |
def list_migration_issues_users(self, user_id, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
path["user_id"] = user_id
# REQUIRED - PATH - content_migration_id
path["content_migration_id... | List migration issues.
Returns paginated migration issues | null | null | null | |
def update_migration_issue_accounts(self, id, account_id, workflow_state, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - PATH - content_migration_id
... | Update a migration issue.
Update the workflow_state of a migration issue | null | null | null | |
def update_migration_issue_courses(self, id, course_id, workflow_state, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - content_migration_id
... | Update a migration issue.
Update the workflow_state of a migration issue | null | null | null | |
def update_migration_issue_groups(self, id, group_id, workflow_state, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - PATH - content_migration_id
... | Update a migration issue.
Update the workflow_state of a migration issue | null | null | null | |
def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
path["user_id"] = user_id
# REQUIRED - PATH - content_migration_id
path[... | Update a migration issue.
Update the workflow_state of a migration issue | null | null | null | |
coor_width = max(rnf_profile.coor_width, len(str(self.left)), len(str(self.right)))
return "({},{},{},{},{})".format(
str(self.genome_id).zfill(rnf_profile.genome_id_width),
str(self.chr_id).zfill(rnf_profile.chr_id_width), self.direction,
str(self.left).zfi... | def stringize(
self,
rnf_profile,
) | Create RNF representation of this segment.
Args:
rnf_profile (rnftools.rnfformat.RnfProfile): RNF profile (with widths). | 3.002996 | 3.108715 | 0.965993 |
m = segment_destr_pattern.match(string)
self.genome_id = int(m.group(1))
self.chr_id = int(m.group(2))
self.direction = m.group(3)
self.left = int(m.group(4))
self.right = int(m.group(5)) | def destringize(self, string) | Get RNF values for this segment from its textual representation and
save them into this object.
Args:
string (str): Textual representation of a segment. | 3.25591 | 3.376866 | 0.964181 |
def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None, search_term=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"]... | List assignments.
Returns the list of assignments for the current context. | null | null | null | |
def list_assignments_for_user(self, user_id, course_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
path["user_id"] = user_id
# REQUIRED - PATH - course_id
path["course_id"] = course_id
self.logg... | List assignments for user.
Returns the list of assignments for the specified user if the current user has rights to view.
See {api:AssignmentsApiController#index List assignments} for valid arguments. | null | null | null | |
def get_single_assignment(self, id, course_id, all_dates=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# R... | Get a single assignment.
Returns the assignment with the given id.
"observed_users" is passed, submissions for observed users will also be included. | null | null | null | |
def list_assignment_overrides(self, course_id, assignment_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - assignment_id
path["assignment_id"] = assignment... | List assignment overrides.
Returns the list of overrides for this assignment that target
sections/groups/students visible to the current user. | null | null | null | |
def redirect_to_assignment_override_for_group(self, group_id, assignment_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - PATH - assignment_id
path["assignment_id"] ... | Redirect to the assignment override for a group.
Responds with a redirect to the override for the given group, if any
(404 otherwise). | null | null | null | |
def redirect_to_assignment_override_for_section(self, assignment_id, course_section_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_section_id
path["course_section_id"] = course_section_id
# REQUIRED - PATH - assignment_id
... | Redirect to the assignment override for a section.
Responds with a redirect to the override for the given section, if any
(404 otherwise). | null | null | null | |
def create_assignment_override(self, course_id, assignment_id, assignment_override_course_section_id=None, assignment_override_due_at=None, assignment_override_group_id=None, assignment_override_lock_at=None, assignment_override_student_ids=None, assignment_override_title=None, assignment_override_unlock_at=None):
... | Create an assignment override.
One of student_ids, group_id, or course_section_id must be present. At most
one should be present; if multiple are present only the most specific
(student_ids first, then group_id, then course_section_id) is used and any
others are ignored. | null | null | null | |
def update_assignment_override(self, id, course_id, assignment_id, assignment_override_due_at=None, assignment_override_lock_at=None, assignment_override_student_ids=None, assignment_override_title=None, assignment_override_unlock_at=None):
path = {}
data = {}
params = {}
... | Update an assignment override.
All current overridden values must be supplied if they are to be retained;
e.g. if due_at was overridden, but this PUT omits a value for due_at,
due_at will no longer be overridden. If the override is adhoc and
student_ids is not supplied, the target ... | null | null | null | |
def batch_retrieve_overrides_in_course(self, course_id, assignment_overrides_id, assignment_overrides_assignment_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - assignment_override... | Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the current user.
Returns null elements in the list for requests that were not found. | null | null | null | |
def batch_create_overrides_in_course(self, course_id, assignment_overrides):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - assignment_overrides
data["assignment_ove... | Batch create overrides in a course.
Creates the specified overrides for each assignment. Handles creation in a
transaction, so all records are created or none are.
One of student_ids, group_id, or course_section_id must be present. At most
one should be present; if multi... | null | null | null | |
return es_queryset.query(
query.FunctionScore(
functions=[function.RandomScore()]
)
).sort("-_score") | def randomize_es(es_queryset) | Randomize an elasticsearch queryset. | 7.346239 | 6.511722 | 1.128156 |
'''
:param X: list of dict which contains metabolic measurements.
'''
return Parallel(n_jobs=self.n_jobs)(delayed(self._transform)(x)
for x in X) | def transform(self, X, y=None) | :param X: list of dict which contains metabolic measurements. | 8.629873 | 3.398505 | 2.539315 |
encodings = ['guess', 'fixpoint', 'rss']
if self.optimum is None:
clingo = self.__get_clingo__(encodings + ['opt'])
if configure is not None:
configure(clingo.conf)
clingo.ground([("base", [])])
clingo.solve(on_model=self.__keep_l... | def learn(self, fit=0, size=0, configure=None) | Learns all (nearly) optimal logical networks with give fitness and size tolerance.
The first optimum logical network found is saved in the attribute :attr:`optimum` while
all enumerated logical networks are saved in the attribute :attr:`networks`.
Example::
>>> from caspo import co... | 4.632291 | 4.211715 | 1.099859 |
args = ['-c minsize=%s' % size[0], '-c maxsize=%s' % size[1],
'-c minnand=%s' % n_and[0], '-c maxnand=%s' % n_and[1], '-c maxin=%s' % max_in]
encodings = ['guess', 'random']
self.networks.reset()
clingo = self.__get_clingo__(args, encodings)
clingo.conf... | def random(self, size, n_and, max_in, n=1) | Generates `n` random logical networks with given size range, number of AND gates and maximum
input signals for AND gates. Logical networks are saved in the attribute :attr:`networks`.
Parameters
----------
n : int
Number of random logical networks to be generated
si... | 4.647204 | 4.221921 | 1.100732 |
# configure simple value attributes (str, int etc.)
for name, attr in handler.attributes():
if cfg.get(name) is not None:
continue
if attr.expected_type not in [list, dict]:
cfg[name] = self.set(handler, attr, name, path, cfg)
... | def configure(self, cfg, handler, path="") | Start configuration process for the provided handler
Args:
cfg (dict): config container
handler (config.Handler class): config handler to use
path (str): current path in the configuration progress | 4.373958 | 4.199195 | 1.041618 |
full_name = ("%s.%s" % (path, name)).strip(".")
# obtain default value
if attr.default is None:
default = None
else:
try:
comp = vodka.component.Component(cfg)
default = handler.default(name, inst=comp)
i... | def set(self, handler, attr, name, path, cfg) | Obtain value for config variable, by prompting the user
for input and substituting a default value if needed.
Also does validation on user input | 3.697577 | 3.718771 | 0.994301 |
data_val = pd.DataFrame(data[['epoch']])
data_val['acc'] = data['val_acc']
data_val['loss'] = data['val_loss']
data_val['data'] = 'validation'
data_training = pd.DataFrame(data[['acc', 'loss', 'epoch']])
data_training['data'] = 'training'
result = pd.concat([data_training, data_val],... | def _from_keras_log_format(data, **kwargs) | Plot accuracy and loss from a panda's dataframe.
Args:
data: Panda dataframe in the format of the Keras CSV log.
output_dir_path: The path to the directory where the resultings plots
should end up. | 2.964884 | 3.075581 | 0.964008 |
# automatically get seperator by using Python's CSV parser
data = pd.read_csv(csv_path, sep=None, engine='python')
_from_keras_log_format(data, output_dir_path=output_dir_path, **kwargs) | def from_keras_log(csv_path, output_dir_path, **kwargs) | Plot accuracy and loss from a Keras CSV log.
Args:
csv_path: The path to the CSV log with the actual data.
output_dir_path: The path to the directory where the resultings plots
should end up. | 5.689652 | 7.159625 | 0.794686 |
if key_name in self.config:
return self.config.get(key_name)
return self.Configuration.default(key_name, inst=self) | def get_config(self, key_name) | Return configuration value
Args:
key_name (str): configuration key
Returns:
The value for the specified configuration key, or if not found
in the config the default value specified in the Configuration Handler
class specified inside this component | 5.074647 | 6.392905 | 0.793794 |
lastpage = math.ceil(total / limit) - 1
headers = {'X-Total-Count': str(total), 'X-Limit': str(limit),
'X-Page-Last': str(lastpage), 'X-Page': str(curpage)}
if links:
base = "{}?%s".format(request.path)
links = {}
links['first'] = base % urlencode(dict(request.que... | def make_pagination_headers(request, limit, curpage, total, links=False) | Return Link Hypermedia Header. | 1.989086 | 1.958519 | 1.015607 |
paths = paths or ['/%s(/{%s})?/?' % (cls.name, cls.name)]
name = name or "api.%s" % cls.name
return super(RESTHandler, cls).bind(app, *paths, methods=methods, name=name, **kwargs) | def bind(cls, app, *paths, methods=None, name=None, **kwargs) | Bind to the application.
Generate URL, name if it's not provided. | 4.082146 | 4.079849 | 1.000563 |
# Authorization endpoint
self.auth = await self.authorize(request, **kwargs) # noqa
# Load collection
self.collection = await self.get_many(request, **kwargs)
if request.method == 'POST' and view is None:
return await super(RESTHandler, self).dispatch(requ... | async def dispatch(self, request, view=None, **kwargs) | Process request. | 3.008198 | 2.969635 | 1.012986 |
while iscoroutine(response):
response = await response
if isinstance(response, StreamResponse):
return response
response_kwargs.setdefault('content_type', 'application/json')
return Response(text=dumps(response), **response_kwargs) | async def make_response(self, request, response, **response_kwargs) | Convert a handler result to web response. | 3.46496 | 2.98412 | 1.161133 |
try:
data = loads(request.query.get(VAR_WHERE))
except (ValueError, TypeError):
return self.collection
self.filters, collection = self.meta.filters.filter(
data, self.collection, resource=self, **kwargs)
return collection | async def filter(self, request, **kwargs) | Filter collection. | 10.261665 | 8.75478 | 1.172121 |
if resource is not None and resource != '':
return self.to_simple(request, resource, **kwargs)
return self.to_simple(request, self.collection, many=True, **kwargs) | async def get(self, request, resource=None, **kwargs) | Get resource or collection of resources.
---
parameters:
- name: resource
in: path
type: string | 4.962316 | 6.505683 | 0.762766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.