Skip to content

Commit c03973c

Browse files
committed
Run black diffpy
1 parent 3256040 commit c03973c

13 files changed

+681
-256
lines changed

diffpy/snmf/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
"""
1818

1919
# obtain version information
20-
__version__ = '0.0.1'
20+
__version__ = "0.0.1"
2121

2222
# top-level import
23-
#from diffpy.snmf.pdfmorph_api import pdfmorph, morph_default_config, plot_morph
23+
# from diffpy.snmf.pdfmorph_api import pdfmorph, morph_default_config, plot_morph
2424

2525
# End of file

diffpy/snmf/containers.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,21 @@ def apply_stretch(self, m):
4040
stretching operation, and one vector is the second derivative of the stretching operation.
4141
"""
4242
normalized_grid = np.arange(len(self.grid))
43-
func = lambda stretching_factor: np.interp(normalized_grid / stretching_factor, normalized_grid, self.iq,
44-
left=0, right=0)
43+
func = lambda stretching_factor: np.interp(
44+
normalized_grid / stretching_factor, normalized_grid, self.iq, left=0, right=0
45+
)
4546
derivative_func = numdifftools.Derivative(func)
4647
second_derivative_func = numdifftools.Derivative(derivative_func)
4748

4849
stretched_component = func(self.stretching_factors[m])
4950
stretched_component_gra = derivative_func(self.stretching_factors[m])
5051
stretched_component_hess = second_derivative_func(self.stretching_factors[m])
5152

52-
return np.asarray(stretched_component), np.asarray(stretched_component_gra), np.asarray(
53-
stretched_component_hess)
53+
return (
54+
np.asarray(stretched_component),
55+
np.asarray(stretched_component_gra),
56+
np.asarray(stretched_component_hess),
57+
)
5458

5559
def apply_weight(self, m, stretched_component=None):
5660
"""Applies as weight factor to a component signal.

diffpy/snmf/io.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,21 @@ def initialize_variables(data_input, number_of_components, data_type, sparsity=1
4242
signal_length = data_input.shape[0]
4343
number_of_signals = data_input.shape[1]
4444

45-
diagonals = [np.ones(number_of_signals - 2), -2 * np.ones(number_of_signals - 2), np.ones(number_of_signals - 2)]
46-
smoothness_term = .25 * scipy.sparse.diags(diagonals, [0, 1, 2], shape=(number_of_signals - 2, number_of_signals))
45+
diagonals = [
46+
np.ones(number_of_signals - 2),
47+
-2 * np.ones(number_of_signals - 2),
48+
np.ones(number_of_signals - 2),
49+
]
50+
smoothness_term = 0.25 * scipy.sparse.diags(
51+
diagonals, [0, 1, 2], shape=(number_of_signals - 2, number_of_signals)
52+
)
4753

4854
hessian_helper_matrix = scipy.sparse.block_diag([smoothness_term.T @ smoothness_term] * number_of_components)
49-
sequence = np.arange(number_of_signals * number_of_components).reshape(number_of_components, number_of_signals).T.flatten()
55+
sequence = (
56+
np.arange(number_of_signals * number_of_components)
57+
.reshape(number_of_components, number_of_signals)
58+
.T.flatten()
59+
)
5060
hessian_helper_matrix = hessian_helper_matrix[sequence, :][:, sequence]
5161

5262
return {
@@ -57,7 +67,7 @@ def initialize_variables(data_input, number_of_components, data_type, sparsity=1
5767
"smoothness": smoothness,
5868
"sparsity": sparsity,
5969
"smoothness_term": smoothness_term,
60-
"hessian_helper_matrix": hessian_helper_matrix
70+
"hessian_helper_matrix": hessian_helper_matrix,
6171
}
6272

6373

diffpy/snmf/optimizers.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def get_weights(stretched_component_gram_matrix, linear_coefficient, lower_bound
2020
Has length C.
2121
2222
lower_bound: 1d array like
23-
The lower bound on the values of the output weights. Has the same dimensions of the function output. Each
23+
The lower bound on the values of the output weights. Has the same dimensions of the function output. Each
2424
element in 'lower_bound' determines the minimum value the corresponding element in the function output may take.
2525
2626
upper_bound: 1d array like
@@ -43,8 +43,9 @@ def get_weights(stretched_component_gram_matrix, linear_coefficient, lower_bound
4343
solution_variable = cvxpy.Variable(problem_size)
4444

4545
objective = cvxpy.Minimize(
46-
linear_coefficient.T @ solution_variable + 0.5 * cvxpy.quad_form(solution_variable,
47-
stretched_component_gram_matrix))
46+
linear_coefficient.T @ solution_variable
47+
+ 0.5 * cvxpy.quad_form(solution_variable, stretched_component_gram_matrix)
48+
)
4849
constraints = [lower_bound <= solution_variable, solution_variable <= upper_bound]
4950

5051
cvxpy.Problem(objective, constraints).solve()

diffpy/snmf/stretchednmfapp.py

+37-15
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,47 @@
55
from diffpy.snmf.containers import ComponentSignal
66
from diffpy.snmf.io import load_input_signals, initialize_variables
77

8-
ALLOWED_DATA_TYPES = ['powder_diffraction', 'pd', 'pair_distribution_function', 'pdf']
8+
ALLOWED_DATA_TYPES = ["powder_diffraction", "pd", "pair_distribution_function", "pdf"]
99

1010

1111
def create_parser():
1212
parser = argparse.ArgumentParser(
13-
prog="stretched_nmf",
14-
description="Stretched Nonnegative Matrix Factorization"
13+
prog="stretched_nmf", description="Stretched Nonnegative Matrix Factorization"
1514
)
16-
parser.add_argument('-i', '--input-directory', type=str, default=None,
17-
help="Directory containing experimental data. Defaults to current working directory.")
18-
parser.add_argument('-o', '--output-directory', type=str,
19-
help="The directory where the results will be written. Defaults to '<input_directory>/snmf_results'.")
20-
parser.add_argument('t', '--data-type', type=str, default=None, choices=ALLOWED_DATA_TYPES,
21-
help="The type of the experimental data.")
22-
parser.add_argument('-l', '--lift-factor', type=float, default=1,
23-
help="The lifting factor. Data will be lifted by lifted_data = data + abs(min(data) * lift). Default is 1.")
24-
parser.add_argument('number-of-components', type=int,
25-
help="The number of component signals for the NMF decomposition. Must be an integer greater than 0")
26-
parser.add_argument('-v', '--version', action='version', help='Print the software version number')
15+
parser.add_argument(
16+
"-i",
17+
"--input-directory",
18+
type=str,
19+
default=None,
20+
help="Directory containing experimental data. Defaults to current working directory.",
21+
)
22+
parser.add_argument(
23+
"-o",
24+
"--output-directory",
25+
type=str,
26+
help="The directory where the results will be written. Defaults to '<input_directory>/snmf_results'.",
27+
)
28+
parser.add_argument(
29+
"t",
30+
"--data-type",
31+
type=str,
32+
default=None,
33+
choices=ALLOWED_DATA_TYPES,
34+
help="The type of the experimental data.",
35+
)
36+
parser.add_argument(
37+
"-l",
38+
"--lift-factor",
39+
type=float,
40+
default=1,
41+
help="The lifting factor. Data will be lifted by lifted_data = data + abs(min(data) * lift). Default is 1.",
42+
)
43+
parser.add_argument(
44+
"number-of-components",
45+
type=int,
46+
help="The number of component signals for the NMF decomposition. Must be an integer greater than 0",
47+
)
48+
parser.add_argument("-v", "--version", action="version", help="Print the software version number")
2749
args = parser.parse_args()
2850
return args
2951

@@ -35,5 +57,5 @@ def main():
3557
grid, input_data = load_input_signals(args.input_directory)
3658
lifted_input_data = lift_data(input_data, args.lift_factor)
3759
variables = initialize_variables(lifted_input_data, args.number_of_components, args.data_type)
38-
components = initialize_components(variables['number_of_components'], variables['number_of_signals'], grid)
60+
components = initialize_components(variables["number_of_components"], variables["number_of_signals"], grid)
3961
return components

diffpy/snmf/subroutines.py

+51-23
Original file line numberDiff line numberDiff line change
@@ -170,11 +170,15 @@ def update_weights(components, data_input, method=None):
170170
stretched_components = np.zeros((signal_length, number_of_components))
171171
for i, component in enumerate(components):
172172
stretched_components[:, i] = component.apply_stretch(signal)[0]
173-
if method == 'align':
173+
if method == "align":
174174
weights = lsqnonneg(stretched_components, data_input[:, signal])
175175
else:
176-
weights = get_weights(stretched_components.T @ stretched_components,
177-
-stretched_components.T @ data_input[:, signal], 0, 1)
176+
weights = get_weights(
177+
stretched_components.T @ stretched_components,
178+
-stretched_components.T @ data_input[:, signal],
179+
0,
180+
1,
181+
)
178182
weight_matrix[:, signal] = weights
179183
return weight_matrix
180184

@@ -236,13 +240,16 @@ def initialize_arrays(number_of_components, number_of_moments, signal_length):
236240
"""
237241
component_matrix_guess = np.random.rand(signal_length, number_of_components)
238242
weight_matrix_guess = np.random.rand(number_of_components, number_of_moments)
239-
stretching_matrix_guess = np.ones(number_of_components, number_of_moments) + np.random.randn(number_of_components,
240-
number_of_moments) * 1e-3
243+
stretching_matrix_guess = (
244+
np.ones(number_of_components, number_of_moments)
245+
+ np.random.randn(number_of_components, number_of_moments) * 1e-3
246+
)
241247
return component_matrix_guess, weight_matrix_guess, stretching_matrix_guess
242248

243249

244-
def objective_function(residual_matrix, stretching_factor_matrix, smoothness, smoothness_term, component_matrix,
245-
sparsity):
250+
def objective_function(
251+
residual_matrix, stretching_factor_matrix, smoothness, smoothness_term, component_matrix, sparsity
252+
):
246253
"""Defines the objective function of the algorithm and returns its value.
247254
248255
Calculates the value of '(||residual_matrix||_F) ** 2 + smoothness * (||smoothness_term *
@@ -284,8 +291,11 @@ def objective_function(residual_matrix, stretching_factor_matrix, smoothness, sm
284291
residual_matrix = np.asarray(residual_matrix)
285292
stretching_factor_matrix = np.asarray(stretching_factor_matrix)
286293
component_matrix = np.asarray(component_matrix)
287-
return .5 * np.linalg.norm(residual_matrix, 'fro') ** 2 + .5 * smoothness * np.linalg.norm(
288-
smoothness_term @ stretching_factor_matrix.T, 'fro') ** 2 + sparsity * np.sum(np.sqrt(component_matrix))
294+
return (
295+
0.5 * np.linalg.norm(residual_matrix, "fro") ** 2
296+
+ 0.5 * smoothness * np.linalg.norm(smoothness_term @ stretching_factor_matrix.T, "fro") ** 2
297+
+ sparsity * np.sum(np.sqrt(component_matrix))
298+
)
289299

290300

291301
def get_stretched_component(stretching_factor, component, signal_length):
@@ -325,11 +335,23 @@ def stretched_component_func(stretching_factor):
325335
stretched_component_gra = derivative_func(stretching_factor)
326336
stretched_component_hess = second_derivative_func(stretching_factor)
327337

328-
return np.asarray(stretched_component), np.asarray(stretched_component_gra), np.asarray(stretched_component_hess)
329-
330-
331-
def update_weights_matrix(component_amount, signal_length, stretching_factor_matrix, component_matrix, data_input,
332-
moment_amount, weights_matrix, method):
338+
return (
339+
np.asarray(stretched_component),
340+
np.asarray(stretched_component_gra),
341+
np.asarray(stretched_component_hess),
342+
)
343+
344+
345+
def update_weights_matrix(
346+
component_amount,
347+
signal_length,
348+
stretching_factor_matrix,
349+
component_matrix,
350+
data_input,
351+
moment_amount,
352+
weights_matrix,
353+
method,
354+
):
333355
"""Update the weight factors matrix.
334356
335357
Parameters
@@ -376,21 +398,25 @@ def update_weights_matrix(component_amount, signal_length, stretching_factor_mat
376398
for i in range(moment_amount):
377399
stretched_components = np.zeros((signal_length, component_amount))
378400
for n in range(component_amount):
379-
stretched_components[:, n] = get_stretched_component(stretching_factor_matrix[n, i], component_matrix[:, n],
380-
signal_length)[0]
381-
if method == 'align':
401+
stretched_components[:, n] = get_stretched_component(
402+
stretching_factor_matrix[n, i], component_matrix[:, n], signal_length
403+
)[0]
404+
if method == "align":
382405
weight = lsqnonneg(stretched_components[0:signal_length, :], data_input[0:signal_length, i])
383406
else:
384407
weight = get_weights(
385408
stretched_components[0:signal_length, :].T @ stretched_components[0:signal_length, :],
386409
-1 * stretched_components[0:signal_length, :].T @ data_input[0:signal_length, i],
387-
0, 1)
410+
0,
411+
1,
412+
)
388413
weights_matrix[:, i] = weight
389414
return weights_matrix
390415

391416

392-
def get_residual_matrix(component_matrix, weights_matrix, stretching_matrix, data_input, moment_amount,
393-
component_amount, signal_length):
417+
def get_residual_matrix(
418+
component_matrix, weights_matrix, stretching_matrix, data_input, moment_amount, component_amount, signal_length
419+
):
394420
"""Obtains the residual matrix between the experimental data and calculated data
395421
396422
Calculates the difference between the experimental data and the reconstructed experimental data created from the
@@ -442,9 +468,11 @@ def get_residual_matrix(component_matrix, weights_matrix, stretching_matrix, dat
442468
for m in range(moment_amount):
443469
residual = residual_matrx[:, m]
444470
for k in range(component_amount):
445-
residual = residual + weights_matrix[k, m] * get_stretched_component(stretching_matrix[k, m],
446-
component_matrix[:, k], signal_length)[
447-
0]
471+
residual = (
472+
residual
473+
+ weights_matrix[k, m]
474+
* get_stretched_component(stretching_matrix[k, m], component_matrix[:, k], signal_length)[0]
475+
)
448476
residual_matrx[:, m] = residual
449477
return residual_matrx
450478

0 commit comments

Comments
 (0)