def __init__(self, K, s, r=None): U, S, VT, r_ = TSVD(K) if r is None: r = r_ self.truncation_index = r signal = s.y[0].components[0].T if isinstance(s, cp.CSDM) else s ( self.compressed_K, compressed_signal, projectedSignal, __, # guess_solution, ) = reduced_subspace_kernel_and_data(U[:, :r], S[:r], VT[:r, :], signal) factor = signal.size / compressed_signal.size print(f"compression factor = {factor}") self.filtered_s = projectedSignal self.compressed_s = compressed_signal if isinstance(s, cp.CSDM): self.compressed_s = cp.as_csdm(self.compressed_s.T.copy()) self.filtered_s = cp.as_csdm(self.filtered_s.T.copy()) if len(s.x) > 1: self.compressed_s.x[1] = s.x[1] self.filtered_s.x[1] = s.x[1]
def test_get_spectral_dimensions_odd_count_positive_increment(): # odd # complex_fft csdm = cp.as_csdm(np.arange(15)) csdm.x[0] = cp.LinearDimension(count=15, increment="1 Hz", complex_fft=True) res = {"count": 15, "spectral_width": 15, "reference_offset": 0} assertion(csdm, res, "odd complex_fft") csdm.x[0] = cp.LinearDimension(count=15, increment="3.4 Hz", complex_fft=True) res = {"count": 15, "spectral_width": 51, "reference_offset": 0} assertion(csdm, res, "odd complex_fft") # odd # complex_fft # coordinates_offset csdm.x[0] = cp.LinearDimension(count=15, increment="1 Hz", complex_fft=True, coordinates_offset="12 Hz") res = {"count": 15, "spectral_width": 15, "reference_offset": 12} assertion(csdm, res, "odd complex_fft coordinates_offset") csdm.x[0] = cp.LinearDimension(count=15, increment="3.4 Hz", coordinates_offset="12 Hz", complex_fft=True) res = {"count": 15, "spectral_width": 51, "reference_offset": 12} assertion(csdm, res, "odd complex_fft coordinates_offset") # odd csdm = cp.as_csdm(np.arange(15)) csdm.x[0] = cp.LinearDimension(count=15, increment="1 Hz") res = {"count": 15, "spectral_width": 15, "reference_offset": 7} assertion(csdm, res, "odd complex_fft") csdm.x[0] = cp.LinearDimension(count=15, increment="3.4 Hz") res = {"count": 15, "spectral_width": 51, "reference_offset": 23.8} assertion(csdm, res, "odd complex_fft") # odd # coordinates_offset csdm.x[0] = cp.LinearDimension(count=15, increment="1 Hz", coordinates_offset="12 Hz") res = {"count": 15, "spectral_width": 15, "reference_offset": 19} assertion(csdm, res, "odd coordinates_offset") csdm.x[0] = cp.LinearDimension(count=15, increment="3.4 Hz", coordinates_offset="12 Hz") res = {"count": 15, "spectral_width": 51, "reference_offset": 35.8} assertion(csdm, res, "odd coordinates_offset")
def test_method_exp_sim(): spin_system = SpinSystem(sites=[ Site( isotope="27Al", isotropic_chemical_shift=64.5, # in ppm quadrupolar={ "Cq": 3.22e6, "eta": 0.66 }, # Cq is in Hz ) ]) data = cp.as_csdm(np.random.rand(1024, 512)) method = ThreeQ_VAS( channels=["27Al"], magnetic_flux_density=7, spectral_dimensions=[ { "count": 1024, "spectral_width": 5000, "reference_offset": -3e3 }, { "count": 512, "spectral_width": 10000, "reference_offset": 4e3 }, ], experiment=data, ) sim = Simulator() sim.spin_systems = [spin_system] sim.methods = [method] sim.run()
def residuals(self, K, s): r"""Return the residual as the difference the data and the predicted data(fit), following .. math:: \text{residuals} = {\bf s - Kf^*} where :math:`{\bf f^*}` is the optimum solution. Args ---- K: ndarray. A :math:`m \times n` kernel matrix, :math:`{\bf K}`. A numpy array of shape (m, n). s: ndarray ot CSDM object. A csdm object or a :math:`m \times m_\text{count}` signal matrix, :math:`{\bf s}`. Return ------ ndarray or CSDM object. If `s` is a csdm object, returns a csdm object with the residuals. If `s` is a numpy array, return a :math:`m \times m_\text{count}` residue matrix. csdm object """ s_ = s.y[0].components[0].T if isinstance(s, cp.CSDM) else s predict = np.squeeze(self.predict(K)) residue = s_ - predict if not isinstance(s, cp.CSDM): return residue residue = cp.as_csdm(residue.T.copy()) residue._dimensions = s._dimensions return residue
def _sol_to_csdm(self, s): """Pack solution as csdm object""" if not isinstance(s, cp.CSDM): return self.f = cp.as_csdm(self.f) for i, dim in enumerate(self.inverse_dimension): app = dim.application or {} if "com.github.deepanshs.mrinversion" in app: meta = app["com.github.deepanshs.mrinversion"] is_log = meta.get("log", False) if is_log: coords = np.log10(dim.coordinates.value) self.inverse_dimension[i] = cp.as_dimension( array=coords, label=meta["label"]) if len(s.dimensions) > 1 and len(self.f.shape) == 3: self.f.dimensions[2] = s.dimensions[1] self.f.dimensions[1] = self.inverse_dimension[1] self.f.dimensions[0] = self.inverse_dimension[0] elif len(s.dimensions) == 1 and len(self.f.shape) == 2: self.f.dimensions[1] = self.inverse_dimension[1] self.f.dimensions[0] = self.inverse_dimension[0] elif len(s.dimensions) > 1: self.f.dimensions[1] = s.dimensions[1] self.f.dimensions[0] = self.inverse_dimension[0]
def test_2D_area(): data = np.zeros((256, 128), dtype=float) data[128, 64] = 1.0 csdm_obj = cp.as_csdm(data) # test00 PS = [ sp.IFFT(dim_index=(0, 1)), sp.apodization.Gaussian(FWHM="35", dim_index=0), sp.apodization.Gaussian(FWHM="55", dim_index=1), sp.FFT(dim_index=(0, 1)), ] post_sim = sp.SignalProcessor(operations=PS) data_new = post_sim.apply_operations(data=csdm_obj.copy()) _, __, y1 = data_new.to_list() assert np.allclose(y1.sum(), data.sum()) # test01 PS = [ sp.IFFT(dim_index=(0, 1)), sp.apodization.Gaussian(FWHM="35", dim_index=0), sp.apodization.Exponential(FWHM="55", dim_index=1), sp.FFT(dim_index=(0, 1)), ] post_sim = sp.SignalProcessor(operations=PS) data_new = post_sim.apply_operations(data=csdm_obj.copy()) _, __, y1 = data_new.to_list() assert np.allclose(y1.sum(), data.sum())
def fit(self, K, s): r"""Fit the model using the coordinate descent method from scikit-learn for all alpha anf lambda values using the `n`-folds cross-validation technique. The cross-validation metric is the mean squared error. Args: K: A :math:`m \times n` kernel matrix, :math:`{\bf K}`. A numpy array of shape (m, n). s: A :math:`m \times m_\text{count}` signal matrix, :math:`{\bf s}` as a csdm object or a numpy array or shape (m, m_count). """ s_, self.scale = prepare_signal(s) sin_val = np.linalg.svd(K, full_matrices=False)[1] K_, s_ = np.asfortranarray(K), np.asfortranarray(s_) lipszit = sin_val[0]**2 # test train CV set k_train, s_train, k_test, s_test, m = test_train_set( K_, s_, self.folds, self.randomize, self.times) self.cv_map, self.std, _, _, _, self.prediction_error = fista_cv.fista( matrix=k_train, s=s_train, matrixtest=k_test, stest=s_test, lambdaval=self.cv_lambdas, maxiter=self.max_iterations, nonnegative=int(self.positive), linv=(1 / lipszit), tol=self.tolerance, npros=self.n_jobs, m=m, ) # subtract the variance. # self.cv_map -= (self.sigma / self.scale) ** 2 self.cv_map = np.abs(self.cv_map) lambdas = np.log10(self.cv_lambdas) l1_index, l2_index = calculate_opt_lambda(self.cv_map, self.std) lambda1, _ = lambdas[l1_index], lambdas[l2_index] self.hyperparameters["lambda"] = 10**lambda1 # Calculate the solution using the complete data at the optimized lambda self.opt = LassoFista( lambda1=self.hyperparameters["lambda"], max_iterations=self.max_iterations, tolerance=self.tolerance, positive=self.positive, inverse_dimension=self.inverse_dimension, ) self.opt.fit(K, s) self.f = self.opt.f # convert cv_map to csdm self.cv_map = cp.as_csdm(np.squeeze(self.cv_map.T.copy())) self.cv_map.y[0].component_labels = ["log10"] d0 = cp.as_dimension(np.log10(self.cv_lambdas), label="log(λ)") self.cv_map.dimensions[0] = d0 self.cross_validation_curve = self.cv_map
def test_get_spectral_dimensions_even_count_positive_increment(): # even # complex_fft csdm = cp.as_csdm(np.arange(10)) csdm.x[0] = cp.LinearDimension(count=10, increment="1 Hz", complex_fft=True) res = {"count": 10, "spectral_width": 10, "reference_offset": 0} assertion(csdm, res, "even complex_fft") csdm.x[0] = cp.LinearDimension(count=10, increment="3.4 Hz", complex_fft=True) res = {"count": 10, "spectral_width": 34, "reference_offset": 0} assertion(csdm, res, "even complex_fft") # even # complex_fft # coordinates_offset csdm.x[0] = cp.LinearDimension(count=10, increment="1 Hz", coordinates_offset="-0.05 kHz", complex_fft=True) res = {"count": 10, "spectral_width": 10, "reference_offset": -50} assertion(csdm, res, "even complex_fft coordinates_offset") csdm.x[0] = cp.LinearDimension(count=10, increment="3.4 Hz", coordinates_offset="-0.05 kHz", complex_fft=True) res = {"count": 10, "spectral_width": 34, "reference_offset": -50} assertion(csdm, res, "even complex_fft coordinates_offset") # even csdm.x[0] = cp.LinearDimension(count=10, increment="1 Hz") res = {"count": 10, "spectral_width": 10, "reference_offset": 5} assertion(csdm, res, "even") csdm.x[0] = cp.LinearDimension(count=10, increment="3.4 Hz") res = {"count": 10, "spectral_width": 34, "reference_offset": 17} assertion(csdm, res, "even") # even # coordinates_offset csdm.x[0] = cp.LinearDimension(count=10, increment="1 Hz", coordinates_offset="5 Hz", label="1H") res = { "count": 10, "spectral_width": 10, "reference_offset": 10, "label": "1H" } assertion(csdm, res, "even coordinates_offset") csdm.x[0] = cp.LinearDimension(count=10, increment="3.4 Hz", coordinates_offset="-0.05 kHz") res = {"count": 10, "spectral_width": 34, "reference_offset": -33} assertion(csdm, res, "even coordinates_offset")
def fit(self, K, s, warm_start=False): s_, self.scale = prepare_signal(s) sin_val = np.linalg.svd(K, full_matrices=False)[1] K_, s_ = np.asfortranarray(K), np.asfortranarray(s_) self.f = np.asfortranarray(np.zeros((K_.shape[1], s_.shape[1]))) lipszit = sin_val[0]**2 if warm_start: self.f_1 = np.asfortranarray(np.zeros((K_.shape[1], 1))) _ = fista.fista( matrix=K_, s=s_.mean(axis=1), lambd=self.hyperparameters["lambda"], maxiter=self.max_iterations, f_k=self.f_1, nonnegative=int(self.positive), linv=(1 / lipszit), tol=self.tolerance, npros=1, ) self.f = np.asfortranarray(np.tile(self.f_1, s_.shape[1])) _ = fista.fista( matrix=K_, s=s_, lambd=self.hyperparameters["lambda"], maxiter=self.max_iterations, f_k=self.f, nonnegative=int(self.positive), linv=(1 / lipszit), tol=self.tolerance, npros=1, ) self.f *= self.scale if not isinstance(s, cp.CSDM): return # CSDM pack self.f = cp.as_csdm(np.squeeze(self.f.T)) app = self.inverse_dimension.application or {} if "com.github.deepanshs.mrinversion" in app: meta = app["com.github.deepanshs.mrinversion"] is_log = meta.get("log", False) if is_log: # unit = self.inverse_dimension.coordinates.unit coords = np.log10(self.inverse_dimension.coordinates.value) self.inverse_dimension = cp.as_dimension(array=coords, label=meta["label"]) if len(s.dimensions) > 1: self.f.dimensions[1] = s.dimensions[1] self.f.dimensions[0] = self.inverse_dimension
def cv_map_to_csdm(self): # convert cv_map to csdm self.cv_map = cp.as_csdm(np.squeeze(self.cv_map.T.copy())) if len(self.cv_alphas) != 1: d0 = cp.as_dimension(-np.log10(self.cv_alphas), label="-log(α)") self.cv_map.dimensions[0] = d0 if len(self.cv_lambdas) == 1: return d1 = cp.as_dimension(-np.log10(self.cv_lambdas), label="-log(λ)") if len(self.cv_alphas) != 1: self.cv_map.dimensions[1] = d1 else: self.cv_map.dimensions[0] = d1
def test_get_spectral_dimensions_odd_count_negative_increment(): # odd csdm = cp.as_csdm(np.arange(15)) csdm.x[0] = cp.LinearDimension(count=15, increment="-1 Hz", label="1H") res = { "count": 15, "spectral_width": 15, "reference_offset": -7, "label": "1H" } assertion(csdm, res, "odd") csdm.x[0] = cp.LinearDimension(count=15, increment="-3.4 Hz", label="1H") res = { "count": 15, "spectral_width": 51, "reference_offset": -23.8, "label": "1H" } assertion(csdm, res, "odd") # even # coordinates_offset csdm.x[0] = cp.LinearDimension(count=15, increment="-1 Hz", coordinates_offset="-10 Hz", label="1H") res = { "count": 15, "spectral_width": 15, "reference_offset": -17, "label": "1H" } assertion(csdm, res, "odd coordinates_offset") csdm.x[0] = cp.LinearDimension(count=15, increment="-3.4 Hz", coordinates_offset="-10 Hz", label="1H") res = { "count": 15, "spectral_width": 51, "reference_offset": -33.8, "label": "1H" } assertion(csdm, res, "odd coordinates_offset")
def test_get_spectral_dimensions_even_count_negative_increment(): # even csdm = cp.as_csdm(np.arange(10)) csdm.x[0] = cp.LinearDimension(count=10, increment="-1 Hz", label="1H") res = { "count": 10, "spectral_width": 10, "reference_offset": -4, "label": "1H" } assertion(csdm, res, "even") csdm.x[0] = cp.LinearDimension(count=10, increment="-3.4 Hz", label="1H") res = { "count": 10, "spectral_width": 34, "reference_offset": -13.6, "label": "1H" } assertion(csdm, res, "even") # even # coordinates_offset csdm.x[0] = cp.LinearDimension(count=10, increment="-1 Hz", coordinates_offset="-10 Hz", label="1H") res = { "count": 10, "spectral_width": 10, "reference_offset": -14, "label": "1H" } assertion(csdm, res, "even coordinates_offset") csdm.x[0] = cp.LinearDimension(count=10, increment="-3.4 Hz", coordinates_offset="-10 Hz", label="1H") res = { "count": 10, "spectral_width": 34, "reference_offset": -23.6, "label": "1H" } assertion(csdm, res, "even coordinates_offset")
def test_generic(): # 7 csdm = cp.as_csdm(np.arange(10)) csdm.x[0] = cp.LinearDimension( count=10, increment="-1 Hz", coordinates_offset="-10 Hz", origin_offset="100 MHz", label="1H", ) res = { "count": 10, "spectral_width": 10, "reference_offset": -14, "origin_offset": 100e6, "label": "1H", } assertion(csdm, res, "7")
def test_01(): post_sim = sp.SignalProcessor() operations = [ sp.IFFT(), sp.apodization.Gaussian(FWHM="12 K", dim_index=0, dv_index=0), sp.FFT(), ] post_sim.operations = operations with pytest.raises(ValueError, match="The data must be a CSDM object."): post_sim.apply_operations([]) data = cp.as_csdm(np.arange(20)) data.x[0] = cp.LinearDimension(count=20, increment="10 K") post_sim.apply_operations(data) # to dict with units dict_ = post_sim.json() assert dict_ == { "operations": [ { "dim_index": 0, "function": "IFFT" }, { "function": "apodization", "type": "Gaussian", "FWHM": "12.0 K", "dim_index": 0, "dv_index": 0, }, { "dim_index": 0, "function": "FFT" }, ], } # parse dict with units post_sim_2 = sp.SignalProcessor.parse_dict_with_units(dict_) assert post_sim.operations == post_sim_2.operations
def test_simulator_2(): sim = Simulator() sim.spin_systems = [ SpinSystem( sites=[Site(isotope="1H"), Site(isotope="23Na")], couplings=[Coupling(site_index=[0, 1], isotropic_j=15)], ) ] sim.methods = [ BlochDecaySpectrum( channels=["1H"], spectral_dimensions=[{ "count": 10 }], experiment=cp.as_csdm(np.arange(10)), ) ] sim.name = "test" sim.label = "test0" sim.description = "testing-testing 1.2.3" sim.run() # save sim.save("test_sim_save.temp") sim_load = Simulator.load("test_sim_save.temp") sim_load_data = sim_load.methods[0].simulation sim_data = sim.methods[0].simulation sim_load_data._timestamp = "" assert sim_load_data.dict() == sim_data.dict() sim_load.methods[0].simulation = None sim.methods[0].simulation = None assert sim_load.spin_systems == sim.spin_systems assert sim_load.methods == sim.methods assert sim_load.name == sim.name assert sim_load.description == sim.description os.remove("test_sim_save.temp")
def test_get_spectral_dimensions(): # 1 csdm = cp.as_csdm(np.arange(10)) csdm.dimensions[0] = cp.LinearDimension(count=10, increment="1 Hz", complex_fft=True) res = {"count": 10, "spectral_width": 10, "reference_offset": 0} assert get_spectral_dimensions(csdm)[0] == res # 2 csdm.dimensions[0] = cp.LinearDimension(count=10, increment="1 Hz", coordinates_offset="-0.05 kHz", complex_fft=True) res = {"count": 10, "spectral_width": 10, "reference_offset": -50} assert get_spectral_dimensions(csdm)[0] == res # 3 csdm.dimensions[0] = cp.LinearDimension(count=10, increment="1 Hz") res = {"count": 10, "spectral_width": 10, "reference_offset": 5} assert get_spectral_dimensions(csdm)[0] == res # 4 csdm.dimensions[0] = cp.LinearDimension(count=10, increment="1 Hz", label="1H") res = { "count": 10, "spectral_width": 10, "reference_offset": 5, "label": "1H" } assert get_spectral_dimensions(csdm)[0] == res
def test_7(): site = Site(isotope="23Na") sys = SpinSystem(sites=[site], abundance=50) sim = Simulator() sim.spin_systems = [sys, sys] sim.methods = [BlochDecayCTSpectrum(channels=["23Na"])] sim.methods[0].experiment = cp.as_csdm(np.zeros(1024)) processor = sp.SignalProcessor(operations=[ sp.IFFT(dim_index=0), sp.apodization.Gaussian(FWHM="0.2 kHz", dim_index=0), sp.FFT(dim_index=0), ]) def test_array(): sim.run() dataset = processor.apply_operations(sim.methods[0].simulation) data_sum = 0 for dv in dataset.y: data_sum += dv.components[0] params = sf.make_LMFIT_params(sim, processor) a = sf.LMFIT_min_function(params, sim, processor) np.testing.assert_almost_equal(-a, data_sum, decimal=8) dat = sf.add_csdm_dvs(dataset.real) fits = sf.bestfit(sim, processor) assert sf.add_csdm_dvs(fits[0]) == dat res = sf.residuals(sim, processor) assert res[0] == -dat test_array() sim.config.decompose_spectrum = "spin_system" test_array()
def to_Haeberlen_grid(csdm_object, zeta, eta, n=5): """Convert the three-dimensional p(iso, x, y) to p(iso, zeta, eta) tensor distribution. Args ---- csdm_object: CSDM A CSDM object containing the 3D p(iso, x, y) distribution. zeta: CSDM.Dimension A CSDM dimension object describing the zeta dimension. eta: CSDM.Dimension A CSDM dimension object describing the eta dimension. n: int An integer used in linear interpolation of the data. The default is 5. """ [item.to("ppm", "nmr_frequency_ratio") for item in csdm_object.x] data = csdm_object.y[0].components[0] iso = csdm_object.x[2].coordinates.value reg_x, reg_y = (csdm_object.x[i].coordinates.value for i in range(2)) dx = reg_x[1] - reg_x[0] dy = reg_y[1] - reg_y[0] sol = np.zeros((data.shape[0], zeta.count, eta.count)) bins = [zeta.count, eta.count] d_zeta = zeta.increment.value / 2 d_eta = eta.increment.value / 2 range_ = [ [ zeta.coordinates[0].value - d_zeta, zeta.coordinates[-1].value + d_zeta ], [eta.coordinates[0] - d_eta, eta.coordinates[-1] + d_eta], ] avg_range_x = (np.arange(n) - (n - 1) / 2) * dx / n avg_range_y = (np.arange(n) - (n - 1) / 2) * dy / n for x_item in avg_range_x: for y_item in avg_range_y: x__ = np.abs(reg_x + x_item) y__ = np.abs(reg_y + y_item) x_, y_ = np.meshgrid(x__, y__) x_ = x_.ravel() y_ = y_.ravel() zeta_grid = np.sqrt(x_**2 + y_**2) eta_grid = np.ones(zeta_grid.shape) index = np.where(x_ < y_) eta_grid[index] = (4 / np.pi) * np.arctan(x_[index] / y_[index]) index = np.where(x_ > y_) zeta_grid[index] *= -1 eta_grid[index] = (4 / np.pi) * np.arctan(y_[index] / x_[index]) index = np.where(x_ == y_) np.append(zeta, -zeta_grid[index]) np.append(eta, np.ones(index[0].size)) for i in range(iso.size): weight = deepcopy(data[i]).ravel() weight[index] /= 2 np.append(weight, weight[index]) sol_, _, _ = np.histogram2d(zeta_grid, eta_grid, weights=weight, bins=bins, range=range_) sol[i] += sol_ sol /= n * n del zeta_grid, eta_grid, index, x_, y_, avg_range_x, avg_range_y csdm_new = cp.as_csdm(sol) csdm_new.x[0] = eta csdm_new.x[1] = zeta csdm_new.x[2] = csdm_object.x[2] return csdm_new
def test_method(): # test-1 single dimension method # parse dict with units event_dictionary = { "fraction": 0.5, "freq_contrib": freq_default, "magnetic_flux_density": "9.6 T", "rotor_frequency": "1 kHz", "rotor_angle": "54.735 deg", } dimension_dictionary = { "count": 1024, "spectral_width": "100 Hz", "reference_offset": "0 GHz", "events": [event_dictionary], } method_dictionary = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "spectral_dimensions": [dimension_dictionary], } the_method = Method.parse_dict_with_units(method_dictionary) basic_method_tests(the_method) # test-2 two dimensional two events method # parse dict with units event_dictionary = { "fraction": 0.5, "freq_contrib": freq_default, "magnetic_flux_density": "9.6 T", "rotor_frequency": "1 kHz", "rotor_angle": "54.735 deg", } dimension_dictionary = { "count": 1024, "spectral_width": "100 Hz", "reference_offset": "0 GHz", "events": [event_dictionary, event_dictionary], } method_dictionary = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "spectral_dimensions": [dimension_dictionary, dimension_dictionary], } the_method = Method.parse_dict_with_units(method_dictionary) # test experiment assignment assert the_method.experiment is None with pytest.raises(ValidationError, match="Unable to read the data."): the_method.experiment = "test" data = np.random.rand(100).reshape(10, 10) csdm_data = cp.as_csdm(data) csdm_data.dimensions[0] *= cp.ScalarQuantity("Hz") csdm_data.dimensions[1] *= cp.ScalarQuantity("Hz") the_method.experiment = csdm_data assert isinstance(the_method.experiment, cp.CSDM) csdm_dict = csdm_data.to_dict() the_method.experiment = csdm_dict assert isinstance(the_method.experiment, cp.CSDM) assert the_method.experiment == csdm_data # to_dict_with_unit() event_dictionary_ = { "fraction": 0.5, "transition_query": { "P": { "channel-1": [[-1.0]] } }, } dimension_dictionary_ = { "count": 1024, "spectral_width": "100.0 Hz", "reference_offset": "0.0 Hz", "events": [event_dictionary_, event_dictionary_], } method_dictionary_ = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "magnetic_flux_density": "9.6 T", "rotor_frequency": "1000.0 Hz", "rotor_angle": "0.9553059660790962 rad", "spectral_dimensions": [dimension_dictionary_, dimension_dictionary_], "experiment": csdm_data.to_dict(), } assert the_method.json() == method_dictionary_ # reduced_dict() event_dictionary_ = { "fraction": 0.5, "freq_contrib": freq_default, "magnetic_flux_density": 9.6, "rotor_frequency": 1000.0, "rotor_angle": 0.9553059660790962, "transition_query": { "P": { "channel-1": [[-1.0]] } }, } dimension_dictionary_ = { "count": 1024, "spectral_width": 100.0, "reference_offset": 0.0, "events": [event_dictionary_, event_dictionary_], } method_dictionary_ = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "spectral_dimensions": [dimension_dictionary_, dimension_dictionary_], "experiment": csdm_data.to_dict(), } assert the_method.reduced_dict() == method_dictionary_ # update_spectral_dimension_attributes_from_experiment the_method.update_spectral_dimension_attributes_from_experiment() for i in range(2): assert the_method.spectral_dimensions[i].count == 10 assert the_method.spectral_dimensions[i].spectral_width == 10 assert the_method.spectral_dimensions[i].reference_offset == 0 assert the_method.spectral_dimensions[i].origin_offset == 0
def test_method(): # test-1 single dimension method # parse dict with units method_dictionary = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "magnetic_flux_density": "9.6 T", "rotor_frequency": "1 kHz", "rotor_angle": "54.735 deg", "spectral_dimensions": [dimension_dictionary], } the_method = Method.parse_dict_with_units(method_dictionary) basic_method_tests(the_method) # test-2 two dimensional two events method # parse dict with units dimension_dictionary["events"].append(event_dictionary) method_dictionary = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "magnetic_flux_density": "9.6 T", "rotor_frequency": "1 kHz", "rotor_angle": "54.735 deg", "spectral_dimensions": [dimension_dictionary, dimension_dictionary], } the_method = Method.parse_dict_with_units(method_dictionary) # test experiment assignment assert the_method.experiment is None with pytest.raises(ValidationError, match="Unable to read the data."): the_method.experiment = "test" data = np.random.rand(100).reshape(10, 10) csdm_data = cp.as_csdm(data) csdm_data.x[0] *= cp.ScalarQuantity("Hz") csdm_data.x[1] *= cp.ScalarQuantity("Hz") the_method.experiment = csdm_data the_method.simulation = csdm_data assert isinstance(the_method.experiment, cp.CSDM) assert isinstance(the_method.simulation, cp.CSDM) csdm_dict = csdm_data.to_dict() the_method.experiment = csdm_dict assert isinstance(the_method.experiment, cp.CSDM) assert the_method.experiment == csdm_data the_method.simulation = csdm_dict assert isinstance(the_method.simulation, cp.CSDM) assert the_method.simulation == csdm_data # json() event_dictionary_ = { "fraction": 0.5, "transition_query": [{ "ch1": { "P": [-1] } }] } dimension_dictionary_ = { "count": 1024, "spectral_width": "100.0 Hz", "events": [event_dictionary_, event_dictionary_], } method_dictionary_ = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "magnetic_flux_density": "9.6 T", "rotor_frequency": "1000.0 Hz", "rotor_angle": "0.9553059660790962 rad", "spectral_dimensions": [dimension_dictionary_, dimension_dictionary_], "simulation": csdm_data.to_dict(), "experiment": csdm_data.to_dict(), } serialize = the_method.json() serialize["simulation"]["csdm"].pop("timestamp") assert serialize == method_dictionary_ # json(units=False) event_dictionary_ = { "fraction": 0.5, "transition_query": [{ "ch1": { "P": [-1] } }] } dimension_dictionary_ = { "count": 1024, "spectral_width": 100.0, "events": [event_dictionary_, event_dictionary_], } method_dictionary_ = { "name": "test-1-d", "description": "Test-1", "channels": ["29Si"], "magnetic_flux_density": 9.6, "rotor_frequency": 1000.0, "rotor_angle": 0.9553059660790962, "spectral_dimensions": [dimension_dictionary_, dimension_dictionary_], "simulation": csdm_data.to_dict(), "experiment": csdm_data.to_dict(), } serialize = the_method.json(units=False) serialize["simulation"]["csdm"].pop("timestamp") assert serialize == method_dictionary_