def parse_dict_with_units(cls, py_dict): """ Parse the physical quantity from a dictionary representation of the Method object, where the physical quantity is expressed as a string with a number and a unit. Args: dict py_dict: A python dict representation of the Method object. Returns: A :ref:`method_api` object. """ py_dict_copy = deepcopy(py_dict) if "spectral_dimensions" in py_dict_copy: py_dict_copy = expand_spectral_dimension_object(py_dict_copy) py_dict_copy["spectral_dimensions"] = [ SpectralDimension.parse_dict_with_units(s) for s in py_dict_copy["spectral_dimensions"] ] if "simulation" in py_dict_copy: if py_dict_copy["simulation"] is not None: py_dict_copy["simulation"] = cp.parse_dict( py_dict_copy["simulation"]) if "experiment" in py_dict_copy: if py_dict_copy["experiment"] is not None: py_dict_copy["experiment"] = cp.parse_dict( py_dict_copy["experiment"]) return update_method(super().parse_dict_with_units(py_dict_copy))
def solve(l1, l2, data): inverse_dimensions = [ cp.LinearDimension(**item) for item in data["inverse_dimensions"] ] compressed_K = np.asarray(data["kernel"], dtype=np.float64) compressed_s = cp.parse_dict(data["signal"]) print(compressed_K, compressed_s, inverse_dimensions) # s_lasso = SmoothLassoCV( # # alpha=l2, # # lambda1=l1, # inverse_dimension=inverse_dimensions, # # method="lars", # tolerance=1e-3, # ) s_lasso = SmoothLasso( alpha=l2, lambda1=l1, inverse_dimension=inverse_dimensions, method="lars", tolerance=1e-3, ) s_lasso.fit(K=compressed_K, s=compressed_s) res = s_lasso.f / s_lasso.f.max() return [ res.to_dict(), s_lasso.hyperparameters["lambda"], s_lasso.hyperparameters["alpha"], ]
def validate_experiment(cls, v, *, values, **kwargs): if v is None: return None if isinstance(v, dict): return cp.parse_dict(v) if isinstance(v, cp.CSDM): return v raise ValueError("Unable to read the data.")
def __check_csdm__(dataset): if dataset is None: return None if isinstance(dataset, dict): return cp.parse_dict(dataset) if isinstance(dataset, cp.CSDM): return dataset raise ValueError("Unable to read the dataset.")
def update_input_graph(contents, tr_val, url, figure, data): # if contents is None: # raise PreventUpdate trigger_id = ctx.triggered[0]["prop_id"].split(".")[0] if trigger_id == "url-search": slogger("url", url) if url in [None, ""]: raise PreventUpdate response = urlopen(url[3:]) content = json.loads(response.read()) exp_data = cp.parse_dict(content) pre_figure(exp_data, figure) return [figure, exp_data.real.dict()] if trigger_id == "INV-upload-from-graph": content = contents.split(",")[1] decoded = base64.b64decode(content) success, exp_data, _ = load_csdm(decoded) if not success: raise PreventUpdate pre_figure(exp_data, figure) return [figure, exp_data.real.dict()] if trigger_id == "INV-transpose": if data is None: raise PreventUpdate data = cp.parse_dict(data).T figure["data"][0]["x"] = data.x[0].coordinates.value figure["data"][0]["y"] = data.x[1].coordinates.value figure["data"][0]["z"] = data.y[0].components[0] return [figure, data.dict()]
def generate_kernel(n, data, count0, inc0, count1, inc1, channel, B0, theta, n_su, d_range, k_typ): if data is None: raise PreventUpdate if d_range is None: d_range = [[0, -1], [0, -1]] data = cp.parse_dict(data) anisotropic_dimension = data.dimensions[0] inverse_dimensions = [ cp.LinearDimension(count=count0, increment=f"{inc0} Hz", label="x"), cp.LinearDimension(count=count1, increment=f"{inc1} Hz", label="y"), ] vr = 0 ns = 1 if k_typ == "sideband-correlation": vr = anisotropic_dimension.increment.to("Hz") ns = anisotropic_dimension.count if k_typ == "MAF": vr = "1 GHz" ns = 1 K = ShieldingPALineshape( anisotropic_dimension=anisotropic_dimension, inverse_dimension=inverse_dimensions, channel=channel, magnetic_flux_density=f"{B0} T", rotor_angle=f"{theta} °", rotor_frequency=f"{vr}", number_of_sidebands=ns, ).kernel(supersampling=int(n_su)) ranges = slice(d_range[1][0], d_range[1][1], None) data_truncated = data[:, ranges] new_system = TSVDCompression(K, data_truncated) compressed_K = new_system.compressed_K compressed_s = new_system.compressed_s return { "kernel": compressed_K, "signal": compressed_s.dict(), "inverse_dimensions": [item.dict() for item in inverse_dimensions], }
def update_plot(data): res = cp.parse_dict(data) _ = [item.to("ppm", "nmr_frequency_ratio") for item in res.x] x, y, z = [item.coordinates.value for item in res.x] x_, y_, z_ = np.meshgrid(x, y, z, indexing="ij") trace = go.Volume( x=x_.ravel(), y=y_.ravel(), z=z_.ravel(), value=res.y[0].components[0].T.ravel(), isomin=0.05, isomax=0.95, opacity=0.1, # needs to be small to see through all surfaces surface_count=25, # needs to be a large number for good volume rendering colorscale="RdBu", ) return {"data": [trace]}
def plot(*args): """Generate and return a one-dimensional plot instance.""" # time_of_computation = ctx.inputs["local-computed-data.modified_timestamp"] trigger = ctx.triggered[0]["prop_id"] trigger_id = trigger.split(".")[0] sim_data = ctx.inputs["local-simulator-data.data"] if sim_data is None: return [DEFAULT_FIGURE, no_update] if sim_data["methods"] == []: return [DEFAULT_FIGURE, no_update] method_index = ctx.inputs["select-method.value"] if method_index is None: raise PreventUpdate normalized = ctx.states["normalize_amp.active"] figure = ctx.states["nmr_spectrum.figure"] mth = sim_data["methods"][method_index] simulation_data = None if "simulation" not in mth else mth["simulation"] experiment_data = None if "experiment" not in mth else mth["experiment"] # [item["simulation"] for item in sim_data["methods"]] # print("inside plot, time of computation", time_of_computation) print("method_index", method_index) # if method_index is None or method_options == []: # return [DEFAULT_FIGURE, no_update] # if not ctx.triggered: # raise PreventUpdate if trigger == "normalize_amp.n_clicks": normalized = not normalized decompose = False if "decompose_spectrum" in sim_data["config"]: decompose = sim_data["config"]["decompose_spectrum"] == "spin_system" print("plot trigger, trigger id", trigger, trigger_id) dim_axes = None plot_trace = [] if experiment_data is not None: dim_axes = made_dimensionless(experiment_data) exp_data = cp.parse_dict(experiment_data).real plot_trace += get_plot_trace( exp_data, normalized, decompose=False, name="experiment", dimensionless_axes=dim_axes, ) if simulation_data is not None: sim_data = cp.parse_dict(simulation_data).real plot_trace += get_plot_trace( sim_data, normalized, decompose=decompose, name="simulation", dimensionless_axes=dim_axes, ) if experiment_data is not None and simulation_data is not None: index = [-i - 1 for i, x in enumerate(exp_data.x) if x.increment.value < 0] residue = exp_data.copy() sim_sum = np.asarray([y.components for y in sim_data.y]).sum(axis=0) residue.y[0].components -= np.flip(sim_sum, axis=tuple(index)) plot_trace += get_plot_trace( residue, normalized, decompose=decompose, name="residual", dimensionless_axes=dim_axes, ) layout = figure["layout"] # layout_graph = ctx.states['graph-view-layout.data'][method_index] # layout.update(layout_graph) # Let graph resize ranges if new method has been selected mrsim_data = ctx.states["local-mrsim-data.data"] trigger = mrsim_data["trigger"] if "trigger" in mrsim_data else None if (trigger and trigger["method_index"] is None) or trigger_id == "select-method": layout["xaxis"]["autorange"] = "reversed" layout["yaxis"]["autorange"] = True else: layout["xaxis"]["autorange"] = False layout["yaxis"]["autorange"] = False data_object = {"data": plot_trace, "layout": go.Layout(**layout)} if trigger_id in [ "local-exp-external-data", "normalize_amp", # "nmr_spectrum", ]: return [data_object, no_update] if simulation_data is None: return [data_object, no_update] args = (sim_data,) if experiment_data is None else (sim_data, exp_data, residue) csdm_obj = construct_csdm_object(*args) return [data_object, csdm_obj.dict()]