-
Notifications
You must be signed in to change notification settings - Fork 1
sysid implementation #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
34b1ff3
sysid implementation
8ohamed 557a2b9
unittest
8ohamed b628b87
adds functions. Update to sysid
8ohamed da73a6d
updated the plot
8ohamed 6354cb2
minor changes
8ohamed 1f99337
Comments absent examples
prasadtalasila 08a9ad7
updates exp3
8ohamed 2a6b0fe
client disconnect in exp3
8ohamed 120edae
resloved pylint issues
8ohamed cc4528d
sysid test
8ohamed 5be899f
Renames some variables
prasadtalasila fc512dc
resolved issues
MDesktop 5a55894
moved FS metadata, resloved pylint issues
8ohamed File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,9 @@ | ||
| MAX_MAP_SIZE = 52200 # The maximum number of samples saved in FIFO | ||
| MAX_MAP_SIZE = 160100 # The maximum number of samples saved in FIFO | ||
|
|
||
| TIMEOUT = 2 # Max wait time until enough samples are collected for the test_Accelerometer | ||
|
|
||
| INTERVAL = 0.001 # Check every 0.001s to see if samples are collected | ||
|
|
||
| MIN_SAMPLES_NEEDED = 500 # Minimum samples needed before running it to sysid | ||
|
|
||
| WAIT_METADATA = 11 # Wait max 11 seconds for getting metadata message |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import json | ||
| import time | ||
| from typing import Any, Dict | ||
| from paho.mqtt.client import Client as MQTTClient | ||
| from data.accel.constants import WAIT_METADATA | ||
| from data.comm.mqtt import setup_mqtt_client | ||
|
|
||
| def extract_fs_from_metadata(mqtt_config: Dict[str, Any]) -> int: | ||
| fs_result = {"fs": None} | ||
|
|
||
| def _on_metadata(client: MQTTClient, userdata, message) -> None: | ||
| try: | ||
| payload = json.loads(message.payload.decode("utf-8")) | ||
| fs_candidate = payload["Analysis chain"][0]["Sampling"] | ||
| if fs_candidate: | ||
| fs_result["fs"] = fs_candidate | ||
| print(f"Extracted Fs from metadata: {fs_candidate}") | ||
| client.unsubscribe(userdata["metadata_topic"]) | ||
| except Exception as e: | ||
| print(f"Failed to extract Fs: {e}") | ||
|
|
||
| metadata_topic = mqtt_config["TopicsToSubscribe"][1] | ||
| client, _ = setup_mqtt_client(mqtt_config, topic_index=1) | ||
| client.user_data_set({"metadata_topic": metadata_topic}) | ||
| client.message_callback_add(metadata_topic, _on_metadata) | ||
| client.connect(mqtt_config["host"], mqtt_config["port"], 60) | ||
| client.subscribe(metadata_topic) | ||
| client.loop_start() | ||
|
|
||
| start_time = time.time() | ||
| while fs_result["fs"] is None and (time.time() - start_time) < WAIT_METADATA: | ||
| time.sleep(0.1) | ||
|
|
||
| client.loop_stop() | ||
| if fs_result["fs"] is None: | ||
| raise TimeoutError("Sampling frequency not received within timeout") | ||
| return fs_result["fs"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import sys | ||
| import matplotlib.pyplot as plt | ||
| from methods import sys_id as sysID | ||
| from data.comm.mqtt import load_config | ||
| from data.accel.hbk.aligner import Aligner | ||
| from functions.natural_freq import plot_natural_frequencies | ||
|
|
||
|
|
||
| def run_experiment_3_plot(config_path): | ||
| number_of_minutes = 0.2 | ||
| config = load_config(config_path) | ||
| mqtt_config = config["MQTT"] | ||
|
|
||
| # Setting up the client and extracting Fs | ||
| data_client, fs = sysID.setup_client(mqtt_config) | ||
|
|
||
| # Setting up the aligner | ||
| data_topic_indexes = [0, 2] | ||
| selected_topics = [mqtt_config["TopicsToSubscribe"][i] for i in data_topic_indexes] | ||
| aligner = Aligner(data_client, topics=selected_topics) | ||
|
|
||
| fig_ax = None | ||
| aligner_time = None | ||
| while aligner_time is None: | ||
| results, aligner_time = sysID.get_oma_results(number_of_minutes, aligner, fs) | ||
| data_client.disconnect() | ||
| fig_ax = plot_natural_frequencies(results['Fn_poles'], freqlim=(0, 75), fig_ax=fig_ax) | ||
| plt.show(block=True) | ||
| sys.stdout.flush() | ||
|
|
||
|
|
||
| def run_experiment_3_print(config_path): | ||
| number_of_minutes = 0.2 | ||
| config = load_config(config_path) | ||
| mqtt_config = config["MQTT"] | ||
|
|
||
| # Setting up the client and extracting Fs | ||
| data_client, fs = sysID.setup_client(mqtt_config) | ||
|
|
||
| # Setting up the aligner | ||
| data_topic_indexes = [0, 2] | ||
| selected_topics = [mqtt_config["TopicsToSubscribe"][i] for i in data_topic_indexes] | ||
| aligner = Aligner(data_client, topics=selected_topics) | ||
|
|
||
| aligner_time = None | ||
| while aligner_time is None: | ||
| results, aligner_time = sysID.get_oma_results(number_of_minutes, aligner, fs) | ||
| data_client.disconnect() | ||
| sys.stdout.flush() | ||
|
|
||
| print(f"\n System Frequencies \n {results['Fn_poles']}") | ||
| print(f"\n Cov \n{results['Fn_poles_cov']}") | ||
| print(f"\n damping_ratios \n{results['Xi_poles']}") | ||
| print(f"\n cov_damping \n{results['Xi_poles_cov']}") | ||
|
|
||
|
|
||
| def run_experiment_3_publish(config_path): | ||
| number_of_minutes = 0.02 | ||
| config = load_config(config_path) | ||
| mqtt_config = config["MQTT"] | ||
| publish_config = config["sysID"] | ||
|
|
||
| # Setting up the client for getting accelerometer data | ||
| data_client, fs = sysID.setup_client(mqtt_config) | ||
|
|
||
| # Setting up the aligner | ||
| data_topic_indexes = [0, 2] | ||
| selected_topics = [mqtt_config["TopicsToSubscribe"][i] for i in data_topic_indexes] | ||
| aligner = Aligner(data_client, topics=selected_topics) | ||
|
|
||
| # Setting up the client for publishing OMA results | ||
| publish_client, _ = sysID.setup_client(publish_config) # fs not needed here | ||
|
|
||
| sysID.publish_oma_results( | ||
| number_of_minutes, | ||
| aligner, | ||
| publish_client, | ||
| publish_config["TopicsToSubscribe"][0], | ||
| fs | ||
| ) | ||
|
|
||
| print(f"Publishing to topic: {publish_config['TopicsToSubscribe'][0]}") | ||
| sys.stdout.flush() |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| from typing import Optional, Tuple | ||
| import numpy as np | ||
| import matplotlib.pyplot as plt | ||
| from matplotlib import ticker | ||
|
|
||
|
|
||
| def plot_natural_frequencies( | ||
| fn_poles: np.ndarray, | ||
| freqlim: Optional[Tuple[float, float]] = None, | ||
| fig_ax: Optional[Tuple] = None | ||
| ) -> Tuple: | ||
| """ | ||
| Plots a stabilization diagram with optional frequency range filtering. | ||
|
|
||
| Args: | ||
| Fn_poles (np.ndarray): 2D array [model_order x mode] of natural frequencies. | ||
| freqlim (tuple, optional): (f_min, f_max) frequency range to plot. | ||
| fig_ax (tuple, optional): Reuse (fig, ax) for interactive updates. | ||
|
|
||
| Returns: | ||
| (fig, ax): The matplotlib figure and axes used for plotting. | ||
| """ | ||
| if fig_ax is None: | ||
| plt.ion() | ||
| fig, ax = plt.subplots(figsize=(8, 5)) | ||
| else: | ||
| fig, ax = fig_ax | ||
| ax.clear() | ||
|
|
||
| num_orders, num_modes = fn_poles.shape | ||
| freqs, orders = [], [] | ||
| for i in range(num_orders): | ||
| for j in range(num_modes): | ||
| freq = fn_poles[i, j] | ||
| if not np.isnan(freq): | ||
| model_order = num_orders - i | ||
| if freqlim is None or (freqlim[0] <= freq <= freqlim[1]): | ||
| freqs.append(freq) | ||
| orders.append(model_order) | ||
|
|
||
| ax.scatter(freqs, orders, color='red', s=10) | ||
|
|
||
| ax.set_title("Stabilization Diagram") | ||
| ax.set_xlabel("Frequency (Hz)") | ||
| ax.set_ylabel("Model order") | ||
| ax.set_ylim(0, num_orders + 1) | ||
| ax.yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) | ||
| ax.grid(True) | ||
|
|
||
| if freqlim: | ||
| ax.set_xlim(freqlim) | ||
| else: | ||
| ax.set_xlim(0, max(freqs) * 1.05) | ||
|
|
||
| fig.tight_layout() | ||
| fig.canvas.draw() | ||
| fig.canvas.flush_events() | ||
|
|
||
| return fig, ax |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| from typing import Any | ||
| import numpy as np | ||
|
|
||
| # pylint: disable=R0911 | ||
| def convert_numpy_to_list(obj: Any) -> Any: | ||
| """ | ||
| Recursively convert NumPy arrays and complex numbers to JSON-safe types. | ||
|
|
||
| Args: | ||
| obj: Any data type. | ||
|
|
||
| Returns: | ||
| A fully JSON-serializable version of the input. | ||
| """ | ||
| if isinstance(obj, dict): | ||
| return {k: convert_numpy_to_list(v) for k, v in obj.items()} | ||
| if isinstance(obj, list): | ||
| return [convert_numpy_to_list(item) for item in obj] | ||
| if isinstance(obj, tuple): | ||
| return tuple(convert_numpy_to_list(item) for item in obj) | ||
| if isinstance(obj, np.ndarray): | ||
| return convert_numpy_to_list(obj.tolist()) | ||
| if isinstance(obj, complex): | ||
| return {"real": obj.real, "imag": obj.imag} | ||
| if isinstance(obj, (np.integer, np.floating)): | ||
| return obj.item() | ||
| try: | ||
| # fallback: try converting if it's a NumPy scalar or unknown object | ||
| if hasattr(obj, 'item'): | ||
| return obj.item() | ||
| except Exception: | ||
| pass | ||
| return obj |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| DEFAULT_FS = 250 # In case the Fs from metadata doesn't arrive | ||
|
|
||
| MIN_SAMPLES_NEEDED = 540 # Minimum samples for running sysid | ||
|
|
||
| BLOCK_SHIFT = 30 # Used in sysID algorithm | ||
|
|
||
| MODEL_ORDER = 20 # Used in sysID algorithm |
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.