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

Update metrics visualization #23

Merged
merged 3 commits into from
Dec 17, 2024
Merged

Conversation

vlad-stepanov
Copy link
Collaborator

@vlad-stepanov vlad-stepanov commented Dec 17, 2024

Визуализация теперь рассчитывается соответственно максимальному/минимальному betweenness.

image

Summary by CodeRabbit

  • Новые функции

    • Улучшена визуализация дорог и перекрестков на карте с использованием новых функций для расчета радиуса и цвета.
    • Добавлены функции для вычисления радиуса и интерполяции цвета от синего до красного на основе нормализованного значения.
  • Исправления ошибок

    • Добавлена обработка ошибок для случаев, когда максимальное и минимальное значения равны.
  • Документация

    • Обновлены комментарии для улучшения ясности кода.
  • Чистка кода

    • Удалены неиспользуемые атрибуты из класса GraphBase.

Copy link

coderabbitai bot commented Dec 17, 2024

📝 Walkthrough
📝 Walkthrough

Обзор изменений

Walkthrough

В этом обновлении были внесены изменения в два файла: api/fastapi_service/schemas.py и ui/src/app/roads/roads.component.ts. В файле схем были удалены несколько необязательных атрибутов из класса GraphBase, а в компоненте дорог были добавлены новые функции для расчета цвета и радиуса маркеров на основе метрик Betweenness Centrality.

Changes

Файл Изменения
api/fastapi_service/schemas.py - Удалены атрибуты reversed_edges_csv, reversed_nodes_csv, reversed_metrics_csv из класса GraphBase
- Удалена закомментированная строка reversed_matrix_csv
ui/src/app/roads/roads.component.ts - Добавлена функция getRadiusBasedOnMetric для расчета радиуса
- Добавлена функция getColorFromBlueToRed для интерполяции цвета
- Обновлен метод updateRoads с новой логикой визуализации

Sequence Diagram

sequenceDiagram
    participant Component as RoadsComponent
    participant GraphData as GraphData
    participant Visualization as MapVisualization

    Component->>GraphData: Получить данные графа
    GraphData-->>Component: Вернуть узлы и метрики
    Component->>Component: Вычислить макс/мин Betweenness Centrality
    Component->>Visualization: Применить цвет и радиус маркеров
    Visualization-->>Component: Обновить визуализацию дорог
Loading

Диаграмма последовательности демонстрирует процесс обработки и визуализации данных о дорогах с использованием новых функций расчета цвета и радиуса.

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

@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

🧹 Nitpick comments (2)
ui/src/app/roads/roads.component.ts (2)

22-24: Переосмыслить логику интерполяции цвета

Текущая логика увеличения красного цвета с уменьшением значения и синего с увеличением значения может быть нелогичной. При нормализации значения от 0 до 1 ожидается, что цвет будет переходить от синего (при меньших значениях) к красному (при больших значениях).

Предлагается скорректировать формулы вычисления цветов следующим образом:

const red = Math.floor(255 * normalizedValue); // Увеличиваем красный с увеличением значения
const blue = Math.floor(255 * (1 - normalizedValue)); // Уменьшаем синий с увеличением значения

14-15: Использование стандартного цвета вместо черного

Когда все значения одинаковы, возврат черного цвета может не соответствовать ожиданиям пользователя. Возможно, стоит использовать нейтральный цвет, например, серый.

Пример исправления:

- return `rgb(0, 0, 0)`; // Черный цвет
+ return `rgb(128, 128, 128)`; // Серый цвет
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7fc51c9 and 2468221.

📒 Files selected for processing (2)
  • api/fastapi_service/schemas.py (0 hunks)
  • ui/src/app/roads/roads.component.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • api/fastapi_service/schemas.py

ui/src/app/roads/roads.component.ts Outdated Show resolved Hide resolved
ui/src/app/roads/roads.component.ts Outdated Show resolved Hide resolved
ui/src/app/roads/roads.component.ts Show resolved Hide resolved
Copy link

@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: 0

🧹 Nitpick comments (4)
ui/src/app/roads/roads.component.ts (4)

8-10: Добавить валидацию входных данных

Функция getRadiusBasedOnMetric не проверяет входные данные на отрицательные значения или NaN. Рекомендуется добавить проверки для обеспечения корректной работы функции.

 function getRadiusBasedOnMetric(value: number) {
+  if (isNaN(value) || value < 0) return 1;
   return 1 + 10 * value;
 }

12-25: Улучшить типизацию и документацию функции

Функция getColorFromBlueToRed корректно обрабатывает краевые случаи, но можно улучшить её типизацию и добавить JSDoc документацию для лучшей поддержки.

+/**
+ * Вычисляет цвет в формате RGB на основе значения метрики
+ * @param value - Текущее значение метрики
+ * @param minValue - Минимальное значение в наборе данных
+ * @param maxValue - Максимальное значение в наборе данных
+ * @returns RGB строка в формате 'rgb(r, g, b)'
+ */
 function getColorFromBlueToRed(value: number, minValue: number, maxValue: number): string {

104-108: Оптимизировать вычисление метрик

Текущая реализация вычисления min/max значений использует повторные обходы массива. Можно оптимизировать, используя один проход.

-    const maxBetweenness = Math.max(...nodeValues.map(node => Number(node.betweenness_value) || 0));
-    const minBetweenness = Math.min(...nodeValues.map(node => Number(node.betweenness_value) || 0));
+    const [minBetweenness, maxBetweenness] = nodeValues.reduce(
+      ([min, max], node) => {
+        const value = Number(node.betweenness_value) || 0;
+        return [Math.min(min, value), Math.max(max, value)];
+      },
+      [Infinity, -Infinity]
+    );

167-178: Улучшить форматирование всплывающего окна

Рекомендуется выделить шаблон всплывающего окна в отдельную константу и использовать более структурированный формат для улучшения читаемости.

+    const POPUP_TEMPLATE = `
+      <div class="intersection-popup">
+        <h3>Перекресток</h3>
+        <div class="metrics">
+          <div><strong>Degree:</strong> {degree}</div>
+          <div><strong>In-Degree:</strong> {inDegree}</div>
+          <div><strong>Out-Degree:</strong> {outDegree}</div>
+          <div><strong>Eigenvector:</strong> {eigenvector}</div>
+          <div><strong>Betweenness:</strong> {betweenness}</div>
+        </div>
+        <div class="roads-section">
+          <h4>Дороги ({roadsCount}):</h4>
+          <ul>{roadsList}</ul>
+        </div>
+      </div>
+    `;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2468221 and 360e8b5.

📒 Files selected for processing (1)
  • ui/src/app/roads/roads.component.ts (4 hunks)
🔇 Additional comments (1)
ui/src/app/roads/roads.component.ts (1)

156-164: LGTM: Корректная обработка нормализации значений

Отлично реализована обработка случая деления на ноль при нормализации значений betweenness и корректное применение цветовой схемы.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant