Skip to content
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

feat(gsoc'24): Added helpful functions for debugging of circuit (#3870) #366

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

niladrix719
Copy link
Member

@niladrix719 niladrix719 commented Aug 24, 2024

Fixes #112

Stability improvements

ref PR - #3870

Summary by CodeRabbit

  • New Features
    • Introduced a method to load circuit data from JSON, enhancing circuit management.
    • Added functionality to retrieve the last autosaved circuit state from local storage.
    • Implemented cycle detection in circuits, providing visual feedback for identified cycles.
    • New method added for highlighting nodes involved in detected cycles.

Copy link
Contributor

coderabbitai bot commented Aug 24, 2024

Walkthrough

The changes to the Scope class in src/simulator/src/circuit.ts enhance circuit management capabilities by introducing new functionalities such as loading circuit data from JSON, autosave retrieval, and cycle detection. The class now includes methods for detecting cyclic paths and highlighting affected nodes, improving interaction and usability within circuit simulations.

Changes

File Change Summary
src/simulator/src/circuit.ts - New methods: loadCircuit(data: JSON), detectCycle(), highlightNodes(array)
- Modified method: previous() to load from local storage
- Unchanged methods: findNodeIndexById(nodeId: string), getCurrentlySelectedComponent(), getAllSelectedComponents(), modifyCurrentlySelectedComponent(property, value)

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Scope
    participant LocalStorage
    participant JSONHandler

    User->>Scope: Load Circuit
    Scope->>JSONHandler: loadCircuit(data)
    JSONHandler-->>Scope: Circuit Data Loaded
    Scope->>LocalStorage: previous()
    LocalStorage-->>Scope: Last autosaved circuit retrieved
    Scope->>Scope: detectCycle()
    Scope->>Scope: highlightNodes(array)
    Scope-->>User: Circuit Updated with Cycle Highlighting
Loading

🐇 "In circuits bright, new paths unfold,
With cycles found and stories told.
From JSON's grasp to saves of yore,
Our circuits dance, forevermore!" 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Aug 24, 2024

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 6e1cab8
🔍 Latest deploy log https://app.netlify.com/sites/circuitverse/deploys/66ca1e19ad0140000890493e
😎 Deploy Preview https://deploy-preview-366--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 129048f and 6e1cab8.

Files selected for processing (1)
  • src/simulator/src/circuit.ts (2 hunks)
Additional comments not posted (2)
src/simulator/src/circuit.ts (2)

520-527: LGTM!

The code changes are approved.


634-646: LGTM!

The code changes are approved.

Comment on lines +532 to +628
detectCycle() {
const obj = {};
const result = [];

for (let i = 0; i < globalScope.allNodes.length; i++) {
const nodeId = globalScope.allNodes[i].id;
for (let j = 0; j < globalScope.allNodes[i].connections.length; j++) {
const connection = globalScope.allNodes[i].connections[j].id;
if (obj[nodeId]) {
obj[nodeId].push(connection);
} else {
obj[nodeId] = [connection];
}
}
}

const newNestedArray = [];
const singleConnectionNodes = [];

for (const node in obj) {
const connections = obj[node];
if (connections.length === 1) {
singleConnectionNodes.push(node);
}
if (!isVisited(newNestedArray.flat(), node)) {
const connectedNodes = [node];
exploreNodes(obj, node, newNestedArray.flat(), connectedNodes);
newNestedArray.push(connectedNodes);
}
}

for (let i = 0; i < singleConnectionNodes.length - 1; i++) {
for (let j = i + 1; j < singleConnectionNodes.length; j++) {
if (areElementsInSameNode(newNestedArray, singleConnectionNodes[i], singleConnectionNodes[j])) {
const val1 = this.findNodeIndexById(singleConnectionNodes[i]);
const val2 = this.findNodeIndexById(singleConnectionNodes[j]);
if (globalScope.allNodes[val1].parent === globalScope.allNodes[val2].parent) {
result.push(dfs(obj, singleConnectionNodes[i], singleConnectionNodes[j]));
}
}
}
}

// Function to check whether a node is already visited
function isVisited(visited, node) {
return visited.includes(node);
}

// Function to explore interconnected nodes
function exploreNodes(graph, startNode, visited, connectedNodes) {
visited.push(startNode);
if (graph[startNode]) {
for (let i = 0; i < graph[startNode].length; i++) {
const connectedNode = graph[startNode][i];
if (!isVisited(visited, connectedNode)) {
connectedNodes.push(connectedNode);
exploreNodes(graph, connectedNode, visited, connectedNodes);
}
}
}
}

function areElementsInSameNode(nestedArray, element1, element2) {
for (const node of nestedArray) {
if (node.includes(element1) && node.includes(element2)) {
return true;
}
}
return false;
}

// Function to locate the nodes present between two specified nodes
function dfs(graph, start, end, path = []) {
if (start === end) {
path.push(end);
return path;
}
path.push(start);
for (const neighbor of graph[start]) {
if (!path.includes(neighbor)) {
const newPath = dfs(graph, neighbor, end, path);
if (newPath) {
return newPath;
}
}
}
path.pop();
return [];
}

if (result.length) {
this.highlightNodes(result);
return result;
}

return 'No cycle found';
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor detectCycle for readability and maintainability.

  1. Move nested helper functions outside to improve readability.
  2. Avoid using globalScope within the function by passing it as a parameter.
  3. Add comments explaining the logic.

Apply this diff to refactor the function:

+    // Helper function to check whether a node is already visited
+    function isVisited(visited, node) {
+        return visited.includes(node);
+    }
+
+    // Helper function to explore interconnected nodes
+    function exploreNodes(graph, startNode, visited, connectedNodes) {
+        visited.push(startNode);
+        if (graph[startNode]) {
+            for (let i = 0; i < graph[startNode].length; i++) {
+                const connectedNode = graph[startNode][i];
+                if (!isVisited(visited, connectedNode)) {
+                    connectedNodes.push(connectedNode);
+                    exploreNodes(graph, connectedNode, visited, connectedNodes);
+                }
+            }
+        }
+    }
+
+    // Helper function to check if elements are in the same node
+    function areElementsInSameNode(nestedArray, element1, element2) {
+        for (const node of nestedArray) {
+            if (node.includes(element1) && node.includes(element2)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // Helper function to locate the nodes present between two specified nodes
+    function dfs(graph, start, end, path = []) {
+        if (start === end) {
+            path.push(end);
+            return path;
+        }
+        path.push(start);
+        for (const neighbor of graph[start]) {
+            if (!path.includes(neighbor)) {
+                const newPath = dfs(graph, neighbor, end, path);
+                if (newPath) {
+                    return newPath;
+                }
+            }
+        }
+        path.pop();
+        return [];
+    }

    detectCycle() {
        const obj = {};
        const result = [];

        for (let i = 0; i < globalScope.allNodes.length; i++) {
            const nodeId = globalScope.allNodes[i].id;
            for (let j = 0; j < globalScope.allNodes[i].connections.length; j++) {
                const connection = globalScope.allNodes[i].connections[j].id;
                if (obj[nodeId]) {
                    obj[nodeId].push(connection);
                } else {
                    obj[nodeId] = [connection];
                }
            }
        }

        const newNestedArray = [];
        const singleConnectionNodes = [];

        for (const node in obj) {
            const connections = obj[node];
            if (connections.length === 1) {
                singleConnectionNodes.push(node);
            }
            if (!isVisited(newNestedArray.flat(), node)) {
                const connectedNodes = [node];
                exploreNodes(obj, node, newNestedArray.flat(), connectedNodes);
                newNestedArray.push(connectedNodes);
            }
        }

        for (let i = 0; i < singleConnectionNodes.length - 1; i++) {
            for (let j = i + 1; j < singleConnectionNodes.length; j++) {
                if (areElementsInSameNode(newNestedArray, singleConnectionNodes[i], singleConnectionNodes[j])) {
                    const val1 = this.findNodeIndexById(singleConnectionNodes[i]);
                    const val2 = this.findNodeIndexById(singleConnectionNodes[j]);
                    if (globalScope.allNodes[val1].parent === globalScope.allNodes[val2].parent) {
                        result.push(dfs(obj, singleConnectionNodes[i], singleConnectionNodes[j]));
                    }
                }
            }
        }

        if (result.length) {
            this.highlightNodes(result);
            return result;
        }

        return 'No cycle found';
    }

Committable suggestion was skipped due to low confidence.

Comment on lines +509 to +515
loadCircuit(data: JSON) {
if (data) {
load(data);
} else {
alert('Invalid data');
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve error handling in loadCircuit.

Using alert for error handling is not user-friendly. Consider using a more user-friendly approach, such as displaying a message in the UI.

Apply this diff to improve error handling:

-        alert('Invalid data');
+        // Replace this with a more user-friendly error handling approach
+        showMessage('Invalid data', 'error');

Committable suggestion was skipped due to low confidence.

Comment on lines +651 to +657
findNodeIndexById(nodeId: string) {
for (let i = 0; i < globalScope.allNodes.length; i++) {
if (globalScope.allNodes[i].id === nodeId) {
return i;
}
}
return 'Not found';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure consistent return type in findNodeIndexById.

The function should return a consistent type. Instead of returning a string 'Not found', consider returning -1 to indicate that the node was not found.

Apply this diff to ensure a consistent return type:

-        return 'Not found';
+        return -1;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
findNodeIndexById(nodeId: string) {
for (let i = 0; i < globalScope.allNodes.length; i++) {
if (globalScope.allNodes[i].id === nodeId) {
return i;
}
}
return 'Not found';
findNodeIndexById(nodeId: string) {
for (let i = 0; i < globalScope.allNodes.length; i++) {
if (globalScope.allNodes[i].id === nodeId) {
return i;
}
}
return -1;

@niladrix719 niladrix719 added the GSOC'24 PR's for GSoC'24 label Aug 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
GSOC'24 PR's for GSoC'24
Projects
None yet
1 participant