_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q241900 | Observable.remove_observer | train | def remove_observer(self, signal, observer):
"""Remove an observer from the object.
Raise an eception if the signal is not allowed.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
... | python | {
"resource": ""
} |
q241901 | Observable.notify_observers | train | def notify_observers(self, signal, **kwargs):
""" Notify observers of a given signal.
Parameters
----------
signal : str
a valid signal.
kwargs : dict
the parameters that will be sent to the observers.
Returns
-------
out: bool
... | python | {
"resource": ""
} |
q241902 | Observable._is_allowed_signal | train | def _is_allowed_signal(self, signal):
"""Check if a signal is valid.
Raise an exception if the signal is not allowed.
Parameters
----------
signal: str
a signal.
"""
if signal not in self._allowed_signals:
raise Exception("Signal '{0}' ... | python | {
"resource": ""
} |
q241903 | Observable._add_observer | train | def _add_observer(self, signal, observer):
"""Associate an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function.
"""
if observer not in self._observers[signal]:
... | python | {
"resource": ""
} |
q241904 | Observable._remove_observer | train | def _remove_observer(self, signal, observer):
"""Remove an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed.
"""
if observer in self._observers[signal]:
... | python | {
"resource": ""
} |
q241905 | MetricObserver.is_converge | train | def is_converge(self):
"""Return True if the convergence criteria is matched.
"""
if len(self.list_cv_values) < self.wind:
return
start_idx = -self.wind
mid_idx = -(self.wind // 2)
old_mean = np.array(self.list_cv_values[start_idx:mid_idx]).mean()
cu... | python | {
"resource": ""
} |
q241906 | MetricObserver.retrieve_metrics | train | def retrieve_metrics(self):
"""Return the convergence metrics saved with the corresponding
iterations.
"""
time = np.array(self.list_dates)
if len(time) >= 1:
time -= time[0]
return {'time': time, 'index': self.list_iters,
'values': self.list... | python | {
"resource": ""
} |
q241907 | costObj._check_cost | train | def _check_cost(self):
"""Check cost function
This method tests the cost function for convergence in the specified
interval of iterations using the last n (test_range) cost values
Returns
-------
bool result of the convergence test
"""
# Add current co... | python | {
"resource": ""
} |
q241908 | costObj._calc_cost | train | def _calc_cost(self, *args, **kwargs):
"""Calculate the cost
This method calculates the cost from each of the input operators
Returns
-------
float cost
"""
return np.sum([op.cost(*args, **kwargs) for op in self._operators]) | python | {
"resource": ""
} |
q241909 | costObj.get_cost | train | def get_cost(self, *args, **kwargs):
"""Get cost function
This method calculates the current cost and tests for convergence
Returns
-------
bool result of the convergence test
"""
# Check if the cost should be calculated
if self._iteration % self._cost... | python | {
"resource": ""
} |
q241910 | add_noise | train | def add_noise(data, sigma=1.0, noise_type='gauss'):
r"""Add noise to data
This method adds Gaussian or Poisson noise to the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
sigma : float or list, optional
Standard deviation of the noise to be a... | python | {
"resource": ""
} |
q241911 | thresh | train | def thresh(data, threshold, threshold_type='hard'):
r"""Threshold data
This method perfoms hard or soft thresholding on the input data
Parameters
----------
data : np.ndarray, list or tuple
Input data array
threshold : float or np.ndarray
Threshold level(s)
threshold_type :... | python | {
"resource": ""
} |
q241912 | GradBasic._get_grad_method | train | def _get_grad_method(self, data):
r"""Get the gradient
This method calculates the gradient step from the input data
Parameters
----------
data : np.ndarray
Input data array
Notes
-----
Implements the following equation:
.. math::
... | python | {
"resource": ""
} |
q241913 | GradBasic._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate gradient component of the cost
This method returns the l2 norm error of the difference between the
original data and the data obtained after optimisation
Returns
-------
float gradient cost component
"""
... | python | {
"resource": ""
} |
q241914 | Positivity._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate positivity component of the cost
This method returns 0 as the posivituty does not contribute to the
cost.
Returns
-------
float zero
"""
if 'verbose' in kwargs and kwargs['verbose']:
pri... | python | {
"resource": ""
} |
q241915 | SparseThreshold._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component
"""
cost_val = np.sum(np.abs(self.weights * se... | python | {
"resource": ""
} |
q241916 | LowRankMatrix._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate low-rank component of the cost
This method returns the nuclear norm error of the deconvolved data in
matrix form
Returns
-------
float low-rank cost component
"""
cost_val = self.thresh * nuclear_no... | python | {
"resource": ""
} |
q241917 | LinearCompositionProx._op_method | train | def _op_method(self, data, extra_factor=1.0):
r"""Operator method
This method returns the scaled version of the proximity operator as
given by Lemma 2.8 of [CW2005].
Parameters
----------
data : np.ndarray
Input data array
extra_factor : float
... | python | {
"resource": ""
} |
q241918 | LinearCompositionProx._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate the cost function associated to the composed function
Returns
-------
float the cost of the associated composed function
"""
return self.prox_op.cost(self.linear_op.op(args[0]), **kwargs) | python | {
"resource": ""
} |
q241919 | ProximityCombo._cost_method | train | def _cost_method(self, *args, **kwargs):
"""Calculate combined proximity operator components of the cost
This method returns the sum of the cost components from each of the
proximity operators
Returns
-------
float combinded cost components
"""
return ... | python | {
"resource": ""
} |
q241920 | min_max_normalize | train | def min_max_normalize(img):
"""Centre and normalize a given array.
Parameters:
----------
img: np.ndarray
"""
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | python | {
"resource": ""
} |
q241921 | _preprocess_input | train | def _preprocess_input(test, ref, mask=None):
"""Wrapper to the metric
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnet... | python | {
"resource": ""
} |
q241922 | file_name_error | train | def file_name_error(file_name):
"""File name error
This method checks if the input file name is valid.
Parameters
----------
file_name : str
File name string
Raises
------
IOError
If file name not specified or file not found
"""
if file_name == '' or file_nam... | python | {
"resource": ""
} |
q241923 | is_executable | train | def is_executable(exe_name):
"""Check if Input is Executable
This methid checks if the input executable exists.
Parameters
----------
exe_name : str
Executable name
Returns
-------
Bool result of test
Raises
------
TypeError
For invalid input type
"""... | python | {
"resource": ""
} |
q241924 | SetUp._check_operator | train | def _check_operator(self, operator):
""" Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check
"""
if not isinstance(operator, type(None)):
... | python | {
"resource": ""
} |
q241925 | FISTA._check_restart_params | train | def _check_restart_params(self, restart_strategy, min_beta, s_greedy,
xi_restart):
r""" Check restarting parameters
This method checks that the restarting parameters are set and satisfy
the correct assumptions. It also checks that the current mode is
regula... | python | {
"resource": ""
} |
q241926 | FISTA.is_restart | train | def is_restart(self, z_old, x_new, x_old):
r""" Check whether the algorithm needs to restart
This method implements the checks necessary to tell whether the
algorithm needs to restart depending on the restarting strategy.
It also updates the FISTA parameters according to the restarting
... | python | {
"resource": ""
} |
q241927 | FISTA.update_beta | train | def update_beta(self, beta):
r"""Update beta
This method updates beta only in the case of safeguarding (should only
be done in the greedy restarting strategy).
Parameters
----------
beta: float
The beta parameter
Returns
-------
floa... | python | {
"resource": ""
} |
q241928 | FISTA.update_lambda | train | def update_lambda(self, *args, **kwargs):
r"""Update lambda
This method updates the value of lambda
Returns
-------
float current lambda value
Notes
-----
Implements steps 3 and 4 from algoritm 10.7 in [B2011]_
"""
if self.restart_stra... | python | {
"resource": ""
} |
q241929 | call_mr_transform | train | def call_mr_transform(data, opt='', path='./',
remove_files=True): # pragma: no cover
r"""Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to ... | python | {
"resource": ""
} |
q241930 | get_mr_filters | train | def get_mr_filters(data_shape, opt='', coarse=False): # pragma: no cover
"""Get mr_transform filters
This method obtains wavelet filters by calling mr_transform
Parameters
----------
data_shape : tuple
2D data shape
opt : list, optional
List of additonal mr_transform options
... | python | {
"resource": ""
} |
q241931 | gram_schmidt | train | def gram_schmidt(matrix, return_opt='orthonormal'):
r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
... | python | {
"resource": ""
} |
q241932 | nuclear_norm | train | def nuclear_norm(data):
r"""Nuclear norm
This method computes the nuclear (or trace) norm of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float nuclear norm value
Examples
--------
>>> from modopt.math.matrix import nucl... | python | {
"resource": ""
} |
q241933 | project | train | def project(u, v):
r"""Project vector
This method projects vector v onto vector u.
Parameters
----------
u : np.ndarray
Input vector
v : np.ndarray
Input vector
Returns
-------
np.ndarray projection
Examples
--------
>>> from modopt.math.matrix import ... | python | {
"resource": ""
} |
q241934 | rot_matrix | train | def rot_matrix(angle):
r"""Rotation matrix
This method produces a 2x2 rotation matrix for the given input angle.
Parameters
----------
angle : float
Rotation angle in radians
Returns
-------
np.ndarray 2x2 rotation matrix
Examples
--------
>>> from modopt.math.mat... | python | {
"resource": ""
} |
q241935 | PowerMethod._set_initial_x | train | def _set_initial_x(self):
"""Set initial value of x
This method sets the initial value of x to an arrray of random values
Returns
-------
np.ndarray of random values of the same shape as the input data
"""
return np.random.random(self._data_shape).astype(self.... | python | {
"resource": ""
} |
q241936 | PowerMethod.get_spec_rad | train | def get_spec_rad(self, tolerance=1e-6, max_iter=20, extra_factor=1.0):
"""Get spectral radius
This method calculates the spectral radius
Parameters
----------
tolerance : float, optional
Tolerance threshold for convergence (default is "1e-6")
max_iter : int,... | python | {
"resource": ""
} |
q241937 | LinearCombo._check_type | train | def _check_type(self, input_val):
""" Check Input Type
This method checks if the input is a list, tuple or a numpy array and
converts the input to a numpy array
Parameters
----------
input_val : list, tuple or np.ndarray
Returns
-------
np.ndarr... | python | {
"resource": ""
} |
q241938 | find_n_pc | train | def find_n_pc(u, factor=0.5):
"""Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correla... | python | {
"resource": ""
} |
q241939 | calculate_svd | train | def calculate_svd(data):
"""Calculate Singular Value Decomposition
This method calculates the Singular Value Decomposition (SVD) of the input
data using SciPy.
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
Returns
-------
tuple of left singular vector... | python | {
"resource": ""
} |
q241940 | svd_thresh | train | def svd_thresh(data, threshold=None, n_pc=None, thresh_type='hard'):
r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
... | python | {
"resource": ""
} |
q241941 | svd_thresh_coef | train | def svd_thresh_coef(data, operator, threshold, thresh_type='hard'):
"""Threshold the singular values coefficients
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
operator : class
Operat... | python | {
"resource": ""
} |
q241942 | gaussian_kernel | train | def gaussian_kernel(data_shape, sigma, norm='max'):
r"""Gaussian kernel
This method produces a Gaussian kerenal of a specified size and dispersion
Parameters
----------
data_shape : tuple
Desiered shape of the kernel
sigma : float
Standard deviation of the kernel
norm : str... | python | {
"resource": ""
} |
q241943 | mad | train | def mad(data):
r"""Median absolute deviation
This method calculates the median absolute deviation of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float MAD value
Examples
--------
>>> from modopt.math.stats import mad
... | python | {
"resource": ""
} |
q241944 | psnr | train | def psnr(data1, data2, method='starck', max_pix=255):
r"""Peak Signal-to-Noise Ratio
This method calculates the Peak Signal-to-Noise Ratio between an two data
sets
Parameters
----------
data1 : np.ndarray
First data set
data2 : np.ndarray
Second data set
method : str {'... | python | {
"resource": ""
} |
q241945 | psnr_stack | train | def psnr_stack(data1, data2, metric=np.mean, method='starck'):
r"""Peak Signa-to-Noise for stack of images
This method calculates the PSNRs for two stacks of 2D arrays.
By default the metod returns the mean value of the PSNRs, but any other
metric can be used.
Parameters
----------
data1 :... | python | {
"resource": ""
} |
q241946 | cube2map | train | def cube2map(data_cube, layout):
r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
... | python | {
"resource": ""
} |
q241947 | map2cube | train | def map2cube(data_map, layout):
r"""Map to cube
This method transforms the input data from a 2D map with given layout to
a 3D cube
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndar... | python | {
"resource": ""
} |
q241948 | map2matrix | train | def map2matrix(data_map, layout):
r"""Map to Matrix
This method transforms a 2D map to a 2D matrix
Parameters
----------
data_map : np.ndarray
Input data map, 2D array
layout : tuple
2D layout of 2D images
Returns
-------
np.ndarray 2D matrix
Raises
------... | python | {
"resource": ""
} |
q241949 | matrix2map | train | def matrix2map(data_matrix, map_shape):
r"""Matrix to Map
This method transforms a 2D matrix to a 2D map
Parameters
----------
data_matrix : np.ndarray
Input data matrix, 2D array
map_shape : tuple
2D shape of the output map
Returns
-------
np.ndarray 2D map
R... | python | {
"resource": ""
} |
q241950 | cube2matrix | train | def cube2matrix(data_cube):
r"""Cube to Matrix
This method transforms a 3D cube to a 2D matrix
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array
Returns
-------
np.ndarray 2D matrix
Examples
--------
>>> from modopt.base.transform import cube2... | python | {
"resource": ""
} |
q241951 | matrix2cube | train | def matrix2cube(data_matrix, im_shape):
r"""Matrix to Cube
This method transforms a 2D matrix to a 3D cube
Parameters
----------
data_matrix : np.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
np.ndarray 3D cube... | python | {
"resource": ""
} |
q241952 | plotCost | train | def plotCost(cost_list, output=None):
"""Plot cost function
Plot the final cost function
Parameters
----------
cost_list : list
List of cost function values
output : str, optional
Output file name
"""
if not import_fail:
if isinstance(output, type(None)):
... | python | {
"resource": ""
} |
q241953 | Gaussian_filter | train | def Gaussian_filter(x, sigma, norm=True):
r"""Gaussian filter
This method implements a Gaussian filter.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
norm : bool
Option to return normalised data. Default (norm=True)... | python | {
"resource": ""
} |
q241954 | mex_hat | train | def mex_hat(x, sigma):
r"""Mexican hat
This method implements a Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point
sigma : float
Standard deviation (filter scale)
Returns
-------
float Mexican hat filtered data point
Examples
... | python | {
"resource": ""
} |
q241955 | mex_hat_dir | train | def mex_hat_dir(x, y, sigma):
r"""Directional Mexican hat
This method implements a directional Mexican hat (or Ricker) wavelet.
Parameters
----------
x : float
Input data point for Gaussian
y : float
Input data point for Mexican hat
sigma : float
Standard deviation ... | python | {
"resource": ""
} |
q241956 | convolve | train | def convolve(data, kernel, method='scipy'):
r"""Convolve data with kernel
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input data array, normally a 2D image
kernel : n... | python | {
"resource": ""
} |
q241957 | convolve_stack | train | def convolve_stack(data, kernel, rot_kernel=False, method='scipy'):
r"""Convolve stack of data with stack of kernels
This method convolves the input data with a given kernel using FFT and
is the default convolution used for all routines
Parameters
----------
data : np.ndarray
Input dat... | python | {
"resource": ""
} |
q241958 | check_callable | train | def check_callable(val, add_agrs=True):
r""" Check input object is callable
This method checks if the input operator is a callable funciton and
optionally adds support for arguments and keyword arguments if not already
provided
Parameters
----------
val : function
Callable function... | python | {
"resource": ""
} |
q241959 | check_float | train | def check_float(val):
r"""Check if input value is a float or a np.ndarray of floats, if not
convert.
Parameters
----------
val : any
Input value
Returns
-------
float or np.ndarray of floats
Examples
--------
>>> from modopt.base.types import check_float
>>> a ... | python | {
"resource": ""
} |
q241960 | check_int | train | def check_int(val):
r"""Check if input value is an int or a np.ndarray of ints, if not convert.
Parameters
----------
val : any
Input value
Returns
-------
int or np.ndarray of ints
Examples
--------
>>> from modopt.base.types import check_int
>>> a = np.arange(5).... | python | {
"resource": ""
} |
q241961 | check_npndarray | train | def check_npndarray(val, dtype=None, writeable=True, verbose=True):
"""Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object
"""
if not isinstance(val, np.ndarray):
raise TypeError('Input is not a numpy array.')
if ((not isinstance(dt... | python | {
"resource": ""
} |
q241962 | positive | train | def positive(data):
r"""Positivity operator
This method preserves only the positive coefficients of the input data, all
negative coefficients are set to zero
Parameters
----------
data : int, float, list, tuple or np.ndarray
Input data
Returns
-------
int or float, or np.n... | python | {
"resource": ""
} |
q241963 | ScoreArray.mean | train | def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) | python | {
"resource": ""
} |
q241964 | ScoreMatrix.T | train | def T(self):
"""Get transpose of this ScoreMatrix."""
return ScoreMatrix(self.tests, self.models, scores=self.values,
weights=self.weights, transpose=True) | python | {
"resource": ""
} |
q241965 | ScoreMatrix.to_html | train | def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
**kwargs):
"""Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix."""
if show_mean is None:
show_mean = self.show_mean
if sortable is None:
... | python | {
"resource": ""
} |
q241966 | rec_apply | train | def rec_apply(func, n):
"""
Used to determine parent directory n levels up
by repeatedly applying os.path.dirname
"""
if n > 1:
rec_func = rec_apply(func, n - 1)
return lambda x: func(rec_func(x))
return func | python | {
"resource": ""
} |
q241967 | printd | train | def printd(*args, **kwargs):
"""Print if PRINT_DEBUG_STATE is True"""
global settings
if settings['PRINT_DEBUG_STATE']:
print(*args, **kwargs)
return True
return False | python | {
"resource": ""
} |
q241968 | assert_dimensionless | train | def assert_dimensionless(value):
"""
Tests for dimensionlessness of input.
If input is dimensionless but expressed as a Quantity, it returns the
bare value. If it not, it raised an error.
"""
if isinstance(value, Quantity):
value = value.simplified
if value.dimensionality == Di... | python | {
"resource": ""
} |
q241969 | import_all_modules | train | def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0):
"""Recursively imports all subpackages, modules, and submodules of a
given package.
'package' should be an imported package, not a string.
'skip' is a list of modules or subpackages not to import.
"""
skip = [] if sk... | python | {
"resource": ""
} |
q241970 | method_cache | train | def method_cache(by='value',method='run'):
"""A decorator used on any model method which calls the model's 'method'
method if that latter method has not been called using the current
arguments or simply sets model attributes to match the run results if
it has."""
def decorate_(func):
def de... | python | {
"resource": ""
} |
q241971 | NotebookTools.convert_path | train | def convert_path(cls, file):
"""
Check to see if an extended path is given and convert appropriately
"""
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
... | python | {
"resource": ""
} |
q241972 | NotebookTools.get_path | train | def get_path(self, file):
"""Get the full path of the notebook found in the directory
specified by self.path.
"""
class_path = inspect.getfile(self.__class__)
parent_path = os.path.dirname(class_path)
path = os.path.join(parent_path,self.path,file)
return os.path... | python | {
"resource": ""
} |
q241973 | NotebookTools.fix_display | train | def fix_display(self):
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
impor... | python | {
"resource": ""
} |
q241974 | NotebookTools.load_notebook | train | def load_notebook(self, name):
"""Loads a notebook file into memory."""
with open(self.get_path('%s.ipynb'%name)) as f:
nb = nbformat.read(f, as_version=4)
return nb,f | python | {
"resource": ""
} |
q241975 | NotebookTools.run_notebook | train | def run_notebook(self, nb, f):
"""Runs a loaded notebook file."""
if PYTHON_MAJOR_VERSION == 3:
kernel_name = 'python3'
elif PYTHON_MAJOR_VERSION == 2:
kernel_name = 'python2'
else:
raise Exception('Only Python 2 and 3 are supported')
ep = Exe... | python | {
"resource": ""
} |
q241976 | NotebookTools.execute_notebook | train | def execute_notebook(self, name):
"""Loads and then runs a notebook file."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | python | {
"resource": ""
} |
q241977 | NotebookTools.convert_notebook | train | def convert_notebook(self, name):
"""Converts a notebook into a python file."""
#subprocess.call(["jupyter","nbconvert","--to","python",
# self.get_path("%s.ipynb"%name)])
exporter = nbconvert.exporters.python.PythonExporter()
relative_path = self.convert_path(nam... | python | {
"resource": ""
} |
q241978 | NotebookTools.convert_and_execute_notebook | train | def convert_and_execute_notebook(self, name):
"""Converts a notebook into a python file and then runs it."""
self.convert_notebook(name)
code = self.read_code(name)#clean_code(name,'get_ipython')
exec(code,globals()) | python | {
"resource": ""
} |
q241979 | NotebookTools.gen_file_path | train | def gen_file_path(self, name):
"""
Returns full path to generated files. Checks to see if directory
exists where generated files are stored and creates one otherwise.
"""
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
... | python | {
"resource": ""
} |
q241980 | NotebookTools.read_code | train | def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()
return code | python | {
"resource": ""
} |
q241981 | NotebookTools.clean_code | train | def clean_code(self, name, forbidden):
"""
Remove lines containing items in 'forbidden' from the code.
Helpful for executing converted notebooks that still retain IPython
magic commands.
"""
code = self.read_code(name)
code = code.split('\n')
new_code = [... | python | {
"resource": ""
} |
q241982 | NotebookTools.do_notebook | train | def do_notebook(self, name):
"""Run a notebook file after optionally
converting it to a python file."""
CONVERT_NOTEBOOKS = int(os.getenv('CONVERT_NOTEBOOKS', True))
s = StringIO()
if mock:
out = unittest.mock.patch('sys.stdout', new=MockDevice(s))
err = u... | python | {
"resource": ""
} |
q241983 | NotebookTools._do_notebook | train | def _do_notebook(self, name, convert_notebooks=False):
"""Called by do_notebook to actually run the notebook."""
if convert_notebooks:
self.convert_and_execute_notebook(name)
else:
self.execute_notebook(name) | python | {
"resource": ""
} |
q241984 | Model.get_capabilities | train | def get_capabilities(cls):
"""List the model's capabilities."""
capabilities = []
for _cls in cls.mro():
if issubclass(_cls, Capability) and _cls is not Capability \
and not issubclass(_cls, Model):
capabilities.append(_cls)
return capabilities | python | {
"resource": ""
} |
q241985 | Model.failed_extra_capabilities | train | def failed_extra_capabilities(self):
"""Check to see if instance passes its `extra_capability_checks`."""
failed = []
for capability, f_name in self.extra_capability_checks.items():
f = getattr(self, f_name)
instance_capable = f()
if not instance_capable:
... | python | {
"resource": ""
} |
q241986 | Model.describe | train | def describe(self):
"""Describe the model."""
result = "No description available"
if self.description:
result = "%s" % self.description
else:
if self.__doc__:
s = []
s += [self.__doc__.strip().replace('\n', '').
... | python | {
"resource": ""
} |
q241987 | Model.is_match | train | def is_match(self, match):
"""Return whether this model is the same as `match`.
Matches if the model is the same as or has the same name as `match`.
"""
result = False
if self == match:
result = True
elif isinstance(match, str) and fnmatchcase(self.name, matc... | python | {
"resource": ""
} |
q241988 | main | train | def main(*args):
"""Launch the main routine."""
parser = argparse.ArgumentParser()
parser.add_argument("action",
help="create, check, run, make-nb, or run-nb")
parser.add_argument("--directory", "-dir", default=os.getcwd(),
help="path to directory with a .... | python | {
"resource": ""
} |
q241989 | create | train | def create(file_path):
"""Create a default .sciunit config file if one does not already exist."""
if os.path.exists(file_path):
raise IOError("There is already a configuration file at %s" %
file_path)
with open(file_path, 'w') as f:
config = configparser.ConfigParser()
... | python | {
"resource": ""
} |
q241990 | parse | train | def parse(file_path=None, show=False):
"""Parse a .sciunit config file."""
if file_path is None:
file_path = os.path.join(os.getcwd(), '.sciunit')
if not os.path.exists(file_path):
raise IOError('No .sciunit file was found at %s' % file_path)
# Load the configuration file
config = c... | python | {
"resource": ""
} |
q241991 | prep | train | def prep(config=None, path=None):
"""Prepare to read the configuration information."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
os.environ['SCIDASH_H... | python | {
"resource": ""
} |
q241992 | run | train | def run(config, path=None, stop_on_error=True, just_tests=False):
"""Run sciunit tests for the given configuration."""
if path is None:
path = os.getcwd()
prep(config, path=path)
models = __import__('models')
tests = __import__('tests')
suites = __import__('suites')
print('\n')
... | python | {
"resource": ""
} |
q241993 | nb_name_from_path | train | def nb_name_from_path(config, path):
"""Get a notebook name from a path to a notebook"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
default_nb_name = os.path.split(os.path.realpath(root))[1]
nb_n... | python | {
"resource": ""
} |
q241994 | make_nb | train | def make_nb(config, path=None, stop_on_error=True, just_tests=False):
"""Create a Jupyter notebook sciunit tests for the given configuration."""
root, nb_name = nb_name_from_path(config, path)
clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr)
name = clean(nb_name)
mpl_style = config.get('mis... | python | {
"resource": ""
} |
q241995 | write_nb | train | def write_nb(root, nb_name, cells):
"""Write a jupyter notebook to disk.
Takes a given a root directory, a notebook name, and a list of cells.
"""
nb = new_notebook(cells=cells,
metadata={
'language': 'python',
})
nb_path = os.pa... | python | {
"resource": ""
} |
q241996 | run_nb | train | def run_nb(config, path=None):
"""Run a notebook file.
Runs the one specified by the config file, or the one at
the location specificed by 'path'.
"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
nb_name = config.get('misc... | python | {
"resource": ""
} |
q241997 | add_code_cell | train | def add_code_cell(cells, source):
"""Add a code cell containing `source` to the notebook."""
from nbformat.v4.nbbase import new_code_cell
n_code_cells = len([c for c in cells if c['cell_type'] == 'code'])
cells.append(new_code_cell(source=source, execution_count=n_code_cells+1)) | python | {
"resource": ""
} |
q241998 | cleanup | train | def cleanup(config=None, path=None):
"""Cleanup by removing paths added during earlier in configuration."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
if sys.path[0] == root:
sy... | python | {
"resource": ""
} |
q241999 | Versioned.get_repo | train | def get_repo(self, cached=True):
"""Get a git repository object for this instance."""
module = sys.modules[self.__module__]
# We use module.__file__ instead of module.__path__[0]
# to include modules without a __path__ attribute.
if hasattr(self.__class__, '_repo') and cached:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.