id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
26,800 | CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable._add_observer | 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]:
self._observers[signal].append(observer) | python | def _add_observer(self, signal, observer):
if observer not in self._observers[signal]:
self._observers[signal].append(observer) | [
"def",
"_add_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"if",
"observer",
"not",
"in",
"self",
".",
"_observers",
"[",
"signal",
"]",
":",
"self",
".",
"_observers",
"[",
"signal",
"]",
".",
"append",
"(",
"observer",
")"
] | Associate an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function. | [
"Associate",
"an",
"observer",
"to",
"a",
"valid",
"signal",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L153-L166 |
26,801 | CEA-COSMIC/ModOpt | modopt/base/observable.py | Observable._remove_observer | 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]:
self._observers[signal].remove(observer) | python | def _remove_observer(self, signal, observer):
if observer in self._observers[signal]:
self._observers[signal].remove(observer) | [
"def",
"_remove_observer",
"(",
"self",
",",
"signal",
",",
"observer",
")",
":",
"if",
"observer",
"in",
"self",
".",
"_observers",
"[",
"signal",
"]",
":",
"self",
".",
"_observers",
"[",
"signal",
"]",
".",
"remove",
"(",
"observer",
")"
] | Remove an observer to a valid signal.
Parameters
----------
signal : str
a valid signal.
observer : @func
an obervation function to be removed. | [
"Remove",
"an",
"observer",
"to",
"a",
"valid",
"signal",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L168-L181 |
26,802 | CEA-COSMIC/ModOpt | modopt/base/observable.py | MetricObserver.is_converge | 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()
current_mean = np.array(self.list_cv_values[mid_idx:]).mean()
normalize_residual_metrics = (np.abs(old_mean - current_mean) /
np.abs(old_mean))
self.converge_flag = normalize_residual_metrics < self.eps | python | def is_converge(self):
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()
current_mean = np.array(self.list_cv_values[mid_idx:]).mean()
normalize_residual_metrics = (np.abs(old_mean - current_mean) /
np.abs(old_mean))
self.converge_flag = normalize_residual_metrics < self.eps | [
"def",
"is_converge",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"list_cv_values",
")",
"<",
"self",
".",
"wind",
":",
"return",
"start_idx",
"=",
"-",
"self",
".",
"wind",
"mid_idx",
"=",
"-",
"(",
"self",
".",
"wind",
"//",
"2",
")",
... | Return True if the convergence criteria is matched. | [
"Return",
"True",
"if",
"the",
"convergence",
"criteria",
"is",
"matched",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L256-L269 |
26,803 | CEA-COSMIC/ModOpt | modopt/base/observable.py | MetricObserver.retrieve_metrics | 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_cv_values} | python | def retrieve_metrics(self):
time = np.array(self.list_dates)
if len(time) >= 1:
time -= time[0]
return {'time': time, 'index': self.list_iters,
'values': self.list_cv_values} | [
"def",
"retrieve_metrics",
"(",
"self",
")",
":",
"time",
"=",
"np",
".",
"array",
"(",
"self",
".",
"list_dates",
")",
"if",
"len",
"(",
"time",
")",
">=",
"1",
":",
"time",
"-=",
"time",
"[",
"0",
"]",
"return",
"{",
"'time'",
":",
"time",
",",... | Return the convergence metrics saved with the corresponding
iterations. | [
"Return",
"the",
"convergence",
"metrics",
"saved",
"with",
"the",
"corresponding",
"iterations",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/observable.py#L271-L281 |
26,804 | CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj._check_cost | 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 cost value to the test list
self._test_list.append(self.cost)
# Check if enough cost values have been collected
if len(self._test_list) == self._test_range:
# The mean of the first half of the test list
t1 = np.mean(self._test_list[len(self._test_list) // 2:], axis=0)
# The mean of the second half of the test list
t2 = np.mean(self._test_list[:len(self._test_list) // 2], axis=0)
# Calculate the change across the test list
if not np.around(t1, decimals=16):
cost_diff = 0.0
else:
cost_diff = (np.linalg.norm(t1 - t2) / np.linalg.norm(t1))
# Reset the test list
self._test_list = []
if self._verbose:
print(' - CONVERGENCE TEST - ')
print(' - CHANGE IN COST:', cost_diff)
print('')
# Check for convergence
return cost_diff <= self._tolerance
else:
return False | python | def _check_cost(self):
# Add current cost value to the test list
self._test_list.append(self.cost)
# Check if enough cost values have been collected
if len(self._test_list) == self._test_range:
# The mean of the first half of the test list
t1 = np.mean(self._test_list[len(self._test_list) // 2:], axis=0)
# The mean of the second half of the test list
t2 = np.mean(self._test_list[:len(self._test_list) // 2], axis=0)
# Calculate the change across the test list
if not np.around(t1, decimals=16):
cost_diff = 0.0
else:
cost_diff = (np.linalg.norm(t1 - t2) / np.linalg.norm(t1))
# Reset the test list
self._test_list = []
if self._verbose:
print(' - CONVERGENCE TEST - ')
print(' - CHANGE IN COST:', cost_diff)
print('')
# Check for convergence
return cost_diff <= self._tolerance
else:
return False | [
"def",
"_check_cost",
"(",
"self",
")",
":",
"# Add current cost value to the test list",
"self",
".",
"_test_list",
".",
"append",
"(",
"self",
".",
"cost",
")",
"# Check if enough cost values have been collected",
"if",
"len",
"(",
"self",
".",
"_test_list",
")",
... | 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 | [
"Check",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L120-L160 |
26,805 | CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj._calc_cost | 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 | def _calc_cost(self, *args, **kwargs):
return np.sum([op.cost(*args, **kwargs) for op in self._operators]) | [
"def",
"_calc_cost",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"op",
".",
"cost",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"op",
"in",
"self",
".",
"_operators",
"]",
... | Calculate the cost
This method calculates the cost from each of the input operators
Returns
-------
float cost | [
"Calculate",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L162-L173 |
26,806 | CEA-COSMIC/ModOpt | modopt/opt/cost.py | costObj.get_cost | 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_interval:
test_result = False
else:
if self._verbose:
print(' - ITERATION:', self._iteration)
# Calculate the current cost
self.cost = self._calc_cost(verbose=self._verbose, *args, **kwargs)
self._cost_list.append(self.cost)
if self._verbose:
print(' - COST:', self.cost)
print('')
# Test for convergence
test_result = self._check_cost()
# Update the current iteration number
self._iteration += 1
return test_result | python | def get_cost(self, *args, **kwargs):
# Check if the cost should be calculated
if self._iteration % self._cost_interval:
test_result = False
else:
if self._verbose:
print(' - ITERATION:', self._iteration)
# Calculate the current cost
self.cost = self._calc_cost(verbose=self._verbose, *args, **kwargs)
self._cost_list.append(self.cost)
if self._verbose:
print(' - COST:', self.cost)
print('')
# Test for convergence
test_result = self._check_cost()
# Update the current iteration number
self._iteration += 1
return test_result | [
"def",
"get_cost",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if the cost should be calculated",
"if",
"self",
".",
"_iteration",
"%",
"self",
".",
"_cost_interval",
":",
"test_result",
"=",
"False",
"else",
":",
"if",
"self",... | Get cost function
This method calculates the current cost and tests for convergence
Returns
-------
bool result of the convergence test | [
"Get",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/cost.py#L175-L210 |
26,807 | CEA-COSMIC/ModOpt | modopt/signal/noise.py | add_noise | 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 added ('gauss' only)
noise_type : str {'gauss', 'poisson'}
Type of noise to be added (default is 'gauss')
Returns
-------
np.ndarray input data with added noise
Raises
------
ValueError
If `noise_type` is not 'gauss' or 'poisson'
ValueError
If number of `sigma` values does not match the first dimension of the
input data
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.arange(9).reshape(3, 3).astype(float)
>>> x
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.random.seed(1)
>>> add_noise(x, noise_type='poisson')
array([[ 0., 2., 2.],
[ 4., 5., 10.],
[ 11., 15., 18.]])
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.zeros(5)
>>> x
array([ 0., 0., 0., 0., 0.])
>>> np.random.seed(1)
>>> add_noise(x, sigma=2.0)
array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526])
"""
data = np.array(data)
if noise_type not in ('gauss', 'poisson'):
raise ValueError('Invalid noise type. Options are "gauss" or'
'"poisson"')
if isinstance(sigma, (list, tuple, np.ndarray)):
if len(sigma) != data.shape[0]:
raise ValueError('Number of sigma values must match first '
'dimension of input data')
if noise_type is 'gauss':
random = np.random.randn(*data.shape)
elif noise_type is 'poisson':
random = np.random.poisson(np.abs(data))
if isinstance(sigma, (int, float)):
return data + sigma * random
else:
return data + np.array([s * r for s, r in zip(sigma, random)]) | python | 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 added ('gauss' only)
noise_type : str {'gauss', 'poisson'}
Type of noise to be added (default is 'gauss')
Returns
-------
np.ndarray input data with added noise
Raises
------
ValueError
If `noise_type` is not 'gauss' or 'poisson'
ValueError
If number of `sigma` values does not match the first dimension of the
input data
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.arange(9).reshape(3, 3).astype(float)
>>> x
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.random.seed(1)
>>> add_noise(x, noise_type='poisson')
array([[ 0., 2., 2.],
[ 4., 5., 10.],
[ 11., 15., 18.]])
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.zeros(5)
>>> x
array([ 0., 0., 0., 0., 0.])
>>> np.random.seed(1)
>>> add_noise(x, sigma=2.0)
array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526])
"""
data = np.array(data)
if noise_type not in ('gauss', 'poisson'):
raise ValueError('Invalid noise type. Options are "gauss" or'
'"poisson"')
if isinstance(sigma, (list, tuple, np.ndarray)):
if len(sigma) != data.shape[0]:
raise ValueError('Number of sigma values must match first '
'dimension of input data')
if noise_type is 'gauss':
random = np.random.randn(*data.shape)
elif noise_type is 'poisson':
random = np.random.poisson(np.abs(data))
if isinstance(sigma, (int, float)):
return data + sigma * random
else:
return data + np.array([s * r for s, r in zip(sigma, random)]) | [
"def",
"add_noise",
"(",
"data",
",",
"sigma",
"=",
"1.0",
",",
"noise_type",
"=",
"'gauss'",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"if",
"noise_type",
"not",
"in",
"(",
"'gauss'",
",",
"'poisson'",
")",
":",
"raise",
"ValueErr... | 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 added ('gauss' only)
noise_type : str {'gauss', 'poisson'}
Type of noise to be added (default is 'gauss')
Returns
-------
np.ndarray input data with added noise
Raises
------
ValueError
If `noise_type` is not 'gauss' or 'poisson'
ValueError
If number of `sigma` values does not match the first dimension of the
input data
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.arange(9).reshape(3, 3).astype(float)
>>> x
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.random.seed(1)
>>> add_noise(x, noise_type='poisson')
array([[ 0., 2., 2.],
[ 4., 5., 10.],
[ 11., 15., 18.]])
>>> import numpy as np
>>> from modopt.signal.noise import add_noise
>>> x = np.zeros(5)
>>> x
array([ 0., 0., 0., 0., 0.])
>>> np.random.seed(1)
>>> add_noise(x, sigma=2.0)
array([ 3.24869073, -1.22351283, -1.0563435 , -2.14593724, 1.73081526]) | [
"r",
"Add",
"noise",
"to",
"data"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L15-L88 |
26,808 | CEA-COSMIC/ModOpt | modopt/signal/noise.py | thresh | 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 : str {'hard', 'soft'}
Type of noise to be added (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
If `threshold_type` is not 'hard' or 'soft'
Notes
-----
Implements one of the following two equations:
* Hard Threshold
.. math::
\mathrm{HT}_\lambda(x) =
\begin{cases}
x & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
* Soft Threshold
.. math::
\mathrm{ST}_\lambda(x) =
\begin{cases}
x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.randint(-9, 9, 10)
>>> x
array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7])
>>> thresh(x, 4)
array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7])
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.ranf((3, 3))
>>> x
array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04],
[ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02],
[ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]])
>>> thresh(x, 0.2, threshold_type='soft')
array([[ 0.217022 , 0.52032449, -0. ],
[ 0.10233257, -0. , -0. ],
[-0. , 0.14556073, 0.19676747]])
"""
data = np.array(data)
if threshold_type not in ('hard', 'soft'):
raise ValueError('Invalid threshold type. Options are "hard" or'
'"soft"')
if threshold_type == 'soft':
return np.around(np.maximum((1.0 - threshold /
np.maximum(np.finfo(np.float64).eps, np.abs(data))),
0.0) * data, decimals=15)
else:
return data * (np.abs(data) >= threshold) | python | 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 : str {'hard', 'soft'}
Type of noise to be added (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
If `threshold_type` is not 'hard' or 'soft'
Notes
-----
Implements one of the following two equations:
* Hard Threshold
.. math::
\mathrm{HT}_\lambda(x) =
\begin{cases}
x & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
* Soft Threshold
.. math::
\mathrm{ST}_\lambda(x) =
\begin{cases}
x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.randint(-9, 9, 10)
>>> x
array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7])
>>> thresh(x, 4)
array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7])
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.ranf((3, 3))
>>> x
array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04],
[ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02],
[ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]])
>>> thresh(x, 0.2, threshold_type='soft')
array([[ 0.217022 , 0.52032449, -0. ],
[ 0.10233257, -0. , -0. ],
[-0. , 0.14556073, 0.19676747]])
"""
data = np.array(data)
if threshold_type not in ('hard', 'soft'):
raise ValueError('Invalid threshold type. Options are "hard" or'
'"soft"')
if threshold_type == 'soft':
return np.around(np.maximum((1.0 - threshold /
np.maximum(np.finfo(np.float64).eps, np.abs(data))),
0.0) * data, decimals=15)
else:
return data * (np.abs(data) >= threshold) | [
"def",
"thresh",
"(",
"data",
",",
"threshold",
",",
"threshold_type",
"=",
"'hard'",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
")",
"if",
"threshold_type",
"not",
"in",
"(",
"'hard'",
",",
"'soft'",
")",
":",
"raise",
"ValueError",
"(",
... | 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 : str {'hard', 'soft'}
Type of noise to be added (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
If `threshold_type` is not 'hard' or 'soft'
Notes
-----
Implements one of the following two equations:
* Hard Threshold
.. math::
\mathrm{HT}_\lambda(x) =
\begin{cases}
x & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
* Soft Threshold
.. math::
\mathrm{ST}_\lambda(x) =
\begin{cases}
x-\lambda\text{sign}(x) & \text{if } |x|\geq\lambda \\
0 & \text{otherwise}
\end{cases}
Examples
--------
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.randint(-9, 9, 10)
>>> x
array([-4, 2, 3, -1, 0, 2, -4, 6, -9, 7])
>>> thresh(x, 4)
array([-4, 0, 0, 0, 0, 0, -4, 6, -9, 7])
>>> import numpy as np
>>> from modopt.signal.noise import thresh
>>> np.random.seed(1)
>>> x = np.random.ranf((3, 3))
>>> x
array([[ 4.17022005e-01, 7.20324493e-01, 1.14374817e-04],
[ 3.02332573e-01, 1.46755891e-01, 9.23385948e-02],
[ 1.86260211e-01, 3.45560727e-01, 3.96767474e-01]])
>>> thresh(x, 0.2, threshold_type='soft')
array([[ 0.217022 , 0.52032449, -0. ],
[ 0.10233257, -0. , -0. ],
[-0. , 0.14556073, 0.19676747]]) | [
"r",
"Threshold",
"data"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/noise.py#L91-L173 |
26,809 | CEA-COSMIC/ModOpt | modopt/opt/gradient.py | GradBasic._get_grad_method | 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::
\nabla F(x) = \mathbf{H}^T(\mathbf{H}\mathbf{x} - \mathbf{y})
"""
self.grad = self.trans_op(self.op(data) - self.obs_data) | python | 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::
\nabla F(x) = \mathbf{H}^T(\mathbf{H}\mathbf{x} - \mathbf{y})
"""
self.grad = self.trans_op(self.op(data) - self.obs_data) | [
"def",
"_get_grad_method",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"grad",
"=",
"self",
".",
"trans_op",
"(",
"self",
".",
"op",
"(",
"data",
")",
"-",
"self",
".",
"obs_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::
\nabla F(x) = \mathbf{H}^T(\mathbf{H}\mathbf{x} - \mathbf{y}) | [
"r",
"Get",
"the",
"gradient"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L222-L241 |
26,810 | CEA-COSMIC/ModOpt | modopt/opt/gradient.py | GradBasic._cost_method | 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
"""
cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2
if 'verbose' in kwargs and kwargs['verbose']:
print(' - DATA FIDELITY (X):', cost_val)
return cost_val | python | def _cost_method(self, *args, **kwargs):
cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2
if 'verbose' in kwargs and kwargs['verbose']:
print(' - DATA FIDELITY (X):', cost_val)
return cost_val | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cost_val",
"=",
"0.5",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"obs_data",
"-",
"self",
".",
"op",
"(",
"args",
"[",
"0",
"]",
")",
")",
... | 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 | [
"Calculate",
"gradient",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/gradient.py#L243-L260 |
26,811 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | Positivity._cost_method | 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']:
print(' - Min (X):', np.min(args[0]))
return 0.0 | python | def _cost_method(self, *args, **kwargs):
if 'verbose' in kwargs and kwargs['verbose']:
print(' - Min (X):', np.min(args[0]))
return 0.0 | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'verbose'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'verbose'",
"]",
":",
"print",
"(",
"' - Min (X):'",
",",
"np",
".",
"min",
"(",
"args",
"[",
"0",
"]... | Calculate positivity component of the cost
This method returns 0 as the posivituty does not contribute to the
cost.
Returns
-------
float zero | [
"Calculate",
"positivity",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L90-L105 |
26,812 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | SparseThreshold._cost_method | 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 * self._linear.op(args[0])))
if 'verbose' in kwargs and kwargs['verbose']:
print(' - L1 NORM (X):', cost_val)
return cost_val | python | def _cost_method(self, *args, **kwargs):
cost_val = np.sum(np.abs(self.weights * self._linear.op(args[0])))
if 'verbose' in kwargs and kwargs['verbose']:
print(' - L1 NORM (X):', cost_val)
return cost_val | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cost_val",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"self",
".",
"weights",
"*",
"self",
".",
"_linear",
".",
"op",
"(",
"args",
"[",
"0",
"]",
... | Calculate sparsity component of the cost
This method returns the l1 norm error of the weighted wavelet
coefficients
Returns
-------
float sparsity cost component | [
"Calculate",
"sparsity",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L154-L171 |
26,813 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LowRankMatrix._cost_method | 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_norm(cube2matrix(args[0]))
if 'verbose' in kwargs and kwargs['verbose']:
print(' - NUCLEAR NORM (X):', cost_val)
return cost_val | python | def _cost_method(self, *args, **kwargs):
cost_val = self.thresh * nuclear_norm(cube2matrix(args[0]))
if 'verbose' in kwargs and kwargs['verbose']:
print(' - NUCLEAR NORM (X):', cost_val)
return cost_val | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cost_val",
"=",
"self",
".",
"thresh",
"*",
"nuclear_norm",
"(",
"cube2matrix",
"(",
"args",
"[",
"0",
"]",
")",
")",
"if",
"'verbose'",
"in",
"kwargs",
"and",
... | 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 | [
"Calculate",
"low",
"-",
"rank",
"component",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L255-L272 |
26,814 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LinearCompositionProx._op_method | 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
Additional multiplication factor
Returns
-------
np.ndarray result of the scaled proximity operator
"""
return self.linear_op.adj_op(
self.prox_op.op(self.linear_op.op(data), extra_factor=extra_factor)
) | python | 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
Additional multiplication factor
Returns
-------
np.ndarray result of the scaled proximity operator
"""
return self.linear_op.adj_op(
self.prox_op.op(self.linear_op.op(data), extra_factor=extra_factor)
) | [
"def",
"_op_method",
"(",
"self",
",",
"data",
",",
"extra_factor",
"=",
"1.0",
")",
":",
"return",
"self",
".",
"linear_op",
".",
"adj_op",
"(",
"self",
".",
"prox_op",
".",
"op",
"(",
"self",
".",
"linear_op",
".",
"op",
"(",
"data",
")",
",",
"e... | 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
Additional multiplication factor
Returns
-------
np.ndarray result of the scaled proximity operator | [
"r",
"Operator",
"method"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L295-L314 |
26,815 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | LinearCompositionProx._cost_method | 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 | def _cost_method(self, *args, **kwargs):
return self.prox_op.cost(self.linear_op.op(args[0]), **kwargs) | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"prox_op",
".",
"cost",
"(",
"self",
".",
"linear_op",
".",
"op",
"(",
"args",
"[",
"0",
"]",
")",
",",
"*",
"*",
"kwargs",
")"
] | Calculate the cost function associated to the composed function
Returns
-------
float the cost of the associated composed function | [
"Calculate",
"the",
"cost",
"function",
"associated",
"to",
"the",
"composed",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L316-L323 |
26,816 | CEA-COSMIC/ModOpt | modopt/opt/proximity.py | ProximityCombo._cost_method | 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 np.sum([operator.cost(data) for operator, data in
zip(self.operators, args[0])]) | python | def _cost_method(self, *args, **kwargs):
return np.sum([operator.cost(data) for operator, data in
zip(self.operators, args[0])]) | [
"def",
"_cost_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"operator",
".",
"cost",
"(",
"data",
")",
"for",
"operator",
",",
"data",
"in",
"zip",
"(",
"self",
".",
"operators",
... | 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 | [
"Calculate",
"combined",
"proximity",
"operator",
"components",
"of",
"the",
"cost"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L423-L436 |
26,817 | CEA-COSMIC/ModOpt | modopt/math/metrics.py | min_max_normalize | 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 | def min_max_normalize(img):
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | [
"def",
"min_max_normalize",
"(",
"img",
")",
":",
"min_img",
"=",
"img",
".",
"min",
"(",
")",
"max_img",
"=",
"img",
".",
"max",
"(",
")",
"return",
"(",
"img",
"-",
"min_img",
")",
"/",
"(",
"max_img",
"-",
"min_img",
")"
] | Centre and normalize a given array.
Parameters:
----------
img: np.ndarray | [
"Centre",
"and",
"normalize",
"a",
"given",
"array",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L21-L33 |
26,818 | CEA-COSMIC/ModOpt | modopt/math/metrics.py | _preprocess_input | 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 magnetude.
Returns
-------
ssim: float, the snr
"""
test = np.abs(np.copy(test)).astype('float64')
ref = np.abs(np.copy(ref)).astype('float64')
test = min_max_normalize(test)
ref = min_max_normalize(ref)
if (not isinstance(mask, np.ndarray)) and (mask is not None):
raise ValueError("mask should be None, or a np.ndarray,"
" got '{0}' instead.".format(mask))
if mask is None:
return test, ref, None
return test, ref, mask | python | def _preprocess_input(test, ref, mask=None):
test = np.abs(np.copy(test)).astype('float64')
ref = np.abs(np.copy(ref)).astype('float64')
test = min_max_normalize(test)
ref = min_max_normalize(ref)
if (not isinstance(mask, np.ndarray)) and (mask is not None):
raise ValueError("mask should be None, or a np.ndarray,"
" got '{0}' instead.".format(mask))
if mask is None:
return test, ref, None
return test, ref, mask | [
"def",
"_preprocess_input",
"(",
"test",
",",
"ref",
",",
"mask",
"=",
"None",
")",
":",
"test",
"=",
"np",
".",
"abs",
"(",
"np",
".",
"copy",
"(",
"test",
")",
")",
".",
"astype",
"(",
"'float64'",
")",
"ref",
"=",
"np",
".",
"abs",
"(",
"np"... | 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 magnetude.
Returns
-------
ssim: float, the snr | [
"Wrapper",
"to",
"the",
"metric"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L36-L70 |
26,819 | CEA-COSMIC/ModOpt | modopt/interface/errors.py | file_name_error | 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_name[0][0] == '-':
raise IOError('Input file name not specified.')
elif not os.path.isfile(file_name):
raise IOError('Input file name [%s] not found!' % file_name) | python | def file_name_error(file_name):
if file_name == '' or file_name[0][0] == '-':
raise IOError('Input file name not specified.')
elif not os.path.isfile(file_name):
raise IOError('Input file name [%s] not found!' % file_name) | [
"def",
"file_name_error",
"(",
"file_name",
")",
":",
"if",
"file_name",
"==",
"''",
"or",
"file_name",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'-'",
":",
"raise",
"IOError",
"(",
"'Input file name not specified.'",
")",
"elif",
"not",
"os",
".",
"path",
".... | 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 | [
"File",
"name",
"error"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/errors.py#L79-L100 |
26,820 | CEA-COSMIC/ModOpt | modopt/interface/errors.py | is_executable | 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
"""
if not isinstance(exe_name, str):
raise TypeError('Executable name must be a string.')
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(exe_name)
if not fpath:
res = any([is_exe(os.path.join(path, exe_name)) for path in
os.environ["PATH"].split(os.pathsep)])
else:
res = is_exe(exe_name)
if not res:
raise IOError('{} does not appear to be a valid executable on this '
'system.'.format(exe_name)) | python | def is_executable(exe_name):
if not isinstance(exe_name, str):
raise TypeError('Executable name must be a string.')
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(exe_name)
if not fpath:
res = any([is_exe(os.path.join(path, exe_name)) for path in
os.environ["PATH"].split(os.pathsep)])
else:
res = is_exe(exe_name)
if not res:
raise IOError('{} does not appear to be a valid executable on this '
'system.'.format(exe_name)) | [
"def",
"is_executable",
"(",
"exe_name",
")",
":",
"if",
"not",
"isinstance",
"(",
"exe_name",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Executable name must be a string.'",
")",
"def",
"is_exe",
"(",
"fpath",
")",
":",
"return",
"os",
".",
"path",
... | 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 | [
"Check",
"if",
"Input",
"is",
"Executable"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/interface/errors.py#L103-L145 |
26,821 | CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | SetUp._check_operator | 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)):
tree = [obj.__name__ for obj in getmro(operator.__class__)]
if not any([parent in tree for parent in self._op_parents]):
warn('{0} does not inherit an operator '
'parent.'.format(str(operator.__class__))) | python | def _check_operator(self, operator):
if not isinstance(operator, type(None)):
tree = [obj.__name__ for obj in getmro(operator.__class__)]
if not any([parent in tree for parent in self._op_parents]):
warn('{0} does not inherit an operator '
'parent.'.format(str(operator.__class__))) | [
"def",
"_check_operator",
"(",
"self",
",",
"operator",
")",
":",
"if",
"not",
"isinstance",
"(",
"operator",
",",
"type",
"(",
"None",
")",
")",
":",
"tree",
"=",
"[",
"obj",
".",
"__name__",
"for",
"obj",
"in",
"getmro",
"(",
"operator",
".",
"__cl... | Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check | [
"Check",
"Set",
"-",
"Up"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L157-L175 |
26,822 | CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA._check_restart_params | 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
regular (as opposed to CD for now).
Parameters
----------
restart_strategy: str or None
name of the restarting strategy. If None, there is no restarting.
Defaults to None.
min_beta: float or None
the minimum beta when using the greedy restarting strategy.
Defaults to None.
s_greedy: float or None.
parameter for the safeguard comparison in the greedy restarting
strategy. It has to be > 1.
Defaults to None.
xi_restart: float or None.
mutlitplicative parameter for the update of beta in the greedy
restarting strategy and for the update of r_lazy in the adaptive
restarting strategies. It has to be > 1.
Defaults to None.
Returns
-------
bool: True
Raises
------
ValueError
When a parameter that should be set isn't or doesn't verify the
correct assumptions.
"""
if restart_strategy is None:
return True
if self.mode != 'regular':
raise ValueError('Restarting strategies can only be used with '
'regular mode.')
greedy_params_check = (min_beta is None or s_greedy is None or
s_greedy <= 1)
if restart_strategy == 'greedy' and greedy_params_check:
raise ValueError('You need a min_beta and an s_greedy > 1 for '
'greedy restart.')
if xi_restart is None or xi_restart >= 1:
raise ValueError('You need a xi_restart < 1 for restart.')
return True | python | 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
regular (as opposed to CD for now).
Parameters
----------
restart_strategy: str or None
name of the restarting strategy. If None, there is no restarting.
Defaults to None.
min_beta: float or None
the minimum beta when using the greedy restarting strategy.
Defaults to None.
s_greedy: float or None.
parameter for the safeguard comparison in the greedy restarting
strategy. It has to be > 1.
Defaults to None.
xi_restart: float or None.
mutlitplicative parameter for the update of beta in the greedy
restarting strategy and for the update of r_lazy in the adaptive
restarting strategies. It has to be > 1.
Defaults to None.
Returns
-------
bool: True
Raises
------
ValueError
When a parameter that should be set isn't or doesn't verify the
correct assumptions.
"""
if restart_strategy is None:
return True
if self.mode != 'regular':
raise ValueError('Restarting strategies can only be used with '
'regular mode.')
greedy_params_check = (min_beta is None or s_greedy is None or
s_greedy <= 1)
if restart_strategy == 'greedy' and greedy_params_check:
raise ValueError('You need a min_beta and an s_greedy > 1 for '
'greedy restart.')
if xi_restart is None or xi_restart >= 1:
raise ValueError('You need a xi_restart < 1 for restart.')
return True | [
"def",
"_check_restart_params",
"(",
"self",
",",
"restart_strategy",
",",
"min_beta",
",",
"s_greedy",
",",
"xi_restart",
")",
":",
"if",
"restart_strategy",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"mode",
"!=",
"'regular'",
":",
"raise",
"V... | 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
regular (as opposed to CD for now).
Parameters
----------
restart_strategy: str or None
name of the restarting strategy. If None, there is no restarting.
Defaults to None.
min_beta: float or None
the minimum beta when using the greedy restarting strategy.
Defaults to None.
s_greedy: float or None.
parameter for the safeguard comparison in the greedy restarting
strategy. It has to be > 1.
Defaults to None.
xi_restart: float or None.
mutlitplicative parameter for the update of beta in the greedy
restarting strategy and for the update of r_lazy in the adaptive
restarting strategies. It has to be > 1.
Defaults to None.
Returns
-------
bool: True
Raises
------
ValueError
When a parameter that should be set isn't or doesn't verify the
correct assumptions. | [
"r",
"Check",
"restarting",
"parameters"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L307-L361 |
26,823 | CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.is_restart | 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
strategy (namely beta and r).
Parameters
----------
z_old: ndarray
Corresponds to y_n in [L2018].
x_new: ndarray
Corresponds to x_{n+1} in [L2018].
x_old: ndarray
Corresponds to x_n in [L2018].
Returns
-------
bool: whether the algorithm should restart
Notes
-----
Implements restarting and safeguarding steps in alg 4-5 o [L2018]
"""
if self.restart_strategy is None:
return False
criterion = np.vdot(z_old - x_new, x_new - x_old) >= 0
if criterion:
if 'adaptive' in self.restart_strategy:
self.r_lazy *= self.xi_restart
if self.restart_strategy in ['adaptive-ii', 'adaptive-2']:
self._t_now = 1
if self.restart_strategy == 'greedy':
cur_delta = np.linalg.norm(x_new - x_old)
if self._delta_0 is None:
self._delta_0 = self.s_greedy * cur_delta
else:
self._safeguard = cur_delta >= self._delta_0
return criterion | python | 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
strategy (namely beta and r).
Parameters
----------
z_old: ndarray
Corresponds to y_n in [L2018].
x_new: ndarray
Corresponds to x_{n+1} in [L2018].
x_old: ndarray
Corresponds to x_n in [L2018].
Returns
-------
bool: whether the algorithm should restart
Notes
-----
Implements restarting and safeguarding steps in alg 4-5 o [L2018]
"""
if self.restart_strategy is None:
return False
criterion = np.vdot(z_old - x_new, x_new - x_old) >= 0
if criterion:
if 'adaptive' in self.restart_strategy:
self.r_lazy *= self.xi_restart
if self.restart_strategy in ['adaptive-ii', 'adaptive-2']:
self._t_now = 1
if self.restart_strategy == 'greedy':
cur_delta = np.linalg.norm(x_new - x_old)
if self._delta_0 is None:
self._delta_0 = self.s_greedy * cur_delta
else:
self._safeguard = cur_delta >= self._delta_0
return criterion | [
"def",
"is_restart",
"(",
"self",
",",
"z_old",
",",
"x_new",
",",
"x_old",
")",
":",
"if",
"self",
".",
"restart_strategy",
"is",
"None",
":",
"return",
"False",
"criterion",
"=",
"np",
".",
"vdot",
"(",
"z_old",
"-",
"x_new",
",",
"x_new",
"-",
"x_... | 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
strategy (namely beta and r).
Parameters
----------
z_old: ndarray
Corresponds to y_n in [L2018].
x_new: ndarray
Corresponds to x_{n+1} in [L2018].
x_old: ndarray
Corresponds to x_n in [L2018].
Returns
-------
bool: whether the algorithm should restart
Notes
-----
Implements restarting and safeguarding steps in alg 4-5 o [L2018] | [
"r",
"Check",
"whether",
"the",
"algorithm",
"needs",
"to",
"restart"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L363-L407 |
26,824 | CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.update_beta | 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
-------
float: the new value for the beta parameter
"""
if self._safeguard:
beta *= self.xi_restart
beta = max(beta, self.min_beta)
return beta | python | 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
-------
float: the new value for the beta parameter
"""
if self._safeguard:
beta *= self.xi_restart
beta = max(beta, self.min_beta)
return beta | [
"def",
"update_beta",
"(",
"self",
",",
"beta",
")",
":",
"if",
"self",
".",
"_safeguard",
":",
"beta",
"*=",
"self",
".",
"xi_restart",
"beta",
"=",
"max",
"(",
"beta",
",",
"self",
".",
"min_beta",
")",
"return",
"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
-------
float: the new value for the beta parameter | [
"r",
"Update",
"beta"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L409-L429 |
26,825 | CEA-COSMIC/ModOpt | modopt/opt/algorithms.py | FISTA.update_lambda | 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_strategy == 'greedy':
return 2
# Steps 3 and 4 from alg.10.7.
self._t_prev = self._t_now
if self.mode == 'regular':
self._t_now = (self.p_lazy + np.sqrt(self.r_lazy *
self._t_prev ** 2 + self.q_lazy)) * 0.5
elif self.mode == 'CD':
self._t_now = (self._n + self.a_cd - 1) / self.a_cd
self._n += 1
return 1 + (self._t_prev - 1) / self._t_now | python | 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_strategy == 'greedy':
return 2
# Steps 3 and 4 from alg.10.7.
self._t_prev = self._t_now
if self.mode == 'regular':
self._t_now = (self.p_lazy + np.sqrt(self.r_lazy *
self._t_prev ** 2 + self.q_lazy)) * 0.5
elif self.mode == 'CD':
self._t_now = (self._n + self.a_cd - 1) / self.a_cd
self._n += 1
return 1 + (self._t_prev - 1) / self._t_now | [
"def",
"update_lambda",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"restart_strategy",
"==",
"'greedy'",
":",
"return",
"2",
"# Steps 3 and 4 from alg.10.7.",
"self",
".",
"_t_prev",
"=",
"self",
".",
"_t_now",
"if... | 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]_ | [
"r",
"Update",
"lambda"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/algorithms.py#L431-L460 |
26,826 | CEA-COSMIC/ModOpt | modopt/signal/wavelet.py | call_mr_transform | 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 be passed to mr_transform
path : str, optional
Path for output files (default is './')
remove_files : bool, optional
Option to remove output files (default is 'True')
Returns
-------
np.ndarray results of mr_transform
Raises
------
ValueError
If the input data is not a 2D numpy array
Examples
--------
>>> from modopt.signal.wavelet import *
>>> a = np.arange(9).reshape(3, 3).astype(float)
>>> call_mr_transform(a)
array([[[-1.5 , -1.125 , -0.75 ],
[-0.375 , 0. , 0.375 ],
[ 0.75 , 1.125 , 1.5 ]],
[[-1.5625 , -1.171875 , -0.78125 ],
[-0.390625 , 0. , 0.390625 ],
[ 0.78125 , 1.171875 , 1.5625 ]],
[[-0.5859375 , -0.43945312, -0.29296875],
[-0.14648438, 0. , 0.14648438],
[ 0.29296875, 0.43945312, 0.5859375 ]],
[[ 3.6484375 , 3.73632812, 3.82421875],
[ 3.91210938, 4. , 4.08789062],
[ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32)
"""
if not import_astropy:
raise ImportError('Astropy package not found.')
if (not isinstance(data, np.ndarray)) or (data.ndim != 2):
raise ValueError('Input data must be a 2D numpy array.')
executable = 'mr_transform'
# Make sure mr_transform is installed.
is_executable(executable)
# Create a unique string using the current date and time.
unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S')
# Set the ouput file names.
file_name = path + 'mr_temp_' + unique_string
file_fits = file_name + '.fits'
file_mr = file_name + '.mr'
# Write the input data to a fits file.
fits.writeto(file_fits, data)
if isinstance(opt, str):
opt = opt.split()
# Call mr_transform.
try:
check_call([executable] + opt + [file_fits, file_mr])
except Exception:
warn('{} failed to run with the options provided.'.format(executable))
remove(file_fits)
else:
# Retrieve wavelet transformed data.
result = fits.getdata(file_mr)
# Remove the temporary files.
if remove_files:
remove(file_fits)
remove(file_mr)
# Return the mr_transform results.
return result | python | 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 be passed to mr_transform
path : str, optional
Path for output files (default is './')
remove_files : bool, optional
Option to remove output files (default is 'True')
Returns
-------
np.ndarray results of mr_transform
Raises
------
ValueError
If the input data is not a 2D numpy array
Examples
--------
>>> from modopt.signal.wavelet import *
>>> a = np.arange(9).reshape(3, 3).astype(float)
>>> call_mr_transform(a)
array([[[-1.5 , -1.125 , -0.75 ],
[-0.375 , 0. , 0.375 ],
[ 0.75 , 1.125 , 1.5 ]],
[[-1.5625 , -1.171875 , -0.78125 ],
[-0.390625 , 0. , 0.390625 ],
[ 0.78125 , 1.171875 , 1.5625 ]],
[[-0.5859375 , -0.43945312, -0.29296875],
[-0.14648438, 0. , 0.14648438],
[ 0.29296875, 0.43945312, 0.5859375 ]],
[[ 3.6484375 , 3.73632812, 3.82421875],
[ 3.91210938, 4. , 4.08789062],
[ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32)
"""
if not import_astropy:
raise ImportError('Astropy package not found.')
if (not isinstance(data, np.ndarray)) or (data.ndim != 2):
raise ValueError('Input data must be a 2D numpy array.')
executable = 'mr_transform'
# Make sure mr_transform is installed.
is_executable(executable)
# Create a unique string using the current date and time.
unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S')
# Set the ouput file names.
file_name = path + 'mr_temp_' + unique_string
file_fits = file_name + '.fits'
file_mr = file_name + '.mr'
# Write the input data to a fits file.
fits.writeto(file_fits, data)
if isinstance(opt, str):
opt = opt.split()
# Call mr_transform.
try:
check_call([executable] + opt + [file_fits, file_mr])
except Exception:
warn('{} failed to run with the options provided.'.format(executable))
remove(file_fits)
else:
# Retrieve wavelet transformed data.
result = fits.getdata(file_mr)
# Remove the temporary files.
if remove_files:
remove(file_fits)
remove(file_mr)
# Return the mr_transform results.
return result | [
"def",
"call_mr_transform",
"(",
"data",
",",
"opt",
"=",
"''",
",",
"path",
"=",
"'./'",
",",
"remove_files",
"=",
"True",
")",
":",
"# pragma: no cover",
"if",
"not",
"import_astropy",
":",
"raise",
"ImportError",
"(",
"'Astropy package not found.'",
")",
"i... | 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 be passed to mr_transform
path : str, optional
Path for output files (default is './')
remove_files : bool, optional
Option to remove output files (default is 'True')
Returns
-------
np.ndarray results of mr_transform
Raises
------
ValueError
If the input data is not a 2D numpy array
Examples
--------
>>> from modopt.signal.wavelet import *
>>> a = np.arange(9).reshape(3, 3).astype(float)
>>> call_mr_transform(a)
array([[[-1.5 , -1.125 , -0.75 ],
[-0.375 , 0. , 0.375 ],
[ 0.75 , 1.125 , 1.5 ]],
[[-1.5625 , -1.171875 , -0.78125 ],
[-0.390625 , 0. , 0.390625 ],
[ 0.78125 , 1.171875 , 1.5625 ]],
[[-0.5859375 , -0.43945312, -0.29296875],
[-0.14648438, 0. , 0.14648438],
[ 0.29296875, 0.43945312, 0.5859375 ]],
[[ 3.6484375 , 3.73632812, 3.82421875],
[ 3.91210938, 4. , 4.08789062],
[ 4.17578125, 4.26367188, 4.3515625 ]]], dtype=float32) | [
"r",
"Call",
"mr_transform"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L36-L131 |
26,827 | CEA-COSMIC/ModOpt | modopt/signal/wavelet.py | get_mr_filters | 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
coarse : bool, optional
Option to keep coarse scale (default is 'False')
Returns
-------
np.ndarray 3D array of wavelet filters
"""
# Adjust the shape of the input data.
data_shape = np.array(data_shape)
data_shape += data_shape % 2 - 1
# Create fake data.
fake_data = np.zeros(data_shape)
fake_data[tuple(zip(data_shape // 2))] = 1
# Call mr_transform.
mr_filters = call_mr_transform(fake_data, opt=opt)
# Return filters
if coarse:
return mr_filters
else:
return mr_filters[:-1] | python | def get_mr_filters(data_shape, opt='', coarse=False): # pragma: no cover
# Adjust the shape of the input data.
data_shape = np.array(data_shape)
data_shape += data_shape % 2 - 1
# Create fake data.
fake_data = np.zeros(data_shape)
fake_data[tuple(zip(data_shape // 2))] = 1
# Call mr_transform.
mr_filters = call_mr_transform(fake_data, opt=opt)
# Return filters
if coarse:
return mr_filters
else:
return mr_filters[:-1] | [
"def",
"get_mr_filters",
"(",
"data_shape",
",",
"opt",
"=",
"''",
",",
"coarse",
"=",
"False",
")",
":",
"# pragma: no cover",
"# Adjust the shape of the input data.",
"data_shape",
"=",
"np",
".",
"array",
"(",
"data_shape",
")",
"data_shape",
"+=",
"data_shape"... | 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
coarse : bool, optional
Option to keep coarse scale (default is 'False')
Returns
-------
np.ndarray 3D array of wavelet filters | [
"Get",
"mr_transform",
"filters"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/wavelet.py#L134-L169 |
26,828 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | gram_schmidt | 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.
Returns
-------
Lists of orthogonal vectors, u, and/or orthonormal vectors, e
Examples
--------
>>> from modopt.math.matrix import gram_schmidt
>>> a = np.arange(9).reshape(3, 3)
>>> gram_schmidt(a)
array([[ 0. , 0.4472136 , 0.89442719],
[ 0.91287093, 0.36514837, -0.18257419],
[-1. , 0. , 0. ]])
Notes
-----
Implementation from:
https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
"""
if return_opt not in ('orthonormal', 'orthogonal', 'both'):
raise ValueError('Invalid return_opt, options are: "orthonormal", '
'"orthogonal" or "both"')
u = []
e = []
for vector in matrix:
if len(u) == 0:
u_now = vector
else:
u_now = vector - sum([project(u_i, vector) for u_i in u])
u.append(u_now)
e.append(u_now / np.linalg.norm(u_now, 2))
u = np.array(u)
e = np.array(e)
if return_opt == 'orthonormal':
return e
elif return_opt == 'orthogonal':
return u
elif return_opt == 'both':
return u, e | python | 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.
Returns
-------
Lists of orthogonal vectors, u, and/or orthonormal vectors, e
Examples
--------
>>> from modopt.math.matrix import gram_schmidt
>>> a = np.arange(9).reshape(3, 3)
>>> gram_schmidt(a)
array([[ 0. , 0.4472136 , 0.89442719],
[ 0.91287093, 0.36514837, -0.18257419],
[-1. , 0. , 0. ]])
Notes
-----
Implementation from:
https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
"""
if return_opt not in ('orthonormal', 'orthogonal', 'both'):
raise ValueError('Invalid return_opt, options are: "orthonormal", '
'"orthogonal" or "both"')
u = []
e = []
for vector in matrix:
if len(u) == 0:
u_now = vector
else:
u_now = vector - sum([project(u_i, vector) for u_i in u])
u.append(u_now)
e.append(u_now / np.linalg.norm(u_now, 2))
u = np.array(u)
e = np.array(e)
if return_opt == 'orthonormal':
return e
elif return_opt == 'orthogonal':
return u
elif return_opt == 'both':
return u, e | [
"def",
"gram_schmidt",
"(",
"matrix",
",",
"return_opt",
"=",
"'orthonormal'",
")",
":",
"if",
"return_opt",
"not",
"in",
"(",
"'orthonormal'",
",",
"'orthogonal'",
",",
"'both'",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid return_opt, options are: \"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.
Returns
-------
Lists of orthogonal vectors, u, and/or orthonormal vectors, e
Examples
--------
>>> from modopt.math.matrix import gram_schmidt
>>> a = np.arange(9).reshape(3, 3)
>>> gram_schmidt(a)
array([[ 0. , 0.4472136 , 0.89442719],
[ 0.91287093, 0.36514837, -0.18257419],
[-1. , 0. , 0. ]])
Notes
-----
Implementation from:
https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process | [
"r",
"Gram",
"-",
"Schmit"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L17-L74 |
26,829 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | nuclear_norm | 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 nuclear_norm
>>> a = np.arange(9).reshape(3, 3)
>>> nuclear_norm(a)
15.49193338482967
Notes
-----
Implements the following equation:
.. math::
\|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A})
"""
# Get SVD of the data.
u, s, v = np.linalg.svd(data)
# Return nuclear norm.
return np.sum(s) | python | 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 nuclear_norm
>>> a = np.arange(9).reshape(3, 3)
>>> nuclear_norm(a)
15.49193338482967
Notes
-----
Implements the following equation:
.. math::
\|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A})
"""
# Get SVD of the data.
u, s, v = np.linalg.svd(data)
# Return nuclear norm.
return np.sum(s) | [
"def",
"nuclear_norm",
"(",
"data",
")",
":",
"# Get SVD of the data.",
"u",
",",
"s",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"data",
")",
"# Return nuclear norm.",
"return",
"np",
".",
"sum",
"(",
"s",
")"
] | 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 nuclear_norm
>>> a = np.arange(9).reshape(3, 3)
>>> nuclear_norm(a)
15.49193338482967
Notes
-----
Implements the following equation:
.. math::
\|\mathbf{A}\|_* = \sum_{i=1}^{\min\{m,n\}} \sigma_i (\mathbf{A}) | [
"r",
"Nuclear",
"norm"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L77-L111 |
26,830 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | project | 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 project
>>> a = np.arange(3)
>>> b = a + 3
>>> project(a, b)
array([ 0. , 2.8, 5.6])
Notes
-----
Implements the following equation:
.. math::
\textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u},
\mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u}
(see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process)
"""
return np.inner(v, u) / np.inner(u, u) * u | python | 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 project
>>> a = np.arange(3)
>>> b = a + 3
>>> project(a, b)
array([ 0. , 2.8, 5.6])
Notes
-----
Implements the following equation:
.. math::
\textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u},
\mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u}
(see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process)
"""
return np.inner(v, u) / np.inner(u, u) * u | [
"def",
"project",
"(",
"u",
",",
"v",
")",
":",
"return",
"np",
".",
"inner",
"(",
"v",
",",
"u",
")",
"/",
"np",
".",
"inner",
"(",
"u",
",",
"u",
")",
"*",
"u"
] | 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 project
>>> a = np.arange(3)
>>> b = a + 3
>>> project(a, b)
array([ 0. , 2.8, 5.6])
Notes
-----
Implements the following equation:
.. math::
\textrm{proj}_\mathbf{u}(\mathbf{v}) = \frac{\langle\mathbf{u},
\mathbf{v}\rangle}{\langle\mathbf{u}, \mathbf{u}\rangle}\mathbf{u}
(see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process) | [
"r",
"Project",
"vector"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L114-L150 |
26,831 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | rot_matrix | 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.matrix import rot_matrix
>>> rot_matrix(np.pi / 6)
array([[ 0.8660254, -0.5 ],
[ 0.5 , 0.8660254]])
Notes
-----
Implements the following equation:
.. math::
R(\theta) = \begin{bmatrix}
\cos(\theta) & -\sin(\theta) \\
\sin(\theta) & \cos(\theta)
\end{bmatrix}
"""
return np.around(np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]], dtype='float'), 10) | python | 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.matrix import rot_matrix
>>> rot_matrix(np.pi / 6)
array([[ 0.8660254, -0.5 ],
[ 0.5 , 0.8660254]])
Notes
-----
Implements the following equation:
.. math::
R(\theta) = \begin{bmatrix}
\cos(\theta) & -\sin(\theta) \\
\sin(\theta) & \cos(\theta)
\end{bmatrix}
"""
return np.around(np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]], dtype='float'), 10) | [
"def",
"rot_matrix",
"(",
"angle",
")",
":",
"return",
"np",
".",
"around",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"angle",
")",
",",
"-",
"np",
".",
"sin",
"(",
"angle",
")",
"]",
",",
"[",
"np",
".",
"sin",
"(",
"a... | 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.matrix import rot_matrix
>>> rot_matrix(np.pi / 6)
array([[ 0.8660254, -0.5 ],
[ 0.5 , 0.8660254]])
Notes
-----
Implements the following equation:
.. math::
R(\theta) = \begin{bmatrix}
\cos(\theta) & -\sin(\theta) \\
\sin(\theta) & \cos(\theta)
\end{bmatrix} | [
"r",
"Rotation",
"matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L153-L187 |
26,832 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | PowerMethod._set_initial_x | 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._data_type) | python | def _set_initial_x(self):
return np.random.random(self._data_shape).astype(self._data_type) | [
"def",
"_set_initial_x",
"(",
"self",
")",
":",
"return",
"np",
".",
"random",
".",
"random",
"(",
"self",
".",
"_data_shape",
")",
".",
"astype",
"(",
"self",
".",
"_data_type",
")"
] | 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 | [
"Set",
"initial",
"value",
"of",
"x"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L285-L296 |
26,833 | CEA-COSMIC/ModOpt | modopt/math/matrix.py | PowerMethod.get_spec_rad | 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, optional
Maximum number of iterations (default is 20)
extra_factor : float, optional
Extra multiplicative factor for calculating the spectral radius
(default is 1.0)
"""
# Set (or reset) values of x.
x_old = self._set_initial_x()
# Iterate until the L2 norm of x converges.
for i in range(max_iter):
x_old_norm = np.linalg.norm(x_old)
x_new = self._operator(x_old) / x_old_norm
x_new_norm = np.linalg.norm(x_new)
if(np.abs(x_new_norm - x_old_norm) < tolerance):
if self._verbose:
print(' - Power Method converged after %d iterations!' %
(i + 1))
break
elif i == max_iter - 1 and self._verbose:
print(' - Power Method did not converge after %d '
'iterations!' % max_iter)
np.copyto(x_old, x_new)
self.spec_rad = x_new_norm * extra_factor
self.inv_spec_rad = 1.0 / self.spec_rad | python | def get_spec_rad(self, tolerance=1e-6, max_iter=20, extra_factor=1.0):
# Set (or reset) values of x.
x_old = self._set_initial_x()
# Iterate until the L2 norm of x converges.
for i in range(max_iter):
x_old_norm = np.linalg.norm(x_old)
x_new = self._operator(x_old) / x_old_norm
x_new_norm = np.linalg.norm(x_new)
if(np.abs(x_new_norm - x_old_norm) < tolerance):
if self._verbose:
print(' - Power Method converged after %d iterations!' %
(i + 1))
break
elif i == max_iter - 1 and self._verbose:
print(' - Power Method did not converge after %d '
'iterations!' % max_iter)
np.copyto(x_old, x_new)
self.spec_rad = x_new_norm * extra_factor
self.inv_spec_rad = 1.0 / self.spec_rad | [
"def",
"get_spec_rad",
"(",
"self",
",",
"tolerance",
"=",
"1e-6",
",",
"max_iter",
"=",
"20",
",",
"extra_factor",
"=",
"1.0",
")",
":",
"# Set (or reset) values of x.",
"x_old",
"=",
"self",
".",
"_set_initial_x",
"(",
")",
"# Iterate until the L2 norm of x conv... | Get spectral radius
This method calculates the spectral radius
Parameters
----------
tolerance : float, optional
Tolerance threshold for convergence (default is "1e-6")
max_iter : int, optional
Maximum number of iterations (default is 20)
extra_factor : float, optional
Extra multiplicative factor for calculating the spectral radius
(default is 1.0) | [
"Get",
"spectral",
"radius"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/matrix.py#L298-L340 |
26,834 | CEA-COSMIC/ModOpt | modopt/opt/linear.py | LinearCombo._check_type | 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.ndarray of input
Raises
------
TypeError
For invalid input type
"""
if not isinstance(input_val, (list, tuple, np.ndarray)):
raise TypeError('Invalid input type, input must be a list, tuple '
'or numpy array.')
input_val = np.array(input_val)
if not input_val.size:
raise ValueError('Input list is empty.')
return input_val | python | def _check_type(self, input_val):
if not isinstance(input_val, (list, tuple, np.ndarray)):
raise TypeError('Invalid input type, input must be a list, tuple '
'or numpy array.')
input_val = np.array(input_val)
if not input_val.size:
raise ValueError('Input list is empty.')
return input_val | [
"def",
"_check_type",
"(",
"self",
",",
"input_val",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_val",
",",
"(",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type, input must be a list, tuple '... | 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.ndarray of input
Raises
------
TypeError
For invalid input type | [
"Check",
"Input",
"Type"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/linear.py#L154-L184 |
26,835 | CEA-COSMIC/ModOpt | modopt/signal/svd.py | find_n_pc | 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 correlation (default is '0.5')
Returns
-------
int number of principal components
Examples
--------
>>> from scipy.linalg import svd
>>> from modopt.signal.svd import find_n_pc
>>> x = np.arange(18).reshape(9, 2).astype(float)
>>> find_n_pc(svd(x)[0])
array([3])
"""
if np.sqrt(u.shape[0]) % 1:
raise ValueError('Invalid left singular value. The size of the first '
'dimenion of u must be perfect square.')
# Get the shape of the array
array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2)
# Find the auto correlation of the left singular vector.
u_auto = [convolve(a.reshape(array_shape),
np.rot90(a.reshape(array_shape), 2)) for a in u.T]
# Return the required number of principal components.
return np.sum([(a[tuple(zip(array_shape // 2))] ** 2 <= factor *
np.sum(a ** 2)) for a in u_auto]) | python | def find_n_pc(u, factor=0.5):
if np.sqrt(u.shape[0]) % 1:
raise ValueError('Invalid left singular value. The size of the first '
'dimenion of u must be perfect square.')
# Get the shape of the array
array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2)
# Find the auto correlation of the left singular vector.
u_auto = [convolve(a.reshape(array_shape),
np.rot90(a.reshape(array_shape), 2)) for a in u.T]
# Return the required number of principal components.
return np.sum([(a[tuple(zip(array_shape // 2))] ** 2 <= factor *
np.sum(a ** 2)) for a in u_auto]) | [
"def",
"find_n_pc",
"(",
"u",
",",
"factor",
"=",
"0.5",
")",
":",
"if",
"np",
".",
"sqrt",
"(",
"u",
".",
"shape",
"[",
"0",
"]",
")",
"%",
"1",
":",
"raise",
"ValueError",
"(",
"'Invalid left singular value. The size of the first '",
"'dimenion of u must b... | 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 correlation (default is '0.5')
Returns
-------
int number of principal components
Examples
--------
>>> from scipy.linalg import svd
>>> from modopt.signal.svd import find_n_pc
>>> x = np.arange(18).reshape(9, 2).astype(float)
>>> find_n_pc(svd(x)[0])
array([3]) | [
"Find",
"number",
"of",
"principal",
"components"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L21-L60 |
26,836 | CEA-COSMIC/ModOpt | modopt/signal/svd.py | calculate_svd | 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, singular values and right singular vector
Raises
------
TypeError
For invalid data type
"""
if (not isinstance(data, np.ndarray)) or (data.ndim != 2):
raise TypeError('Input data must be a 2D np.ndarray.')
return svd(data, check_finite=False, lapack_driver='gesvd',
full_matrices=False) | python | def calculate_svd(data):
if (not isinstance(data, np.ndarray)) or (data.ndim != 2):
raise TypeError('Input data must be a 2D np.ndarray.')
return svd(data, check_finite=False, lapack_driver='gesvd',
full_matrices=False) | [
"def",
"calculate_svd",
"(",
"data",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
")",
"or",
"(",
"data",
".",
"ndim",
"!=",
"2",
")",
":",
"raise",
"TypeError",
"(",
"'Input data must be a 2D np.ndarray.'",
")",... | 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, singular values and right singular vector
Raises
------
TypeError
For invalid data type | [
"Calculate",
"Singular",
"Value",
"Decomposition"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L63-L89 |
26,837 | CEA-COSMIC/ModOpt | modopt/signal/svd.py | svd_thresh | 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
Threshold value(s)
n_pc : int or str, optional
Number of principal components, specify an integer value or 'all'
threshold_type : str {'hard', 'soft'}, optional
Type of thresholding (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
For invalid n_pc value
Examples
--------
>>> from modopt.signal.svd import svd_thresh
>>> x = np.arange(18).reshape(9, 2).astype(float)
>>> svd_thresh(x, n_pc=1)
array([[ 0.49815487, 0.54291537],
[ 2.40863386, 2.62505584],
[ 4.31911286, 4.70719631],
[ 6.22959185, 6.78933678],
[ 8.14007085, 8.87147725],
[ 10.05054985, 10.95361772],
[ 11.96102884, 13.03575819],
[ 13.87150784, 15.11789866],
[ 15.78198684, 17.20003913]])
"""
if ((not isinstance(n_pc, (int, str, type(None)))) or
(isinstance(n_pc, int) and n_pc <= 0) or
(isinstance(n_pc, str) and n_pc != 'all')):
raise ValueError('Invalid value for "n_pc", specify a positive '
'integer value or "all"')
# Get SVD of input data.
u, s, v = calculate_svd(data)
# Find the threshold if not provided.
if isinstance(threshold, type(None)):
# Find the required number of principal components if not specified.
if isinstance(n_pc, type(None)):
n_pc = find_n_pc(u, factor=0.1)
# If the number of PCs is too large use all of the singular values.
if ((isinstance(n_pc, int) and n_pc >= s.size) or
(isinstance(n_pc, str) and n_pc == 'all')):
n_pc = s.size
warn('Using all singular values.')
threshold = s[n_pc - 1]
# Threshold the singular values.
s_new = thresh(s, threshold, thresh_type)
if np.all(s_new == s):
warn('No change to singular values.')
# Diagonalize the svd
s_new = np.diag(s_new)
# Return the thresholded data.
return np.dot(u, np.dot(s_new, v)) | python | 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
Threshold value(s)
n_pc : int or str, optional
Number of principal components, specify an integer value or 'all'
threshold_type : str {'hard', 'soft'}, optional
Type of thresholding (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
For invalid n_pc value
Examples
--------
>>> from modopt.signal.svd import svd_thresh
>>> x = np.arange(18).reshape(9, 2).astype(float)
>>> svd_thresh(x, n_pc=1)
array([[ 0.49815487, 0.54291537],
[ 2.40863386, 2.62505584],
[ 4.31911286, 4.70719631],
[ 6.22959185, 6.78933678],
[ 8.14007085, 8.87147725],
[ 10.05054985, 10.95361772],
[ 11.96102884, 13.03575819],
[ 13.87150784, 15.11789866],
[ 15.78198684, 17.20003913]])
"""
if ((not isinstance(n_pc, (int, str, type(None)))) or
(isinstance(n_pc, int) and n_pc <= 0) or
(isinstance(n_pc, str) and n_pc != 'all')):
raise ValueError('Invalid value for "n_pc", specify a positive '
'integer value or "all"')
# Get SVD of input data.
u, s, v = calculate_svd(data)
# Find the threshold if not provided.
if isinstance(threshold, type(None)):
# Find the required number of principal components if not specified.
if isinstance(n_pc, type(None)):
n_pc = find_n_pc(u, factor=0.1)
# If the number of PCs is too large use all of the singular values.
if ((isinstance(n_pc, int) and n_pc >= s.size) or
(isinstance(n_pc, str) and n_pc == 'all')):
n_pc = s.size
warn('Using all singular values.')
threshold = s[n_pc - 1]
# Threshold the singular values.
s_new = thresh(s, threshold, thresh_type)
if np.all(s_new == s):
warn('No change to singular values.')
# Diagonalize the svd
s_new = np.diag(s_new)
# Return the thresholded data.
return np.dot(u, np.dot(s_new, v)) | [
"def",
"svd_thresh",
"(",
"data",
",",
"threshold",
"=",
"None",
",",
"n_pc",
"=",
"None",
",",
"thresh_type",
"=",
"'hard'",
")",
":",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"n_pc",
",",
"(",
"int",
",",
"str",
",",
"type",
"(",
"None",
")",
... | 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
Threshold value(s)
n_pc : int or str, optional
Number of principal components, specify an integer value or 'all'
threshold_type : str {'hard', 'soft'}, optional
Type of thresholding (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
For invalid n_pc value
Examples
--------
>>> from modopt.signal.svd import svd_thresh
>>> x = np.arange(18).reshape(9, 2).astype(float)
>>> svd_thresh(x, n_pc=1)
array([[ 0.49815487, 0.54291537],
[ 2.40863386, 2.62505584],
[ 4.31911286, 4.70719631],
[ 6.22959185, 6.78933678],
[ 8.14007085, 8.87147725],
[ 10.05054985, 10.95361772],
[ 11.96102884, 13.03575819],
[ 13.87150784, 15.11789866],
[ 15.78198684, 17.20003913]]) | [
"r",
"Threshold",
"the",
"singular",
"values"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L92-L168 |
26,838 | CEA-COSMIC/ModOpt | modopt/signal/svd.py | svd_thresh_coef | 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
Operator class instance
threshold : float or np.ndarray
Threshold value(s)
threshold_type : str {'hard', 'soft'}
Type of noise to be added (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
For invalid string entry for n_pc
"""
if not callable(operator):
raise TypeError('Operator must be a callable function.')
# Get SVD of data matrix
u, s, v = calculate_svd(data)
# Diagnalise s
s = np.diag(s)
# Compute coefficients
a = np.dot(s, v)
# Get the shape of the array
array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2)
# Compute threshold matrix.
ti = np.array([np.linalg.norm(x) for x in
operator(matrix2cube(u, array_shape))])
threshold *= np.repeat(ti, a.shape[1]).reshape(a.shape)
# Threshold coefficients.
a_new = thresh(a, threshold, thresh_type)
# Return the thresholded image.
return np.dot(u, a_new) | python | def svd_thresh_coef(data, operator, threshold, thresh_type='hard'):
if not callable(operator):
raise TypeError('Operator must be a callable function.')
# Get SVD of data matrix
u, s, v = calculate_svd(data)
# Diagnalise s
s = np.diag(s)
# Compute coefficients
a = np.dot(s, v)
# Get the shape of the array
array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2)
# Compute threshold matrix.
ti = np.array([np.linalg.norm(x) for x in
operator(matrix2cube(u, array_shape))])
threshold *= np.repeat(ti, a.shape[1]).reshape(a.shape)
# Threshold coefficients.
a_new = thresh(a, threshold, thresh_type)
# Return the thresholded image.
return np.dot(u, a_new) | [
"def",
"svd_thresh_coef",
"(",
"data",
",",
"operator",
",",
"threshold",
",",
"thresh_type",
"=",
"'hard'",
")",
":",
"if",
"not",
"callable",
"(",
"operator",
")",
":",
"raise",
"TypeError",
"(",
"'Operator must be a callable function.'",
")",
"# Get SVD of data... | 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
Operator class instance
threshold : float or np.ndarray
Threshold value(s)
threshold_type : str {'hard', 'soft'}
Type of noise to be added (default is 'hard')
Returns
-------
np.ndarray thresholded data
Raises
------
ValueError
For invalid string entry for n_pc | [
"Threshold",
"the",
"singular",
"values",
"coefficients"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/svd.py#L171-L222 |
26,839 | CEA-COSMIC/ModOpt | modopt/math/stats.py | gaussian_kernel | 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 {'max', 'sum', 'none'}, optional
Normalisation of the kerenl (options are 'max', 'sum' or 'none')
Returns
-------
np.ndarray kernel
Examples
--------
>>> from modopt.math.stats import gaussian_kernel
>>> gaussian_kernel((3, 3), 1)
array([[ 0.36787944, 0.60653066, 0.36787944],
[ 0.60653066, 1. , 0.60653066],
[ 0.36787944, 0.60653066, 0.36787944]])
>>> gaussian_kernel((3, 3), 1, norm='sum')
array([[ 0.07511361, 0.1238414 , 0.07511361],
[ 0.1238414 , 0.20417996, 0.1238414 ],
[ 0.07511361, 0.1238414 , 0.07511361]])
"""
if not import_astropy: # pragma: no cover
raise ImportError('Astropy package not found.')
if norm not in ('max', 'sum', 'none'):
raise ValueError('Invalid norm, options are "max", "sum" or "none".')
kernel = np.array(Gaussian2DKernel(sigma, x_size=data_shape[1],
y_size=data_shape[0]))
if norm == 'max':
return kernel / np.max(kernel)
elif norm == 'sum':
return kernel / np.sum(kernel)
elif norm == 'none':
return kernel | python | 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 {'max', 'sum', 'none'}, optional
Normalisation of the kerenl (options are 'max', 'sum' or 'none')
Returns
-------
np.ndarray kernel
Examples
--------
>>> from modopt.math.stats import gaussian_kernel
>>> gaussian_kernel((3, 3), 1)
array([[ 0.36787944, 0.60653066, 0.36787944],
[ 0.60653066, 1. , 0.60653066],
[ 0.36787944, 0.60653066, 0.36787944]])
>>> gaussian_kernel((3, 3), 1, norm='sum')
array([[ 0.07511361, 0.1238414 , 0.07511361],
[ 0.1238414 , 0.20417996, 0.1238414 ],
[ 0.07511361, 0.1238414 , 0.07511361]])
"""
if not import_astropy: # pragma: no cover
raise ImportError('Astropy package not found.')
if norm not in ('max', 'sum', 'none'):
raise ValueError('Invalid norm, options are "max", "sum" or "none".')
kernel = np.array(Gaussian2DKernel(sigma, x_size=data_shape[1],
y_size=data_shape[0]))
if norm == 'max':
return kernel / np.max(kernel)
elif norm == 'sum':
return kernel / np.sum(kernel)
elif norm == 'none':
return kernel | [
"def",
"gaussian_kernel",
"(",
"data_shape",
",",
"sigma",
",",
"norm",
"=",
"'max'",
")",
":",
"if",
"not",
"import_astropy",
":",
"# pragma: no cover",
"raise",
"ImportError",
"(",
"'Astropy package not found.'",
")",
"if",
"norm",
"not",
"in",
"(",
"'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 {'max', 'sum', 'none'}, optional
Normalisation of the kerenl (options are 'max', 'sum' or 'none')
Returns
-------
np.ndarray kernel
Examples
--------
>>> from modopt.math.stats import gaussian_kernel
>>> gaussian_kernel((3, 3), 1)
array([[ 0.36787944, 0.60653066, 0.36787944],
[ 0.60653066, 1. , 0.60653066],
[ 0.36787944, 0.60653066, 0.36787944]])
>>> gaussian_kernel((3, 3), 1, norm='sum')
array([[ 0.07511361, 0.1238414 , 0.07511361],
[ 0.1238414 , 0.20417996, 0.1238414 ],
[ 0.07511361, 0.1238414 , 0.07511361]]) | [
"r",
"Gaussian",
"kernel"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L23-L72 |
26,840 | CEA-COSMIC/ModOpt | modopt/math/stats.py | mad | 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
>>> a = np.arange(9).reshape(3, 3)
>>> mad(a)
2.0
Notes
-----
The MAD is calculated as follows:
.. math::
\mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right)
"""
return np.median(np.abs(data - np.median(data))) | python | 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
>>> a = np.arange(9).reshape(3, 3)
>>> mad(a)
2.0
Notes
-----
The MAD is calculated as follows:
.. math::
\mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right)
"""
return np.median(np.abs(data - np.median(data))) | [
"def",
"mad",
"(",
"data",
")",
":",
"return",
"np",
".",
"median",
"(",
"np",
".",
"abs",
"(",
"data",
"-",
"np",
".",
"median",
"(",
"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
>>> a = np.arange(9).reshape(3, 3)
>>> mad(a)
2.0
Notes
-----
The MAD is calculated as follows:
.. math::
\mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right) | [
"r",
"Median",
"absolute",
"deviation"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L75-L106 |
26,841 | CEA-COSMIC/ModOpt | modopt/math/stats.py | psnr | 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 {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
max_pix : int, optional
Maximum number of pixels, default (max_pix=255)
Returns
-------
float PSNR value
Examples
--------
>>> from modopt.math.stats import psnr
>>> a = np.arange(9).reshape(3, 3)
>>> psnr(a, a + 2)
12.041199826559248
>>> psnr(a, a + 2, method='wiki')
42.110203695399477
Notes
-----
'starck':
Implements eq.3.7 from _[S2010]
'wiki':
Implements PSNR equation on
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
.. math::
\mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I -
10\log_{10}(\mathrm{MSE}))
"""
if method == 'starck':
return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) -
np.min(data1))) / np.linalg.norm(data1 - data2)))
elif method == 'wiki':
return (20 * np.log10(max_pix) - 10 *
np.log10(mse(data1, data2)))
else:
raise ValueError('Invalid PSNR method. Options are "starck" and '
'"wiki"') | python | 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 {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
max_pix : int, optional
Maximum number of pixels, default (max_pix=255)
Returns
-------
float PSNR value
Examples
--------
>>> from modopt.math.stats import psnr
>>> a = np.arange(9).reshape(3, 3)
>>> psnr(a, a + 2)
12.041199826559248
>>> psnr(a, a + 2, method='wiki')
42.110203695399477
Notes
-----
'starck':
Implements eq.3.7 from _[S2010]
'wiki':
Implements PSNR equation on
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
.. math::
\mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I -
10\log_{10}(\mathrm{MSE}))
"""
if method == 'starck':
return (20 * np.log10((data1.shape[0] * np.abs(np.max(data1) -
np.min(data1))) / np.linalg.norm(data1 - data2)))
elif method == 'wiki':
return (20 * np.log10(max_pix) - 10 *
np.log10(mse(data1, data2)))
else:
raise ValueError('Invalid PSNR method. Options are "starck" and '
'"wiki"') | [
"def",
"psnr",
"(",
"data1",
",",
"data2",
",",
"method",
"=",
"'starck'",
",",
"max_pix",
"=",
"255",
")",
":",
"if",
"method",
"==",
"'starck'",
":",
"return",
"(",
"20",
"*",
"np",
".",
"log10",
"(",
"(",
"data1",
".",
"shape",
"[",
"0",
"]",
... | 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 {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
max_pix : int, optional
Maximum number of pixels, default (max_pix=255)
Returns
-------
float PSNR value
Examples
--------
>>> from modopt.math.stats import psnr
>>> a = np.arange(9).reshape(3, 3)
>>> psnr(a, a + 2)
12.041199826559248
>>> psnr(a, a + 2, method='wiki')
42.110203695399477
Notes
-----
'starck':
Implements eq.3.7 from _[S2010]
'wiki':
Implements PSNR equation on
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
.. math::
\mathrm{PSNR} = 20\log_{10}(\mathrm{MAX}_I -
10\log_{10}(\mathrm{MSE})) | [
"r",
"Peak",
"Signal",
"-",
"to",
"-",
"Noise",
"Ratio"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L133-L195 |
26,842 | CEA-COSMIC/ModOpt | modopt/math/stats.py | psnr_stack | 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 : np.ndarray
Stack of images, 3D array
data2 : np.ndarray
Stack of recovered images, 3D array
method : str {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
metric : function
The desired metric to be applied to the PSNR values (default is
'np.mean')
Returns
-------
float metric result of PSNR values
Raises
------
ValueError
For invalid input data dimensions
Examples
--------
>>> from modopt.math.stats import psnr_stack
>>> a = np.arange(18).reshape(2, 3, 3)
>>> psnr_stack(a, a + 2)
12.041199826559248
"""
if data1.ndim != 3 or data2.ndim != 3:
raise ValueError('Input data must be a 3D np.ndarray')
return metric([psnr(i, j, method=method) for i, j in
zip(data1, data2)]) | python | 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 : np.ndarray
Stack of images, 3D array
data2 : np.ndarray
Stack of recovered images, 3D array
method : str {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
metric : function
The desired metric to be applied to the PSNR values (default is
'np.mean')
Returns
-------
float metric result of PSNR values
Raises
------
ValueError
For invalid input data dimensions
Examples
--------
>>> from modopt.math.stats import psnr_stack
>>> a = np.arange(18).reshape(2, 3, 3)
>>> psnr_stack(a, a + 2)
12.041199826559248
"""
if data1.ndim != 3 or data2.ndim != 3:
raise ValueError('Input data must be a 3D np.ndarray')
return metric([psnr(i, j, method=method) for i, j in
zip(data1, data2)]) | [
"def",
"psnr_stack",
"(",
"data1",
",",
"data2",
",",
"metric",
"=",
"np",
".",
"mean",
",",
"method",
"=",
"'starck'",
")",
":",
"if",
"data1",
".",
"ndim",
"!=",
"3",
"or",
"data2",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Input... | 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 : np.ndarray
Stack of images, 3D array
data2 : np.ndarray
Stack of recovered images, 3D array
method : str {'starck', 'wiki'}, optional
PSNR implementation, default ('starck')
metric : function
The desired metric to be applied to the PSNR values (default is
'np.mean')
Returns
-------
float metric result of PSNR values
Raises
------
ValueError
For invalid input data dimensions
Examples
--------
>>> from modopt.math.stats import psnr_stack
>>> a = np.arange(18).reshape(2, 3, 3)
>>> psnr_stack(a, a + 2)
12.041199826559248 | [
"r",
"Peak",
"Signa",
"-",
"to",
"-",
"Noise",
"for",
"stack",
"of",
"images"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L198-L239 |
26,843 | CEA-COSMIC/ModOpt | modopt/base/transform.py | cube2map | 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
-------
np.ndarray 2D map
Raises
------
ValueError
For invalid data dimensions
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import cube2map
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]])
"""
if data_cube.ndim != 3:
raise ValueError('The input data must have 3 dimensions.')
if data_cube.shape[0] != np.prod(layout):
raise ValueError('The desired layout must match the number of input '
'data layers.')
return np.vstack([np.hstack(data_cube[slice(layout[1] * i, layout[1] *
(i + 1))]) for i in range(layout[0])]) | python | 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
-------
np.ndarray 2D map
Raises
------
ValueError
For invalid data dimensions
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import cube2map
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]])
"""
if data_cube.ndim != 3:
raise ValueError('The input data must have 3 dimensions.')
if data_cube.shape[0] != np.prod(layout):
raise ValueError('The desired layout must match the number of input '
'data layers.')
return np.vstack([np.hstack(data_cube[slice(layout[1] * i, layout[1] *
(i + 1))]) for i in range(layout[0])]) | [
"def",
"cube2map",
"(",
"data_cube",
",",
"layout",
")",
":",
"if",
"data_cube",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'The input data must have 3 dimensions.'",
")",
"if",
"data_cube",
".",
"shape",
"[",
"0",
"]",
"!=",
"np",
".",
"pro... | 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
-------
np.ndarray 2D map
Raises
------
ValueError
For invalid data dimensions
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import cube2map
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]]) | [
"r",
"Cube",
"to",
"Map"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L16-L60 |
26,844 | CEA-COSMIC/ModOpt | modopt/base/transform.py | map2cube | 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.ndarray 3D cube
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2cube
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]])
"""
if np.all(np.array(data_map.shape) % np.array(layout)):
raise ValueError('The desired layout must be a multiple of the number '
'pixels in the data map.')
d_shape = np.array(data_map.shape) // np.array(layout)
return np.array([data_map[(slice(i * d_shape[0], (i + 1) * d_shape[0]),
slice(j * d_shape[1], (j + 1) * d_shape[1]))] for i in
range(layout[0]) for j in range(layout[1])]) | python | 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.ndarray 3D cube
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2cube
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]])
"""
if np.all(np.array(data_map.shape) % np.array(layout)):
raise ValueError('The desired layout must be a multiple of the number '
'pixels in the data map.')
d_shape = np.array(data_map.shape) // np.array(layout)
return np.array([data_map[(slice(i * d_shape[0], (i + 1) * d_shape[0]),
slice(j * d_shape[1], (j + 1) * d_shape[1]))] for i in
range(layout[0]) for j in range(layout[1])]) | [
"def",
"map2cube",
"(",
"data_map",
",",
"layout",
")",
":",
"if",
"np",
".",
"all",
"(",
"np",
".",
"array",
"(",
"data_map",
".",
"shape",
")",
"%",
"np",
".",
"array",
"(",
"layout",
")",
")",
":",
"raise",
"ValueError",
"(",
"'The desired 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.ndarray 3D cube
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2cube
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]) | [
"r",
"Map",
"to",
"cube"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L63-L113 |
26,845 | CEA-COSMIC/ModOpt | modopt/base/transform.py | map2matrix | 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
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2matrix
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2matrix(a, (2, 2))
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]])
"""
layout = np.array(layout)
# Select n objects
n_obj = np.prod(layout)
# Get the shape of the images
image_shape = (np.array(data_map.shape) // layout)[0]
# Stack objects from map
data_matrix = []
for i in range(n_obj):
lower = (image_shape * (i // layout[1]),
image_shape * (i % layout[1]))
upper = (image_shape * (i // layout[1] + 1),
image_shape * (i % layout[1] + 1))
data_matrix.append((data_map[lower[0]:upper[0],
lower[1]:upper[1]]).reshape(image_shape ** 2))
return np.array(data_matrix).T | python | 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
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2matrix
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2matrix(a, (2, 2))
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]])
"""
layout = np.array(layout)
# Select n objects
n_obj = np.prod(layout)
# Get the shape of the images
image_shape = (np.array(data_map.shape) // layout)[0]
# Stack objects from map
data_matrix = []
for i in range(n_obj):
lower = (image_shape * (i // layout[1]),
image_shape * (i % layout[1]))
upper = (image_shape * (i // layout[1] + 1),
image_shape * (i % layout[1] + 1))
data_matrix.append((data_map[lower[0]:upper[0],
lower[1]:upper[1]]).reshape(image_shape ** 2))
return np.array(data_matrix).T | [
"def",
"map2matrix",
"(",
"data_map",
",",
"layout",
")",
":",
"layout",
"=",
"np",
".",
"array",
"(",
"layout",
")",
"# Select n objects",
"n_obj",
"=",
"np",
".",
"prod",
"(",
"layout",
")",
"# Get the shape of the images",
"image_shape",
"=",
"(",
"np",
... | 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
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import map2matrix
>>> a = np.array([[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13],
[10, 11, 14, 15]])
>>> map2matrix(a, (2, 2))
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]]) | [
"r",
"Map",
"to",
"Matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L116-L169 |
26,846 | CEA-COSMIC/ModOpt | modopt/base/transform.py | matrix2map | 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
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import matrix2map
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]])
"""
map_shape = np.array(map_shape)
# Get the shape and layout of the images
image_shape = np.sqrt(data_matrix.shape[0]).astype(int)
layout = np.array(map_shape // np.repeat(image_shape, 2), dtype='int')
# Map objects from matrix
data_map = np.zeros(map_shape)
temp = data_matrix.reshape(image_shape, image_shape, data_matrix.shape[1])
for i in range(data_matrix.shape[1]):
lower = (image_shape * (i // layout[1]),
image_shape * (i % layout[1]))
upper = (image_shape * (i // layout[1] + 1),
image_shape * (i % layout[1] + 1))
data_map[lower[0]:upper[0], lower[1]:upper[1]] = temp[:, :, i]
return data_map.astype(int) | python | 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
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import matrix2map
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]])
"""
map_shape = np.array(map_shape)
# Get the shape and layout of the images
image_shape = np.sqrt(data_matrix.shape[0]).astype(int)
layout = np.array(map_shape // np.repeat(image_shape, 2), dtype='int')
# Map objects from matrix
data_map = np.zeros(map_shape)
temp = data_matrix.reshape(image_shape, image_shape, data_matrix.shape[1])
for i in range(data_matrix.shape[1]):
lower = (image_shape * (i // layout[1]),
image_shape * (i % layout[1]))
upper = (image_shape * (i // layout[1] + 1),
image_shape * (i % layout[1] + 1))
data_map[lower[0]:upper[0], lower[1]:upper[1]] = temp[:, :, i]
return data_map.astype(int) | [
"def",
"matrix2map",
"(",
"data_matrix",
",",
"map_shape",
")",
":",
"map_shape",
"=",
"np",
".",
"array",
"(",
"map_shape",
")",
"# Get the shape and layout of the images",
"image_shape",
"=",
"np",
".",
"sqrt",
"(",
"data_matrix",
".",
"shape",
"[",
"0",
"]"... | 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
Raises
------
ValueError
For invalid layout
Examples
--------
>>> from modopt.base.transform import matrix2map
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2map(a, (2, 2))
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15]]) | [
"r",
"Matrix",
"to",
"Map"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L172-L224 |
26,847 | CEA-COSMIC/ModOpt | modopt/base/transform.py | cube2matrix | 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 cube2matrix
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2matrix(a)
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]])
"""
return data_cube.reshape([data_cube.shape[0]] +
[np.prod(data_cube.shape[1:])]).T | python | 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 cube2matrix
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2matrix(a)
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]])
"""
return data_cube.reshape([data_cube.shape[0]] +
[np.prod(data_cube.shape[1:])]).T | [
"def",
"cube2matrix",
"(",
"data_cube",
")",
":",
"return",
"data_cube",
".",
"reshape",
"(",
"[",
"data_cube",
".",
"shape",
"[",
"0",
"]",
"]",
"+",
"[",
"np",
".",
"prod",
"(",
"data_cube",
".",
"shape",
"[",
"1",
":",
"]",
")",
"]",
")",
".",... | 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 cube2matrix
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2matrix(a)
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]]) | [
"r",
"Cube",
"to",
"Matrix"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L227-L254 |
26,848 | CEA-COSMIC/ModOpt | modopt/base/transform.py | matrix2cube | 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
Examples
--------
>>> from modopt.base.transform import matrix2cube
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]])
"""
return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape)) | python | 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
Examples
--------
>>> from modopt.base.transform import matrix2cube
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]])
"""
return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape)) | [
"def",
"matrix2cube",
"(",
"data_matrix",
",",
"im_shape",
")",
":",
"return",
"data_matrix",
".",
"T",
".",
"reshape",
"(",
"[",
"data_matrix",
".",
"shape",
"[",
"1",
"]",
"]",
"+",
"list",
"(",
"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
Examples
--------
>>> from modopt.base.transform import matrix2cube
>>> a = np.array([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14],
[3, 7, 11, 15]])
>>> matrix2cube(a, (2, 2))
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]) | [
"r",
"Matrix",
"to",
"Cube"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L257-L293 |
26,849 | CEA-COSMIC/ModOpt | modopt/plot/cost_plot.py | plotCost | 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)):
file_name = 'cost_function.png'
else:
file_name = output + '_cost_function.png'
plt.figure()
plt.plot(np.log10(cost_list), 'r-')
plt.title('Cost Function')
plt.xlabel('Iteration')
plt.ylabel(r'$\log_{10}$ Cost')
plt.savefig(file_name)
plt.close()
print(' - Saving cost function data to:', file_name)
else:
warn('Matplotlib not installed.') | python | def plotCost(cost_list, output=None):
if not import_fail:
if isinstance(output, type(None)):
file_name = 'cost_function.png'
else:
file_name = output + '_cost_function.png'
plt.figure()
plt.plot(np.log10(cost_list), 'r-')
plt.title('Cost Function')
plt.xlabel('Iteration')
plt.ylabel(r'$\log_{10}$ Cost')
plt.savefig(file_name)
plt.close()
print(' - Saving cost function data to:', file_name)
else:
warn('Matplotlib not installed.') | [
"def",
"plotCost",
"(",
"cost_list",
",",
"output",
"=",
"None",
")",
":",
"if",
"not",
"import_fail",
":",
"if",
"isinstance",
"(",
"output",
",",
"type",
"(",
"None",
")",
")",
":",
"file_name",
"=",
"'cost_function.png'",
"else",
":",
"file_name",
"="... | Plot cost function
Plot the final cost function
Parameters
----------
cost_list : list
List of cost function values
output : str, optional
Output file name | [
"Plot",
"cost",
"function"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/plot/cost_plot.py#L22-L55 |
26,850 | CEA-COSMIC/ModOpt | modopt/signal/filter.py | Gaussian_filter | 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)
Returns
-------
float Gaussian filtered data point
Examples
--------
>>> from modopt.signal.filter import Gaussian_filter
>>> Gaussian_filter(1, 1)
0.24197072451914337
>>> Gaussian_filter(1, 1, False)
0.60653065971263342
"""
x = check_float(x)
sigma = check_float(sigma)
val = np.exp(-0.5 * (x / sigma) ** 2)
if norm:
return val / (np.sqrt(2 * np.pi) * sigma)
else:
return val | python | 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)
Returns
-------
float Gaussian filtered data point
Examples
--------
>>> from modopt.signal.filter import Gaussian_filter
>>> Gaussian_filter(1, 1)
0.24197072451914337
>>> Gaussian_filter(1, 1, False)
0.60653065971263342
"""
x = check_float(x)
sigma = check_float(sigma)
val = np.exp(-0.5 * (x / sigma) ** 2)
if norm:
return val / (np.sqrt(2 * np.pi) * sigma)
else:
return val | [
"def",
"Gaussian_filter",
"(",
"x",
",",
"sigma",
",",
"norm",
"=",
"True",
")",
":",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"val",
"=",
"np",
".",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"x",
"/",
"si... | 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)
Returns
-------
float Gaussian filtered data point
Examples
--------
>>> from modopt.signal.filter import Gaussian_filter
>>> Gaussian_filter(1, 1)
0.24197072451914337
>>> Gaussian_filter(1, 1, False)
0.60653065971263342 | [
"r",
"Gaussian",
"filter"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L16-L54 |
26,851 | CEA-COSMIC/ModOpt | modopt/signal/filter.py | mex_hat | 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
--------
>>> from modopt.signal.filter import mex_hat
>>> mex_hat(2, 1)
-0.35213905225713371
"""
x = check_float(x)
sigma = check_float(sigma)
xs = (x / sigma) ** 2
val = 2 * (3 * sigma) ** -0.5 * np.pi ** -0.25
return val * (1 - xs) * np.exp(-0.5 * xs) | python | 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
--------
>>> from modopt.signal.filter import mex_hat
>>> mex_hat(2, 1)
-0.35213905225713371
"""
x = check_float(x)
sigma = check_float(sigma)
xs = (x / sigma) ** 2
val = 2 * (3 * sigma) ** -0.5 * np.pi ** -0.25
return val * (1 - xs) * np.exp(-0.5 * xs) | [
"def",
"mex_hat",
"(",
"x",
",",
"sigma",
")",
":",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"xs",
"=",
"(",
"x",
"/",
"sigma",
")",
"**",
"2",
"val",
"=",
"2",
"*",
"(",
"3",
"*",
"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
--------
>>> from modopt.signal.filter import mex_hat
>>> mex_hat(2, 1)
-0.35213905225713371 | [
"r",
"Mexican",
"hat"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L57-L87 |
26,852 | CEA-COSMIC/ModOpt | modopt/signal/filter.py | mex_hat_dir | 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 (filter scale)
Returns
-------
float directional Mexican hat filtered data point
Examples
--------
>>> from modopt.signal.filter import mex_hat_dir
>>> mex_hat_dir(1, 2, 1)
0.17606952612856686
"""
x = check_float(x)
sigma = check_float(sigma)
return -0.5 * (x / sigma) ** 2 * mex_hat(y, sigma) | python | 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 (filter scale)
Returns
-------
float directional Mexican hat filtered data point
Examples
--------
>>> from modopt.signal.filter import mex_hat_dir
>>> mex_hat_dir(1, 2, 1)
0.17606952612856686
"""
x = check_float(x)
sigma = check_float(sigma)
return -0.5 * (x / sigma) ** 2 * mex_hat(y, sigma) | [
"def",
"mex_hat_dir",
"(",
"x",
",",
"y",
",",
"sigma",
")",
":",
"x",
"=",
"check_float",
"(",
"x",
")",
"sigma",
"=",
"check_float",
"(",
"sigma",
")",
"return",
"-",
"0.5",
"*",
"(",
"x",
"/",
"sigma",
")",
"**",
"2",
"*",
"mex_hat",
"(",
"y... | 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 (filter scale)
Returns
-------
float directional Mexican hat filtered data point
Examples
--------
>>> from modopt.signal.filter import mex_hat_dir
>>> mex_hat_dir(1, 2, 1)
0.17606952612856686 | [
"r",
"Directional",
"Mexican",
"hat"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/filter.py#L90-L119 |
26,853 | CEA-COSMIC/ModOpt | modopt/math/convolve.py | convolve | 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 : np.ndarray
Input kernel array, normally a 2D kernel
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Raises
------
ValueError
If `data` and `kernel` do not have the same number of dimensions
ValueError
If `method` is not 'astropy' or 'scipy'
Notes
-----
The convolution methods are:
'astropy':
Uses the astropy.convolution.convolve_fft method provided in
Astropy (http://www.astropy.org/)
'scipy':
Uses the scipy.signal.fftconvolve method provided in SciPy
(https://www.scipy.org/)
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(9).reshape(3, 3)
>>> b = a + 10
>>> convolve(a, b)
array([[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]])
>>> convolve(a, b, method='scipy')
array([[ 86., 170., 146.],
[ 246., 444., 354.],
[ 290., 494., 374.]])
"""
if data.ndim != kernel.ndim:
raise ValueError('Data and kernel must have the same dimensions.')
if method not in ('astropy', 'scipy'):
raise ValueError('Invalid method. Options are "astropy" or "scipy".')
if not import_astropy: # pragma: no cover
method = 'scipy'
if method == 'astropy':
return convolve_fft(data, kernel, boundary='wrap', crop=False,
nan_treatment='fill', normalize_kernel=False)
elif method == 'scipy':
return scipy.signal.fftconvolve(data, kernel, mode='same') | python | 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 : np.ndarray
Input kernel array, normally a 2D kernel
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Raises
------
ValueError
If `data` and `kernel` do not have the same number of dimensions
ValueError
If `method` is not 'astropy' or 'scipy'
Notes
-----
The convolution methods are:
'astropy':
Uses the astropy.convolution.convolve_fft method provided in
Astropy (http://www.astropy.org/)
'scipy':
Uses the scipy.signal.fftconvolve method provided in SciPy
(https://www.scipy.org/)
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(9).reshape(3, 3)
>>> b = a + 10
>>> convolve(a, b)
array([[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]])
>>> convolve(a, b, method='scipy')
array([[ 86., 170., 146.],
[ 246., 444., 354.],
[ 290., 494., 374.]])
"""
if data.ndim != kernel.ndim:
raise ValueError('Data and kernel must have the same dimensions.')
if method not in ('astropy', 'scipy'):
raise ValueError('Invalid method. Options are "astropy" or "scipy".')
if not import_astropy: # pragma: no cover
method = 'scipy'
if method == 'astropy':
return convolve_fft(data, kernel, boundary='wrap', crop=False,
nan_treatment='fill', normalize_kernel=False)
elif method == 'scipy':
return scipy.signal.fftconvolve(data, kernel, mode='same') | [
"def",
"convolve",
"(",
"data",
",",
"kernel",
",",
"method",
"=",
"'scipy'",
")",
":",
"if",
"data",
".",
"ndim",
"!=",
"kernel",
".",
"ndim",
":",
"raise",
"ValueError",
"(",
"'Data and kernel must have the same dimensions.'",
")",
"if",
"method",
"not",
"... | 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 : np.ndarray
Input kernel array, normally a 2D kernel
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Raises
------
ValueError
If `data` and `kernel` do not have the same number of dimensions
ValueError
If `method` is not 'astropy' or 'scipy'
Notes
-----
The convolution methods are:
'astropy':
Uses the astropy.convolution.convolve_fft method provided in
Astropy (http://www.astropy.org/)
'scipy':
Uses the scipy.signal.fftconvolve method provided in SciPy
(https://www.scipy.org/)
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(9).reshape(3, 3)
>>> b = a + 10
>>> convolve(a, b)
array([[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]])
>>> convolve(a, b, method='scipy')
array([[ 86., 170., 146.],
[ 246., 444., 354.],
[ 290., 494., 374.]]) | [
"r",
"Convolve",
"data",
"with",
"kernel"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/convolve.py#L33-L103 |
26,854 | CEA-COSMIC/ModOpt | modopt/math/convolve.py | convolve_stack | 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 data array, normally a 2D image
kernel : np.ndarray
Input kernel array, normally a 2D kernel
rot_kernel : bool
Option to rotate kernels by 180 degrees
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(18).reshape(2, 3, 3)
>>> b = a + 10
>>> convolve_stack(a, b)
array([[[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]],
<BLANKLINE>
[[ 2721., 2712., 2721.],
[ 2640., 2631., 2640.],
[ 2721., 2712., 2721.]]])
>>> convolve_stack(a, b, rot_kernel=True)
array([[[ 474., 483., 474.],
[ 555., 564., 555.],
[ 474., 483., 474.]],
<BLANKLINE>
[[ 2661., 2670., 2661.],
[ 2742., 2751., 2742.],
[ 2661., 2670., 2661.]]])
See Also
--------
convolve : The convolution function called by convolve_stack
"""
if rot_kernel:
kernel = rotate_stack(kernel)
return np.array([convolve(data_i, kernel_i, method=method) for data_i,
kernel_i in zip(data, kernel)]) | python | 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 data array, normally a 2D image
kernel : np.ndarray
Input kernel array, normally a 2D kernel
rot_kernel : bool
Option to rotate kernels by 180 degrees
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(18).reshape(2, 3, 3)
>>> b = a + 10
>>> convolve_stack(a, b)
array([[[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]],
<BLANKLINE>
[[ 2721., 2712., 2721.],
[ 2640., 2631., 2640.],
[ 2721., 2712., 2721.]]])
>>> convolve_stack(a, b, rot_kernel=True)
array([[[ 474., 483., 474.],
[ 555., 564., 555.],
[ 474., 483., 474.]],
<BLANKLINE>
[[ 2661., 2670., 2661.],
[ 2742., 2751., 2742.],
[ 2661., 2670., 2661.]]])
See Also
--------
convolve : The convolution function called by convolve_stack
"""
if rot_kernel:
kernel = rotate_stack(kernel)
return np.array([convolve(data_i, kernel_i, method=method) for data_i,
kernel_i in zip(data, kernel)]) | [
"def",
"convolve_stack",
"(",
"data",
",",
"kernel",
",",
"rot_kernel",
"=",
"False",
",",
"method",
"=",
"'scipy'",
")",
":",
"if",
"rot_kernel",
":",
"kernel",
"=",
"rotate_stack",
"(",
"kernel",
")",
"return",
"np",
".",
"array",
"(",
"[",
"convolve",... | 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 data array, normally a 2D image
kernel : np.ndarray
Input kernel array, normally a 2D kernel
rot_kernel : bool
Option to rotate kernels by 180 degrees
method : str {'astropy', 'scipy'}, optional
Convolution method (default is 'scipy')
Returns
-------
np.ndarray convolved data
Examples
--------
>>> from math.convolve import convolve
>>> import numpy as np
>>> a = np.arange(18).reshape(2, 3, 3)
>>> b = a + 10
>>> convolve_stack(a, b)
array([[[ 534., 525., 534.],
[ 453., 444., 453.],
[ 534., 525., 534.]],
<BLANKLINE>
[[ 2721., 2712., 2721.],
[ 2640., 2631., 2640.],
[ 2721., 2712., 2721.]]])
>>> convolve_stack(a, b, rot_kernel=True)
array([[[ 474., 483., 474.],
[ 555., 564., 555.],
[ 474., 483., 474.]],
<BLANKLINE>
[[ 2661., 2670., 2661.],
[ 2742., 2751., 2742.],
[ 2661., 2670., 2661.]]])
See Also
--------
convolve : The convolution function called by convolve_stack | [
"r",
"Convolve",
"stack",
"of",
"data",
"with",
"stack",
"of",
"kernels"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/convolve.py#L106-L161 |
26,855 | CEA-COSMIC/ModOpt | modopt/base/types.py | check_callable | 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
add_agrs : bool, optional
Option to add support for agrs and kwargs
Returns
-------
func wrapped by `add_args_kwargs`
Raises
------
TypeError
For invalid input type
"""
if not callable(val):
raise TypeError('The input object must be a callable function.')
if add_agrs:
val = add_args_kwargs(val)
return val | python | 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
add_agrs : bool, optional
Option to add support for agrs and kwargs
Returns
-------
func wrapped by `add_args_kwargs`
Raises
------
TypeError
For invalid input type
"""
if not callable(val):
raise TypeError('The input object must be a callable function.')
if add_agrs:
val = add_args_kwargs(val)
return val | [
"def",
"check_callable",
"(",
"val",
",",
"add_agrs",
"=",
"True",
")",
":",
"if",
"not",
"callable",
"(",
"val",
")",
":",
"raise",
"TypeError",
"(",
"'The input object must be a callable function.'",
")",
"if",
"add_agrs",
":",
"val",
"=",
"add_args_kwargs",
... | 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
add_agrs : bool, optional
Option to add support for agrs and kwargs
Returns
-------
func wrapped by `add_args_kwargs`
Raises
------
TypeError
For invalid input type | [
"r",
"Check",
"input",
"object",
"is",
"callable"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L16-L47 |
26,856 | CEA-COSMIC/ModOpt | modopt/base/types.py | check_float | 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 = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> check_float(a)
array([ 0., 1., 2., 3., 4.])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, int):
val = float(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=float)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.floating)):
val = val.astype(float)
return val | python | 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 = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> check_float(a)
array([ 0., 1., 2., 3., 4.])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, int):
val = float(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=float)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.floating)):
val = val.astype(float)
return val | [
"def",
"check_float",
"(",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type.'",
")",
"if",
"isi... | 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 = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> check_float(a)
array([ 0., 1., 2., 3., 4.]) | [
"r",
"Check",
"if",
"input",
"value",
"is",
"a",
"float",
"or",
"a",
"np",
".",
"ndarray",
"of",
"floats",
"if",
"not",
"convert",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L50-L84 |
26,857 | CEA-COSMIC/ModOpt | modopt/base/types.py | check_int | 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).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, float):
val = int(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=int)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.integer)):
val = val.astype(int)
return val | python | 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).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, float):
val = int(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=int)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.integer)):
val = val.astype(int)
return val | [
"def",
"check_int",
"(",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type.'",
")",
"if",
"isins... | 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).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4]) | [
"r",
"Check",
"if",
"input",
"value",
"is",
"an",
"int",
"or",
"a",
"np",
".",
"ndarray",
"of",
"ints",
"if",
"not",
"convert",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L87-L120 |
26,858 | CEA-COSMIC/ModOpt | modopt/base/types.py | check_npndarray | 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(dtype, type(None))) and
(not np.issubdtype(val.dtype, dtype))):
raise TypeError('The numpy array elements are not of type: {}'
''.format(dtype))
if not writeable and verbose and val.flags.writeable:
warn('Making input data immutable.')
val.flags.writeable = writeable | python | def check_npndarray(val, dtype=None, writeable=True, verbose=True):
if not isinstance(val, np.ndarray):
raise TypeError('Input is not a numpy array.')
if ((not isinstance(dtype, type(None))) and
(not np.issubdtype(val.dtype, dtype))):
raise TypeError('The numpy array elements are not of type: {}'
''.format(dtype))
if not writeable and verbose and val.flags.writeable:
warn('Making input data immutable.')
val.flags.writeable = writeable | [
"def",
"check_npndarray",
"(",
"val",
",",
"dtype",
"=",
"None",
",",
"writeable",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Input is not... | Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object | [
"Check",
"if",
"input",
"object",
"is",
"a",
"numpy",
"array",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L123-L144 |
26,859 | CEA-COSMIC/ModOpt | modopt/signal/positivity.py | positive | 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.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]])
"""
if not isinstance(data, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid data type, input must be `int`, `float`, '
'`list`, `tuple` or `np.ndarray`.')
def pos_thresh(data):
return data * (data > 0)
def pos_recursive(data):
data = np.array(data)
if not data.dtype == 'O':
result = list(pos_thresh(data))
else:
result = [pos_recursive(x) for x in data]
return result
if isinstance(data, (int, float)):
return pos_thresh(data)
else:
return np.array(pos_recursive(data)) | python | 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.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]])
"""
if not isinstance(data, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid data type, input must be `int`, `float`, '
'`list`, `tuple` or `np.ndarray`.')
def pos_thresh(data):
return data * (data > 0)
def pos_recursive(data):
data = np.array(data)
if not data.dtype == 'O':
result = list(pos_thresh(data))
else:
result = [pos_recursive(x) for x in data]
return result
if isinstance(data, (int, float)):
return pos_thresh(data)
else:
return np.array(pos_recursive(data)) | [
"def",
"positive",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid data type, input must be `int`, `floa... | 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.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]]) | [
"r",
"Positivity",
"operator"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/positivity.py#L15-L78 |
26,860 | scidash/sciunit | sciunit/scores/collections.py | ScoreArray.mean | 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 | def mean(self):
return np.dot(np.array(self.norm_scores), self.weights) | [
"def",
"mean",
"(",
"self",
")",
":",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"array",
"(",
"self",
".",
"norm_scores",
")",
",",
"self",
".",
"weights",
")"
] | 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. | [
"Compute",
"a",
"total",
"score",
"for",
"each",
"model",
"over",
"all",
"the",
"tests",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L84-L91 |
26,861 | scidash/sciunit | sciunit/scores/collections.py | ScoreMatrix.T | def T(self):
"""Get transpose of this ScoreMatrix."""
return ScoreMatrix(self.tests, self.models, scores=self.values,
weights=self.weights, transpose=True) | python | def T(self):
return ScoreMatrix(self.tests, self.models, scores=self.values,
weights=self.weights, transpose=True) | [
"def",
"T",
"(",
"self",
")",
":",
"return",
"ScoreMatrix",
"(",
"self",
".",
"tests",
",",
"self",
".",
"models",
",",
"scores",
"=",
"self",
".",
"values",
",",
"weights",
"=",
"self",
".",
"weights",
",",
"transpose",
"=",
"True",
")"
] | Get transpose of this ScoreMatrix. | [
"Get",
"transpose",
"of",
"this",
"ScoreMatrix",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L210-L213 |
26,862 | scidash/sciunit | sciunit/scores/collections.py | ScoreMatrix.to_html | 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:
sortable = self.sortable
df = self.copy()
if show_mean:
df.insert(0, 'Mean', None)
df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
html = df.to_html(*args, **kwargs) # Pandas method
html, table_id = self.annotate(df, html, show_mean, colorize)
if sortable:
self.dynamify(table_id)
return html | python | def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
**kwargs):
if show_mean is None:
show_mean = self.show_mean
if sortable is None:
sortable = self.sortable
df = self.copy()
if show_mean:
df.insert(0, 'Mean', None)
df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
html = df.to_html(*args, **kwargs) # Pandas method
html, table_id = self.annotate(df, html, show_mean, colorize)
if sortable:
self.dynamify(table_id)
return html | [
"def",
"to_html",
"(",
"self",
",",
"show_mean",
"=",
"None",
",",
"sortable",
"=",
"None",
",",
"colorize",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"show_mean",
"is",
"None",
":",
"show_mean",
"=",
"self",
".",
"sho... | Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix. | [
"Extend",
"Pandas",
"built",
"in",
"to_html",
"method",
"for",
"rendering",
"a",
"DataFrame",
"and",
"use",
"it",
"to",
"render",
"a",
"ScoreMatrix",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L215-L231 |
26,863 | scidash/sciunit | sciunit/utils.py | rec_apply | 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 | def rec_apply(func, n):
if n > 1:
rec_func = rec_apply(func, n - 1)
return lambda x: func(rec_func(x))
return func | [
"def",
"rec_apply",
"(",
"func",
",",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"rec_func",
"=",
"rec_apply",
"(",
"func",
",",
"n",
"-",
"1",
")",
"return",
"lambda",
"x",
":",
"func",
"(",
"rec_func",
"(",
"x",
")",
")",
"return",
"func"
] | Used to determine parent directory n levels up
by repeatedly applying os.path.dirname | [
"Used",
"to",
"determine",
"parent",
"directory",
"n",
"levels",
"up",
"by",
"repeatedly",
"applying",
"os",
".",
"path",
".",
"dirname"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L50-L58 |
26,864 | scidash/sciunit | sciunit/utils.py | printd | 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 | def printd(*args, **kwargs):
global settings
if settings['PRINT_DEBUG_STATE']:
print(*args, **kwargs)
return True
return False | [
"def",
"printd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"settings",
"if",
"settings",
"[",
"'PRINT_DEBUG_STATE'",
"]",
":",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"return",
"False"
] | Print if PRINT_DEBUG_STATE is True | [
"Print",
"if",
"PRINT_DEBUG_STATE",
"is",
"True"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L71-L78 |
26,865 | scidash/sciunit | sciunit/utils.py | assert_dimensionless | 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 == Dimensionality({}):
value = value.base.item()
else:
raise TypeError("Score value %s must be dimensionless" % value)
return value | python | def assert_dimensionless(value):
if isinstance(value, Quantity):
value = value.simplified
if value.dimensionality == Dimensionality({}):
value = value.base.item()
else:
raise TypeError("Score value %s must be dimensionless" % value)
return value | [
"def",
"assert_dimensionless",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Quantity",
")",
":",
"value",
"=",
"value",
".",
"simplified",
"if",
"value",
".",
"dimensionality",
"==",
"Dimensionality",
"(",
"{",
"}",
")",
":",
"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. | [
"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",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L92-L105 |
26,866 | scidash/sciunit | sciunit/utils.py | import_all_modules | 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 skip is None else skip
for ff, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
prefix=prefix,
onerror=lambda x: None):
if ff.path not in package.__path__[0]: # Solves weird bug
continue
if verbose:
print('\t'*depth,modname)
if modname in skip:
if verbose:
print('\t'*depth,'*Skipping*')
continue
module = '%s.%s' % (package.__name__,modname)
subpackage = importlib.import_module(module)
if ispkg:
import_all_modules(subpackage, skip=skip,
verbose=verbose,depth=depth+1) | python | def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0):
skip = [] if skip is None else skip
for ff, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
prefix=prefix,
onerror=lambda x: None):
if ff.path not in package.__path__[0]: # Solves weird bug
continue
if verbose:
print('\t'*depth,modname)
if modname in skip:
if verbose:
print('\t'*depth,'*Skipping*')
continue
module = '%s.%s' % (package.__name__,modname)
subpackage = importlib.import_module(module)
if ispkg:
import_all_modules(subpackage, skip=skip,
verbose=verbose,depth=depth+1) | [
"def",
"import_all_modules",
"(",
"package",
",",
"skip",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
",",
"depth",
"=",
"0",
")",
":",
"skip",
"=",
"[",
"]",
"if",
"skip",
"is",
"None",
"else",
"skip",
"for",
"ff",
",",
... | 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. | [
"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",
"subpacka... | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L352-L376 |
26,867 | scidash/sciunit | sciunit/utils.py | method_cache | 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 decorate(*args, **kwargs):
model = args[0] # Assumed to be self.
assert hasattr(model,method), "Model must have a '%s' method."%method
if func.__name__ == method: # Run itself.
method_args = kwargs
else: # Any other method.
method_args = kwargs[method] if method in kwargs else {}
if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
model.__class__.cached_runs = {} # Create the method cache.
cache = model.__class__.cached_runs
if by == 'value':
model_dict = {key:value for key,value in list(model.__dict__.items()) \
if key[0]!='_'}
method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
elif by == 'instance':
method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
else:
raise ValueError("Cache type must be 'value' or 'instance'")
if method_signature not in cache:
print("Method with this signature not found in the cache. Running...")
f = getattr(model,method)
f(**method_args)
cache[method_signature] = (datetime.now(),model.__dict__.copy())
else:
print("Method with this signature found in the cache. Restoring...")
_,attrs = cache[method_signature]
model.__dict__.update(attrs)
return func(*args, **kwargs)
return decorate
return decorate_ | python | def method_cache(by='value',method='run'):
def decorate_(func):
def decorate(*args, **kwargs):
model = args[0] # Assumed to be self.
assert hasattr(model,method), "Model must have a '%s' method."%method
if func.__name__ == method: # Run itself.
method_args = kwargs
else: # Any other method.
method_args = kwargs[method] if method in kwargs else {}
if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
model.__class__.cached_runs = {} # Create the method cache.
cache = model.__class__.cached_runs
if by == 'value':
model_dict = {key:value for key,value in list(model.__dict__.items()) \
if key[0]!='_'}
method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
elif by == 'instance':
method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
else:
raise ValueError("Cache type must be 'value' or 'instance'")
if method_signature not in cache:
print("Method with this signature not found in the cache. Running...")
f = getattr(model,method)
f(**method_args)
cache[method_signature] = (datetime.now(),model.__dict__.copy())
else:
print("Method with this signature found in the cache. Restoring...")
_,attrs = cache[method_signature]
model.__dict__.update(attrs)
return func(*args, **kwargs)
return decorate
return decorate_ | [
"def",
"method_cache",
"(",
"by",
"=",
"'value'",
",",
"method",
"=",
"'run'",
")",
":",
"def",
"decorate_",
"(",
"func",
")",
":",
"def",
"decorate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"args",
"[",
"0",
"]",
"# As... | 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. | [
"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",
... | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L401-L437 |
26,868 | scidash/sciunit | sciunit/utils.py | NotebookTools.convert_path | 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:
print("Incorrect path specified")
return -1 | python | def convert_path(cls, file):
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
print("Incorrect path specified")
return -1 | [
"def",
"convert_path",
"(",
"cls",
",",
"file",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"return",
"file",
"elif",
"isinstance",
"(",
"file",
",",
"list",
")",
"and",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",... | Check to see if an extended path is given and convert appropriately | [
"Check",
"to",
"see",
"if",
"an",
"extended",
"path",
"is",
"given",
"and",
"convert",
"appropriately"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L120-L131 |
26,869 | scidash/sciunit | sciunit/utils.py | NotebookTools.get_path | 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.realpath(path) | python | def get_path(self, file):
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.realpath(path) | [
"def",
"get_path",
"(",
"self",
",",
"file",
")",
":",
"class_path",
"=",
"inspect",
".",
"getfile",
"(",
"self",
".",
"__class__",
")",
"parent_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"class_path",
")",
"path",
"=",
"os",
".",
"path",
".... | Get the full path of the notebook found in the directory
specified by self.path. | [
"Get",
"the",
"full",
"path",
"of",
"the",
"notebook",
"found",
"in",
"the",
"directory",
"specified",
"by",
"self",
".",
"path",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L133-L141 |
26,870 | scidash/sciunit | sciunit/utils.py | NotebookTools.fix_display | 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:
import matplotlib as mpl
except ImportError:
pass
else:
print("Setting matplotlib backend to Agg")
mpl.use('Agg') | python | def fix_display(self):
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
import matplotlib as mpl
except ImportError:
pass
else:
print("Setting matplotlib backend to Agg")
mpl.use('Agg') | [
"def",
"fix_display",
"(",
"self",
")",
":",
"try",
":",
"tkinter",
".",
"Tk",
"(",
")",
"except",
"(",
"tkinter",
".",
"TclError",
",",
"NameError",
")",
":",
"# If there is no display.",
"try",
":",
"import",
"matplotlib",
"as",
"mpl",
"except",
"ImportE... | If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display. | [
"If",
"this",
"is",
"being",
"run",
"on",
"a",
"headless",
"system",
"the",
"Matplotlib",
"backend",
"must",
"be",
"changed",
"to",
"one",
"that",
"doesn",
"t",
"need",
"a",
"display",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L143-L157 |
26,871 | scidash/sciunit | sciunit/utils.py | NotebookTools.load_notebook | 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 | def load_notebook(self, name):
with open(self.get_path('%s.ipynb'%name)) as f:
nb = nbformat.read(f, as_version=4)
return nb,f | [
"def",
"load_notebook",
"(",
"self",
",",
"name",
")",
":",
"with",
"open",
"(",
"self",
".",
"get_path",
"(",
"'%s.ipynb'",
"%",
"name",
")",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"f",
",",
"as_version",
"=",
"4",
")",
"r... | Loads a notebook file into memory. | [
"Loads",
"a",
"notebook",
"file",
"into",
"memory",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L159-L164 |
26,872 | scidash/sciunit | sciunit/utils.py | NotebookTools.run_notebook | 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 = ExecutePreprocessor(timeout=600, kernel_name=kernel_name)
try:
ep.preprocess(nb, {'metadata': {'path': '.'}})
except CellExecutionError:
msg = 'Error executing the notebook "%s".\n\n' % f.name
msg += 'See notebook "%s" for the traceback.' % f.name
print(msg)
raise
finally:
nbformat.write(nb, f) | python | def run_notebook(self, nb, f):
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 = ExecutePreprocessor(timeout=600, kernel_name=kernel_name)
try:
ep.preprocess(nb, {'metadata': {'path': '.'}})
except CellExecutionError:
msg = 'Error executing the notebook "%s".\n\n' % f.name
msg += 'See notebook "%s" for the traceback.' % f.name
print(msg)
raise
finally:
nbformat.write(nb, f) | [
"def",
"run_notebook",
"(",
"self",
",",
"nb",
",",
"f",
")",
":",
"if",
"PYTHON_MAJOR_VERSION",
"==",
"3",
":",
"kernel_name",
"=",
"'python3'",
"elif",
"PYTHON_MAJOR_VERSION",
"==",
"2",
":",
"kernel_name",
"=",
"'python2'",
"else",
":",
"raise",
"Exceptio... | Runs a loaded notebook file. | [
"Runs",
"a",
"loaded",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L166-L184 |
26,873 | scidash/sciunit | sciunit/utils.py | NotebookTools.execute_notebook | 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 | def execute_notebook(self, name):
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | [
"def",
"execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"DeprecationWarning",
")",
"nb",
",",
"f",
"=",
"self",
".",
"load_notebook",
"(",
"name",
")",
"self",
".",
"run_not... | Loads and then runs a notebook file. | [
"Loads",
"and",
"then",
"runs",
"a",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L186-L192 |
26,874 | scidash/sciunit | sciunit/utils.py | NotebookTools.convert_notebook | 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(name)
file_path = self.get_path("%s.ipynb"%relative_path)
code = exporter.from_filename(file_path)[0]
self.write_code(name, code)
self.clean_code(name, []) | python | def convert_notebook(self, name):
#subprocess.call(["jupyter","nbconvert","--to","python",
# self.get_path("%s.ipynb"%name)])
exporter = nbconvert.exporters.python.PythonExporter()
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
code = exporter.from_filename(file_path)[0]
self.write_code(name, code)
self.clean_code(name, []) | [
"def",
"convert_notebook",
"(",
"self",
",",
"name",
")",
":",
"#subprocess.call([\"jupyter\",\"nbconvert\",\"--to\",\"python\",",
"# self.get_path(\"%s.ipynb\"%name)])",
"exporter",
"=",
"nbconvert",
".",
"exporters",
".",
"python",
".",
"PythonExporter",
"(",
... | Converts a notebook into a python file. | [
"Converts",
"a",
"notebook",
"into",
"a",
"python",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L194-L204 |
26,875 | scidash/sciunit | sciunit/utils.py | NotebookTools.convert_and_execute_notebook | 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 | def convert_and_execute_notebook(self, name):
self.convert_notebook(name)
code = self.read_code(name)#clean_code(name,'get_ipython')
exec(code,globals()) | [
"def",
"convert_and_execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"convert_notebook",
"(",
"name",
")",
"code",
"=",
"self",
".",
"read_code",
"(",
"name",
")",
"#clean_code(name,'get_ipython')",
"exec",
"(",
"code",
",",
"globals",
"(",
... | Converts a notebook into a python file and then runs it. | [
"Converts",
"a",
"notebook",
"into",
"a",
"python",
"file",
"and",
"then",
"runs",
"it",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L206-L211 |
26,876 | scidash/sciunit | sciunit/utils.py | NotebookTools.gen_file_path | 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)
parent_path = rec_apply(os.path.dirname, self.gen_file_level)(file_path)
gen_file_name = name if isinstance(name,str) else name[1] #Name of generated file
gen_dir_path = self.get_path(os.path.join(parent_path, self.gen_dir_name))
if not os.path.exists(gen_dir_path): # Create folder for generated files if needed
os.makedirs(gen_dir_path)
new_file_path = self.get_path('%s.py'%os.path.join(gen_dir_path, gen_file_name))
return new_file_path | python | def gen_file_path(self, name):
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
parent_path = rec_apply(os.path.dirname, self.gen_file_level)(file_path)
gen_file_name = name if isinstance(name,str) else name[1] #Name of generated file
gen_dir_path = self.get_path(os.path.join(parent_path, self.gen_dir_name))
if not os.path.exists(gen_dir_path): # Create folder for generated files if needed
os.makedirs(gen_dir_path)
new_file_path = self.get_path('%s.py'%os.path.join(gen_dir_path, gen_file_name))
return new_file_path | [
"def",
"gen_file_path",
"(",
"self",
",",
"name",
")",
":",
"relative_path",
"=",
"self",
".",
"convert_path",
"(",
"name",
")",
"file_path",
"=",
"self",
".",
"get_path",
"(",
"\"%s.ipynb\"",
"%",
"relative_path",
")",
"parent_path",
"=",
"rec_apply",
"(",
... | Returns full path to generated files. Checks to see if directory
exists where generated files are stored and creates one otherwise. | [
"Returns",
"full",
"path",
"to",
"generated",
"files",
".",
"Checks",
"to",
"see",
"if",
"directory",
"exists",
"where",
"generated",
"files",
"are",
"stored",
"and",
"creates",
"one",
"otherwise",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L213-L226 |
26,877 | scidash/sciunit | sciunit/utils.py | NotebookTools.read_code | 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 | 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 | [
"def",
"read_code",
"(",
"self",
",",
"name",
")",
":",
"file_path",
"=",
"self",
".",
"gen_file_path",
"(",
"name",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"read",
"(",
")",
"return",
"code"
] | Reads code from a python file called 'name | [
"Reads",
"code",
"from",
"a",
"python",
"file",
"called",
"name"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L228-L234 |
26,878 | scidash/sciunit | sciunit/utils.py | NotebookTools.clean_code | 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 = []
for line in code:
if [bad for bad in forbidden if bad in line]:
pass
else:
allowed = ['time','timeit'] # Magics where we want to keep the command
line = self.strip_line_magic(line, allowed)
if isinstance(line,list):
line = ' '.join(line)
new_code.append(line)
new_code = '\n'.join(new_code)
self.write_code(name, new_code)
return new_code | python | def clean_code(self, name, forbidden):
code = self.read_code(name)
code = code.split('\n')
new_code = []
for line in code:
if [bad for bad in forbidden if bad in line]:
pass
else:
allowed = ['time','timeit'] # Magics where we want to keep the command
line = self.strip_line_magic(line, allowed)
if isinstance(line,list):
line = ' '.join(line)
new_code.append(line)
new_code = '\n'.join(new_code)
self.write_code(name, new_code)
return new_code | [
"def",
"clean_code",
"(",
"self",
",",
"name",
",",
"forbidden",
")",
":",
"code",
"=",
"self",
".",
"read_code",
"(",
"name",
")",
"code",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
"new_code",
"=",
"[",
"]",
"for",
"line",
"in",
"code",
":",
... | Remove lines containing items in 'forbidden' from the code.
Helpful for executing converted notebooks that still retain IPython
magic commands. | [
"Remove",
"lines",
"containing",
"items",
"in",
"forbidden",
"from",
"the",
"code",
".",
"Helpful",
"for",
"executing",
"converted",
"notebooks",
"that",
"still",
"retain",
"IPython",
"magic",
"commands",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L247-L268 |
26,879 | scidash/sciunit | sciunit/utils.py | NotebookTools.do_notebook | 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 = unittest.mock.patch('sys.stderr', new=MockDevice(s))
self._do_notebook(name, CONVERT_NOTEBOOKS)
out.close()
err.close()
else:
self._do_notebook(name, CONVERT_NOTEBOOKS)
self.assertTrue(True) | python | def do_notebook(self, name):
CONVERT_NOTEBOOKS = int(os.getenv('CONVERT_NOTEBOOKS', True))
s = StringIO()
if mock:
out = unittest.mock.patch('sys.stdout', new=MockDevice(s))
err = unittest.mock.patch('sys.stderr', new=MockDevice(s))
self._do_notebook(name, CONVERT_NOTEBOOKS)
out.close()
err.close()
else:
self._do_notebook(name, CONVERT_NOTEBOOKS)
self.assertTrue(True) | [
"def",
"do_notebook",
"(",
"self",
",",
"name",
")",
":",
"CONVERT_NOTEBOOKS",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'CONVERT_NOTEBOOKS'",
",",
"True",
")",
")",
"s",
"=",
"StringIO",
"(",
")",
"if",
"mock",
":",
"out",
"=",
"unittest",
".",
"m... | Run a notebook file after optionally
converting it to a python file. | [
"Run",
"a",
"notebook",
"file",
"after",
"optionally",
"converting",
"it",
"to",
"a",
"python",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L319-L332 |
26,880 | scidash/sciunit | sciunit/utils.py | NotebookTools._do_notebook | 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 | def _do_notebook(self, name, convert_notebooks=False):
if convert_notebooks:
self.convert_and_execute_notebook(name)
else:
self.execute_notebook(name) | [
"def",
"_do_notebook",
"(",
"self",
",",
"name",
",",
"convert_notebooks",
"=",
"False",
")",
":",
"if",
"convert_notebooks",
":",
"self",
".",
"convert_and_execute_notebook",
"(",
"name",
")",
"else",
":",
"self",
".",
"execute_notebook",
"(",
"name",
")"
] | Called by do_notebook to actually run the notebook. | [
"Called",
"by",
"do_notebook",
"to",
"actually",
"run",
"the",
"notebook",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L334-L339 |
26,881 | scidash/sciunit | sciunit/models/base.py | Model.get_capabilities | 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 | def get_capabilities(cls):
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 | [
"def",
"get_capabilities",
"(",
"cls",
")",
":",
"capabilities",
"=",
"[",
"]",
"for",
"_cls",
"in",
"cls",
".",
"mro",
"(",
")",
":",
"if",
"issubclass",
"(",
"_cls",
",",
"Capability",
")",
"and",
"_cls",
"is",
"not",
"Capability",
"and",
"not",
"i... | List the model's capabilities. | [
"List",
"the",
"model",
"s",
"capabilities",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L42-L49 |
26,882 | scidash/sciunit | sciunit/models/base.py | Model.failed_extra_capabilities | 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:
failed.append(capability)
return failed | python | def failed_extra_capabilities(self):
failed = []
for capability, f_name in self.extra_capability_checks.items():
f = getattr(self, f_name)
instance_capable = f()
if not instance_capable:
failed.append(capability)
return failed | [
"def",
"failed_extra_capabilities",
"(",
"self",
")",
":",
"failed",
"=",
"[",
"]",
"for",
"capability",
",",
"f_name",
"in",
"self",
".",
"extra_capability_checks",
".",
"items",
"(",
")",
":",
"f",
"=",
"getattr",
"(",
"self",
",",
"f_name",
")",
"inst... | Check to see if instance passes its `extra_capability_checks`. | [
"Check",
"to",
"see",
"if",
"instance",
"passes",
"its",
"extra_capability_checks",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L56-L64 |
26,883 | scidash/sciunit | sciunit/models/base.py | Model.describe | 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', '').
replace(' ', ' ')]
result = '\n'.join(s)
return result | python | def describe(self):
result = "No description available"
if self.description:
result = "%s" % self.description
else:
if self.__doc__:
s = []
s += [self.__doc__.strip().replace('\n', '').
replace(' ', ' ')]
result = '\n'.join(s)
return result | [
"def",
"describe",
"(",
"self",
")",
":",
"result",
"=",
"\"No description available\"",
"if",
"self",
".",
"description",
":",
"result",
"=",
"\"%s\"",
"%",
"self",
".",
"description",
"else",
":",
"if",
"self",
".",
"__doc__",
":",
"s",
"=",
"[",
"]",
... | Describe the model. | [
"Describe",
"the",
"model",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L66-L77 |
26,884 | scidash/sciunit | sciunit/models/base.py | Model.is_match | 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, match):
result = True # Found by instance or name
return result | python | def is_match(self, match):
result = False
if self == match:
result = True
elif isinstance(match, str) and fnmatchcase(self.name, match):
result = True # Found by instance or name
return result | [
"def",
"is_match",
"(",
"self",
",",
"match",
")",
":",
"result",
"=",
"False",
"if",
"self",
"==",
"match",
":",
"result",
"=",
"True",
"elif",
"isinstance",
"(",
"match",
",",
"str",
")",
"and",
"fnmatchcase",
"(",
"self",
".",
"name",
",",
"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`. | [
"Return",
"whether",
"this",
"model",
"is",
"the",
"same",
"as",
"match",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L92-L102 |
26,885 | scidash/sciunit | sciunit/__main__.py | main | 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 .sciunit file")
parser.add_argument("--stop", "-s", default=True,
help="stop and raise errors, halting the program")
parser.add_argument("--tests", "-t", default=False,
help="runs tests instead of suites")
if args:
args = parser.parse_args(args)
else:
args = parser.parse_args()
file_path = os.path.join(args.directory, '.sciunit')
config = None
if args.action == 'create':
create(file_path)
elif args.action == 'check':
config = parse(file_path, show=True)
print("\nNo configuration errors reported.")
elif args.action == 'run':
config = parse(file_path)
run(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'make-nb':
config = parse(file_path)
make_nb(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'run-nb':
config = parse(file_path)
run_nb(config, path=args.directory)
else:
raise NameError('No such action %s' % args.action)
if config:
cleanup(config, path=args.directory) | python | def main(*args):
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 .sciunit file")
parser.add_argument("--stop", "-s", default=True,
help="stop and raise errors, halting the program")
parser.add_argument("--tests", "-t", default=False,
help="runs tests instead of suites")
if args:
args = parser.parse_args(args)
else:
args = parser.parse_args()
file_path = os.path.join(args.directory, '.sciunit')
config = None
if args.action == 'create':
create(file_path)
elif args.action == 'check':
config = parse(file_path, show=True)
print("\nNo configuration errors reported.")
elif args.action == 'run':
config = parse(file_path)
run(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'make-nb':
config = parse(file_path)
make_nb(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'run-nb':
config = parse(file_path)
run_nb(config, path=args.directory)
else:
raise NameError('No such action %s' % args.action)
if config:
cleanup(config, path=args.directory) | [
"def",
"main",
"(",
"*",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"action\"",
",",
"help",
"=",
"\"create, check, run, make-nb, or run-nb\"",
")",
"parser",
".",
"add_argument",
"(",
"\... | Launch the main routine. | [
"Launch",
"the",
"main",
"routine",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L40-L76 |
26,886 | scidash/sciunit | sciunit/__main__.py | create | 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()
config.add_section('misc')
config.set('misc', 'config-version', '1.0')
default_nb_name = os.path.split(os.path.dirname(file_path))[1]
config.set('misc', 'nb-name', default_nb_name)
config.add_section('root')
config.set('root', 'path', '.')
config.add_section('models')
config.set('models', 'module', 'models')
config.add_section('tests')
config.set('tests', 'module', 'tests')
config.add_section('suites')
config.set('suites', 'module', 'suites')
config.write(f) | python | def create(file_path):
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()
config.add_section('misc')
config.set('misc', 'config-version', '1.0')
default_nb_name = os.path.split(os.path.dirname(file_path))[1]
config.set('misc', 'nb-name', default_nb_name)
config.add_section('root')
config.set('root', 'path', '.')
config.add_section('models')
config.set('models', 'module', 'models')
config.add_section('tests')
config.set('tests', 'module', 'tests')
config.add_section('suites')
config.set('suites', 'module', 'suites')
config.write(f) | [
"def",
"create",
"(",
"file_path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raise",
"IOError",
"(",
"\"There is already a configuration file at %s\"",
"%",
"file_path",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
... | Create a default .sciunit config file if one does not already exist. | [
"Create",
"a",
"default",
".",
"sciunit",
"config",
"file",
"if",
"one",
"does",
"not",
"already",
"exist",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L79-L98 |
26,887 | scidash/sciunit | sciunit/__main__.py | parse | 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 = configparser.RawConfigParser(allow_no_value=True)
config.read(file_path)
# List all contents
for section in config.sections():
if show:
print(section)
for options in config.options(section):
if show:
print("\t%s: %s" % (options, config.get(section, options)))
return config | python | def parse(file_path=None, show=False):
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 = configparser.RawConfigParser(allow_no_value=True)
config.read(file_path)
# List all contents
for section in config.sections():
if show:
print(section)
for options in config.options(section):
if show:
print("\t%s: %s" % (options, config.get(section, options)))
return config | [
"def",
"parse",
"(",
"file_path",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"if",
"file_path",
"is",
"None",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'.sciunit'",
")",
"if",
"not",
"... | Parse a .sciunit config file. | [
"Parse",
"a",
".",
"sciunit",
"config",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L101-L119 |
26,888 | scidash/sciunit | sciunit/__main__.py | prep | 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_HOME'] = root
if sys.path[0] != root:
sys.path.insert(0, root) | python | def prep(config=None, path=None):
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_HOME'] = root
if sys.path[0] != root:
sys.path.insert(0, root) | [
"def",
"prep",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"parse",
"(",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"confi... | Prepare to read the configuration information. | [
"Prepare",
"to",
"read",
"the",
"configuration",
"information",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L122-L133 |
26,889 | scidash/sciunit | sciunit/__main__.py | run | 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')
for x in ['models', 'tests', 'suites']:
module = __import__(x)
assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
(x, x)
if just_tests:
for test in tests.tests:
_run(test, models, stop_on_error)
else:
for suite in suites.suites:
_run(suite, models, stop_on_error) | python | def run(config, path=None, stop_on_error=True, just_tests=False):
if path is None:
path = os.getcwd()
prep(config, path=path)
models = __import__('models')
tests = __import__('tests')
suites = __import__('suites')
print('\n')
for x in ['models', 'tests', 'suites']:
module = __import__(x)
assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
(x, x)
if just_tests:
for test in tests.tests:
_run(test, models, stop_on_error)
else:
for suite in suites.suites:
_run(suite, models, stop_on_error) | [
"def",
"run",
"(",
"config",
",",
"path",
"=",
"None",
",",
"stop_on_error",
"=",
"True",
",",
"just_tests",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"prep",
"(",
"config",
",",
"path",
... | Run sciunit tests for the given configuration. | [
"Run",
"sciunit",
"tests",
"for",
"the",
"given",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L136-L158 |
26,890 | scidash/sciunit | sciunit/__main__.py | nb_name_from_path | 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_name = config.get('misc', 'nb-name', fallback=default_nb_name)
return root, nb_name | python | def nb_name_from_path(config, path):
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_name = config.get('misc', 'nb-name', fallback=default_nb_name)
return root, nb_name | [
"def",
"nb_name_from_path",
"(",
"config",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"config",
".",
"get",
"(",
"'root'",
",",
"'path'",
")",
"root",
"=",
"os",
".",
"path",
"... | Get a notebook name from a path to a notebook | [
"Get",
"a",
"notebook",
"name",
"from",
"a",
"path",
"to",
"a",
"notebook"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L168-L177 |
26,891 | scidash/sciunit | sciunit/__main__.py | make_nb | 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('misc', 'matplotlib', fallback='inline')
cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
add_code_cell(cells, (
"%%matplotlib %s\n"
"from IPython.display import display\n"
"from importlib.machinery import SourceFileLoader\n"
"%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
(mpl_style, name, root))
if just_tests:
add_code_cell(cells, (
"for test in %s.tests.tests:\n"
" score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
" display(score_array)") % (name, name, stop_on_error))
else:
add_code_cell(cells, (
"for suite in %s.suites.suites:\n"
" score_matrix = suite.judge("
"%s.models.models, stop_on_error=%r)\n"
" display(score_matrix)") % (name, name, stop_on_error))
write_nb(root, nb_name, cells) | python | def make_nb(config, path=None, stop_on_error=True, just_tests=False):
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('misc', 'matplotlib', fallback='inline')
cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
add_code_cell(cells, (
"%%matplotlib %s\n"
"from IPython.display import display\n"
"from importlib.machinery import SourceFileLoader\n"
"%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
(mpl_style, name, root))
if just_tests:
add_code_cell(cells, (
"for test in %s.tests.tests:\n"
" score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
" display(score_array)") % (name, name, stop_on_error))
else:
add_code_cell(cells, (
"for suite in %s.suites.suites:\n"
" score_matrix = suite.judge("
"%s.models.models, stop_on_error=%r)\n"
" display(score_matrix)") % (name, name, stop_on_error))
write_nb(root, nb_name, cells) | [
"def",
"make_nb",
"(",
"config",
",",
"path",
"=",
"None",
",",
"stop_on_error",
"=",
"True",
",",
"just_tests",
"=",
"False",
")",
":",
"root",
",",
"nb_name",
"=",
"nb_name_from_path",
"(",
"config",
",",
"path",
")",
"clean",
"=",
"lambda",
"varStr",
... | Create a Jupyter notebook sciunit tests for the given configuration. | [
"Create",
"a",
"Jupyter",
"notebook",
"sciunit",
"tests",
"for",
"the",
"given",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L180-L205 |
26,892 | scidash/sciunit | sciunit/__main__.py | write_nb | 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.path.join(root, '%s.ipynb' % nb_name)
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION)
print("Created Jupyter notebook at:\n%s" % nb_path) | python | def write_nb(root, nb_name, cells):
nb = new_notebook(cells=cells,
metadata={
'language': 'python',
})
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION)
print("Created Jupyter notebook at:\n%s" % nb_path) | [
"def",
"write_nb",
"(",
"root",
",",
"nb_name",
",",
"cells",
")",
":",
"nb",
"=",
"new_notebook",
"(",
"cells",
"=",
"cells",
",",
"metadata",
"=",
"{",
"'language'",
":",
"'python'",
",",
"}",
")",
"nb_path",
"=",
"os",
".",
"path",
".",
"join",
... | Write a jupyter notebook to disk.
Takes a given a root directory, a notebook name, and a list of cells. | [
"Write",
"a",
"jupyter",
"notebook",
"to",
"disk",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L208-L220 |
26,893 | scidash/sciunit | sciunit/__main__.py | run_nb | 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', 'nb-name')
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
if not os.path.exists(nb_path):
print(("No notebook found at %s. "
"Create the notebook first with make-nb?") % path)
sys.exit(0)
with codecs.open(nb_path, encoding='utf-8', mode='r') as nb_file:
nb = nbformat.read(nb_file, as_version=NB_VERSION)
ep = ExecutePreprocessor(timeout=600)
ep.preprocess(nb, {'metadata': {'path': root}})
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION) | python | def run_nb(config, path=None):
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
nb_name = config.get('misc', 'nb-name')
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
if not os.path.exists(nb_path):
print(("No notebook found at %s. "
"Create the notebook first with make-nb?") % path)
sys.exit(0)
with codecs.open(nb_path, encoding='utf-8', mode='r') as nb_file:
nb = nbformat.read(nb_file, as_version=NB_VERSION)
ep = ExecutePreprocessor(timeout=600)
ep.preprocess(nb, {'metadata': {'path': root}})
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION) | [
"def",
"run_nb",
"(",
"config",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"config",
".",
"get",
"(",
"'root'",
",",
"'path'",
")",
"root",
"=",
"os",
".",
"path... | Run a notebook file.
Runs the one specified by the config file, or the one at
the location specificed by 'path'. | [
"Run",
"a",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L223-L245 |
26,894 | scidash/sciunit | sciunit/__main__.py | add_code_cell | 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 | def add_code_cell(cells, source):
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)) | [
"def",
"add_code_cell",
"(",
"cells",
",",
"source",
")",
":",
"from",
"nbformat",
".",
"v4",
".",
"nbbase",
"import",
"new_code_cell",
"n_code_cells",
"=",
"len",
"(",
"[",
"c",
"for",
"c",
"in",
"cells",
"if",
"c",
"[",
"'cell_type'",
"]",
"==",
"'co... | Add a code cell containing `source` to the notebook. | [
"Add",
"a",
"code",
"cell",
"containing",
"source",
"to",
"the",
"notebook",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L248-L252 |
26,895 | scidash/sciunit | sciunit/__main__.py | cleanup | 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:
sys.path.remove(root) | python | def cleanup(config=None, path=None):
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:
sys.path.remove(root) | [
"def",
"cleanup",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"parse",
"(",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"co... | Cleanup by removing paths added during earlier in configuration. | [
"Cleanup",
"by",
"removing",
"paths",
"added",
"during",
"earlier",
"in",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L255-L264 |
26,896 | scidash/sciunit | sciunit/base.py | Versioned.get_repo | 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:
repo = self.__class__._repo
elif hasattr(module, '__file__'):
path = os.path.realpath(module.__file__)
try:
repo = git.Repo(path, search_parent_directories=True)
except InvalidGitRepositoryError:
repo = None
else:
repo = None
self.__class__._repo = repo
return repo | python | def get_repo(self, cached=True):
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:
repo = self.__class__._repo
elif hasattr(module, '__file__'):
path = os.path.realpath(module.__file__)
try:
repo = git.Repo(path, search_parent_directories=True)
except InvalidGitRepositoryError:
repo = None
else:
repo = None
self.__class__._repo = repo
return repo | [
"def",
"get_repo",
"(",
"self",
",",
"cached",
"=",
"True",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"self",
".",
"__module__",
"]",
"# We use module.__file__ instead of module.__path__[0]",
"# to include modules without a __path__ attribute.",
"if",
"hasatt... | Get a git repository object for this instance. | [
"Get",
"a",
"git",
"repository",
"object",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L43-L59 |
26,897 | scidash/sciunit | sciunit/base.py | Versioned.get_remote | def get_remote(self, remote='origin'):
"""Get a git remote object for this instance."""
repo = self.get_repo()
if repo is not None:
remotes = {r.name: r for r in repo.remotes}
r = repo.remotes[0] if remote not in remotes else remotes[remote]
else:
r = None
return r | python | def get_remote(self, remote='origin'):
repo = self.get_repo()
if repo is not None:
remotes = {r.name: r for r in repo.remotes}
r = repo.remotes[0] if remote not in remotes else remotes[remote]
else:
r = None
return r | [
"def",
"get_remote",
"(",
"self",
",",
"remote",
"=",
"'origin'",
")",
":",
"repo",
"=",
"self",
".",
"get_repo",
"(",
")",
"if",
"repo",
"is",
"not",
"None",
":",
"remotes",
"=",
"{",
"r",
".",
"name",
":",
"r",
"for",
"r",
"in",
"repo",
".",
... | Get a git remote object for this instance. | [
"Get",
"a",
"git",
"remote",
"object",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L78-L86 |
26,898 | scidash/sciunit | sciunit/base.py | Versioned.get_remote_url | def get_remote_url(self, remote='origin', cached=True):
"""Get a git remote URL for this instance."""
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.urls)[0]
except GitCommandError as ex:
if 'correct access rights' in str(ex):
# If ssh is not setup to access this repository
cmd = ['git', 'config', '--get', 'remote.%s.url' % r.name]
url = Git().execute(cmd)
else:
raise ex
except AttributeError:
url = None
if url is not None and url.startswith('git@'):
domain = url.split('@')[1].split(':')[0]
path = url.split(':')[1]
url = "http://%s/%s" % (domain, path)
self.__class__._remote_url = url
return url | python | def get_remote_url(self, remote='origin', cached=True):
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.urls)[0]
except GitCommandError as ex:
if 'correct access rights' in str(ex):
# If ssh is not setup to access this repository
cmd = ['git', 'config', '--get', 'remote.%s.url' % r.name]
url = Git().execute(cmd)
else:
raise ex
except AttributeError:
url = None
if url is not None and url.startswith('git@'):
domain = url.split('@')[1].split(':')[0]
path = url.split(':')[1]
url = "http://%s/%s" % (domain, path)
self.__class__._remote_url = url
return url | [
"def",
"get_remote_url",
"(",
"self",
",",
"remote",
"=",
"'origin'",
",",
"cached",
"=",
"True",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"'_remote_url'",
")",
"and",
"cached",
":",
"url",
"=",
"self",
".",
"__class__",
".",
"_re... | Get a git remote URL for this instance. | [
"Get",
"a",
"git",
"remote",
"URL",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L88-L110 |
26,899 | scidash/sciunit | sciunit/validators.py | ObservationValidator._validate_iterable | def _validate_iterable(self, is_iterable, key, value):
"""Validate fields with `iterable` key in schema set to True"""
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | python | def _validate_iterable(self, is_iterable, key, value):
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | [
"def",
"_validate_iterable",
"(",
"self",
",",
"is_iterable",
",",
"key",
",",
"value",
")",
":",
"if",
"is_iterable",
":",
"try",
":",
"iter",
"(",
"value",
")",
"except",
"TypeError",
":",
"self",
".",
"_error",
"(",
"key",
",",
"\"Must be iterable (e.g.... | Validate fields with `iterable` key in schema set to True | [
"Validate",
"fields",
"with",
"iterable",
"key",
"in",
"schema",
"set",
"to",
"True"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L37-L43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.