From 2c7970eea9761fea8c8c72895742a6cd86bdf199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 25 Apr 2026 18:06:44 -0300 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20adiciona=20novos=20arquivos=20Markd?= =?UTF-8?q?own=20da=20vers=C3=A3o=200.5.4=20como=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/advanced-guides/Core/_category_.json | 3 - .../Core/negative-selection.md | 86 - docs/advanced-guides/Utils/Display.md | 152 - docs/advanced-guides/Utils/Distance.md | 180 - docs/advanced-guides/Utils/Metrics.md | 39 - docs/advanced-guides/Utils/Multiclass.md | 54 - docs/advanced-guides/Utils/Random.md | 17 - docs/advanced-guides/Utils/Sanitizers.md | 85 - docs/advanced-guides/Utils/Validation.md | 104 - docs/advanced-guides/Utils/_category_.json | 4 - docs/advanced-guides/_category_.json | 8 - .../base-module/_category_.json | 5 - docs/advanced-guides/base-module/core/Base.md | 57 - .../base-module/core/Classifier.md | 92 - .../base-module/core/Clusterer.md | 102 - .../base-module/core/Optimizer.md | 173 - .../base-module/immune/cell.md | 116 - .../base-module/immune/mutation.md | 121 - .../base-module/immune/populations.md | 49 - .../clonal-selection-algorithms.md | 39 + .../clonal-selection-algorithms/README.mdx | 16 - .../airs/README.md | 210 - .../clonal-selection-algorithms/airs/abr.md | 47 - .../clonal-selection-algorithms/clonalg.md | 198 - docs/aisp-techniques/immune-network-theory.md | 41 + .../immune-network-theory/AiNet.md | 322 -- .../immune-network-theory/README.mdx | 39 - docs/aisp-techniques/negative-selection.md | 50 + .../negative-selection/BNSA.md | 143 - .../negative-selection/README.md | 42 - .../negative-selection/RNSA.md | 241 -- docs/api/README.md | 85 + docs/api/base/README.md | 33 + docs/api/base/base-classifier.md | 133 + docs/api/base/base-clusterer.md | 122 + docs/api/base/base-optimizer.md | 165 + docs/api/base/immune/README.md | 22 + docs/api/base/immune/cell/README.md | 33 + docs/api/base/immune/cell/antibody.md | 39 + docs/api/base/immune/cell/b-cell.md | 63 + docs/api/base/immune/cell/c-cell.md | 35 + docs/api/base/immune/cell/detector.md | 28 + docs/api/base/immune/mutation.md | 145 + docs/api/base/immune/populations.md | 56 + docs/api/csa/README.md | 33 + docs/api/csa/airs.md | 197 + docs/api/csa/clonalg.md | 183 + docs/api/exceptions.md | 91 + docs/api/ina/README.md | 31 + docs/api/ina/ai-net.md | 227 ++ docs/api/nsa/README.md | 35 + docs/api/nsa/bnsa.md | 193 + docs/api/nsa/rnsa.md | 222 ++ docs/api/utils/README.md | 28 + docs/api/utils/display/README.md | 23 + docs/api/utils/display/progress-table.md | 57 + docs/api/utils/display/table-formatter.md | 85 + docs/api/utils/distance.md | 243 ++ docs/api/utils/metrics.md | 47 + docs/api/utils/multiclass.md | 82 + docs/api/utils/sanitizers.md | 119 + docs/api/utils/types.md | 60 + docs/api/utils/validation.md | 180 + docs/architecture.md | 76 + docs/faq.md | 48 +- docs/intro.md | 36 +- docusaurus.config.js | 15 +- .../advanced-guides/Core/_category_.json | 3 - .../Core/negative-selection.md | 85 - .../current/advanced-guides/Utils/Display.md | 152 - .../current/advanced-guides/Utils/Distance.md | 176 - .../current/advanced-guides/Utils/Metrics.md | 38 - .../advanced-guides/Utils/Multiclass.md | 55 - .../current/advanced-guides/Utils/Random.md | 16 - .../advanced-guides/Utils/Sanitizers.md | 82 - .../advanced-guides/Utils/Validation.md | 108 - .../advanced-guides/Utils/_category_.json | 4 - .../current/advanced-guides/_category_.json | 8 - .../base-module/_category_.json | 4 - .../advanced-guides/base-module/core/Base.md | 55 - .../base-module/core/Classifier.md | 94 - .../base-module/core/Clusterer.md | 93 - .../base-module/core/Optimizer.md | 165 - .../base-module/immune/cell.md | 117 - .../base-module/immune/mutation.md | 94 - .../base-module/immune/populations.md | 49 - .../clonal-selection-algorithms.md | 39 + .../clonal-selection-algorithms/README.mdx | 15 - .../airs/README.md | 216 -- .../clonal-selection-algorithms/airs/abr.md | 47 - .../clonal-selection-algorithms/clonalg.md | 197 - .../aisp-techniques/immune-network-theory.md | 41 + .../immune-network-theory/AiNet.md | 327 -- .../immune-network-theory/README.mdx | 39 - .../aisp-techniques/negative-selection.md | 50 + .../negative-selection/BNSA.md | 134 - .../negative-selection/README.md | 44 - .../negative-selection/RNSA.md | 248 -- .../current/api/README.md | 84 + .../current/api/base/README.md | 33 + .../current/api/base/base-classifier.md | 133 + .../current/api/base/base-clusterer.md | 123 + .../current/api/base/base-optimizer.md | 164 + .../current/api/base/immune/README.md | 22 + .../current/api/base/immune/cell/README.md | 32 + .../current/api/base/immune/cell/antibody.md | 39 + .../current/api/base/immune/cell/b-cell.md | 63 + .../current/api/base/immune/cell/c-cell.md | 35 + .../current/api/base/immune/cell/detector.md | 28 + .../current/api/base/immune/mutation.md | 146 + .../current/api/base/immune/populations.md | 57 + .../current/api/csa/README.md | 33 + .../current/api/csa/airs.md | 196 + .../current/api/csa/clonalg.md | 185 + .../current/api/exceptions.md | 91 + .../current/api/ina/README.md | 30 + .../current/api/ina/ai-net.md | 222 ++ .../current/api/nsa/README.md | 34 + .../current/api/nsa/bnsa.md | 192 + .../current/api/nsa/rnsa.md | 222 ++ .../current/api/utils/README.md | 28 + .../current/api/utils/display/README.md | 23 + .../api/utils/display/progress-table.md | 57 + .../api/utils/display/table-formatter.md | 84 + .../current/api/utils/distance.md | 241 ++ .../current/api/utils/metrics.md | 47 + .../current/api/utils/multiclass.md | 82 + .../current/api/utils/sanitizers.md | 119 + .../current/api/utils/types.md | 60 + .../current/api/utils/validation.md | 180 + .../current/architecture.md | 76 + .../current/faq.md | 53 +- .../current/intro.md | 36 +- .../advanced-guides/Core/_category_.json | 3 - .../Core/negative-selection.md | 85 - .../advanced-guides/Utils/Display.md | 152 - .../advanced-guides/Utils/Distance.md | 176 - .../advanced-guides/Utils/Metrics.md | 38 - .../advanced-guides/Utils/Multiclass.md | 55 - .../advanced-guides/Utils/Random.md | 16 - .../advanced-guides/Utils/Sanitizers.md | 82 - .../advanced-guides/Utils/Validation.md | 108 - .../advanced-guides/Utils/_category_.json | 4 - .../advanced-guides/_category_.json | 8 - .../base-module/_category_.json | 4 - .../advanced-guides/base-module/core/Base.md | 55 - .../base-module/core/Classifier.md | 94 - .../base-module/core/Clusterer.md | 93 - .../base-module/core/Optimizer.md | 165 - .../base-module/immune/cell.md | 117 - .../base-module/immune/mutation.md | 94 - .../base-module/immune/populations.md | 49 - .../clonal-selection-algorithms.md | 39 + .../clonal-selection-algorithms/README.mdx | 15 - .../airs/README.md | 216 -- .../clonal-selection-algorithms/airs/abr.md | 47 - .../clonal-selection-algorithms/clonalg.md | 197 - .../aisp-techniques/immune-network-theory.md | 41 + .../immune-network-theory/AiNet.md | 327 -- .../immune-network-theory/README.mdx | 39 - .../aisp-techniques/negative-selection.md | 50 + .../negative-selection/BNSA.md | 134 - .../negative-selection/README.md | 44 - .../negative-selection/RNSA.md | 248 -- .../version-0.5.x/api/README.md | 84 + .../version-0.5.x/api/base/README.md | 33 + .../version-0.5.x/api/base/base-classifier.md | 133 + .../version-0.5.x/api/base/base-clusterer.md | 123 + .../version-0.5.x/api/base/base-optimizer.md | 164 + .../version-0.5.x/api/base/immune/README.md | 22 + .../api/base/immune/cell/README.md | 32 + .../api/base/immune/cell/antibody.md | 39 + .../api/base/immune/cell/b-cell.md | 63 + .../api/base/immune/cell/c-cell.md | 35 + .../api/base/immune/cell/detector.md | 28 + .../version-0.5.x/api/base/immune/mutation.md | 146 + .../api/base/immune/populations.md | 57 + .../version-0.5.x/api/csa/README.md | 33 + .../version-0.5.x/api/csa/airs.md | 196 + .../version-0.5.x/api/csa/clonalg.md | 185 + .../version-0.5.x/api/exceptions.md | 91 + .../version-0.5.x/api/ina/README.md | 30 + .../version-0.5.x/api/ina/ai-net.md | 222 ++ .../version-0.5.x/api/nsa/README.md | 34 + .../version-0.5.x/api/nsa/bnsa.md | 192 + .../version-0.5.x/api/nsa/rnsa.md | 222 ++ .../version-0.5.x/api/utils/README.md | 28 + .../version-0.5.x/api/utils/display/README.md | 23 + .../api/utils/display/progress-table.md | 57 + .../api/utils/display/table-formatter.md | 84 + .../version-0.5.x/api/utils/distance.md | 241 ++ .../version-0.5.x/api/utils/metrics.md | 47 + .../version-0.5.x/api/utils/multiclass.md | 82 + .../version-0.5.x/api/utils/sanitizers.md | 119 + .../version-0.5.x/api/utils/types.md | 60 + .../version-0.5.x/api/utils/validation.md | 180 + .../version-0.5.x/architecture.md | 76 + .../version-0.5.x/faq.md | 53 +- .../version-0.5.x/intro.md | 36 +- package-lock.json | 3453 +++++++++++------ package.json | 13 +- sidebars.ts | 6 + .../advanced-guides/Core/_category_.json | 3 - .../Core/negative-selection.md | 86 - .../advanced-guides/Utils/Display.md | 152 - .../advanced-guides/Utils/Distance.md | 180 - .../advanced-guides/Utils/Metrics.md | 39 - .../advanced-guides/Utils/Multiclass.md | 54 - .../advanced-guides/Utils/Random.md | 17 - .../advanced-guides/Utils/Sanitizers.md | 85 - .../advanced-guides/Utils/Validation.md | 104 - .../advanced-guides/Utils/_category_.json | 4 - .../advanced-guides/_category_.json | 8 - .../base-module/_category_.json | 5 - .../advanced-guides/base-module/core/Base.md | 57 - .../base-module/core/Classifier.md | 92 - .../base-module/core/Clusterer.md | 102 - .../base-module/core/Optimizer.md | 173 - .../base-module/immune/cell.md | 116 - .../base-module/immune/mutation.md | 121 - .../base-module/immune/populations.md | 49 - .../clonal-selection-algorithms.md | 39 + .../clonal-selection-algorithms/README.mdx | 16 - .../airs/README.md | 210 - .../clonal-selection-algorithms/airs/abr.md | 47 - .../clonal-selection-algorithms/clonalg.md | 198 - .../aisp-techniques/immune-network-theory.md | 41 + .../immune-network-theory/AiNet.md | 322 -- .../immune-network-theory/README.mdx | 39 - .../aisp-techniques/negative-selection.md | 50 + .../negative-selection/BNSA.md | 143 - .../negative-selection/README.md | 42 - .../negative-selection/RNSA.md | 241 -- versioned_docs/version-0.5.x/api/README.md | 85 + .../version-0.5.x/api/base/README.md | 33 + .../version-0.5.x/api/base/base-classifier.md | 133 + .../version-0.5.x/api/base/base-clusterer.md | 122 + .../version-0.5.x/api/base/base-optimizer.md | 165 + .../version-0.5.x/api/base/immune/README.md | 22 + .../api/base/immune/cell/README.md | 33 + .../api/base/immune/cell/antibody.md | 39 + .../api/base/immune/cell/b-cell.md | 63 + .../api/base/immune/cell/c-cell.md | 35 + .../api/base/immune/cell/detector.md | 28 + .../version-0.5.x/api/base/immune/mutation.md | 145 + .../api/base/immune/populations.md | 56 + .../version-0.5.x/api/csa/README.md | 33 + versioned_docs/version-0.5.x/api/csa/airs.md | 197 + .../version-0.5.x/api/csa/clonalg.md | 183 + .../version-0.5.x/api/exceptions.md | 91 + .../version-0.5.x/api/ina/README.md | 31 + .../version-0.5.x/api/ina/ai-net.md | 227 ++ .../version-0.5.x/api/nsa/README.md | 35 + versioned_docs/version-0.5.x/api/nsa/bnsa.md | 193 + versioned_docs/version-0.5.x/api/nsa/rnsa.md | 222 ++ .../version-0.5.x/api/utils/README.md | 28 + .../version-0.5.x/api/utils/display/README.md | 23 + .../api/utils/display/progress-table.md | 57 + .../api/utils/display/table-formatter.md | 85 + .../version-0.5.x/api/utils/distance.md | 243 ++ .../version-0.5.x/api/utils/metrics.md | 47 + .../version-0.5.x/api/utils/multiclass.md | 82 + .../version-0.5.x/api/utils/sanitizers.md | 119 + .../version-0.5.x/api/utils/types.md | 60 + .../version-0.5.x/api/utils/validation.md | 180 + versioned_docs/version-0.5.x/faq.md | 48 +- versioned_docs/version-0.5.x/intro.md | 36 +- .../version-0.5.x-sidebars.json | 6 + 268 files changed, 15708 insertions(+), 11979 deletions(-) delete mode 100644 docs/advanced-guides/Core/_category_.json delete mode 100644 docs/advanced-guides/Core/negative-selection.md delete mode 100644 docs/advanced-guides/Utils/Display.md delete mode 100644 docs/advanced-guides/Utils/Distance.md delete mode 100644 docs/advanced-guides/Utils/Metrics.md delete mode 100644 docs/advanced-guides/Utils/Multiclass.md delete mode 100644 docs/advanced-guides/Utils/Random.md delete mode 100644 docs/advanced-guides/Utils/Sanitizers.md delete mode 100644 docs/advanced-guides/Utils/Validation.md delete mode 100644 docs/advanced-guides/Utils/_category_.json delete mode 100644 docs/advanced-guides/_category_.json delete mode 100644 docs/advanced-guides/base-module/_category_.json delete mode 100644 docs/advanced-guides/base-module/core/Base.md delete mode 100644 docs/advanced-guides/base-module/core/Classifier.md delete mode 100644 docs/advanced-guides/base-module/core/Clusterer.md delete mode 100644 docs/advanced-guides/base-module/core/Optimizer.md delete mode 100644 docs/advanced-guides/base-module/immune/cell.md delete mode 100644 docs/advanced-guides/base-module/immune/mutation.md delete mode 100644 docs/advanced-guides/base-module/immune/populations.md create mode 100644 docs/aisp-techniques/clonal-selection-algorithms.md delete mode 100644 docs/aisp-techniques/clonal-selection-algorithms/README.mdx delete mode 100644 docs/aisp-techniques/clonal-selection-algorithms/airs/README.md delete mode 100644 docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md delete mode 100644 docs/aisp-techniques/clonal-selection-algorithms/clonalg.md create mode 100644 docs/aisp-techniques/immune-network-theory.md delete mode 100644 docs/aisp-techniques/immune-network-theory/AiNet.md delete mode 100644 docs/aisp-techniques/immune-network-theory/README.mdx create mode 100644 docs/aisp-techniques/negative-selection.md delete mode 100644 docs/aisp-techniques/negative-selection/BNSA.md delete mode 100644 docs/aisp-techniques/negative-selection/README.md delete mode 100644 docs/aisp-techniques/negative-selection/RNSA.md create mode 100644 docs/api/README.md create mode 100644 docs/api/base/README.md create mode 100644 docs/api/base/base-classifier.md create mode 100644 docs/api/base/base-clusterer.md create mode 100644 docs/api/base/base-optimizer.md create mode 100644 docs/api/base/immune/README.md create mode 100644 docs/api/base/immune/cell/README.md create mode 100644 docs/api/base/immune/cell/antibody.md create mode 100644 docs/api/base/immune/cell/b-cell.md create mode 100644 docs/api/base/immune/cell/c-cell.md create mode 100644 docs/api/base/immune/cell/detector.md create mode 100644 docs/api/base/immune/mutation.md create mode 100644 docs/api/base/immune/populations.md create mode 100644 docs/api/csa/README.md create mode 100644 docs/api/csa/airs.md create mode 100644 docs/api/csa/clonalg.md create mode 100644 docs/api/exceptions.md create mode 100644 docs/api/ina/README.md create mode 100644 docs/api/ina/ai-net.md create mode 100644 docs/api/nsa/README.md create mode 100644 docs/api/nsa/bnsa.md create mode 100644 docs/api/nsa/rnsa.md create mode 100644 docs/api/utils/README.md create mode 100644 docs/api/utils/display/README.md create mode 100644 docs/api/utils/display/progress-table.md create mode 100644 docs/api/utils/display/table-formatter.md create mode 100644 docs/api/utils/distance.md create mode 100644 docs/api/utils/metrics.md create mode 100644 docs/api/utils/multiclass.md create mode 100644 docs/api/utils/sanitizers.md create mode 100644 docs/api/utils/types.md create mode 100644 docs/api/utils/validation.md create mode 100644 docs/architecture.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/negative-selection.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Display.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Metrics.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Sanitizers.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/README.mdx delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/README.mdx create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/README.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-classifier.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-clusterer.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-optimizer.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/antibody.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/b-cell.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/c-cell.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/detector.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/mutation.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/populations.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/exceptions.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/progress-table.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/table-formatter.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/distance.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/metrics.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/multiclass.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/sanitizers.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/types.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/validation.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/current/architecture.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md delete mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-classifier.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-clusterer.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-optimizer.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/antibody.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/b-cell.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/c-cell.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/detector.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/mutation.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/populations.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/exceptions.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/README.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/progress-table.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/table-formatter.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/distance.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/metrics.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/multiclass.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/sanitizers.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/types.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/validation.md create mode 100644 i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/architecture.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/_category_.json delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md delete mode 100644 versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md create mode 100644 versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md create mode 100644 versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx create mode 100644 versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md delete mode 100644 versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md create mode 100644 versioned_docs/version-0.5.x/api/README.md create mode 100644 versioned_docs/version-0.5.x/api/base/README.md create mode 100644 versioned_docs/version-0.5.x/api/base/base-classifier.md create mode 100644 versioned_docs/version-0.5.x/api/base/base-clusterer.md create mode 100644 versioned_docs/version-0.5.x/api/base/base-optimizer.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/README.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/cell/README.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/cell/antibody.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/cell/b-cell.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/cell/c-cell.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/cell/detector.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/mutation.md create mode 100644 versioned_docs/version-0.5.x/api/base/immune/populations.md create mode 100644 versioned_docs/version-0.5.x/api/csa/README.md create mode 100644 versioned_docs/version-0.5.x/api/csa/airs.md create mode 100644 versioned_docs/version-0.5.x/api/csa/clonalg.md create mode 100644 versioned_docs/version-0.5.x/api/exceptions.md create mode 100644 versioned_docs/version-0.5.x/api/ina/README.md create mode 100644 versioned_docs/version-0.5.x/api/ina/ai-net.md create mode 100644 versioned_docs/version-0.5.x/api/nsa/README.md create mode 100644 versioned_docs/version-0.5.x/api/nsa/bnsa.md create mode 100644 versioned_docs/version-0.5.x/api/nsa/rnsa.md create mode 100644 versioned_docs/version-0.5.x/api/utils/README.md create mode 100644 versioned_docs/version-0.5.x/api/utils/display/README.md create mode 100644 versioned_docs/version-0.5.x/api/utils/display/progress-table.md create mode 100644 versioned_docs/version-0.5.x/api/utils/display/table-formatter.md create mode 100644 versioned_docs/version-0.5.x/api/utils/distance.md create mode 100644 versioned_docs/version-0.5.x/api/utils/metrics.md create mode 100644 versioned_docs/version-0.5.x/api/utils/multiclass.md create mode 100644 versioned_docs/version-0.5.x/api/utils/sanitizers.md create mode 100644 versioned_docs/version-0.5.x/api/utils/types.md create mode 100644 versioned_docs/version-0.5.x/api/utils/validation.md diff --git a/docs/advanced-guides/Core/_category_.json b/docs/advanced-guides/Core/_category_.json deleted file mode 100644 index 650683c42..000000000 --- a/docs/advanced-guides/Core/_category_.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "description": "The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation" -} \ No newline at end of file diff --git a/docs/advanced-guides/Core/negative-selection.md b/docs/advanced-guides/Core/negative-selection.md deleted file mode 100644 index a85f9771f..000000000 --- a/docs/advanced-guides/Core/negative-selection.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Negative Selection - -The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation - -## Function check_detector_bnsa_validity(...) - -```python -def check_detector_bnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - aff_thresh: float -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters**: - -* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). -* aff_thresh (``float``): Affinity threshold. - -**returns**: - -* True if the detector is valid, False otherwise. - ---- - -## Function bnsa_class_prediction(...) - -```python -def bnsa_class_prediction( - features: npt.NDArray, - class_detectors: npt.NDArray, - aff_thresh: float -) -> int: -``` - -Defines the class of a sample from the non-self detectors. - -**Parameters**: - -* features (``npt.NDArray``): binary sample to be classified (shape: [n_features]). -* class_detectors (``npt.NDArray``): Array containing the detectors of all classes -(shape: [n_classes, n_detectors, n_features]). -* aff_thresh (``float``): Affinity threshold that determines whether a detector recognizes the sample as non-self. - -**returns**: - -* int: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- - -## Function check_detector_rnsa_validity(...) - -```python -def check_detector_rnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - threshold: float, - metric: int, - p: float -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters**: - -* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). -* threshold (``float``): threshold. -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**returns**: - -* int: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- diff --git a/docs/advanced-guides/Utils/Display.md b/docs/advanced-guides/Utils/Display.md deleted file mode 100644 index 51c3bbdb3..000000000 --- a/docs/advanced-guides/Utils/Display.md +++ /dev/null @@ -1,152 +0,0 @@ -# Display - -Utility Functions for Displaying Algorithm Information - -## def _supports_box_drawing() - -```python -def _supports_box_drawing() -> bool -``` - -Function to check if the terminal supports boxed characters. - -**Returns**: - -* ***bool*** (`bool`): True if the terminal likely supports boxed characters, False otherwise. - ---- - -## class TableFormatter - -Class to format tabular data into strings for display in the console. - -**Parameters**: - -* ***headers*** (`Mapping[str, int]`): Mapping of column names to their respective widths, in the format `{column_name: column_width}`. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -### def _border(left, middle, right, line, new_line=True) - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str -``` - -Create a horizontal border for the table. - -**Parameters**: - -* ***left*** (`str`): Character on the left side of the border. -* ***middle*** (`str`): Character separator between columns. -* ***right*** (`str`): Character on the right side of the border. -* ***line*** (`str`): Character used to fill the border. -* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is True). - -**Returns**: - -* ***border*** (`str`): String representing the horizontal border. - ---- - -### def get_header() - -```python -def get_header(self) -> str -``` - -Generate the table header, including the top border, column headings, and separator line. - -**Returns**: - -* ***header*** (`str`): Formatted string of the table header. - ---- - -### def get_row(values) - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str -``` - -Generate a formatted row for the table data. - -**Parameters**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Dictionary with values for each column, in the format `{column_name: value}`. - -**Returns**: - -* ***row*** (`str`): Formatted string of the table row. - ---- - -### def get_bottom(new_line=False) - -```python -def get_bottom(self, new_line: bool = False) -> str -``` - -Generate the table's bottom border. - -**Parameters**: - -* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is False). - -**Returns**: - -* ***bottom*** (`str`): Formatted string for the bottom border. - ---- - -## class ProgressTable(TableFormatter) - -Class to display a formatted table in the console to track the algorithm's progress. - -**Parameters**: - -* ***headers*** (`Mapping[str, int]`): Mapping `{column_name: column_width}`. -* ***verbose*** (`bool`): If False, prints nothing to the terminal. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -### def _print_header() - -```python -def _print_header(self) -> None -``` - -Print the table header. - ---- - -### def update(values) - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None -``` - -Add a new row of values to the table. - -**Parameters**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Keys must match the columns defined in headers. - ---- - -### def finish() - -```python -def finish(self) -> None -``` - -End the table display, printing the bottom border and total time. - ---- diff --git a/docs/advanced-guides/Utils/Distance.md b/docs/advanced-guides/Utils/Distance.md deleted file mode 100644 index 1ac5aba8b..000000000 --- a/docs/advanced-guides/Utils/Distance.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -last_update: - date: 2025/08/28 - author: João Paulo ---- - -# Distance - -Utility functions for normalized distance between arrays with numba decorators. - -## def hamming(...) - -```python -def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: -``` - -The function to calculate the normalized Hamming distance between two points. - -$$ -\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def euclidean(...) - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Function to calculate the normalized Euclidean distance between two points. - -$$ -\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def cityblock(...) - -```python -def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Function to calculate the normalized Manhattan distance between two points. - -$$ -\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def minkowski(...) - -```python -def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): -``` - -Function to calculate the normalized Minkowski distance between two points. - -$$ -\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. -* p float: The p parameter defines the type of distance to be calculated: - * p = 1: **Manhattan** distance — sum of absolute differences. - * p = 2: **Euclidean** distance — sum of squared differences (square root). - * p > 2: **Minkowski** distance with an increasing penalty as p increases. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def compute_metric_distance(...) - -```python -def compute_metric_distance( - u: npt.NDArray[np.float64], - v: npt.NDArray[np.float64], - metric: int, - p: np.float64 = 2.0 -) -> np.float64: -``` - -Function to calculate the distance between two points by the chosen ``metric``. - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* Distance (``double``) between the two points with the selected metric. - ---- - -## def min_distance_to_class_vectors(...) - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray, - vector_x: npt.NDArray, - metric: int, - p: float = 2.0 -) -> float: -``` - -Calculates the minimum distance between an input vector and the vectors of a class. - -**Parameters:** - -* x_class (``npt.NDArray``): Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Vector to be compared with the class vectors. Expected shape: (n_features,). -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* float: The minimum distance calculated between the input vector and the class vectors. -* Returns -1.0 if the input dimensions are incompatible. - ---- - -## def get_metric_code(...) - -```python -def get_metric_code(metric: str) -> int: -``` - -Returns the numeric code associated with a distance metric. - -**Parameters:** - -* metric (str): Name of the metric. Can be "euclidean", "manhattan", "minkowski" or "hamming". - -**Raises** - -* ``ValueError``: If the metric provided is not supported - -**Returns:** - -* ``int``: Numeric code corresponding to the metric. - ---- diff --git a/docs/advanced-guides/Utils/Metrics.md b/docs/advanced-guides/Utils/Metrics.md deleted file mode 100644 index d65da92c8..000000000 --- a/docs/advanced-guides/Utils/Metrics.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 1 -title: Metrics -sidebar_label: Metrics -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -The metrics file provides utilities to measure, analyze, and compare the performance of the package's algorithms in a standardized way. - -#### def accuracy_score(...) - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float -``` - -Function to calculate precision accuracy based on lists of true labels and -predicted labels. - -**Parameters**: - -* **_y_true_** (``Union[npt.NDArray, list]``): Ground truth (correct) labels. - Expected to be of the same length as `y_pred`. -* **_y_pred_** (``Union[npt.NDArray, list]``): Predicted labels. Expected to - be of the same length as `y_true`. - -Returns: - -* **_Accuracy_** (``float``): The ratio of correct predictions to the total -number of predictions. - -**Raises**: - -* `ValueError`: If `y_true` or `y_pred` are empty or if they do not have the same length. - ---- diff --git a/docs/advanced-guides/Utils/Multiclass.md b/docs/advanced-guides/Utils/Multiclass.md deleted file mode 100644 index dc919f82a..000000000 --- a/docs/advanced-guides/Utils/Multiclass.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -sidebar_position: 1 -title: Multiclass -sidebar_label: Multiclass -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -This file contains internal utility functions designed to simplify data manipulation and processing in multiclass classification scenarios within the AISP package. - -## def slice_index_list_by_class(...) - -```python -def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict -``` - -The function ``slice_index_list_by_class(...)``, separates the indices of the lines \ -according to the output class, to loop through the sample array, only in positions where \ -the output is the class being trained. - -**Parameters**: - -* ***classes*** (``list or npt.NDArray``): list with unique classes. -* ***y*** (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array. - -**returns**: - -* dict: A dictionary with the list of array positions(``y``), with the classes as key. - ---- - -## def predict_knn_affinity(...) - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray -``` - -Function to predict classes using k-nearest neighbors and trained cells. - -**Parameters:** - -* ***X*** (`npt.NDArray`): Input data to be classified. -* ***k*** (`int`): Number of nearest neighbors to consider for prediction. -* ***all_cell_vectors*** (`List[Tuple[Union[str, int], npt.NDArray]]`): List of tuples containing (class_name, cell vector) pairs. -* ***affinity_func*** (`Callable[[npt.NDArray, npt.NDArray], float]`): Function that takes two vectors and returns an affinity value. - -**Returns:** - -* `npt.NDArray`: Array of predicted labels for each sample in X, based on the k nearest neighbors. diff --git a/docs/advanced-guides/Utils/Random.md b/docs/advanced-guides/Utils/Random.md deleted file mode 100644 index 8bcd03930..000000000 --- a/docs/advanced-guides/Utils/Random.md +++ /dev/null @@ -1,17 +0,0 @@ -# Random - -Utility functions for random number generation and reproducibility. - -## Function set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Set the seed for random numbers used by functions compiled with Numba. - -**Parameters**: - -* **seed**: `int` - Integer value used to initialize Numba's random number generator. diff --git a/docs/advanced-guides/Utils/Sanitizers.md b/docs/advanced-guides/Utils/Sanitizers.md deleted file mode 100644 index b57a80539..000000000 --- a/docs/advanced-guides/Utils/Sanitizers.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Sanitizers - -## def sanitize_choice(...) - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T -``` - -The function ``sanitize_choice(...)``, returns the value if it is present in the set of valid choices; otherwise, returns the default value. - -**Parameters:** - -* ***value*** (``T``): The value to be checked. -* ***valid_choices*** (``Iterable[T]``): A collection of valid choices. -* ***default***: The default value to be returned if ``value`` is not in ``valid_choices``. - -**Returns:** - -* `T`: The original value if valid, or the default value if not. - ---- - -## def sanitize_param(...) - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -The function ``sanitize_param(...)``, returns the value if it satisfies the specified condition; otherwise, returns the default value. - -**Parameters:** - -* value (``T``): The value to be checked. -* default (``T``): The default value to be returned if the condition is not satisfied. -* condition (``Callable[[T], bool]``): A function that takes a value and returns a boolean, determining if the value is valid. - -**Returns:** - -* `T`: The original value if the condition is satisfied, or the default value if not. - ---- - -## def sanitize_seed(...) - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -The function ``sanitize_param(...)``, returns the seed if it is a non-negative integer; otherwise, returns None. - -**Parameters:** - -* seed (``Any``): The seed value to be validated. - -**Returns:** - -* ``Optional[int]``: The original seed if it is a non-negative integer, or ``None`` if it is invalid. - ---- - -## def sanitize_bounds(...) - -```python -def sanitize_bounds( - bounds: Any, - problem_size: int -) -> Dict[str, npt.NDArray[np.float64]] -``` - -The function ``sanitize_bounds(...)``, validate and normalize feature bounds. - -**Parameters:** - -* ***bounds*** (``Any``): he input bounds, which must be either None or a dictionary with 'low' and 'high' keys. -* ***problem_size*** (``int``): The expected length for the normalized bounds lists, corresponding to the number of features in the problem. - -**Returns:** - -* `Dict[str, list]`: Dictionary ``{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}``. diff --git a/docs/advanced-guides/Utils/Validation.md b/docs/advanced-guides/Utils/Validation.md deleted file mode 100644 index c0d5bba6b..000000000 --- a/docs/advanced-guides/Utils/Validation.md +++ /dev/null @@ -1,104 +0,0 @@ -# Validation - -## def detect_vector_data_type(...) - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detects the type of data in a given vector. - -This function analyzes the input vector and classifies its data as one of the supported types: - -* **binary**: Boolean values (`True`/`False`) or integer `0`/`1`. -* **continuous**: Float values within the normalized range `[0.0, 1.0]`. -* **ranged**: Float values outside the normalized range. - -### Parameters - -* `vector` (`npt.NDArray`): An array containing the data to be classified. - -### Returns - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): The detected type of data in the vector. - -### Raises - -* `UnsupportedDataTypeError`: Raised if the vector contains an unsupported data type. - ---- - -## def check_array_type(...) - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Ensure X is a numpy array. Convert from list if needed. - -### Parameters - -* `x` (`Any`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `name` (`str`, default='X'): Variable name used in error messages. - -### Returns - -* `npt.NDArray`: The converted or validated array. - -### Raises - -* `TypeError`: If X or y are not ndarrays or have incompatible shapes. - ---- - -## def check_shape_match(...) - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Ensure X and y have compatible first dimensions. - -### Parameters - -* `x` (`npt.NDArray`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `y` (`npt.NDArray`): Array of target classes of `x` with [`N samples` (lines)]. - -### Raises - -* `TypeError`: If x or y are not ndarrays or have incompatible shapes. - ---- - -## def check_feature_dimension(...) - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Ensure X has the expected number of features. - -### Parameters - -* `x` (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `expected` (`int`): Expected number of features per sample (columns in X). - -### Raises - -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. - ---- - -## def check_binary_array(...) - -```python -def check_binary_array(x: npt.NDArray): -``` - -Ensure X contains only 0 and 1. - -### Raises - -* `ValueError`: If feature_type is binary-features and X contains values that are not composed only of 0 and 1. diff --git a/docs/advanced-guides/Utils/_category_.json b/docs/advanced-guides/Utils/_category_.json deleted file mode 100644 index c57d4b807..000000000 --- a/docs/advanced-guides/Utils/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "label": "Utils", - "description": "Utility functions and helpers for development." -} \ No newline at end of file diff --git a/docs/advanced-guides/_category_.json b/docs/advanced-guides/_category_.json deleted file mode 100644 index 020788b9f..000000000 --- a/docs/advanced-guides/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Guides", - "position": 2.6, - "link": { - "type": "generated-index", - "description": "Explore the advanced documentation of the library, covering the base classes and the utility functions in utils for metrics and multiclass classification handling." - } -} \ No newline at end of file diff --git a/docs/advanced-guides/base-module/_category_.json b/docs/advanced-guides/base-module/_category_.json deleted file mode 100644 index d6566b364..000000000 --- a/docs/advanced-guides/base-module/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Base module", - "position": 1, - "description": "Base class for classification algorithm." -} \ No newline at end of file diff --git a/docs/advanced-guides/base-module/core/Base.md b/docs/advanced-guides/base-module/core/Base.md deleted file mode 100644 index 2d458c1b8..000000000 --- a/docs/advanced-guides/base-module/core/Base.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_position: 1 -title: Base class -sidebar_label: Base -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Class - - Model Base - - Scikit-learn Compatibility - - get_params - - set_params - - Random Seed - - Python Classes ---- - -Base class for scikit-learn API compatibility. - -Provides the `get_params` and `set_params` methods for compatibility with the scikit-learn API, allowing access to the model's public parameters. - -### Function set_params(...) - -```python -def set_params(self, **params) -``` - -Set the parameters of the instance. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **params**: ``dict`` - Dictionary of parameters to set as attributes on the instance. Only public attributes (not starting with "_") are modified. - -**Returns**: - -* self: `Base` - Returns the instance itself after setting the parameters. - ---- - -### Function get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Return a dictionary with the object's main parameters. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **deep**: `bool` - Ignored in this implementation but included for scikit-learn compatibility. - -**Returns**: - -* params: `dict` - Dictionary containing the object's attributes that do not start with "_". diff --git a/docs/advanced-guides/base-module/core/Classifier.md b/docs/advanced-guides/base-module/core/Classifier.md deleted file mode 100644 index 86baa60f3..000000000 --- a/docs/advanced-guides/base-module/core/Classifier.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -sidebar_position: 2 -title: Base class for classification algorithm. -sidebar_label: BaseClassifier -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Classifier - - Classification - - Abstract Base Class - - BaseClassifier - - Machine Learning - - Supervised Learning - - fit Method - - predict Method - - score Method - - Model Evaluation - - Accuracy - - Python ML Classes - - RNSA - - BNSA ---- - -## ``class BaseClassifier(ABC, Base)`` - -Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``, and implementing the ``get_params`` method. - -## Abstract methods - -### def fit(...) - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Fit the model to the training data. - -Implementation: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-fit) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-fit) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) - -### def predict(...) - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -Performs label prediction for the given data. - -Implementation: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-predict) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-predict) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) - ---- - -## Methods - -### def score(...) - -```python -def score(self, X: npt.NDArray, y: list) -> float -``` - -Score function calculates forecast accuracy. - -This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. -This function was added for compatibility with some scikit-learn functions. - -**Parameters**: - -- ***X***: ``np.ndarray`` - Feature set with shape (n_samples, n_features). -- ***y***: ``np.ndarray`` - True values with shape (n_samples,). - -**Returns**: - -- accuracy: ``float`` The accuracy of the model. - -### Function _slice_index_list_by_class(...) - -The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class, to go through the sample array, only in the positions that the output is the class that is being trained: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Returns a dictionary with the classes as key and the indices in ``X`` of the samples. diff --git a/docs/advanced-guides/base-module/core/Clusterer.md b/docs/advanced-guides/base-module/core/Clusterer.md deleted file mode 100644 index 559c30499..000000000 --- a/docs/advanced-guides/base-module/core/Clusterer.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -sidebar_position: 3 -title: Base class for clustering algorithm. -sidebar_label: BaseClusterer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Clusterer - - Clustering - - Unsupervised Learning - - BaseClusterer - - Abstract Base Class - - fit Method - - predict Method - - fit_predict Method - - AiNet - - Cluster Prediction - - Python ML Classes ---- - - -## ``BaseClusterer(ABC, Base)`` - -Abstract base class for clustering algorithms. - -This class defines the core interface for clustering models. It enforces -the implementation of the **`fit`** and **`predict`** methods in all derived classes, -and provides a default implementation for **`fit_predict`** and **`get_params`**. - ---- - -### Function fit(...) - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer -``` - -Fit the model to the training data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data used for training the model. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during training. - -**Returns**: - -* ***self***: - Instance of the class that implements this method. - -**Implementation**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) - ---- - -### Function predict(...) - -```python -def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] -``` - -Generate predictions based on the input data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data for which predictions will be generated. - -**Returns**: - -* ***predictions***: `Optional[npt.NDArray]` - Predicted cluster labels for each input sample, or `None` if prediction is not possible. - -**Implementation**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) - ---- - -### Function fit_predict(...) - -```python -def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] -``` - -Convenience method that combines `fit` and `predict` in a single call. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data for which predictions will be generated. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during training. - -**Returns**: - -* ***predictions***: `Optional[npt.NDArray]` - Predicted cluster labels for each input sample, or `None` if prediction is not possible. diff --git a/docs/advanced-guides/base-module/core/Optimizer.md b/docs/advanced-guides/base-module/core/Optimizer.md deleted file mode 100644 index aa33b86cf..000000000 --- a/docs/advanced-guides/base-module/core/Optimizer.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -sidebar_position: 4 -title: Base class for optimization algorithms. -sidebar_label: BaseOptimizer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - BaseOptimizer - - base class - - optimization algorithms - - abstract base class - - machine learning optimization - - supervised learning - - optimize method - - objective function - - model evaluation - - Python ML classes - - Clonalg - - metaheuristics ---- - - -This class defines the core interface for optimization strategies and -keeps track of the cost history, evaluated solutions, and the best solution found. Subclasses must implement -``optimize`` and ``objective_function``. - ---- - -### Properties - -#### `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Returns the history of costs during optimization. - ---- - -#### `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Returns the history of evaluated solutions. - ---- - -#### `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Returns the best solution found so far, or `None` if unavailable. - ---- - -#### `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Returns the cost of the best solution found so far, or `None` if unavailable. - ---- - -## Functions - -### Function _record_best(...) - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Record a new cost value and update the best solution if improved. - -**Parameters**: - -* ***cost***: `float` - Cost value to be added to the history. - ---- - -### Function get_report() - -```python -def get_report(self) -> str -``` - -Generate a formatted summary report of the optimization process. The report includes the best solution, -its associated cost, and the evolution of cost values per iteration. - -**Returns**: - -* **report**: `str` - A formatted string containing the optimization summary. - ---- - -### Function register(...) - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Register a function dynamically in the optimizer instance. - -**Parameters**: - -* ***alias***: `str` - Name used to access the function as an attribute. -* ***function***: `Callable[..., Any]` - Callable to be registered. - -**Raises**: - -* **TypeError**: If `function` is not callable. -* **AttributeError**: If `alias` is protected and cannot be modified, or if `alias` does not exist in the - optimizer class. - ---- - -### Function reset() - -```python -def reset(self) -``` - -Reset the object's internal state, clearing history and resetting values. - ---- - -### Abstract methods - -#### Function optimize(...) - -```python -def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any -``` - -Execute the optimization process. This method must be implemented by the subclass to define how the optimization strategy explores the search space. - -**Parameters**: - -* ***max_iters***: `int` - Maximum number of iterations. -* ***n_iter_no_change***: `int`, default=10 - The maximum number of iterations without updating the best solution. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during optimization. - -**Implementation**: - -* [Clonalg](../../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) - ---- - -#### Function affinity_function(...) - -```python -def affinity_function(self, solution: Any) -> float -``` - -Evaluate the affinity of a candidate solution. This method must be implemented by the subclass to define the problem-specific. - -**Parameters**: - -* ***solution***: `Any` - Candidate solution to be evaluated. - -**Returns**: - -* **cost**: `float` - Cost value associated with the given solution. diff --git a/docs/advanced-guides/base-module/immune/cell.md b/docs/advanced-guides/base-module/immune/cell.md deleted file mode 100644 index 1ceacb91b..000000000 --- a/docs/advanced-guides/base-module/immune/cell.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Cell Classes -sidebar_label: Cell Classes -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -Representation of immune system cells. - -## Cell - -Represents a basic immune cell. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Attributes - -* **vector** (`np.ndarray`): A vector of cell features. - -### Methods - -* `__eq__(other)`: Check if two cells are equal based on their vectors. -* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. -* `__getitem__(item)`: Get elements from the feature vector using indexing. - ---- - -## BCell - -Represents a memory B-cell. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Methods - -#### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> np.ndarray -``` - -Clones N features from a cell's features, generating a set of mutated vectors. - -##### Parameters - -* **n** (`int`): Number of clones to be generated from mutations of the original cell. -* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): - Specifies the type of feature_type to use based on the nature of the input features -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -##### Returns - -* **npt.NDArray**: An array containing N mutated vectors from the original cell. - ---- - -## Antibody - -Represent an antibody. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Attributes - -* **vector** (`npt.NDArray`): A vector of cell features. -* **affinity** (`float`): Affinity value for the antibody. - -### Methods - -* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. -* `__eq__(other)`: Check if this cell has the same affinity as another cell. - ---- - -## Detector - -Represents a non-self detector of the RNSA class. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Attributes - -* **position** (`npt.NDArray[np.float64]`): Detector feature vector. -* **radius** (`Optional[float]`): Detector radius, used in the V-detector algorithm. diff --git a/docs/advanced-guides/base-module/immune/mutation.md b/docs/advanced-guides/base-module/immune/mutation.md deleted file mode 100644 index d6c3082cd..000000000 --- a/docs/advanced-guides/base-module/immune/mutation.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutation -sidebar_label: Mutation -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - Mutation - - Clonal Expansion - - Immune System - - clone_and_mutate - - clone_and_mutate_continuous - - clone_and_mutate_binary - - clone_and_mutate_ranged - - Artificial Immune Systems - - Python Numba Functions - - Vector Mutation ---- - -Contains functions that generate sets of mutated clones from continuous or binary vectors, simulating the clonal expansion process in artificial immune systems. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector. - -This function creates `n` clones of the input vector and applies random mutations to each one, simulating the clonal expansion process in artificial immune systems. Each clone receives a random number of mutations at distinct positions of the original vector. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int -) -> npt.NDArray[np.bool_]: -``` - -Generates a set of mutated clones from a binary vector. - -This function creates `n` clones of the input binary vector and applies random mutations to some bits, simulating clonal expansion in artificial immune systems with discrete representations. - -### Parameters - -* `vector` (`npt.NDArray[np.bool_]`): The original immune cell with binary values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. - -### Returns - -* `clone_set` (`npt.NDArray[np.bool_]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64] -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector using custom bounds per dimension. - -This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied to distinct positions of the original vector, respecting the mutation bounds defined per dimension. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `bounds` (`npt.NDArray[np.float64]`): A 2D array with shape `(len(vector), 2)` containing the minimum and maximum values for each dimension. - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_permutation - -```python -@njit([(types.int64[:], types.int64, types.float64)], cache=True) -def clone___and_mutate_permutation( - vector: npt.NDArray[np.int64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.int64]: -``` - -Generates a set of mutated clones from a permutation vector. - -This function creates `n` clones of the input permutation vector and applies random mutations to each one, simulating clonal expansion in artificial immune systems with discrete permutations. Each clone receives a random number of swaps according to the mutation rate. - -### Parameters - -* `vector` (`npt.NDArray[np.int64]`): The original immune cell with permutation values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `mutation_rate` (`float`): Probability of mutating each component ($$0 <= mutation\_rate < 1$$). - -### Returns - -* `clone_set` (`npt.NDArray[np.int64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. diff --git a/docs/advanced-guides/base-module/immune/populations.md b/docs/advanced-guides/base-module/immune/populations.md deleted file mode 100644 index 3944371fc..000000000 --- a/docs/advanced-guides/base-module/immune/populations.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Populations Module -sidebar_label: Populations -pagination_next: null -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell - - Clonal Expansion - - Immune System - - Artificial Immune Systems -lastUpdatedAt: 2025/11/21 -author: João Paulo ---- - -Utility functions for generating antibody populations in immunological algorithms. - -## generate_random_antibodies(...) - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -Generate a random antibody population. - -### Parameters - -* **n_samples** (`int`): Number of antibodies (samples) to generate. -* **n_features** (`int`): Number of features (dimensions) for each antibody. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -### Returns - -* **npt.NDArray**: Array of shape (n_samples, n_features) containing the generated antibodies. - -### Raises - -* **ValueError**: If the number of features is less than or equal to zero. \ No newline at end of file diff --git a/docs/aisp-techniques/clonal-selection-algorithms.md b/docs/aisp-techniques/clonal-selection-algorithms.md new file mode 100644 index 000000000..669d832a9 --- /dev/null +++ b/docs/aisp-techniques/clonal-selection-algorithms.md @@ -0,0 +1,39 @@ +--- +id: docs-csa +keywords: + - clonal selection and expansion + - clonalg + - artificial immune systems + - classification + - optimization + - bio-inspired algorithms + - natural computing +--- + +# Clonal selection and expansion + +Algorithms based on clonal selection and expansion are inspired by the process of antibody proliferation after the +detection of an antigen, during which the generated antibodies undergo mutations in an attempt to improve pathogen +recognition. [^1] + +--- + +Clonal selection and expansion can be applied in different contexts, such as: +- **Optimization** +- **Classification** + +## Package implementation + +### Artificial Immune Recognition System ([AIRS](../api/csa/airs.md)) + +Classification algorithm inspired by the clonal selection process. + +### Clonal Selection Algorithm ([CLONALG](../api/csa/clonalg.md)) + +Optimization algorithm inspired by the biological process of clonal selection of the immune system. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Available at: https://dx.doi.org/10.1007/978-3-662-43631-8. \ No newline at end of file diff --git a/docs/aisp-techniques/clonal-selection-algorithms/README.mdx b/docs/aisp-techniques/clonal-selection-algorithms/README.mdx deleted file mode 100644 index 79e838162..000000000 --- a/docs/aisp-techniques/clonal-selection-algorithms/README.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_position: 2 -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- -import DocCardList from '@theme/DocCardList'; - -# Clonal Selection Algorithm. - - -Clonal Selection Algorithms are inspired by the process of antibody proliferation upon detecting an antigen, during which -the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. - -## Classes: - - \ No newline at end of file diff --git a/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md b/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md deleted file mode 100644 index 9e5231210..000000000 --- a/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ /dev/null @@ -1,210 +0,0 @@ ---- -id: airs -sidebar_label: AIRS - Artificial Immune Recognition System -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -# AIRS - Artificial Immune Recognition System - -The ``AIRS`` class aims to perform classification using metaphors of selection and clonal expansion. - -This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. -Introducing adaptations to handle continuous and binary datasets. - -Based on Algorithm 16.5 from Brabazon et al. [1](#1). - -:::tip Related and noteworthy works: - -- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) - -::: - -:::info - -**``AIRS``** extends the **[``BaseClassifier`` class](../../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## AIRS Constructor - -**Attributes:** - -- **n_resources** (``float``): Total amount of available resources. Defaults to 10. -- **rate_clonal** (``float``): Maximum number of possible clones of a class. This quantity is multiplied by (cell stimulus * rate_hypermutation) to define the number of clones. Defaults to 10. -- **rate_hypermutation** (``int``): The rate of mutated clones derived from rate_clonal as a scalar factor. Defaults to 0.75. -- **affinity_threshold_scalar** (``float``): Normalized affinity threshold. Defaults to 0.75. -- **k** (``int``): The number of K nearest neighbors that will be used to choose a label in the prediction. Defaults to 10. -- **max_iters** (``int``): Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. Defaults to 100. -- **resource_amplified** (``float``): Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. -- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - - ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - - ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - - ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to **"Euclidean"**. - -- **seed** (``Optional[int]``): Seed for the random generation of detector values. Defaults to None. - -- ``**kwargs``: - - **p** (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. - The default is ``2``, which means normalized Euclidean distance. Different values of p lead to different variants of the Minkowski distance. [Learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Other initialized variables:** - -- **cells_memory** (``dict``): This variable stores a list of memory cells by class. -- **affinity_threshold** (``dict``): Defines the affinity threshold between antigens. -- **classes** (``npt.NDArray``): List of output classes. - ---- - -## Public Methods - -### Function fit(...) - -The ``fit(...)`` function generates detectors for the non-owners relative to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -> AIRS: -``` - -It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). - -**Input parameters:** - -- **X**: Array with sample features, with **N** samples (rows) and **N** features (columns), normalized to values between [0, 1]. -- **y**: Array with output classes corresponding to **N** samples related to ``X``. -- **verbose**: Boolean, default ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the class instance.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**Input parameter:** - -- **X**: Array with the features for prediction, with **N** samples (rows) and **N** columns. - -**Returns:** - -- **C**: An array of predictions with the output classes for the given features. -- **None**: If there are no detectors. - ---- - -### Function score(...) - -The ``score(...)`` function calculates the accuracy of the trained model by making predictions and calculating the accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -Returns accuracy as a ``float``. - ---- - -## Private Methods - -### Function _refinement_arb(...) - -The function "_refinement_arb(...)" refines the ARB set until the average stimulation value exceeds the defined threshold (``affinity_threshold_scalar``). - -```python -def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: -``` - -Parameters: - -- **c_match** (``Cell``): Cell with the highest stimulation relative to aᵢ. -- **arb_list** (``List[_ARB]``): ARB set. - -Returns the cell (_ARB) with the highest ARB stimulation. - ---- - -### Function _cells_affinity_threshold(...) - -The function "_cells_affinity_threshold(...)" calculates the affinity threshold based on the average affinity between training instances, where aᵢ and aⱼ are a pair of antigens, and affinity is measured by distance (Euclidean, Manhattan, Minkowski, Hamming). -**Following the formula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - -Parameters: - -- **antigens_list** (``NDArray``): List of training antigens. - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - ---- - -### Function _affinity(...) - -The function "_affinity(...)" calculates the stimulus between two vectors using metrics. - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -Parameters: - -- **u** (``npt.NDArray``): Coordinates of the first point. -- **v** (``npt.NDArray``): Coordinates of the second point. - -Returns the stimulus rate between the vectors. - ---- - -### Function _init_memory_c(...) - -The function "_init_memory_c(...)" initializes memory cells by randomly selecting `n_antigens_selected` from the list of training antigens. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[BCell]: -``` - -Parameters: - -- **antigens_list** (``NDArray``): List of training antigens. - -Returns - -- ``List[BCell]``: List of initialized memories. - ---- - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md deleted file mode 100644 index bf2bcf614..000000000 --- a/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -id: abr -title: ABR -sidebar_label: ABR - Artificial Recognition Ball -sidebar_position: 2 -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -## ABR (Artificial Recognition Ball) - -Individual from the set of recognizing cells (ABR), inherits characteristics from a B-cell, adding resource consumption - -:::info - -**``ABR``** extends the **[``BCell`` class](../../../advanced-guides/base-module/immune/cell.md#BCell)**, inheriting its base functionality. - -::: - -### Constructor - -Parameters: - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Function consume_resource(...) - -Parameters: - -* n_resource (```float```) : The initial amount of resources. -* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -Returns the remaining amount of resources after consumption. diff --git a/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md b/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md deleted file mode 100644 index 7ee8a2daf..000000000 --- a/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -id: clonalg -sidebar_label: CLONALG - Clonal Selection Algorithm -keywords: - - CLONALG - - clonal selection algorithm - - optimization - - binary optimization - - real-valued optimization - - ranged-value problems - - permutation problems - - metaheuristics - - bio-inspired algorithms - - machine learning optimization -lastUpdatedAt: 2025/09/21 -author: João Paulo ---- - -# CLONALG - Clonal Selection Algorithm - -The `Clonalg` class is an **optimization algorithm** inspired by the biological process of clonal selection in the immune system. This implementation is designed for minimizing or maximizing cost functions in various problem types, including binary, continuous, ranged-value, and permutation problems. - -:::tip -The CLONALG implementation was inspired by the description presented in [1](#1). -::: - -:::info -This CLONALG implementation contains some changes based on the AISP context, for general -application to various problems, which may produce results different from the standard or -specific implementation. This adaptation aims to generalize CLONALG to minimization and -maximization tasks, in addition to supporting continuous, discrete, and permutation problems. -::: - -:::info - -**``Clonalg``** extends the **[``BaseOptimizer`` class](../../advanced-guides/base-module/core/Optimizer.md)**, inheriting its base functionality. - -::: - ---- - -## CLONALG Constructor - -The constructor initializes the CLONALG instance with key parameters that define the optimization process. - -**Attributes:** - -* **problem_size**: `int` - The dimension of the problem to be optimized. -* **N**: `int`, default=50 - The number of memory cells (antibodies) in the population. -* **rate_clonal**: `float`, default=10 - The maximum number of possible clones of a cell. This value is multiplied by the cell's affinity to determine the number of clones. -* **rate_hypermutation**: `float`, default=0.75 - The rate of mutated clones, used as a scalar factor. -* **n_diversity_injection**: `int`, default=5 - The number of new random memory cells injected to maintain diversity. -* **selection_size**: `int`, default=5 - The number of best antibodies selected for cloning. -* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, default=None - The objective function used to evaluate candidate solutions. -* **feature_type**: `FeatureTypeAll`, default='ranged-features' - The type of problem samples, which can be `'continuous-features'`, `'binary-features'`, `'ranged-features'`, or `'permutation-features'`. -* **bounds**: `Optional[Dict]`, default=None - A dictionary defining the search limits for `'ranged-features'` problems. Can be a single fixed range or a list of ranges for each dimension. -* **mode**: `Literal["min", "max"]`, default="min" - Specifies whether the algorithm minimizes or maximizes the cost function. -* **seed**: `Optional[int]`, default=None - A seed for random number generation. - ---- - -## Public Methods - -### Function `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -This method execute the optimization process and return the population. - -**Input parameters:** - -* **max_iters**: `int`, default=50 - The maximum number of interactions. -* **n_iter_no_change**: `int`, default=10 - The maximum number of iterations without an improvement in the best solution. -* **verbose**: `bool`, default=True - A flag to enable or disable detailed output during the optimization process. - -**Returns:** - -* population : ``List[Antibody]``, [Antibody](../../advanced-guides/base-module/immune/cell.md#Antibody) population after clonal expansion. - ---- - -### Function `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -This method evaluates the affinity of a candidate solution. It raises a `NotImplementedError` if no affinity function has been provided to the class instance. - -**Input parameters:** - -* **solution**: `npt.NDArray` - The candidate solution to be evaluated. - -**Returns:** - -* `np.float64`: The affinity value associated with the solution. - ---- - -## Private Methods - -### Function `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: -``` - -This method selects the top `n` antibodies based on their affinity scores, according to the `mode` (`'min'` or `'max'`). - -**Input parameters:** - -* **n**: `int` - The number of antibodies to select. -* **antibodies**: `list[tuple]` - A list of tuples, where each tuple represents an antibody and its associated score. - -**Returns:** - -* `list[tuple]`: A list containing the `n` selected antibodies. - ---- - -### Function `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -This method initializes the initial population of antibodies randomly. - -**Returns:** - -* `npt.NDArray`: A list of the initialized antibodies. - ---- - -### Function `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -This method introduces new random antibodies into the population to maintain genetic diversity and help prevent premature convergence. - -**Returns:** - -* `npt.NDArray`: An array of new random antibodies. - ---- - -### Function `_clone_and_mutate(...)` - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: -``` - -This method generates mutated clones from a single antibody. The mutation strategy depends on the `feature_type` specified during initialization (`'binary-features'`, `'continuous-features'`, `'ranged-features'`, or `'permutation-features'`). - -**Input parameters:** - -* **antibody**: `npt.NDArray` - The original antibody vector to be cloned and mutated. -* **n_clone**: `int` - The number of clones to generate. -* **rate_hypermutation**: `float` - The hypermutation rate. - -**Returns:** - -* `npt.NDArray`: An array containing the mutated clones. - ---- - -### Function `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation(self, population: list[tuple]) -> list: -``` - -This method clones and hypermutates a population of antibodies. It returns a list of all clones and their affinities with respect to the cost function. - -**Input parameters:** - -* **population**: `list[tuple]` - The list of antibodies to be evaluated and cloned. - -**Returns:** - -* `list`: A list of mutated clones. - ---- - -## References - -### 1 -> -> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/docs/aisp-techniques/immune-network-theory.md b/docs/aisp-techniques/immune-network-theory.md new file mode 100644 index 000000000..065a2f852 --- /dev/null +++ b/docs/aisp-techniques/immune-network-theory.md @@ -0,0 +1,41 @@ +--- +id: docs-ina +keywords: + - immune network theory + - ainet + - artificial immune systems + - classification + - clustering + - optimization + - bio-inspired algorithms + - natural computing +--- + +# Immune network theory + +This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, in which +cells and molecules are capable of recognizing each other. [^1] + +--- + +The Artificial Immune Network can be applied in different contexts, such as: +- **Clustering** +- **Optimization** +- **Classification** + +## Package implementation + +### Artificial Immune Network for clustering and compression ([AiNet](../api/ina/ai-net.md)) + +AiNet is a clustering algorithm based on immune network theory that uses clonal selection and affinity maturation +to compress data and identify groups [^2]. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis diff --git a/docs/aisp-techniques/immune-network-theory/AiNet.md b/docs/aisp-techniques/immune-network-theory/AiNet.md deleted file mode 100644 index 5f6807b93..000000000 --- a/docs/aisp-techniques/immune-network-theory/AiNet.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -id: ainet -sidebar_label: AiNet - Clustering and Compression -sidebar_position: 1 -pagination_next: null -keywords: - - Artificial Immune Network - - AiNet - - Clustering - - Data Compression - - Immune Algorithms - - Bioinspired Computing - - Memory Cells - - Affinity Threshold - - Suppression Threshold - - Clonal Selection - - Clonal Expansion - - Diversity Introduction - - Pattern Recognition - - Anomaly Detection - - MST Clustering - - Minimum Spanning Tree - - Unsupervised Learning - - Bioinspired Algorithms - - Antibody Network -lastUpdatedAt: 2025/08/19 -author: João Paulo ---- - -# AiNet - Artificial Immune Network para Clustering and Compression - -The AiNet class aims to perform clustering using metaphors inspired by immune network theory. - -This class implements the aiNet algorithm, an artificial immune network model designed for -clustering and data compression tasks. The aiNet algorithm uses principles from immune -network theory, clonal selection, and affinity maturation to compress high-dimensional -datasets [1](#1). -For clustering, the class uses SciPy's implementation of the [**Minimum Spanning Tree** -(MST)](#2) to remove the most distant nodes and separate the groups - -:::info - -**``AiNet``** extends the **[``BaseClusterer`` class](../../advanced-guides/base-module/core/Clusterer.md)**, inheriting its base functionality. - -::: - -## Constructor - -```python -class AiNet( - self, - N: int = 50, - n_clone: int = 10, - top_clonal_memory_size: int = 5, - n_diversity_injection: int = 5, - affinity_threshold: float = 0.5, - suppression_threshold: float = 0.5, - mst_inconsistency_factor: float = 2.0, - max_iterations: int = 10, - k: int = 3, - metric: MetricType = "euclidean", - seed: Optional[int] = None, - use_mst_clustering: bool = True, - **kwargs -) -``` - -**Attributes:** - -* **N** (``int``): Number of memory cells (antibodies) in the population. Defaults to 50. -* **n_clone** (``int``): Number of clones generated per selected memory cell. Defaults to 10. -* **top_clonal_memory_size** (``Optional[int]``): Number of highest-affinity antibodies selected for cloning. Defaults to 5. -* **n_diversity_injection** (``int``): Number of new random antibodies injected to maintain diversity. Defaults to 5. -* **affinity_threshold** (``float``): Threshold for cell selection/suppression. Defaults to 0.5. -* **suppression_threshold** (``float``): Threshold for removing similar memory cells. Defaults to 0.5. -* **mst_inconsistency_factor** (``float``): Factor to determine inconsistent MST edges. Defaults to 2.0. -* **max_iterations** (``int``): Maximum number of training iterations. Defaults to 10. -* **k** (``int``): Number of nearest neighbors used for label prediction. Defaults to 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to **"Euclidean"**. - -* **seed** (``Optional[int]``): Seed for random number generation. Defaults to None. -* **use_mst_clustering** (``bool``): Whether to perform MST-based clustering. Defaults to True. -* **kwargs**: - * **p** (``float``): Parameter for Minkowski distance. Defaults to 2. - -**Other initialized variables:** - -* **_population_antibodies** (``npt.NDArray``): Stores the current set of antibodies. -* **_memory_network** (``dict``): Dictionary mapping clusters to antibodies. -* **_mst_structure** (``scipy.sparse.csr_matrix``): MST adjacency structure. -* **_mst_mean_distance** (``float``): Mean of MST edge distances. -* **_mst_std_distance** (``float``): Standard deviation of MST edge distances. -* **classes** (``list``): List of cluster labels. - ---- - -## Public Methods - -### Function fit(...) - -Trains the AiNet model on input data: - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: -``` - -**Input parameters:** - -* **X**: Array with input samples (rows) and features (columns). -* **verbose**: Boolean, default True, enables progress feedback. - -*Returns the class instance.* - ---- - -### Function predict(...) - -Predicts cluster labels for new samples: - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -**Input parameters:** - -* **X**: Array of input features. - -**Returns:** - -* **Predictions**: Array of cluster labels, or None if clustering is disabled. - ---- - -### Function update_clusters(...) - -Partitions clusters using the MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Input parameters:** - -* **mst_inconsistency_factor**: Optional float to override the MST inconsistency factor. - -**Updates:** - -* **_memory_network**: Dictionary of cluster labels to antibody arrays. -* **classes**: List of cluster labels. - ---- - -## Private Methods - -### Function _init_population_antibodies(...) - -Initializes antibody population randomly. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Returns:** Initialized antibodies (`npt.NDArray`). - ---- - -### Function _select_and_clone_population(...) - -Selects top antibodies and generates mutated clones: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Input parameters:** - -* **antigen**: Array representing the antigen to which affinities will be computed. -* **population**: Array of antibodies to be evaluated and cloned. - -**Returns:** List of mutated clones. - ---- - -### Function _clonal_suppression(...) - -Suppresses redundant clones based on thresholds: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Input parameters:** - -* **antigen**: Array representing the antigen. -* **clones**: List of candidate clones to be suppressed. - -**Returns:** List of non-redundant, high-affinity clones. - ---- - -### Function _memory_suppression(...) - -Removes redundant antibodies from memory pool: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Input parameters:** - -* **pool_memory**: List of antibodies currently in memory. - -**Returns:** Cleaned memory pool (`list`). - ---- - -### Function _diversity_introduction(...) - -Introduces new random antibodies: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Returns:** Array of new antibodies (`npt.NDArray`). - ---- - -### Function _affinity(...) - -Calculates stimulus between two vectors: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Input parameters:** - -* **u**: Array representing the first point. -* **v**: Array representing the second point. - -**Returns:** Affinity score (`float`) in [0,1]. - ---- - -### Function _calculate_affinities(...) - -Calculates affinity matrix between reference and target vectors: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Input parameters:** - -* **u**: Reference vector (`npt.NDArray`) of shape `(n_features,)`. -* **v**: Target vectors (`npt.NDArray`) of shape `(n_samples, n_features)`. - -**Returns:** Array of affinities (`npt.NDArray`) with shape `(n_samples,)`. - ---- - -### Function _clone_and_mutate(...) - -Generates mutated clones: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Input parameters:** - -* **antibody**: Original antibody vector to clone and mutate. -* **n_clone**: Number of clones to generate. - -**Returns:** Array of mutated clones (`npt.NDArray`) of shape `(n_clone, len(antibody))`. - ---- - -### Function _build_mst(...) - -Constructs the MST and stores statistics. - -```python -def _build_mst(self): -``` - -**Raises:** ValueError if antibody population is empty. - -**Updates internal variables:** - -* **_mst_structure**: MST adjacency structure. -* **_mst_mean_distance**: Mean edge distance. -* **_mst_std_distance**: Standard deviation of MST edge distances. - ---- - -## References - -### 1 -> -> De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> Available at: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -### 2 -> -> SciPy Documentation. *Minimum Spanning Tree*. -> Available at: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/docs/aisp-techniques/immune-network-theory/README.mdx b/docs/aisp-techniques/immune-network-theory/README.mdx deleted file mode 100644 index 148e0fbe0..000000000 --- a/docs/aisp-techniques/immune-network-theory/README.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 3 -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Immune Network Theory - - AiNet - - Artificial Immune Systems - - Clustering - - Optimization - - Classification - - Machine Learning - - Immune Algorithms ---- - -import DocCardList from '@theme/DocCardList'; - -# Immune Network Theory - -This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, -in which cells and molecules are capable of recognizing each other. [1](#1) - ---- - -The Artificial Immune Network can be applied in different contexts, such as: -- **Clustering** -- **Optimization** -- **Classification** - -## Classes: - - - -## References - ---- - -### 1 -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/aisp-techniques/negative-selection.md b/docs/aisp-techniques/negative-selection.md new file mode 100644 index 000000000..29a68b9b0 --- /dev/null +++ b/docs/aisp-techniques/negative-selection.md @@ -0,0 +1,50 @@ +--- +id: docs-nsa +keywords: + - negative selection + - nsa + - artificial immune systems + - anomaly detection + - classification + - bio-inspired algorithms + - natural computing +--- + +# Seleção Negativa + +Os algoritmos de **seleção negativa** is the process in which the immune system maturates T-cells, also known as +T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) +uses hyperspheres symbolizing the detectors in an N-dimensional data space. [^1] + +--- + +Negative Selection can be applied in different contexts, such as: +- **Anomaly detection** +- **Classification** + +## Package implementation + +### Binary Negative Selection Algorithm ([BNSA](../api/nsa/bnsa.md)) + +The binary algorithm adapted for multiple classes in this project is based on the version proposed by +Forrest et al. (1994)[^2], originally developed for computer security. + +### Real-Valued Negative Selection Algorithm ([RNSA](../api/nsa/rnsa.md)) + +This algorithm has two different versions: one based on the canonical version [^1] and another with variable +radius detectors.[^3] Both are adapted to work with multiple classes and have methods for predicting data +present in the non-self region of all detectors and classes. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Available at: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. + +[^3] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/docs/aisp-techniques/negative-selection/BNSA.md b/docs/aisp-techniques/negative-selection/BNSA.md deleted file mode 100644 index a8f7cd82c..000000000 --- a/docs/aisp-techniques/negative-selection/BNSA.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -id: bnsa -sidebar_label: BNSA - Binary Negative Selection Algorithm -sidebar_position: 2 -pagination_next: null -keywords: - - Binary - - classifying - - anomalies - - not self - - affinity threshold - - Negative Selection Algorithm - - Artificial Immune System (AIS) - - Self and non-self - - Immune - - Computação Natural - - Real-Valued - - V-detector -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# BNSA (Binary Negative Selection Algorithm) - -:::info - -**``BNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## Constructor RNSA - -The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -``` python -class BNSA( - self, - N: int = 100, - aff_thresh: float = 0.1, - max_discards: int = 1000, - seed: int = None, - no_label_sample_selection: Literal[ - "max_average_difference", "max_nearest_difference" - ] = "max_average_difference", -) -``` - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *aff_thresh* (``float``): The variable ('affinity threshold') represents the percentage of dissimilarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. - - :::note - Setting the difference percentage too high can result in the inability to generate detectors for non-self. - ::: - -* *max_discards* (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a -possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``1000``. -* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. -* no_label_sample_selection (``str``): Method for selecting labels for samples designated as non-members by all non-member detectors. **Available method types:** - * (``max_average_difference``): Selects the class with the highest average difference among the detectors. - * (``max_nearest_difference``): Selects the class with the highest difference between the nearest and farthest detector from the sample. - -**Other variables initiated:** - -* *detectors* (``dict``): This variable stores a list of detectors by class. - -* *classes* (``npt.NDArray``): list of output classes. - ---- - -### Function fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -**The input parameters are:** - -* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. - -* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the instance of the class.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**The input parameter is:** - -* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Returns:** - -* ``C``: prediction array, with the output classes for the given characteristics. -* ``None``: if there are no detectors. - ---- - -### Function score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Function __assign_class_to_non_self_sample(...) - -The function ``__assign_class_to_non_self_sample(...)``, determines the class of a sample when all detectors classify it as "non-self". Classification is performed using the ``max_average_difference`` and ``max_nearest_difference`` methods. - -```python -def __assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): -``` - -**The input parameter is:** - -* ***line*** (``npt.NDArray``): Sample to be classified. -* ***c*** (``list``): List of predictions to be updated with the new classification. - ---- diff --git a/docs/aisp-techniques/negative-selection/README.md b/docs/aisp-techniques/negative-selection/README.md deleted file mode 100644 index be74a4825..000000000 --- a/docs/aisp-techniques/negative-selection/README.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Negative selection - -**Negative selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [[1]](#1) - -## classes - -> 1. **[Binary version:](BNSA.md)** -> ->> The binary algorithm adapted for multiple classes in this project is based on the version proposed by [Forrest et al. (1994)](#2), originally developed for computer security. ->>> **Example:** ->>> ->>> + [Mushrooms Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) - -> 2. **[Real-Valued version:](RNSA.md)** -> ->>This algorithm has two different versions: one based on the canonical version [[1]](#1) and another with variable radius detectors [[3]](#3). Both are adapted to work with multiple classes and have methods for predicting data present in the non-self region of all detectors and classes. ->>> **Examples:** ->>> ->>> + [Iris Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) ->>> + [Geyser Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). - -### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). - -### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). - ---- diff --git a/docs/aisp-techniques/negative-selection/RNSA.md b/docs/aisp-techniques/negative-selection/RNSA.md deleted file mode 100644 index 3c102d26a..000000000 --- a/docs/aisp-techniques/negative-selection/RNSA.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -id: rnsa -sidebar_label: RNSA - Real-Valued Negative Selection Algorithm -sidebar_position: 1 -keywords: - - Real-Valued - - classifying - - anomalies - - not self - - V-detector - - Negative Selection Algorithm - - Artificial Immune System (AIS) - - Self and non-self - - Immune - - Computação Natural -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# RNSA (Real-Valued Negative Selection Algorithm) - -:::info - -**``RNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## Constructor RNSA - -The ``RNSA`` (Real-Valued Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -```python -class RNSA( - self, - N: int = 100, - r: float = 0.05, - r_s: float = 0.0001, - k: int = 1, - metric: Literal["manhattan", "minkowski", "euclidean"] = "euclidean", - max_discards: int = 1000, - seed: int = None, - algorithm: Literal["default-NSA", "V-detector"] = "default-NSA", - **kwargs: Dict[str, Union[bool, str, float]], -) -``` - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *r* (``float``): Radius of the detector. Defaults to ``0.05``. - - :::note - it is important to consider that setting a very low radius for the detector can significantly reduce the detection rate. On the other hand, a very large radius can make it impossible to incorporate the detector into the search space, which can also compromise detection performance. It is essential to find a balance between the radius size and detection efficiency to achieve the best possible results. - ::: - -* *k* (``int``): Number of neighbors near the randomly generated detectors to perform the distance average calculation. Defaults to ``1``. -* *metric* (``str``): Way to calculate the distance between the detector and the sample: - - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to ``'euclidean'``. - -* *max_discards* (``int``): This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. Defaults to ``1000``. -* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. - -* *algorithm* (``str``), Set the algorithm version: - - * ``'default-NSA'``: Default algorithm with fixed radius. - * ``'V-detector'``: This algorithm is based on the article "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", by Ji, Z., Dasgupta, D. (2004), and uses a variable radius for anomaly detection in feature spaces. - - Defaults to ``'default-NSA'``. - -* *r_s* (``float``): rₛ Radius of the ``X`` own samples. - -* ``**kwargs``: - * *non_self_label* (``str``): This variable stores the label that will be assigned when the data has only one - output class, and the sample is classified as not belonging to that class. Defaults to ``'non-self'``. - * *cell_bounds* (``bool``): If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. - * p (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. The default is ``2``, which represents normalized Euclidean distance. Different values of p lead to different variants of the Minkowski - distance [learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Other variables initiated:** - -* *detectors* (``dict``): This variable stores a list of detectors by class. - -* *classes* (``npt.NDArray``): list of output classes. - ---- - -### Function fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -The input parameters are: - -* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. - -* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the instance of the class.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**The input parameter is:** - -* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Returns:** - -* ``C``: prediction array, with the output classes for the given characteristics. -* ``None``: if there are no detectors. - ---- - -### Function score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Function __checks_valid_detector(...) - -The ``def __checks_valid_detector(...)`` function checks if the detector has a valid ``r`` radius for the non-self of the class: - -```python -def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: -``` - -**The input parameters are:** - -* ``X``: array with sample characteristics with **N** samples (rows) and **N** characteristics (columns), normalized to values between [0, 1]. - -* ``vector_x``: Randomly generated candidate detector. - -* ``samplesIndexClass``: Array with the indexes of a class. - -**Returns:** ``True`` for detectors that do not have samples inside or ``False`` if they do. - ---- - -### Function __compare_KnearestNeighbors_List(...) - -The ``def __compare_KnearestNeighbors_List(...)`` function compares the distance of the k-nearest neighbors, so if the distance of the new sample is smaller, replaces ``k-1`` and sorts in ascending order: - -```python -def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: -``` - -Returns a list of k-nearest neighbor distances. - ---- - -### Function __compare_sample_to_detectors(...) - -Function to compare a sample with the detectors, verifying if the sample is proper. -In this function, when there is class ambiguity, it returns the class that has the greatest average distance between the detectors. - -```python -def __compare_sample_to_detectors(self, line): -``` - -**The input parameters are:** - -* line: vector with N-features - -**Returns:** The predicted class with the detectors or None if the sample does not qualify for any class. - ---- - -### Function __detector_is_valid_to_Vdetector(...) - -Check if the distance between the detector and the samples, minus the radius of the samples, is greater than the minimum radius. - -```python -def __detector_is_valid_to_Vdetector(self, distance, vector_x): -``` - -**The input parameters are:** - -* distance (``float``): minimum distance calculated between all samples. -* vector_x (``numpy.ndarray``): randomly generated candidate detector vector x with values between 0 and 1. - -**Returns:** - -* ``False``: if the calculated radius is smaller than the minimum distance or exceeds the edge of the space, if this option is enabled. -* ``True`` and the distance minus the radius of the samples, if the radius is valid.` - ---- - -### Function __distance(...) - -The function ``def __distance(...)`` calculates the distance between two points using the technique defined in ``metric``, which are: ``'euclidean', 'norm_euclidean', or 'manhattan'`` - -```python -def __distance(self, u: npt.NDArray, v: npt.NDArray): -``` - -The input parameters are ``u`` and ``v`` NDArrays, with the coordinates for the points. - -**Returns:** the distance (``double``) between the two points. - ---- diff --git a/docs/api/README.md b/docs/api/README.md new file mode 100644 index 000000000..8d775063a --- /dev/null +++ b/docs/api/README.md @@ -0,0 +1,85 @@ +--- +id: api +sidebar_position: 5 +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering +--- + +# AISP - API + +Welcome to the **AISP** (Artificial Immune System Package) api. This documentation demonstrates the package public API. + +## Core Modules ([`aisp.base`](./base/README.md)) + +Fundamental abstractions and base classes that define core interfaces of package. + +| Class | Description | +|-----------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base/base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Abstract base class for optimization algorithms. | + +### Immune Domain components ([`aisp.base.immune`](./base/immune/README.md)) + +Core structures and support utilities for implementations immune. + +| Module | Description | +|-----------------------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representation of immune system cells. | +| [`mutation`](./base/immune/mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./base/immune/populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | + +--- + +## Algorithms + +### Negative Selection Algorithms ([`aisp.nsa`](./nsa/README.md)) + +supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from +not-self. + +| Class | Description | +|-------------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./nsa/bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | + +### Clonal Selection Algorithms ([`aisp.csa`](./csa/README.md)) + +Algorithms inspired by the process of antibody proliferation to detecting an antigen. + +| Class | Description | +|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./csa/clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | + +### Immune Network Algorithms ([`aisp.ina`](./ina/README.md)) + +Algorithms based on Network Theory Algorithms proposed by Jerne. + +| Class | Description | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | + +## Utils ([`aisp.utils`](./utils/README.md)) + +Utility functions and helpers for development. + +| Module | Description | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./utils/distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./utils/metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./utils/multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./utils/sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | + +## Exceptions ([`aisp.exceptions`](./exceptions.md)) + +Custom warnings and errors. diff --git a/docs/api/base/README.md b/docs/api/base/README.md new file mode 100644 index 000000000..631dcb4cb --- /dev/null +++ b/docs/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - immune + - abstract +--- + +# aisp.base + +Base Classes and Core Utilities. + +> **Module:** `aisp.base` + +## Overview + +This module provides the fundamental classes and utilities that serve as the basis for all +Artificial Immune Systems algorithms implemented in the AISP package. + +## Classes + +| Class | Description | +|------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base-optimizer.md) | Abstract base class for optimization algorithms. | + +## Submodules + +| Module | Description | +|--------------------------------|-----------------------------------------------| +| [`immune`](./immune/README.md) | Support Module for Artificial Immune Systems. | \ No newline at end of file diff --git a/docs/api/base/base-classifier.md b/docs/api/base/base-classifier.md new file mode 100644 index 000000000..115053d64 --- /dev/null +++ b/docs/api/base/base-classifier.md @@ -0,0 +1,133 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classifier + - classifier interface + - accuracy score + - fit + - predict +tags: + - classifier + - classification +--- + +# BaseClassifier + +Abstract base class for classification algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClassifier` + +--- + +## Overview + +This class defines the core interface for classification models. It enforces the implementation of the `fit` +and `predict` methods in all derived classes, and provides a default implementation of the `score` method. + +Use cases: + +- Abstract base class for extending classification algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|-----------|-------------------------|:-------:|------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Train the model using the input data X and corresponding labels y. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------| +| `npt.NDArray` | Predicted values for each input sample. | + +--- + +## Public Methods + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +Score function calculates forecast accuracy. + +This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. +This function was added for compatibility with some scikit-learn functions. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | + +**Returns** + +| Type | Description | +|---------|----------------------------| +| `float` | The accuracy of the model. | + diff --git a/docs/api/base/base-clusterer.md b/docs/api/base/base-clusterer.md new file mode 100644 index 000000000..0e554068b --- /dev/null +++ b/docs/api/base/base-clusterer.md @@ -0,0 +1,122 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict +tags: + - clusterer + - clustering +--- + +# BaseClusterer + +Abstract base class for clustering algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClusterer` + +--- + +## Overview + +This class defines the core interface for clustering models. It enforces the implementation of the `fit` and +`predict` methods in all derived classes, and provides a default implementation for `fit_predict` and `get_params`. + +Use cases: + +- Abstract base class for extending clustering algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|-------------------------|:-------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Labels for the clusters generated during model fitting. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Train the model using the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | + +--- + +## Public Methods + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Fit the clustering model to the data and return cluster labels. + +This is a convenience method that combines `fit` and `predict` into a single call. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|-----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | diff --git a/docs/api/base/base-optimizer.md b/docs/api/base/base-optimizer.md new file mode 100644 index 000000000..f3bde23a1 --- /dev/null +++ b/docs/api/base/base-optimizer.md @@ -0,0 +1,165 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - optimizer + - optimization + - optimizer interface + - objective function + - minimization + - maximization +tags: + - optimizer + - optimization +--- + +# BaseOptimizer + +Abstract base class for optimization algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseOptimizer` + +--- + +## Overview + +This class defines the core interface for optimization strategies. It keeps track of cost history, evaluated +solutions, and the best solution found during the optimization process. Subclasses must implement ``optimize`` +and ``affinity_function``. + +Use cases: + +- Abstract base class for extending optimization algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|--------------------|-------------------|:-------:|-------------------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | History of best costs found at each iteration. | +| `solution_history` | `List` | `[]` | History of the best solution found at each iteration. | +| `best_solution` | `Any` | `None` | The best solution found. | +| `best_cost` | `Optional[float]` | `None` | Cost of the best solution found. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | + +--- + +## Abstract Methods + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Execute the optimization process. +This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search +space. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations | +| `n_iter_no_change` | `int` | `10` | the maximum number of iterations without updating the best | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Evaluate the affinity of a candidate solution. + +This method must be implemented according to the specific optimization problem, defining how the solution will be +evaluated. +The returned value should represent the quality of the evaluated solution. + +**Parameters** + +| Name | Type | Default | Description | +|------------|-------|:-------:|-------------------------------------| +| `solution` | `Any` | - | Candidate solution to be evaluated. | + +**Returns** + +| Type | Description | +|---------|------------------------------------------------| +| `float` | Cost value associated with the given solution. | + +--- + +## Public Methods + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Generate a formatted summary report of the optimization process. +The report includes the best solution, its associated cost, and the evolution of cost values per iteration. + +**Returns** + +| Type | Description | +|-------|---------------------------------------------------------| +| `str` | A formatted string containing the optimization summary. | + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Register a function dynamically in the optimizer instance. + +**Parameters** + +| Name | Type | Default | Description | +|------------|----------------------|:-------:|---------------------------------------------------| +| `alias` | `str` | - | Name used to access the function as an attribute. | +| `function` | `Callable[..., Any]` | - | Callable to be registered. | + +**Raises** + +| Exception | Description | +|------------------|---------------------------------------------------------------------------------| +| `TypeError` | If the provided `function` is not callable. | +| `AttributeError` | If `alias` is protected and cannot be modified, or does not exist in the class. | + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reset the object's internal state, clearing history and resetting values. diff --git a/docs/api/base/immune/README.md b/docs/api/base/immune/README.md new file mode 100644 index 000000000..5e196cbca --- /dev/null +++ b/docs/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - cell + - mutation + - population +--- + +# aisp.base.immune + +Support Module for Artificial Immune Systems. + +> **Module:** `aisp.base.immune` + +## Submodules + +| Module | Description | +|-----------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representation of immune system cells. | +| [`mutation`](./mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | \ No newline at end of file diff --git a/docs/api/base/immune/cell/README.md b/docs/api/base/immune/cell/README.md new file mode 100644 index 000000000..2aede005f --- /dev/null +++ b/docs/api/base/immune/cell/README.md @@ -0,0 +1,33 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representation of immune system cells. + +> **Module:** `aisp.base.immune.cell` + +## Overview + +This module defines the representation of cells in artificial immune systems, +implements as dataclass. + +## Classes + +| Class | Description | +|-----------------------------|---------------------------------------------------| +| [`Cell`](./c-cell.md) | Represents a basic immune cell. | +| [`BCell`](./b-cell.md) | Represents a memory B-cell. | +| [`Antibody`](./antibody.md) | Represent an antibody. | +| [`Detector`](./detector.md) | Represents a non-self detector of the RNSA class. | \ No newline at end of file diff --git a/docs/api/base/immune/cell/antibody.md b/docs/api/base/immune/cell/antibody.md new file mode 100644 index 000000000..6f0f72021 --- /dev/null +++ b/docs/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - antibody + - affinity + - cell + - immune + - dataclass +--- + +# Antibody + +Represent an antibody. + +:::tip[Inheritance] + +This class extends [Cell](./c-cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Antibody` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------|:-------:|----------------------------------| +| `vector` | `npt.NDArray` | - | A vector of cell features. | +| `affinity` | `float` | - | Affinity value for the antibody. | + +--- + +## Methods + +* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. +* `__eq__(other)`: Check if this cell has the same affinity as another cell. diff --git a/docs/api/base/immune/cell/b-cell.md b/docs/api/base/immune/cell/b-cell.md new file mode 100644 index 000000000..6eff1ab58 --- /dev/null +++ b/docs/api/base/immune/cell/b-cell.md @@ -0,0 +1,63 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - B-cell + - immune memory + - dataclass + - clonal mutation + - clonal expansion +--- + +# BCell + +Represents a memory B-cell. + +:::tip[Inheritance] + +This class extends [Cell](./c-cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import BCell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Public Methods + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Generate **N** clones of the current cell and apply hypermutation to the clones. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|------------------------------------------------------|:-----------------------:|--------------------------------------------------------| +| `n` | `int` | - | Number of clones to generate from the original b-cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of features of the cell. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|---------------------------------------------------------------| +| `npt.NDArray` | An array containing N mutated vectors from the original cell. | diff --git a/docs/api/base/immune/cell/c-cell.md b/docs/api/base/immune/cell/c-cell.md new file mode 100644 index 000000000..ff94da948 --- /dev/null +++ b/docs/api/base/immune/cell/c-cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Represents a basic immune cell. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Cell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Methods + +* `__eq__(other)`: Check if two cells are equal based on their vectors. +* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. +* `__getitem__(item)`: Get elements from the feature vector using indexing. + diff --git a/docs/api/base/immune/cell/detector.md b/docs/api/base/immune/cell/detector.md new file mode 100644 index 000000000..520294da7 --- /dev/null +++ b/docs/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - cell + - immune + - radius + - non-self + - nsa + - dataclass +--- + +# Detector + +Represents a non-self detector of the RNSA class. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Detector` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------------------|:-------:|----------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Detector feature vector. | +| `radius` | `float, optional` | - | Detector radius, used in the V-detector algorithm. | diff --git a/docs/api/base/immune/mutation.md b/docs/api/base/immune/mutation.md new file mode 100644 index 000000000..c0d34a919 --- /dev/null +++ b/docs/api/base/immune/mutation.md @@ -0,0 +1,145 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutation + - clonal expansion + - immune system + - python numba functions + - vector mutation +--- + +# mutation + +The functions perform utilize Numba decorators for Just-In-Time compilation. + +Contains functions that generate sets of mutated clones from continuous or binary vectors, +simulating the clonal expansion process in artificial immune systems. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import mutation` + +## Functions + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by a continuous vector. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Generate a set of mutated clones from a cell represented by a binary vector. + +This function creates `n` clones of the input binary vector and applies mutations to the +bits, simulating clonal expansion in artificial immune systems with discrete representations. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|-------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by custom ranges per dimension. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_continuous + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +``` + +Generate a set of mutated clones by permutation. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | Probability of mutating each feature 0 ≤ mutation_rate < 1. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | diff --git a/docs/api/base/immune/populations.md b/docs/api/base/immune/populations.md new file mode 100644 index 000000000..0126de2d5 --- /dev/null +++ b/docs/api/base/immune/populations.md @@ -0,0 +1,56 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binary + - classifying + - affinity threshold + - real-Valued + - memory B-cell + - clonal Expansion + - populations +--- + +# populations + +Provide utility functions for generating antibody populations in immunological algorithms. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import populations` + +## Functions + +### generate_random_antibodies + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +``` + +Generate a random antibody population. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|---------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------| +| `npt.NDArray` | Array of shape (n_samples, n_features) containing the generated antibodies. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------| +| `ValueError` | If the number of features is less than or equal to zero. | diff --git a/docs/api/csa/README.md b/docs/api/csa/README.md new file mode 100644 index 000000000..e2872edeb --- /dev/null +++ b/docs/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - immune + - clonal selection + - clonalg + - airsv2 + - antibody proliferation + - mutations + - clonal selection algorithm + - artificial immune systems + - classification + - optimization +--- + +# aisp.csa + +Module (CSA) Clonal Selection Algorithm. + +> **Module:** `aisp.csa` + +## Overview + +CSAs are inspired by the process of antibody proliferation upon detecting an antigen, during which +the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. + +## Classes + +| Class | Description | +|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | diff --git a/docs/api/csa/airs.md b/docs/api/csa/airs.md new file mode 100644 index 000000000..777623883 --- /dev/null +++ b/docs/api/csa/airs.md @@ -0,0 +1,197 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classification + - artificial immune recognition system + - memory cells + - k-nn + - supervised learning + - AIRS2 +tags: + - classification + - supervised + - clonal selection +--- + +# AIRS + +Artificial Immune Recognition System (AIRS) + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import AIRS` + +--- + +## Overview + +The Artificial Immune Recognition System (AIRS) is a classification algorithm inspired by the +clonal selection process of the biological immune system. This implementation is based on the +simplified AIRS2 version described in [^1]. The algorithm has been adapted to support both +real-valued (continuous) and binary feature datasets. + +:::note + +This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. +Introducing adaptations to handle continuous and binary datasets. + +Based on Algorithm 16.5 from Brabazon et al. [^1] + +Related and noteworthy works: access here [^2]. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# AIRS Instance +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` + +Output: + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|---------|:-------------:|---------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Total amount of available resources. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a class. This quantity is multiplied by (cell_stimulus * rate_hypermutation) to define the number of clones. | +| `rate_mc_init` | `float` | `0.2` | Percentage of samples used to initialize memory cells. | +| `rate_hypermutation` | `float` | `0.75` | The rate of mutated clones derived from rate_clonal as a scalar factor. | +| `affinity_threshold_scalar` | `float` | `0.75` | Normalized affinity threshold. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `max_iters` | `int` | `100` | Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. | +| `resource_amplified` | `float` | `1.0` | Resource consumption amplifier is multiplied with the incentive to subtract resources. | +| `metric` | `str` | `"euclidean"` | Distance metric used to compute affinity between cells and samples. | +| `seed` | `int` | `None` | Seed for random generation. | +| `p` | `float` | `2` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|----------------|-------------------------------------------|:-------:|---------------------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` + +Fit the model to the training data using the AIRS. + +The function ``fit(...)``, performs the training according to `X` and `y`, using the +method AIRS. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + +**Raises** + +| Exception | Description | +|-------------|---------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict class labels based on the memory cells created during training. + +This method uses the trained memory cells to perform classification of the input data +using the k-nearest neighbors approach. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/csa.md#airs-artificial-immune-recognition-system) + +--- + +## References + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/docs/api/csa/clonalg.md b/docs/api/csa/clonalg.md new file mode 100644 index 000000000..81811d38d --- /dev/null +++ b/docs/api/csa/clonalg.md @@ -0,0 +1,183 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - optimization + - clonal selection + - clonalg + - antibody population + - objective function +tags: + - optimization + - clonal selection + - minimization + - maximization + - binary + - continuous + - permutation + - ranged +--- + +# Clonalg + +Clonal Selection Algorithm (CLONALG). + +:::tip[Inheritance] + +This class extends [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import Clonalg` + +--- + +## Overview + +The Clonal Selection Algorithm (CSA) is an optimization algorithm inspired by the biological +process of clonal selection and expansion of antibodies in the immune system [^1]. This +implementation of CLONALG has been adapted for the minimization or maximization of cost +functions in binary, continuous, ranged-value, and permutation problems. + +:::note + +This CLONALG implementation contains some changes based on the AISP context, for general +application to various problems, which may produce results different from the standard or +specific implementation. This adaptation aims to generalize CLONALG to minimization and +maximization tasks, in addition to supporting continuous, discrete, and permutation problems. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import Clonalg +# Search space limits +bounds = {'low': -5.12, 'high': 5.12} +# Objective function +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x)) +# CLONALG Instance +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` + +**Output:** + +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-------------------------|------------------------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimension of the problem to be minimized. | +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | +| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | +| `seed` | `int` | `None` | Seed for random generation. | + +## Attributes + +| Name | Type | Default | Description | +|--------------|----------------------------|:-------:|---------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | Population of antibodies. | + +--- + +## Public Methods + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Execute the optimization process and return the population. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|----------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | +| `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | +| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | + +**Returns** + +| Type | Description | +|------------------|---------------------------------------------| +| `List[Antibody]` | Antibody population after clonal expansion. | + + +**Raises** + +| Exception | Description | +|-----------------------|----------------------------------------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided to evaluate candidate solutions. | + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Evaluate the affinity of a candidate cell. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------| +| `solution` | `npt.NDArray` | - | Candidate solution to evaluate. | + +**Returns** + +| Type | Description | +|--------------|------------------------------------------------| +| `np.float64` | Affinity value associated with the given cell. | + + +**Raises** + +| Exception | Description | +|-----------------------|--------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Optimization/csa.md#clonalg-clonal-selection-algorithm) + +--- + +## References + +[^1]: BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired + Programming Recipes., 2011. Available at: + https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html diff --git a/docs/api/exceptions.md b/docs/api/exceptions.md new file mode 100644 index 000000000..688c12e1a --- /dev/null +++ b/docs/api/exceptions.md @@ -0,0 +1,91 @@ +--- +id: exceptions +sidebar_label: aisp.exceptions +keywords: + - exceptions + - raises + - warnings +--- + +# aisp.exceptions + +Custom warnings and errors. + +> **Module:** `aisp.exceptions` +> **Import:** `from aisp import exceptions` + +## Exception classes + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exception thrown when the maximum number of detector discards is reached. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exception raised when the number of input features does not match the expected number. +This exception is triggered during prediction if the input features' dimension is incorrect. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-----------------|:-------:|-----------------------------------------------------| +| `expected` | `int` | - | The expected number of features | +| `received` | `int` | - | The actual number of features received. | +| `variable_name` | `Optional[str]` | `None` | The name of the variable that caused this mismatch. | + +--- + +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exception raised when the input vector type is not supported. +This exception is thrown when the vector data type does not match any of the supported. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|-----------------|:-------:|----------------------------| +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exception raised when a method is called before the model has been fit. +This exception is thrown when the model instance is being used without first training +it via the `fit` method. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | diff --git a/docs/api/ina/README.md b/docs/api/ina/README.md new file mode 100644 index 000000000..59c20b75f --- /dev/null +++ b/docs/api/ina/README.md @@ -0,0 +1,31 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - immune + - clonal selection + - immune networks + - ainet + - opt-ainet + - mutations + - clonal selection + - artificial immune systems + - clustering + - optimization +--- + +# aisp.ina + +Module (ina) Immune Network Algorithm. + +> **Module:** `aisp.ina` + +## Overview + +This module implements algorithms based on Network Theory Algorithms proposed by Jerne. + +## Classes + +| Class | Description | +|------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | diff --git a/docs/api/ina/ai-net.md b/docs/api/ina/ai-net.md new file mode 100644 index 000000000..be83b3e04 --- /dev/null +++ b/docs/api/ina/ai-net.md @@ -0,0 +1,227 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - immune network + - clustering + - data compression + - unsupervised learning + - Minimum Spanning Tree +tags: + - clustering + - unsupervised + - immune network + - data compression +--- + +# AiNet + +Artificial Immune Network (AiNet) for Compression and Clustering. + +:::tip[Inheritance] + +This class extends [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Module:** `aisp.ina` +> **Import:** `from aisp.ina import AiNet` + +--- + +## Overview + +This class implements the aiNet algorithm, an artificial immune network model designed for +clustering and data compression tasks. The aiNet algorithm uses principles from immune +network theory, clonal selection, and affinity maturation to compress high-dimensional +datasets [^1]. +For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** +(MST) to remove the most distant nodes and separate the groups [^2]. + +--- + +## Example + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# AiNet Instance +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Expected: label 0 + [0.85, 0.65], # Expected: label 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|----------------------------|----------------------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells. | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells. | +| `seed` | `Optional[int]` | `None` | Seed for random generation. | +| `use_mst_clustering` | `bool` | `True` | If `True`, performs clustering using the MST. If `False`, clustering is not performed and the predict method raises a ModelNotFittedError. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------------------|-------------------------|:-------:|------------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | The immune network representing clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | The set of memory antibodies. | +| `mst` | `dict` | - | The Minimum Spanning Tree and its statistics (graph, mean_distance, std_distance). | + +--- + +## Public Methods + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Train the AiNet model on input data. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------|--------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | If the data type of the feature on X is not supported. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict cluster labels for input data. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|--------------------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels, or None if clustering is disabled. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If X contains values other than (0 and 1) or (True and False) when the trained features are of type `"binary-features"`. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions. | + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` + +Partition the clusters based on the MST inconsistency factor. + +Uses the precomputed Minimum Spanning Tree (MST) of the antibody population +to redefine clusters. Edges whose weights exceed the mean plus the +`mst_inconsistency_factor` multiplied by the standard deviation of MST edge +weights are removed. Each connected component after pruning is treated as a +distinct cluster. + +**Parameters** + +| Name | Type | Default | Description | +|----------------------------|---------|:-------:|----------------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | If provided, overrides the current inconsistency factor. | + +**Raises** + +| Exception | Description | +|--------------|--------------------------------------------------------------| +| `ValueError` | If the Minimum Spanning Tree (MST) has not yet been created. | +| `ValueError` | If Population of antibodies is empty. | +| `ValueError` | If MST statistics (mean or std) are not available. | + +**Updates** + +| Name | Type | Description | +|------------------|--------------------------|-------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dictionary mapping cluster labels to antibody arrays. | +| `labels` | `list` | List of cluster labels. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Clustering/ina.md#ainet-artificial-immune-network) + +--- + +## References + +[^1]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree diff --git a/docs/api/nsa/README.md b/docs/api/nsa/README.md new file mode 100644 index 000000000..0b354be2e --- /dev/null +++ b/docs/api/nsa/README.md @@ -0,0 +1,35 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - artificial immune systems + - classification + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - multiclass + - real-valued + - v-detector +--- + +# aisp.nsa + +Module (NSA) Negative Selection Algorithm. + +> **Module:** `aisp.nsa` + +## Overview + +NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to +distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are +preserved. + +## Classes + +| Class | Description | +|---------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | diff --git a/docs/api/nsa/bnsa.md b/docs/api/nsa/bnsa.md new file mode 100644 index 000000000..6bec1fb6c --- /dev/null +++ b/docs/api/nsa/bnsa.md @@ -0,0 +1,193 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - multiclass +tags: + - classification + - supervised + - negative selection + - binary-features + - anomaly detection +--- + +# BNSA + +Binary Negative Selection Algorithm (BNSA). + +:::tip[Inheritance] +This class extends [BaseClassifier](../base/base-classifier.md) +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import BNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +The **Binary Negative Selection Algorithm (BNSA)** is based on the original proposal by +Forrest et al. (1994) [^1], originally developed for computer security. In the adaptation, the +algorithm use bits arrays, and it has support for multiclass classification. + +::: + +:::warning + +High `aff_thresh` values may prevent the generation of valid non-self detectors + +::: + +--- + +## Example + +```python +from aisp.nsa import BNSA +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ +... [1, 1, 1, 1, 1], # Sample of Anomaly +... [0, 1, 0, 1, 0], # self sample +... ] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` + +**Output** + +```bash +['non-self' 'self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|-----------------|:--------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `aff_thresh` | `float` | `0.1` | The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% similarity. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Method for selecting labels for samples designated as non-self by all detectors. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|-----------------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Training according to X and y, using the method negative selection method. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X contains any values other than (0 and 1) or (True and False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/nsa.md#bnsa-binary-negative-selection-algorithm) + +--- + +## References + +[^1]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. diff --git a/docs/api/nsa/rnsa.md b/docs/api/nsa/rnsa.md new file mode 100644 index 000000000..ddc07e414 --- /dev/null +++ b/docs/api/nsa/rnsa.md @@ -0,0 +1,222 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - negative selection + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - real-valued + - v-detector + - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection +--- + +# RNSA + +Real-Valued Negative Selection Algorithm (RNSA). + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import RNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +This algorithm has two different versions: one based on the canonical version [^1] and another +with variable radius detectors [^2]. Both are adapted to work with multiple classes and have +methods for predicting data present in the non-self region of all detectors and classes. + +::: + +:::warning + +The parameters `r` and `r_s` can prevent the generation of valid detectors. A very small `r` +value can limit coverage, while a very high one can hinder the generation of valid detectors. +Similarly, a high r_s can restrict detector creation. Thus, proper adjustment of `r` and `r_s` +is essential to ensure good model performance. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Example 1:** Multiclass classification (RNSA supports two or more classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +['a' 'b'] +``` + +**Example 2:** Anomaly Detection (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` + +**Output** + +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `r` | `float` | `0.05` | Radius of the detector. | +| `r_s` | `float` | `0.0001` | rₛ Radius of the `X` own samples. | +| `k` | `int` | `1` | Number of neighbors near the randomly generated detectors to perform the distance average calculation. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Distance metric used to compute the distance between the detector and the sample. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | +| `non_self_label` | `str` | `'non-self'` | This variable stores the label that will be assigned when the data has only one output class, and the sample is classified as not belonging to that class. | +| `cell_bounds` | `bool` | `False` | If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|----------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Perform training according to X and y, using the negative selection method (NegativeSelect). + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/nsa.md#rnsa-real-valued-negative-selection-algorithm) + +--- + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/docs/api/utils/README.md b/docs/api/utils/README.md new file mode 100644 index 000000000..a0467faa1 --- /dev/null +++ b/docs/api/utils/README.md @@ -0,0 +1,28 @@ +--- +id: utils +sidebar_label: aisp.utils +keywords: + - functions + - helpers + - utils +--- + +# aisp.utils + +Utility functions and helpers for development. + +> **Module:** `aisp.utils` +> **Import:** `from aisp import utils` + +## Submodules + +| Module | Description | +|----------------------------------|--------------------------------------------------------------------------| +| [`display`](./display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./validation.md) | Contains functions responsible for validating data types. | + diff --git a/docs/api/utils/display/README.md b/docs/api/utils/display/README.md new file mode 100644 index 000000000..6625dc77f --- /dev/null +++ b/docs/api/utils/display/README.md @@ -0,0 +1,23 @@ +--- +id: display +sidebar_label: display +keywords: + - table + - progress +--- + +# display + +Utility functions for displaying algorithm information. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Description | +|------------------------------------------|-----------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Format tabular data into strings for display in the console. | +| [`ProgressTable`](./progress-table.md) | Display a formatted table in the console to track the algorithm's progress. | diff --git a/docs/api/utils/display/progress-table.md b/docs/api/utils/display/progress-table.md new file mode 100644 index 000000000..7823ef2e3 --- /dev/null +++ b/docs/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Display a formatted table in the console to track the algorithm's progress. + +:::tip[Inheritance] + +This class extends [TableFormatter](./table-formatter.md). + +::: + + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import ProgressTable` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|-------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping `{column_name: column_width}`. | +| `verbose` | `bool` | `True` | If False, prints nothing to the terminal. | + +--- + +## Public Methods + +### update + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +``` + +Add a new row of values to the table. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Keys must match the columns defined in headers. | + +--- + +### finish + +```python +def finish(self) -> None: + ... +``` + +End the table display, printing the bottom border and total time. diff --git a/docs/api/utils/display/table-formatter.md b/docs/api/utils/display/table-formatter.md new file mode 100644 index 000000000..c1c893186 --- /dev/null +++ b/docs/api/utils/display/table-formatter.md @@ -0,0 +1,85 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Format tabular data into strings for display in the console. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import TableFormatter` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|--------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format `{column_name: column_width}`. | + +--- + +## Public Methods + +### get_header + +```python +def get_header(self): + ... +``` + +Generate the table header, including the top border, column headings, and separator line. + +**Returns** + +| Type | Description | +|-------|---------------------------------------| +| `str` | Formatted string of the table header. | + + +--- + +### get_row + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +``` + +Generate a formatted row for the table data. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format `{column_name: value}`. | + +**Returns** + +| Type | Description | +|-------|------------------------------------| +| `str` | Formatted string of the table row. | + +--- + +### get_bottom + +```python +def get_bottom(self, new_line: bool = False): + ... +``` + +Generate the table's bottom border. + +**Parameters** + +| Name | Type | Default | Description | +|------------|--------|:-------:|------------------------------------------------------------------| +| `new_line` | `bool` | `False` | If True, adds a line break before the border (default is False). | + +**Returns** + +| Type | Description | +|-------|-----------------------------------------| +| `str` | Formatted string for the bottom border. | diff --git a/docs/api/utils/distance.md b/docs/api/utils/distance.md new file mode 100644 index 000000000..fc827f683 --- /dev/null +++ b/docs/api/utils/distance.md @@ -0,0 +1,243 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distance +--- + +# distance + +Utility functions for distance between arrays with numba decorators. + +> **Module:** `aisp.utils.distance` +> **Import:** `from aisp.utils import distance` + +## Functions + +### hamming + +```python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +``` + +Calculate the Hamming distance between two points. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|-------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordinates of the second point. | + + +**Returns** + +| Type | Description | +|-----------|--------------------------------------| +| `float64` | Hamming distance between two points. | + +--- + +### euclidean + +```python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +``` + +Calculate the Euclidean distance between two points. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Euclidean distance between two points. | + +--- + +### cityblock + +```python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +``` + +Calculate the Manhattan distance between two points. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Manhattan distance between two points. | + +--- + +### minkowski + +```python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the Minkowski distance between two points. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +:::note[Parameter `p`] + +- p = 1: **Manhattan** distance - sum of absolute differences. +- p = 2: **Euclidean** distance - sum of squared differences (square root). +- p > 2: **Minkowski** distance with an increasing penalty as p increases. + +::: + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Minkowski distance between two points. | + +--- + +### compute_metric_distance + +```python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the distance between two points by the chosen metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|------------------------|:-------:|--------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +**Returns** + +| Type | Description | +|-----------|-----------------------------------------------------------| +| `float64` | Distance between the two points with the selected metric. | + +--- + +### min_distance_to_class_vectors + +```python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +``` + +Calculate the minimum distance between an input vector and the vectors of a class. + +**Parameters** + +| Name | Type | Default | Description | +|------------|------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | Vector to be compared with the class vectors. Expected shape: (n_features,). | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 ("euclidean"), 1 ("manhattan"), 2 ("minkowski") or ("hamming") | +| `p` | `float` | `2.0` | Parameter for the Minkowski distance (used only if `metric` is "minkowski"). | + +**Returns** + +| Type | Description | +|---------|----------------------------------------------------------------------------------------------------------------------------------------| +| `float` | The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. | + +--- + +### get_metric_code + +```python +def get_metric_code(metric: str) -> int: + ... +``` + +Get the numeric code associated with a distance metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|-------|:-------:|----------------------------------------------------------------------------------------| +| `metric` | `str` | - | Name of the metric. Can be `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Returns** + +| Type | Description | +|-------|-------------------------------------------| +| `int` | Numeric code corresponding to the metric. | + + +**Raises** + +| Exception | Description | +|--------------|------------------------------------------| +| `ValueError` | If the metric provided is not supported. | + diff --git a/docs/api/utils/metrics.md b/docs/api/utils/metrics.md new file mode 100644 index 000000000..14e8ff389 --- /dev/null +++ b/docs/api/utils/metrics.md @@ -0,0 +1,47 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Utility functions for measuring accuracy and performance. + +> **Module:** `aisp.utils.metrics` +> **Import:** `from aisp.utils import metrics` + +## Functions + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calculate the accuracy score based on true and predicted labels. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------|:-------:|-------------------------------------------------------------------------------| +| `y_true` | `Union[npt.NDArray, list]` | - | Ground truth (correct) labels. Expected to be of the same length as `y_pred`. | +| `y_pred` | `Union[npt.NDArray, list]` | - | Predicted labels. Expected to be of the same length as `y_true`. | + +**Returns** + +| Type | Description | +|---------|----------------------------------------------------------------------| +| `float` | The ratio of correct predictions to the total number of predictions. | + +**Raises** + +| Exception | Description | +|--------------|---------------------------------------------------------------------------| +| `ValueError` | If `y_true` or `y_pred` are empty or if they do not have the same length. | diff --git a/docs/api/utils/multiclass.md b/docs/api/utils/multiclass.md new file mode 100644 index 000000000..367c641f4 --- /dev/null +++ b/docs/api/utils/multiclass.md @@ -0,0 +1,82 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Utility functions for handling classes with multiple categories. + +> **Module:** `aisp.utils.multiclass` +> **Import:** `from aisp.utils import multiclass` + +## Functions + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separate indices of samples by class for targeted iteration. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------------------------------------|:-------:|-------------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | list with unique classes. | +| `y` | `npt.NDArray` | - | Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. | + +**Returns** + +| Type | Description | +|--------|------------------------------------------------------------------------------| +| `dict` | A dictionary with the list of array positions(`y`), with the classes as key. | + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### predict_knn_affinity + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray: + ... +``` + +Predict classes using k-nearest neighbors and trained cells. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|-----------------------------------------------|:-------:|----------------------------------------------------------------| +| `X` | `npt.NDArray` | - | Input data to be classified. | +| `k` | `int` | - | Number of nearest neighbors to consider for prediction. | +| `all_cell_vectors` | `List[Tuple[Union[str, int], npt.NDArray]]` | - | List of tuples (class_name, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Function that takes two vectors and returns an affinity value. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------------| +| `npt.NDArray` | Array of predicted labels for each sample in X, based on the k nearest neighbors. | diff --git a/docs/api/utils/sanitizers.md b/docs/api/utils/sanitizers.md new file mode 100644 index 000000000..7f01210cf --- /dev/null +++ b/docs/api/utils/sanitizers.md @@ -0,0 +1,119 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Utility functions for validation and treatment of parameters. + +> **Module:** `aisp.utils.sanitizers` +> **Import:** `from aisp.utils import sanitizers` + +## Functions + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Value if present in the set of valid choices; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------|:-------:|------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `valid_choices` | `Iterable[T]` | - | A collection of valid choices. | +| `default` | `T` | - | The default value to be returned if 'value' is not in 'valid_choices'. | + +**Returns** + +| Type | Description | +|------|-----------------------------------------------------------| +| `T` | The original value if valid, or the default value if not. | + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Value if it satisfies the specified condition; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|-----------------------|:-------:|-----------------------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `default` | `T` | - | The default value to be returned if the condition is not satisfied. | +| `condition` | `Callable[[T], bool]` | - | A function that takes a value and returns a boolean, determining if the value is valid. | + +**Returns** + +| Type | Description | +|------|--------------------------------------------------------------------------------| +| `T` | The original value if the condition is satisfied, or the default value if not. | + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Seed if it is a non-negative integer; otherwise, None. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|---------------------------------| +| `seed` | `Any` | - | The seed value to be validated. | + +**Returns** + +| Type | Description | +|-----------------|------------------------------------------------------------------------------| +| `Optional[int]` | The original seed if it is a non-negative integer, or None if it is invalid. | + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Validate and normalize feature bounds. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|-------|:-------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | The input bounds, which must be either None or a dictionary with 'low' and 'high' keys. | +| `problem_size` | `int` | - | The expected length for the normalized bounds lists, corresponding to the number of features in the problem. | + +**Returns** + +| Type | Description | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------------------------------| +| `TypeError` | If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. | +| `ValueError` | If provided iterables have the wrong length. | diff --git a/docs/api/utils/types.md b/docs/api/utils/types.md new file mode 100644 index 000000000..3df506673 --- /dev/null +++ b/docs/api/utils/types.md @@ -0,0 +1,60 @@ +--- +id: types +sidebar_label: types +keywords: + - types + - typing + - aliases + - type hints +--- + +# types + +Defines type aliases used throughout the project to improve readability. + +> **Module:** `aisp.utils.types` +> **Import:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Type of input features: + +- `"binary-features"`: values like 0 or 1. +- `"continuous-features"`: numeric continuous values. +- `"ranged-features"`: values defined by intervals. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Same as ``FeatureType``, plus: + +- `"permutation-features"`: values represented as permutation. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Distance metric used in calculations: + +- `"manhattan"`: the Manhattan distance between two points +- `"minkowski"`: the Minkowski distance between two points. +- `"euclidean"`: the Euclidean distance between two points. + +--- \ No newline at end of file diff --git a/docs/api/utils/validation.md b/docs/api/utils/validation.md new file mode 100644 index 000000000..e224c3461 --- /dev/null +++ b/docs/api/utils/validation.md @@ -0,0 +1,180 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validation +--- + +# module + +Contains functions responsible for validating data types. + +> **Module:** `aisp.utils.validation` +> **Import:** `from aisp.utils import validation` + +## Functions + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detect the type of data in a vector. + +The function detects if the vector contains data of type: + +- Binary features: boolean values or integers restricted to 0 and 1. +- Continuous features: floating-point values in the normalized range [0.0, 1.0]. +- Ranged features: floating-point values outside the normalized range. + +**Parameters** + +| Name | Type | Default | Description | +|----------|---------------|:-------:|------------------------------------------------| +| `vector` | `npt.NDArray` | - | An array containing the data to be classified. | + +**Returns** + +| Type | Description | +|-----------------------------------------|-----------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | The data type of the vector: "binary-features", "continuous-features", or " ranged-features". | + +**Raises** + +| Exception | Description | +|------------------------|------------------------------------------------------------------| +| `UnsupportedTypeError` | If the data type of the vector is not supported by the function. | + +--- + +### check_array_type + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: + ... +``` + +Ensure X is a numpy array. Convert from list if needed. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `name` | `str` | `'X'` | Variable name used in error messages. | + +**Returns** + +| Type | Description | +|---------------|----------------------------------| +| `npt.NDArray` | The converted or validated array | + +**Raises** + +| Exception | Description | +|-------------|--------------------------------| +| `TypeError` | If X is not ndarray or a list. | + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Ensure X and y have compatible first dimensions. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array of target classes of `x` with (`n_samples`). | + +**Raises** + +| Exception | Description | +|-------------|-------------------------------------| +| `TypeError` | If x or y have incompatible shapes. | + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Ensure X has the expected number of features. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Input array for prediction, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `expected` | `int` | - | Expected number of features per sample (columns in X). | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Ensure X contains only 0 and 1. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|--------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | + +**Raises** + +| Exception | Description | +|--------------|--------------------------------------------------| +| `ValueError` | If the array contains values other than 0 and 1. | + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Ensure all values in the x array fall within a range. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|---------------|:-------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | +| `name` | `str` | `'X'` | Name used in the error message. | +| `min_value` | `float` | `0.0` | Minimum allowed value. | +| `max_value` | `float` | `1.0` | Maximum allowed value. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------| +| `ValueError` | If the array fall outside the interval (min_value, max_value). | diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..d0b2edc8f --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,76 @@ +--- +id: architecture +sidebar_position: 5 +sidebar_label: Architecture +keywords: + - architecture +--- + +# AISP Architecture + +AISP (**A**rtificial **I**mmune **S**ystems **P**ackage) is package dedicated to implementing algorithms +inspired by the immune system of vertebrates. This documentation focuses on the project architecture, aiming to +facilitate contributions and maintenance. +The package structure is modular, with a clear separation between algorithms families and support modules for +component reuse across algorithms. + +## Module organization + +The package hierarchy is divided into 3 main cores: base, utils and algorithm families. +The base core concentrates on immunological abstractions and modeling, serving as the foundation for the algorithms. +Meanwhile, utils gathers functions that assist in implementing algorithms while avoiding code redundancy. + +The algorithm families core group different immune system metaphors that define them. + +In aisp, these families are organized into following modules: + +- Danger Theory Algorithms (DTA) - Planned for future versions +- Clonal Selection Algorithms (CSA) +- Immune Network Algorithms (INA) +- Negative Selection Algorithms (NSA) + +### Module details + +#### Package core (`aisp.base`) +The base module is the foundation of the package, divided into: +1. `base.core`: Contains abstract classes that implement parameter management and core logic for compatibility. + - `Base` (Private): Abstract class extended by the other **base** classes listed below. + - `BaseClassifier`: Abstract class for classification algorithms. + - `BaseClusterer`: Abstract class for clustering algorithms. + - `BaseOptimizer`: Abstract class for optimization algorithms. +2. `base.immune`: Defines cells and process from the immune inspired domain. + - `cell`: Representations of immune system cells and antibodies. + - `mutation`: Cell mutation functions. + - `population`: Creation of immune cell populations. +#### Utilities (`aisp.utils`) +Support module with reusable helper functions across the package. +#### Algorithm families +The implementations of immune inspired algorithms in **aisp** are organized into families, based on the taxonomy +presented in Brabazon et al. [^1] + +```mermaid +flowchart TD + AIS[Artificial Immune Systems] + NSA[Negative/Positive Selection] + CSA[Clonal Expansion and Selection] + INA[Network Theory Algorithms] + DT[Danger Theory] + + AIS --- NSA + AIS --- CSA + AIS --- INA + AIS --- DT +``` +**Source: Adapted from Brabazon et al. [^1], Figure 16.1.** + +Structure as follows: + - `aisp.nsa`: Module with algorithms based on Negative Selection. + - `aisp.csa`: Module with algorithms based on Clonal Selection. + - `aisp.ina`: Module with algorithms based on immune network theory. + - `aisp.dta`: Module with algorithms based on Danger Theory (**Ainda não implementado**). + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Available at: https://dx.doi.org/10.1007/978-3-662-43631-8. diff --git a/docs/faq.md b/docs/faq.md index 759ea5ff4..7f392f9cb 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,6 +1,6 @@ --- +id: faq sidebar_position: 6 -title: Frequently Asked Questions sidebar_label: FAQ keywords: - FAQ @@ -9,6 +9,8 @@ keywords: - Help --- +# Frequently Asked Questions + Quick solutions for possible questions about aisp. ## General usage @@ -17,27 +19,30 @@ Quick solutions for possible questions about aisp. It depends on the type of problem: -- **Anomaly detection**: Use ``RNSA`` or ``BNSA``. +- **Anomaly detection**: Use `RNSA` or `BNSA`. - RNSA for problems with continuous data. - BNSA for problems with binary data. -- **Classification**: Use ``AIRS``, ``RNSA``, or ``BNSA``. - - ``RNSA`` and ``BNSA`` were implemented to be applied to multiclass classification. - - ``AIRS`` is more robust to noise in the data. -- **Optimization**: Use ``Clonalg``. +- **Classification**: Use `AIRS`, `RNSA`, or `BNSA`. + - `RNSA` and `BNSA` were implemented to be applied to multiclass classification. + - `AIRS` is more robust to noise in the data. +- **Optimization**: Use `Clonalg`. - The implementation can be applied to objective function optimization (min/max). -- **Clustering**: Use ``AiNet``. +- **Clustering**: Use `AiNet`. - Automatically separates data into groups. - Does not require a predefined number of clusters. --- -### How do I normalize my data to use the ``RNSA`` algorithm? +### How do I normalize my data to use the `RNSA` algorithm? -RNSA works exclusively with data normalized in the range [0, 1]. Therefore, before applying it, the data must be normalized if they are not already in this range. A simple way to do this is by using normalization tools from **scikit-learn**, such as [``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). +RNSA works exclusively with data normalized in the range (0.0, 1.0). Therefore, before applying it, the data must be +normalized if they are not already in this range. A simple way to do this is by using normalization tools from +**scikit-learn**, such as +[``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). #### Example -In this example, ``X`` represents the non-normalized input data. +In this example, `X` represents the non-normalized input data. ```python from sklearn.preprocessing import MinMaxScaler @@ -55,7 +60,7 @@ rnsa.fit(x_norm, y) ## Parameter configuration -### How do I choose the number of detectors (``N``) in ``RNSA`` or ``BNSA``? +### How do I choose the number of detectors (`N`) in `RNSA` or `BNSA`? The number of detectors directly affects performance: @@ -69,7 +74,7 @@ The number of detectors directly affects performance: --- -### Which radius (``r`` or ``aff_thresh``) should I use in ``BNSA`` or ``RNSA``? +### Which radius (`r` or `aff_thresh`) should I use in `BNSA` or `RNSA`? The detector radius depends on the data distribution: @@ -78,15 +83,17 @@ The detector radius depends on the data distribution: --- -### What is the ``r_s`` parameter in ``RNSA``? +### What is the `r_s` parameter in `RNSA`? -``r_s`` is the radius of the self sample. It defines a region around each training sample. +`r_s` is the radius of the self sample. It defines a region around each training sample. --- ### Clonalg: How do I define the objective function? -The objective function must follow the pattern of the [base class](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). It must receive a solution as input and return a cost (or affinity) value. +The objective function must follow the pattern of the +[base class](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). +It must receive a solution as input and return a cost (or affinity) value. ```python def affinity_function(self, solution: Any) -> float: @@ -95,12 +102,14 @@ def affinity_function(self, solution: Any) -> float: There are two ways to define the objective function in Clonalg. -1. Defining the function directly in the class constructor - ```python def sphere(solution): - return np.sum(solution *- 2) + return np.sum(solution ** 2) +``` +1. Defining the function directly in the class constructor + +```python clonalg = Clonalg( problem_size=2, affinity_function=sphere @@ -110,9 +119,6 @@ clonalg = Clonalg( 2. Using the function registry ```python -def sphere(solution): - return np.sum(solution *- 2) - clonalg = Clonalg( problem_size=2, ) diff --git a/docs/intro.md b/docs/intro.md index e4bc38d6d..c7d0664ca 100644 --- a/docs/intro.md +++ b/docs/intro.md @@ -52,9 +52,35 @@ AISP provides implementations of bio-inspired algorithms for: - **Optmization**: Find optimal solutions for objective functions. - **Clustering**: Group data without supervision. -### Algorithms implemented +--- + +## Implemented Algorithms + +### [Negative Selection](./aisp-techniques/negative-selection.md) (`aisp.nsa`) + +- [**BNSA**](./api/nsa/bnsa.md) - Binary Negative Selection Algorithm +- [**RNSA**](./api/nsa/rnsa.md) - Real-Valued Negative Selection Algorithm + +### [Clonal Selection](./aisp-techniques/clonal-selection-algorithms.md) (`aisp.csa`) + +- [**AIRS**](./api/csa/airs.md) - Artificial Immune Recognition System +- [**CLONALG**](./api/csa/clonalg.md) - Clonal Selection Algorithm + +### [Immune Network Theory](./aisp-techniques/immune-network-theory.md) (`aisp.ina`) + +- [**AiNet**](./api/ina/ai-net.md) - Artificial Immune Network for clustering and data compression + +### Module in Development + +#### Danger Theory (`aisp.dta`) + +- **DCA** - Dendritic Cell Algorithm *(planned)* + +## API overview + +All algorithms follow a simple and consistent interface: -> - [x] [**Negative Selection.**](./aisp-techniques/negative-selection/) -> - [x] [**Clonal Selection Algorithms.**](./aisp-techniques/clonal-selection-algorithms/) -> - [x] [**Immune Network Theory.**](./aisp-techniques/immune-network-theory/) -> - [ ] *Danger Theory* +- `fit(X, y, verbose: bool = True)`: trains the model for classification tasks. +- `fit(X, verbose: bool = True)`: trains the model for clustering tasks. +- `predict(X)`: makes predictions based on new data. +- `optimize(max_iters: int =..., n_iter_no_change: int =..., verbose: bool = True)`: run the optimization algorithms diff --git a/docusaurus.config.js b/docusaurus.config.js index c1feed670..9540f1453 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -1,5 +1,7 @@ // @ts-check // Note: type annotations allow type checking and IDEs autocompletion +import rehypeKatex from 'rehype-katex'; +import remarkMath from 'remark-math'; require('dotenv/config'); const { themes } = require('prism-react-renderer') const lightCodeTheme = themes.github; @@ -47,7 +49,7 @@ const config = { locales: ['en', 'pt-br'], localeConfigs: { en: { - htmlLang: 'en-GB', + htmlLang: 'en', }, // You can omit a locale (e.g. fr) if you don't need to override the defaults pt: { @@ -65,10 +67,8 @@ const config = { ({ docs: { sidebarPath: require.resolve('./sidebars.ts'), - remarkPlugins: [require("remark-math")], - rehypePlugins: [ - [require("rehype-katex"), { strict: false }], - ], + remarkPlugins: [remarkMath], + rehypePlugins: [[rehypeKatex, { strict: false }]], showLastUpdateAuthor: true, showLastUpdateTime: true, lastVersion: isDev ? 'current' : getNextVersionName(), @@ -141,7 +141,7 @@ const config = { position: 'left', label: 'Docs', }, - + { href: 'https://github.com/AIS-Package/aisp', label: 'GitHub', @@ -225,6 +225,7 @@ const config = { searchResultLimits: 6, }), ], + '@docusaurus/theme-mermaid', ], markdown: { format: 'mdx', @@ -236,7 +237,7 @@ const config = { headingIds: true, }, anchors: { - maintainCase: true, + maintainCase: false, }, hooks: { onBrokenMarkdownLinks: 'warn', diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/_category_.json deleted file mode 100644 index 3587f3645..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/_category_.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "description": "As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time" -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/negative-selection.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/negative-selection.md deleted file mode 100644 index 9041d2b26..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Core/negative-selection.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Seleção Negativa - -As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time. - -## Função check_detector_bnsa_validity(...) - -```python -def check_detector_bnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - aff_thresh: float -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). -* aff_thresh (``float``): Limiar de afinidade. - -**Retorna:** - -* True se o detector for válido, False caso contrário. - ---- - -## Função bnsa_class_prediction(...) - -```python -def bnsa_class_prediction( - features: npt.NDArray, - class_detectors: npt.NDArray, - aff_thresh: float -) -> int: -``` - -Define a classe de uma amostra a partir dos detectores não-próprios. - -**Os parâmetros de entrada são:** - -* features (``npt.NDArray``): amostra binária a ser classificada (shape: [n_features]). -* class_detectors (``npt.NDArray``): Matriz contendo os detectores de todas as classes (shape: [n_classes, n_detectors, n_features]). -* aff_thresh (``float``): Limiar de afinidade que determina se um detector reconhece a amostra como não-própria. - -**Retorna:** - -* int: Índice da classe predita. Retorna -1 se for não-própria para todas as classes. - ---- - -## Função check_detector_rnsa_validity(...) - -```python -def check_detector_rnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - threshold: float, - metric: int, - p: float -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). -* threshold (``float``): Afinidade. -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Retorna:** - -* True se o detector for válido, False caso contrário. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Display.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Display.md deleted file mode 100644 index 5096345b3..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Display.md +++ /dev/null @@ -1,152 +0,0 @@ -# Display - -Funções utilitárias para exibir informações de algoritmos - -## def _supports_box_drawing() - -```python -def _supports_box_drawing() -> bool -``` - -Função para verificar se o terminal suporta caracteres de borda. - -**Retorna**: - -* ***bool*** (`bool`): True se o terminal provavelmente suporta caracteres de borda, False caso contrário. - ---- - -## class TableFormatter - -Classe para formatar dados tabulares em strings para exibição no console. - -**Parâmetros**: - -* ***headers*** (`Mapping[str, int]`): Mapeamento dos nomes das colunas para suas larguras respectivas, no formato `{nome_coluna: largura_coluna}`. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -### def _border(left, middle, right, line, new_line=True) - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str -``` - -Cria uma borda horizontal para a tabela. - -**Parâmetros**: - -* ***left*** (`str`): Caractere na borda esquerda. -* ***middle*** (`str`): Caractere separador entre colunas. -* ***right*** (`str`): Caractere na borda direita. -* ***line*** (`str`): Caractere usado para preencher a borda. -* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é True). - -**Retorna**: - -* ***border*** (`str`): String representando a borda horizontal. - ---- - -### def get_header() - -```python -def get_header(self) -> str -``` - -Gera o cabeçalho da tabela, incluindo a borda superior, os títulos das colunas e a linha separadora. - -**Retorna**: - -* ***header*** (`str`): String formatada do cabeçalho da tabela. - ---- - -### def get_row(values) - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str -``` - -Gera uma linha formatada para os dados da tabela. - -**Parâmetros**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Dicionário com os valores de cada coluna, no formato `{nome_coluna: valor}`. - -**Retorna**: - -* ***row*** (`str`): String formatada da linha da tabela. - ---- - -### def get_bottom(new_line=False) - -```python -def get_bottom(self, new_line: bool = False) -> str -``` - -Gera a borda inferior da tabela. - -**Parâmetros**: - -* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é False). - -**Retorna**: - -* ***bottom*** (`str`): String formatada da borda inferior. - ---- - -## class ProgressTable(TableFormatter) - -Classe para exibir uma tabela formatada no console para acompanhar o progresso de um algoritmo. - -**Parâmetros**: - -* ***headers*** (`Mapping[str, int]`): Mapeamento `{nome_coluna: largura_coluna}`. -* ***verbose*** (`bool`, padrão=True): Se False, não imprime nada no terminal. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -### def _print_header() - -```python -def _print_header(self) -> None -``` - -Imprime o cabeçalho da tabela. - ---- - -### def update(values) - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None -``` - -Adiciona uma nova linha de valores à tabela. - -**Parâmetros**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): As chaves devem corresponder às colunas definidas em `headers`. - ---- - -### def finish() - -```python -def finish(self) -> None -``` - -Encerra a exibição da tabela, imprimindo a borda inferior e o tempo total. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md deleted file mode 100644 index f4b5939b0..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Distance - -Funções utilitárias para distância normalizada entre matrizes com decoradores numba. - -## def hamming(...) - -```python -def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: -``` - -Função para calcular a distância de Hamming normalizada entre dois pontos. - -$$ -\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def euclidean(...) - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Função para calcular a distância euclidiana normalizada entre dois pontos. - -$$ -\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def cityblock(...) - -```python -def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Função para calcular a distância Manhattan normalizada entre dois pontos. - -$$ -\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def minkowski(...) - -```python -def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): -``` - -Função para calcular a distância de Minkowski normalizada entre dois pontos. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |X_n - Y_n|p) ¹/ₚ) / n$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto. -* v (``npt.NDArray``): Coordenadas do segundo ponto. -* p (``float``): O parâmetro p define o tipo de distância a ser calculada: - * p = 1: Distância **Manhattan** — soma das diferenças absolutas. - * p = 2: Distância **Euclidiana** — soma das diferenças ao quadrado (raiz quadrada). - * p > 2: Distância **Minkowski** com uma penalidade crescente à medida que p aumenta. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def compute_metric_distance(...) - -```python -def compute_metric_distance( - u: npt.NDArray[np.float64], - v: npt.NDArray[np.float64], - metric: int, - p: np.float64 = 2.0 -) -> np.float64: -``` - -Função para calcular a distância entre dois pontos pela ``métrica`` escolhida. - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto. -* v (``npt.NDArray``): Coordenadas do segundo ponto. -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* Distância (``double``) entre os dois pontos com a métrica selecionada. - ---- - -## def min_distance_to_class_vectors(...) - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray, - vector_x: npt.NDArray, - metric: int, - p: float = 2.0 -) -> float: -``` - -Calcula a menor distância entre um vetor de entrada e os vetores de uma classe. - -**Parameters:** - -* x_class (``npt.NDArray``): Array contendo os vetores da classe com os quais o vetor de entrada será comparado. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Vetor a ser comparado com os vetores da classe. Formato esperado: (n_características,). -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* float: A menor distância calculada entre o vetor de entrada e os vetores da classe. -* Retorna -1.0 se as dimensões de entrada forem incompatíveis. - ---- - -## def get_metric_code(...) - -```python -def get_metric_code(metric: str) -> int: -``` - -Retorna o código numérico associado a uma métrica de distância. - -**Parameters:** - -* metric (``str``): Nome da métrica. Pode ser "euclidean", "manhattan", "minkowski" ou "hamming". - -**Raises** - -* ``ValueError``: Se a métrica informada não for suportada. - -**Returns:** - -* ``int``: Código numérico correspondente à métrica. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Metrics.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Metrics.md deleted file mode 100644 index 1bef4601c..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Metrics.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -sidebar_position: 1 -title: Métricas -sidebar_label: Metrics -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -O arquivo de métricas fornece utilitários para medir, analisar e comparar o desempenho dos algoritmos do pacote de forma padronizada. - -### def accuracy_score(...) - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float -``` - -Função para calcular a acurácia de precisão com base em listas de rótulos -verdadeiros e nos rótulos previstos. - -**Parâmetros** - -* y_true (``Union[npt.NDArray, list]``): Rótulos verdadeiros (corretos).. -* y_pred (``Union[npt.NDArray, list]``): Rótulos previstos. - -**Retornos** - -* Precisão (``float``): A proporção de previsões corretas em relação -ao número total de previsões. - -**Lança** - -* ValueError: Se `y_true` ou `y_pred` estiverem vazios ou se não -tiverem o mesmo tamanho. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md deleted file mode 100644 index fbe8d25ee..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_position: 1 -title: Multiclasse -sidebar_label: Multiclass -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -Este arquivo contém funções utilitárias internas desenvolvidas para simplificar a manipulação e o processamento de dados em cenários de classificação multiclasse dentro do pacote AISP. - -### def slice_index_list_by_class(...) - -```python -def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict -``` - -A função ``slice_index_list_by_class(...)``, separa os índices das linhas conforme a \ -classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for \ -a classe que está sendo treinada. - -**Parameters:** - -* classes (``list or npt.NDArray``): lista com classes únicas. -* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saída do \ - array de amostra ``X``. - -**Returns:** - -* dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave. - ---- - -### def predict_knn_affinity(...) - -Função para prever classes usando k-vizinhos mais próximos e células treinadas. - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray -``` - -**Parâmetros:** - -* **_X_** (`npt.NDArray`): Dados de entrada a serem classificados. -* **_k_** (`int`): Número de vizinhos mais próximos a considerar para a previsão. -* **_all_cell_vectors_** (`List[Tuple[Union[str, int], npt.NDArray]]`): Lista de tuplas contendo pares (nome_da_classe, vetor_da_célula). -* **_affinity_func_** (`Callable[[npt.NDArray, npt.NDArray], float]`): Função que recebe dois vetores e retorna um valor de afinidade. - -**Retorna:** - -* `npt.NDArray`: Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md deleted file mode 100644 index b65540711..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md +++ /dev/null @@ -1,16 +0,0 @@ -# Random - -Funções utilitárias para geração e reprodutibilidade de números aleatórios. - -## Função set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Define a semente para números aleatórios usados por funções compiladas com Numba. - -**Parâmetros**: - -* **seed**: `int` - Valor inteiro usado para inicializar o gerador de números aleatórios do Numba. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Sanitizers.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Sanitizers.md deleted file mode 100644 index 56be3c290..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Sanitizers.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Sanitizers - -## def sanitize_choice(...) - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T -``` - -A função ``sanitize_choice(...)``, retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. - -**Parameters:** - -* ***value*** (``T``): O valor a ser verificado. -* ***valid_choices*** (``Iterable[T]``): Uma coleção de opções válidas. -* ***default***: O valor padrão a ser retornado se ``value`` não estiver em ``valid_choices``. - -**Returns:** - -* `T`: O valor original, se válido, ou o valor padrão, se não. - ---- - -## def sanitize_param(...) - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -A função ``sanitize_param(...)``, retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. - -**Parameters:** - -* value (``T``): O valor a ser verificado. -* default (``T``): O valor padrão a ser retornado se a condição não for satisfeita. -* condition (``Callable[[T], bool]``): Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. - -**Returns:** - -* `T`: O valor original se a condição for satisfeita, ou o valor padrão se não for. - ---- - -## def sanitize_seed(...) - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -A função ``sanitize_param(...)``, retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. - -**Parameters:** - -* seed (``Any``): O valor da seed a ser validado. - -**Returns:** - -* ``Optional[int]``: A seed original se for um inteiro não negativo, ou ``None`` se for inválido. - ---- - -## def sanitize_bounds(...) - -```python -def sanitize_bounds(bounds: Any, problem_size: int) -> Dict[str, npt.NDArray[np.float64]] -``` - -A função `sanitize_bounds(...)` valida e normaliza os limites das características (features). - -**Parâmetros**: - -* ***bounds*** (`Any`): Os limites de entrada, que devem ser `None` ou um dicionário com as chaves `'low'` e `'high'`. -* ***problem_size*** (`int`): O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. - -**Retorna**: - -* `Dict[str, list]`: Dicionário no formato `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md deleted file mode 100644 index 030678fc5..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md +++ /dev/null @@ -1,108 +0,0 @@ -# Validation - -## def detect_vector_data_type(...) - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detecta o tipo de dado em um determinado vetor. - -Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: - -* **binário**: Valores booleanos (`True`/`False`) ou inteiro `0`/`1`. -* **contínuo**: Valores float dentro do intervalo normalizado `[0.0, 1.0]`. -* **intervalo**: Valores float fora do intervalo normalizado. - -### Parâmetros - -* `vetor` (`npt.NDArray`): Um array contendo os dados a serem classificados. - -### Retorna - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): O tipo de dado detectado no vetor. - -### Gera - -* `UnsupportedDataTypeError`: Gerado se o vetor contiver um tipo de dado não suportado. - ---- - -## def check_array_type(...) - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Garante que o parâmetro recebido é um array numpy. Converte de lista se necessário. - -**Parâmetros:** - -* `x`: Array ou lista contendo as amostras e características. -* `name`: Nome da variável para mensagens de erro. - -**Retorna:** - -* `npt.NDArray`: O array convertido ou validado. - -**Lança:** - -* `TypeError`: Se não for possível converter para ndarray. - ---- - -## def check_shape_match(...) - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Garante que os arrays `x` e `y` possuem o mesmo número de amostras (primeira dimensão). - -**Parâmetros:** - -* `x`: Array de amostras. -* `y`: Array de classes alvo. - -**Lança:** - -* `TypeError`: Se as dimensões não forem compatíveis. - ---- - -## def check_feature_dimension(...) - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Garante que o array possui o número esperado de características (features). - -**Parâmetros:** - -* `x`: Array de entrada para predição. -* `expected`: Número esperado de características por amostra. - -**Lança:** - -* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. - ---- - -## def check_binary_array(...) - -```python -def check_binary_array(x: npt.NDArray): -``` - -Garante que o array contém apenas valores 0 e 1. - -**Parâmetros:** - -* `x`: Array a ser verificado. - -**Lança:** - -* `ValueError`: Se o array contiver valores diferentes de 0 e 1. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/_category_.json deleted file mode 100644 index 59b3ccf99..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "label": "Utils", - "description": "Funções utilitárias e auxiliares para o desenvolvimento." -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/_category_.json deleted file mode 100644 index 871d71c3d..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Guides", - "position": 2.6, - "link": { - "type": "generated-index", - "description": "Explore a documentação avançada da biblioteca, que abrange as classes base, além das funções utilitárias do módulo utils voltadas para métricas e manipulação de classificação multiclasse." - } -} diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/_category_.json deleted file mode 100644 index 8c11fd000..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "position": 1, - "description": "Classe base para algoritmo de classificação." -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md deleted file mode 100644 index bd5f0f0ef..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_position: 1 -title: Classe Base -sidebar_label: Base -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Classe Base - - Modelo Base - - Compatibilidade com Scikit-learn - - get_params - - set_params - - Semente Aleatória - - Classes Python ---- - -Classe base para compatibilidade com a API do scikit-learn. - -Fornece os métodos `get_params` e `set_params` para compatibilidade com a API do scikit-learn, permitindo acesso aos parâmetros públicos do modelo. - -### Função set_params(...) - -```python -def set_params(self, **params) -``` - -Define os parâmetros da instância. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros**: - -* **params**: dict - Dicionário de parâmetros que serão definidos como atributos da instância. Apenas atributos públicos (que não começam com "_") são modificados. - -**Retorno**: - -* self: `Base` - Retorna a própria instância após definir os parâmetros. - ---- - -### Função get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Retorna um dicionário com os principais parâmetros do objeto. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros**: - -* **deep**: `bool` (padrão=True) - Ignorado nesta implementação, mas incluído para compatibilidade com scikit-learn. - -**Retorno**: - -* params: `dict` - Dicionário contendo os atributos do objeto que não começam com "_". - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md deleted file mode 100644 index 546e22f96..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -sidebar_position: 1 -sidebar_label: BaseClassifier -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Classe base para algoritmo de classificação - -## ``class BaseClassifier(ABC)`` - -Classe base para algoritmos de classificação, definindo os métodos abstratos ``fit`` e ``predict``, e implementando o método ``get_params``. - -## Abstract methods - -### def fit(...) - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Ajusta o modelo aos dados de treinamento. - -Implementação: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-fit) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-fit) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) - -### def predict(...) - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -Realiza a previsão dos rótulos para os dados fornecidos. - -Implementação: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-predict) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-predict) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) - ---- - -## Métodos - -### def score(...) - -```python -def score(self, X: npt.NDArray, y: list) -> float -``` - -A função de pontuação (score) calcula a precisão da previsão. - -Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. -Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. - -**Parâmetros**: - -- ***X***: np.ndarray - Conjunto de características com formato (n_amostras, n_características). -- ***y***: np.ndarray - Valores verdadeiros com formato (n_amostras,). - -**Retorna**: - -- precisão: float - A precisão do modelo. - ---- - -### Método _slice_index_list_by_class(...) - -A função ``_slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -### def get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict: -``` - -A função get_params retorna um dicionário com os parâmetros principais do objeto. - -Esta função é necessária para garantir a compatibilidade com as funções do scikit-learn. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md deleted file mode 100644 index aea519ce3..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -sidebar_position: 3 -title: Base class for clustering algorithm. -sidebar_label: BaseClusterer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Clusterer - - Clustering - - Unsupervised Learning - - BaseClusterer - - Abstract Base Class - - fit Method - - predict Method - - fit_predict Method - - AiNet - - Cluster Prediction - - Python ML Classes ---- - -## ``BaseClusterer(ABC, Base)`` - -Classe base abstrata para algoritmos de clustering. - -Esta classe define a interface central para modelos de agrupamento. Ela exige -a implementação dos métodos **`fit`** e **`predict`** em todas as classes derivadas, -e fornece uma implementação padrão para **`fit_predict`** e **`get_params`**. - ---- - -### Função fit(...) - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer -``` - -Ajusta o modelo aos dados de treinamento. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada utilizados para treinar o modelo. -* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna**: - -* ***self***: `BaseClusterer` - Instância da classe que implementa este método. - -**Implementação**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) - ---- - -### Função predict(...) - -```python -def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] -``` - -Gera previsões com base nos dados de entrada. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. - -**Retorna**: - -* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. - -**Implementação**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) - ---- - -### Função fit_predict(...) - -```python -def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] -``` - -Método de conveniência que combina `fit` e `predict` em uma única chamada. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. -* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna**: - -* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md deleted file mode 100644 index 2bbb5b15a..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -sidebar_position: 4 -title: Classe base para algoritmos de otimização. -sidebar_label: BaseOptimizer -author: João Paulo -keywords: - - BaseOptimizer - - classe base de otimização - - abstract base class - - otimização em machine learning - - função objetivo - - método optimize - - avaliação de modelos - - metaheurísticas - - algoritmos bio-inspirados - - Python ML ---- - -Esta classe define a interface central para estratégias de otimização e mantém o histórico de custos, soluções avaliadas e a melhor solução encontrada. Subclasses devem implementar os métodos `optimize` e `objective_function`. - ---- - -### Propriedades - -#### `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Retorna o histórico de custos durante a otimização. - ---- - -#### `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Retorna o histórico de soluções avaliadas. - ---- - -#### `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Retorna a melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -#### `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Retorna o custo da melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -## Funções - -### Função _record_best(...) - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Registra um novo valor de custo e atualiza a melhor solução se houver melhoria. - -**Parâmetros**: - -* ***cost***: `float` - Valor de custo a ser adicionado ao histórico. - ---- - -### Função get_report() - -```python -def get_report(self) -> str -``` - -Gera um relatório resumido e formatado do processo de otimização. O relatório inclui a melhor solução, seu custo associado e a evolução dos valores de custo por iteração. - -**Retorna**: - -* **report**: `str` - String formatada contendo o resumo da otimização. - ---- - -### Função register(...) - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Registra dinamicamente uma função na instância do otimizador. - -**Parâmetros**: - -* ***alias***: `str` - Nome usado para acessar a função como atributo. -* ***function***: `Callable[..., Any]` - Callable a ser registrado. - -**Exceções**: - -* **TypeError**: Se `function` não for chamável. -* **AttributeError**: Se `alias` for protegido e não puder ser modificado, ou se `alias` não existir na classe do otimizador. - ---- - -### Função reset() - -```python -def reset(self) -``` - -Reinicia o estado interno do objeto, limpando o histórico e resetando os valores. - ---- - -### Métodos abstratos - -#### Função optimize(...) - -```python -def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any -``` - -Executa o processo de otimização. Este método deve ser implementado pela subclasse para definir como a estratégia de otimização explora o espaço de busca. - -**Parâmetros**: - -* ***max_iters***: `int` - Número máximo de iterações. -* ***n_iter_no_change***: `int`, padrão=10 - Número máximo de iterações sem atualização da melhor solução. -* ***verbose***: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante a otimização. - -**Retorna**: - -* **best_solution**: `Any` - A melhor solução encontrada pelo algoritmo de otimização. - ---- - -#### Função affinity_function(...) - -```python -def affinity_function(self, solution: Any) -> float -``` - -Avalia a afinidade de uma solução candidata. Este método deve ser implementado pela subclasse para definir o problema específico. - -**Parâmetros**: - -* ***solution***: `Any` - Solução candidata a ser avaliada. - -**Retorna**: - -* **cost**: `float` - Valor de custo associado à solução fornecida. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md deleted file mode 100644 index ef81da74b..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Cell Classes -sidebar_label: Cell Classes -keywords: - - Binário - - classificação - - limiar de afinidade - - Valores Reais - - classificação - - anomalias - - K-Vizinhos Mais Próximos - - célula-B de memória -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -Representação de células do sistema imunológico. - -## Cell - -Representa uma célula imune básica. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Atributos - -* **vector** (`np.ndarray`): Um vetor de características da célula. - -### Métodos - -* `__eq__(other)`: Verifica se duas células são iguais com base em seus vetores. -* `__array__()`: Interface de array para NumPy, permite que a instância seja tratada como um `np.ndarray`. -* `__getitem__(item)`: Obtém elementos do vetor de características usando indexação. - ---- - -## BCell - -Representa uma célula B de memória, derivada de `Cell`. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Métodos - -### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> np.ndarray -``` - -Clona N características das características de uma célula, gerando um conjunto de vetores mutados. - -#### Parâmetros - -* **n** (`int`): Número de clones a serem gerados a partir de mutações da célula original. -* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): Especifica o tipo de características com base na natureza das características de entrada. -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) com mínimo e máximo por dimensão. - -#### Retorna - -* **npt.NDArray**: Um array contendo N vetores mutados da célula original. - ---- - -## Antibody - -Representa um anticorpo com afinidade, derivado de `Cell`. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Atributos - -* **vector** (`npt.NDArray`): Um vetor de características da célula. -* **affinity** (`float`): Valor de afinidade do anticorpo. - -### Métodos - -* `__lt__(other)`: Compara este anticorpo com outro com base na afinidade. -* `__eq__(other)`: Verifica se dois anticorpos têm a mesma afinidade. - ---- - -## Detector - -Representa um detector não-próprio da classe RNSA. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Atributos - -* **position** (`npt.NDArray[np.float64]`): Vetor de características do detector. -* **radius** (`Optional[float]`): Raio do detector, usado no algoritmo V-detector. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md deleted file mode 100644 index d9e29b669..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Mutation -sidebar_label: Mutation -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - Mutação - - Expansão Clonal - - Sistema Imunológico - - clone_and_mutate - - clone_and_mutate_continuous - - clone_and_mutate_binary - - clone_and_mutate_ranged - - Sistemas Imunológicos Artificiais - - Funções Python Numba - - Mutação Vetorial ---- - -Contém funções que geram conjuntos de clones mutados a partir de vetores contínuos ou binários, simulando o processo de expansão clonal em sistemas imunológicos artificiais. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. - -### Retorno - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int -) -> npt.NDArray[np.bool_]: -``` - -Gera um conjunto de clones mutados a partir de um vetor binário. - -Esta função cria `n` clones do vetor binário de entrada e aplica mutações aleatórias em alguns bits, simulando a expansão clonal em sistemas imunes artificiais com representações discretas. - -### Parâmetros - -* `vector` (`npt.NDArray[np.bool_]`): Vetor binário original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. - -### Retorno - -* `clone_set` (`npt.NDArray[np.bool_]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) -def clone_and_mutate_ranged( -vector: npt.NDArray[np.float64], -n: int, -bounds: npt.NDArray[np.float64] -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo usando limites personalizados por dimensão. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. -* `bounds` (`npt.NDArray[np.float64]`): Um array 2D com o formato `(len(vector), 2)` contendo os valores mínimo e máximo para cada dimensão. - -### Retorna - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md deleted file mode 100644 index f3cbae8d9..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Módulo de Populações -sidebar_label: Populações -pagination_next: null -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell - - Clonal Expansion - - Immune System - - Artificial Immune Systems -lastUpdatedAt: 2025/11/21 -author: João Paulo ---- - -Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. - -## generate_random_antibodies(...) - -Gera uma população aleatória de anticorpos. - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -### Parâmetros - -* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. -* **n_features** (`int`): Número de características (dimensões) para cada anticorpo. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. - -### Retorno - -* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. - -### Exceções - -* **ValueError**: Caso o número de características seja menor ou igual a zero. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms.md new file mode 100644 index 000000000..c2cbcd1d2 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms.md @@ -0,0 +1,39 @@ +--- +id: docs-csa +keywords: + - seleção e expansão clonal + - clonalg + - artificial immune systems + - classificação + - otimização + - algoritmos bioinspirados + - computação natural +--- + +# Seleção e expansão clonal + +Os Algoritmos baseados na seleção e expansão clonal são inspirados no processo de proliferação de anticorpos +após a detecção de um antígeno, durante o qual os anticorpos gerados sofrem mutações na tentativa de aumentar +o reconhecimento do patógeno. [^1] + +--- + +A Seleção e expansão clonal pode ser aplicada em diferentes contextos, tais como: +- **Otimização** +- **Classificação** + +## Implementações do pacote + +### Sistema Imunológico Artificial de Reconhecimento ([AIRS](../api/csa/airs.md)) + +Algoritmo de classificação inspirado no processo de seleção clonal. + +### Algoritmo de Seleção Clonal ([CLONALG](../api/csa/clonalg.md)) + +Algoritmo de otimização inspirado no processo biológico de seleção clonal do sistema imunológico. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/README.mdx deleted file mode 100644 index fc3db09dc..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/README.mdx +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_position: 2 -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- -import DocCardList from '@theme/DocCardList'; - -# Algoritmos de Seleção Clonal. - -Os Algoritmos de Seleção Clonal são inspirados no processo de proliferação de anticorpos após a detecção de um antígeno, -durante o qual os anticorpos gerados sofrem mutações na tentativa de aumentar o reconhecimento do patógeno. - -## Classes: - - \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md deleted file mode 100644 index 1c5003080..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -id: airs -sidebar_label: AIRS - Sistema Imunológico Artificial de Reconhecimento -keywords: - - Binário - - Classificação - - Limiar de Afinidade - - Valores Reais - - Anomalias - - K-Vizinhos Mais Próximos -lastUpdatedAt: 2025/08/22 -author: João Paulo ---- - -# AIRS - Sistema Imunológico Artificial de Reconhecimento - -O ``AIRS`` é um algoritmo de classificação inspirado no processo de seleção clonal. A versão implementada nesta classe é inspirada na sua versão simplificada, o AIRS2, descrito em[Brabazon, O'Neill, and McGarraghy (2015)](#1) - -Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo adaptações para lidar com conjuntos de dados contínuos e binários. - -Com base no algoritmo 16.5 de Brabazon et al. [1](#1). - -:::tip Trabalhos relacionados e notáveis: - -- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) - -::: - -:::info - -**``AIRS``** estende a classe **[classe ``BaseClassifier``](../../../advanced-guides/base-module/core/Classifier.md)**, herdando sua funcionalidade base. - -::: - -## Construtor AIRS - -A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas de seleção e expansão clonal. - -**Atributos:** - -- **n_resources** (`float`): Quantidade total de recursos disponíveis. O padrão é 10. - -- **rate_clonal** (`float`): Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * taxa de hipermutação) para definir o número de clones. O padrão é 10. - -- **rate_hypermutation** (`int`): Taxa de clones mutados derivada de rate_clonal como um fator escalar. O padrão é 0,75. - -- **affinity_threshold_scalar** (`float`): Limiar de afinidade normalizado. O padrão é 0,75. - -- **k** (`int`): Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. O padrão é 10. - -- **max_iters** (`int`): Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. O padrão é 100. - -- **resource_amplified** (`float`): Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. O padrão é 1.0 (sem amplificação). - -- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$. - - Defaults to ``'euclidean'``. - -- **seed** (``Optional[int]``): Semente para geração aleatória de valores dos detectores. O padrão é None. - -- `**kwargs`: - - - **p** (`float`): Este parâmetro armazena o valor de `p` usado na distância de Minkowski. - O padrão é `2`, que corresponde à distância euclidiana normalizada. Diferentes valores de p resultam em variantes distintas da distância de Minkowski. [Saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Outras variáveis inicializadas:** - -- **cells_memory** (`dict`): Armazena uma lista de células de memória por classe. -- **affinity_threshold** (`dict`): Define o limiar de afinidade entre antígenos. -- **classes** (`npt.NDArray`): Lista de classes de saída. - ---- - -## Métodos Públicos - -### Método fit(...) - -A função `fit(...)` gera detectores para os não-pertencentes em relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray): -``` - -Realiza o treinamento conforme `X` e `y`, utilizando o método Sistema de Reconhecimento Imune Artificial (`AIRS`). - -**Parâmetros de entrada:** - -- **X**: Array com as características das amostras, com **N** amostras (linhas) e **N** características (colunas), normalizado para valores entre [0, 1]. -- **y**: Array com as classes de saída correspondentes às **N** amostras relacionadas a `X`. -- **verbose**: Booleano, padrão `True`, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -### Método predict(...) - -A função `predict(...)` realiza a predição de classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**Parâmetro de entrada:** - -- **X**: Array com as características para predição, com **N** amostras (linhas) e **N** colunas. - -**Retorna:** - -- **C**: Um array de predições com as classes de saída para as características fornecidas. -- **None**: Se não houver detectores. - ---- - -### Método score(...) - -A função `score(...)` calcula a acurácia do modelo treinado realizando predições e calculando a precisão. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -Retorna a acurácia como um `float`. - ---- - -## Métodos Privados - -### Método _refinement_arb(...) - -A função "_refinement_arb(...)" refina o conjunto ARB até que o valor médio de estímulo ultrapasse o limiar definido (`affinity_threshold_scalar`). - -Parâmetros: - -- **c_match** (`Cell`): Célula com o maior estímulo em relação a aᵢ. -- **arb_list** (`List[_ARB]`): Conjunto ARB. - -```python -def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: -``` - -Retorna a célula (_ARB) com o maior estímulo ARB. - ---- - -### Método _cells_affinity_threshold(...) - -A função "_cells_affinity_threshold(...)" calcula o limiar de afinidade com base na afinidade média entre instâncias de treinamento, onde aᵢ e aⱼ são um par de antígenos, e a afinidade é medida pela distância (Euclidiana, Manhattan, Minkowski, Hamming). -**Seguindo a fórmula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - -Parâmetros: - -- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - ---- - -### Método _affinity(...) - -A função "_affinity(...)" calcula o estímulo entre dois vetores usando métricas. - -Parâmetros: - -- **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -- **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -Retorna a taxa de estímulo entre os vetores. - ---- - -### Método _init_memory_c(...) - -A função "_init_memory_c(...)" inicializa células de memória selecionando aleatoriamente `n_antigens_selected` da lista de antígenos de treinamento. - -Parâmetros: - -- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: -``` - ---- - -## Referências - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md deleted file mode 100644 index eb0e525bd..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -id: abr -title: ABR -sidebar_label: ABR - Bolha de reconhecimento artificial -sidebar_position: 2 -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -## ABR (Artificial Recognition Ball) - -Individuo do conjunto de células reconhecedoras (ABR), herda características de uma célula-B, adicionando o consumo de recursos - -:::info - -**``ABR``** estende a classe **[``BCell``](../../../advanced-guides/base-module/immune/cell.md#BCell)**, herdando sua funcionalidade base. - -::: - -### Constructor - -Parameters: - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Function consume_resource(...) - -Parameters: - -* n_resource (```float```) : The initial amount of resources. -* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -Returns the remaining amount of resources after consumption. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md deleted file mode 100644 index 452753963..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -id: clonalg -sidebar_label: CLONALG - Algoritmo de Seleção Clonal -keywords: - - CLONALG - - algoritmo de seleção clonal - - otimização bio-inspirada - - inteligência artificial - - problemas binários - - problemas contínuos - - ranged optimization - - permutação - - metaheurísticas ---- - -# CLONALG - Algoritmo de Seleção Clonal - -A classe `Clonalg` é um **algoritmo de otimização** inspirado no processo biológico de seleção clonal do sistema imunológico. Esta implementação é projetada para minimizar ou maximizar funções de custo em diversos tipos de problemas, incluindo problemas binários, contínuos, com valores limitados (ranged) e de permutação. - -:::tip -A implementação do CLONALG foi inspirada na descrição apresentada em [1](#1). -::: - -:::info -Esta implementação do CLONALG contém algumas alterações baseadas no contexto do AISP, para aplicação geral -a diversos problemas, que podem produzir resultados diferentes da implementação padrão ou -específica. Esta adaptação visa generalizar o CLONALG para tarefas de minimização e -maximização, além de suportar problemas contínuos, discretos e de permutação. -::: - -:::info - -**``Clonalg``** estende a **[classe ``BaseOptimizer`` ](../../advanced-guides/base-module/core/Optimizer.md)**, herdando suas funcionalidades básicas. - -::: - ---- - -## CLONALG Constructor - -O construtor inicializa a instância do CLONALG com os principais parâmetros que definem o processo de otimização. - -**Atributos:** - -* **problem_size**: `int` - Dimensão do problema a ser otimizado. -* **N**: `int`, padrão=50 - Número de células de memória (anticorpos) na população. -* **rate_clonal**: `float`, padrão=10 - Número máximo de clones possíveis de uma célula. Este valor é multiplicado pela afinidade da célula para determinar o número de clones. -* **rate_hypermutation**: `float`, padrão=0.75 - Taxa de clones mutados, usada como fator escalar. -* **n_diversity_injection**: `int`, padrão=5 - Número de novas células de memória aleatórias injetadas para manter a diversidade. -* **selection_size**: `int`, padrão=5 - Número de melhores anticorpos selecionados para clonagem. -* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, padrão=None - Função objetivo usada para avaliar soluções candidatas. -* **feature_type**: `FeatureTypeAll`, padrão='ranged-features' - Tipo de amostra do problema, podendo ser `'continuous-features'`, `'binary-features'`, `'ranged-features'` ou `'permutation-features'`. -* **bounds**: `Optional[Dict]`, padrão=None - Dicionário definindo os limites de busca para problemas `'ranged-features'`. Pode ser um único intervalo ou uma lista de intervalos para cada dimensão. -* **mode**: `Literal["min", "max"]`, padrão="min" - Especifica se o algoritmo minimiza ou maximiza a função de custo. -* **seed**: `Optional[int]`, padrão=None - Semente para geração de números aleatórios. - ---- - -### Métodos Públicos - -#### Função `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -Este método executa o processo de otimização e retorna a população de anticorpos. - -**Parâmetros de entrada:** - -* **max_iters**: `int`, padrão=50 - Número máximo de interações. -* **n_iter_no_change**: `int`, padrão=10 - Número máximo de iterações sem melhoria na melhor solução. -* **verbose**: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante o processo de otimização. - -**Retorna:** - -* population : ``List[Antibody]``, A população de [anticorpos](../../advanced-guides/base-module/immune/cell.md#Antibody) após a expansão clonal. - ---- - -#### Função `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -Este método avalia a afinidade de uma solução candidata. Levanta `NotImplementedError` se nenhuma função de afinidade tiver sido fornecida à instância da classe. - -**Parâmetros de entrada:** - -* **solution**: `npt.NDArray` - Solução candidata a ser avaliada. - -**Retorna:** - -* `np.float64`: Valor de afinidade associado à solução. - ---- - -### Métodos Privados - -#### Função `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: -``` - -Seleciona os `n` melhores anticorpos com base em suas pontuações de afinidade, de acordo com o `mode` (`'min'` ou `'max'`). - -**Parâmetros de entrada:** - -* **n**: `int` - Número de anticorpos a serem selecionados. -* **antibodies**: `list[tuple]` - Lista de tuplas, onde cada tupla representa um anticorpo e sua pontuação associada. - -**Retorna:** - -* `list[tuple]`: Lista contendo os `n` anticorpos selecionados. - ---- - -#### Função `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -Inicializa aleatoriamente a população inicial de anticorpos. - -**Retorna:** - -* `npt.NDArray`: Lista com os anticorpos inicializados. - ---- - -#### Função `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -Introduz novos anticorpos aleatórios na população para manter a diversidade genética e ajudar a evitar convergência prematura. - -**Retorna:** - -* `npt.NDArray`: Array contendo os novos anticorpos aleatórios. - ---- - -#### Função `_clone_and_mutate(...)` - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: -``` - -Gera clones mutados a partir de um único anticorpo. A estratégia de mutação depende do `feature_type` especificado durante a inicialização (`'binary-features'`, `'continuous-features'`, `'ranged-features'` ou `'permutation-features'`). - -**Parâmetros de entrada:** - -* **antibody**: `npt.NDArray` - Vetor original do anticorpo a ser clonado e mutado. -* **n_clone**: `int` - Número de clones a serem gerados. -* **rate_hypermutation**: `float` - Taxa de hipermutação. - -**Retorna:** - -* `npt.NDArray`: Array contendo os clones mutados. - ---- - -#### Função `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation(self, population: list[tuple]) -> list: -``` - -Clona e aplica hipermutação a uma população de anticorpos. Retorna uma lista de todos os clones e suas afinidades em relação à função de custo. - -**Parâmetros de entrada:** - -* **population**: `list[tuple]` - Lista de anticorpos a serem avaliados e clonados. - -**Retorna:** - -* `list`: Lista contendo os clones mutados. - ---- - -## Referências - ---- - -### 1 -> -> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory.md new file mode 100644 index 000000000..55fa1162f --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory.md @@ -0,0 +1,41 @@ +--- +id: docs-ina +keywords: + - teoria da rede imunológica + - ainet + - artificial immune systems + - classificação + - clusterização + - otimização + - algoritmos bioinspirados + - computação natural +--- + +# Teoria da Rede Imunológica + +Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, +na qual células e moléculas são capazes de se reconhecer mutuamente[^1]. + +--- + +A Rede Imunológica Artificial pode ser aplicada em diferentes contextos, tais como: +- **Agrupamento (Clustering)** +- **Otimização** +- **Classificação** + +## Implementações do pacote + +### Rede Imunológica Artificial para Agrupamento e Compressão ([AiNet](../api/ina/ai-net.md)) + +AiNet é um algoritmo de clustering baseado na teoria das redes imunológicas, que utiliza seleção clonal e maturação +por afinidade para comprimir dados e identificar grupos[^2]. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md deleted file mode 100644 index 5738f143c..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md +++ /dev/null @@ -1,327 +0,0 @@ ---- -id: ainet -sidebar_label: AiNet - Agrupamento e Compressão -sidebar_position: 1 -pagination_next: null -keywords: - - Rede Imunológica Artificial - - AiNet - - Agrupamento - - Compressão de Dados - - Algoritmos Imunológicos - - Computação Bioinspirada - - Células de Memória - - Limite de Afinidade - - Limite de Supressão - - Seleção Clonal - - Expansão Clonal - - Introdução de Diversidade - - Reconhecimento de Padrões - - Detecção de Anomalias - - Agrupamento MST - - Árvore Geradora Mínima - - Aprendizado Não Supervisionado - - Algoritmos Bioinspirados - - Rede de Anticorpos -lastUpdatedAt: 2025/08/19 -author: João Paulo ---- - -# AiNet - Rede Imunológica Artificial para Agrupamento e Compressão - -A classe AiNet tem como objetivo realizar agrupamento utilizando metáforas inspiradas na teoria da rede imunológica. - -A classe AiNet implementa o algoritmo de Rede Imune Artificial para compressão e clustering. Ela utiliza princípios da teoria de redes imunes, -seleção clonal e maturação por afinidade para comprimir conjuntos de dados e encontrar clusters [1](#1). -Para clustering, pode opcionalmente utilizar uma [**Árvore Geradora Mínima** -(MST)](#2) para separar nós distantes em grupos. - -:::info - -**``AiNet``** estende a **[classe ``BaseClusterer``](../../advanced-guides/base-module/core/Clusterer.md)**, herdando sua funcionalidade básica. - -::: - -## Constructor - -```python -class AiNet( - self, - N: int = 50, - n_clone: int = 10, - top_clonal_memory_size: int = 5, - n_diversity_injection: int = 5, - affinity_threshold: float = 0.5, - suppression_threshold: float = 0.5, - mst_inconsistency_factor: float = 2.0, - max_iterations: int = 10, - k: int = 3, - metric: MetricType = "euclidean", - seed: Optional[int] = None, - use_mst_clustering: bool = True, - **kwargs -) -``` - -**Atributos:** - -* **N** (`int`): Número de células de memória (anticorpos) na população. Padrão: 50. -* **n_clone** (`int`): Número de clones gerados por célula de memória selecionada. Padrão: 10. -* **top_clonal_memory_size** (`Optional[int]`): Número de anticorpos de maior afinidade selecionados para clonagem. Padrão: 5. -* **n_diversity_injection** (`int`): Número de novos anticorpos aleatórios injetados para manter a diversidade. Padrão: 5. -* **affinity_threshold** (`float`): Limite para seleção/supressão de células. Padrão: 0.5. -* **suppression_threshold** (`float`): Limite para remoção de células de memória semelhantes. Padrão: 0.5. -* **mst_inconsistency_factor** (`float`): Fator para determinar arestas inconsistentes na MST. Padrão: 2.0. -* **max_iterations** (`int`): Número máximo de iterações de treinamento. Padrão: 10. -* **k** (`int`): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Padrão: **"Euclidean"**. - -* **seed** (`Optional[int]`): Semente para geração de números aleatórios. Padrão: None. -* **use_mst_clustering** (`bool`): Define se o clustering baseado em MST deve ser utilizado. Padrão: True. -* **kwargs**: - * **p** (`float`): Parâmetro para distância de Minkowski. Padrão: 2. - -**Outras variáveis inicializadas:** - -* **_population_antibodies** (`npt.NDArray`): Conjunto atual de anticorpos. -* **_memory_network** (`dict`): Dicionário que mapeia clusters para anticorpos. -* **_mst_structure** (`scipy.sparse.csr_matrix`): Estrutura de adjacência da MST. -* **_mst_mean_distance** (`float`): Média das distâncias das arestas da MST. -* **_mst_std_distance** (`float`): Desvio padrão das distâncias das arestas da MST. -* **classes** (`list`): Lista de rótulos dos clusters. - ---- - -## Métodos Públicos - -### Função fit(...) - -Treina o modelo AiNet com os dados de entrada: - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: -``` - -**Parâmetros de entrada:** - -* **X**: Matriz com amostras (linhas) e atributos (colunas). -* **verbose**: Booleano, padrão True, habilita feedback de progresso. - -*Retorna a instância da classe.* - ---- - -### Função predict(...) - -Prediz os rótulos dos clusters para novas amostras: - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -**Parâmetros de entrada:** - -* **X**: Matriz de atributos de entrada. - -**Retorna:** - -* **Predictions**: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado. - ---- - -### Função update_clusters(...) - -Particiona os clusters utilizando a MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parâmetros de entrada:** - -* **mst_inconsistency_factor**: Valor opcional (float) para sobrescrever o fator de inconsistência da MST. - -**Atualiza:** - -* **_memory_network**: Dicionário de rótulos de clusters para vetores de anticorpos. -* **classes**: Lista de rótulos de clusters. - ---- - -## Métodos Privados - -### Função _init_population_antibodies(...) - -Inicializa a população de anticorpos aleatoriamente. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Parâmetros de entrada:** Nenhum - -**Retorna:** Anticorpos inicializados (`npt.NDArray`). - ---- - -### Função _select_and_clone_population(...) - -Seleciona os melhores anticorpos e gera clones mutados: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Parâmetros de entrada:** - -* **antigen**: Vetor representando o antígeno para o qual as afinidades serão calculadas. -* **population**: Matriz de anticorpos a serem avaliados e clonados. - -**Retorna:** Lista de clones mutados. - ---- - -### Função _clonal_suppression(...) - -Suprime clones redundantes com base em limiares: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parâmetros de entrada:** - -* **antigen**: Vetor representando o antígeno. -* **clones**: Lista de clones candidatos a serem suprimidos. - -**Retorna:** Lista de clones não redundantes e de alta afinidade. - ---- - -### Função _memory_suppression(...) - -Remove anticorpos redundantes da memória: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parâmetros de entrada:** - -* **pool_memory**: Lista de anticorpos atualmente na memória. - -**Retorna:** Memória filtrada (`list`). - ---- - -### Função _diversity_introduction(...) - -Introduce novos anticorpos aleatórios: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Parâmetros de entrada:** Nenhum - -**Retorna:** Conjunto de novos anticorpos (`npt.NDArray`). - ---- - -### Função _affinity(...) - -Calcula o estímulo entre dois vetores: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros de entrada:** - -* **u**: Vetor representando o primeiro ponto. -* **v**: Vetor representando o segundo ponto. - -**Retorna:** Valor de afinidade (`float`) no intervalo [0,1]. - ---- - -### Função _calculate_affinities(...) - -Calcula a matriz de afinidades entre um vetor de referência e vetores-alvo: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Parâmetros de entrada:** - -* **u**: Vetor de referência (`npt.NDArray`) de formato `(n_features,)`. -* **v**: Vetores-alvo (`npt.NDArray`) de formato `(n_samples, n_features)`. - -**Retorna:** Vetor de afinidades (`npt.NDArray`) com formato `(n_samples,)`. - ---- - -### Função _clone_and_mutate(...) - -Gera clones mutados: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parâmetros de entrada:** - -* **antibody**: Vetor de anticorpo original a ser clonado e mutado. -* **n_clone**: Número de clones a serem gerados. - -**Retorna:** Matriz de clones mutados (`npt.NDArray`) de formato `(n_clone, len(antibody))`. - ---- - -### Função _build_mst(...) - -Constrói a MST e armazena estatísticas: - -```python -def _build_mst(self): -``` - -**Parâmetros de entrada:** Nenhum - -**Exceções:** ValueError se a população de anticorpos estiver vazia. - -**Atualiza variáveis internas:** - -* **_mst_structure**: Estrutura de adjacência da MST. -* **_mst_mean_distance**: Distância média das arestas. -* **_mst_std_distance**: Desvio padrão das distâncias das arestas da MST. - ---- - -## Referências - -### 1 -> -> 1. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> Disponível em: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -### 2 -> -> 2. SciPy Documentation. *Minimum Spanning Tree*. -> Disponível em: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/README.mdx deleted file mode 100644 index cfa989ea5..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/README.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 3 -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Teoria da Rede Imunológica - - AiNet - - Sistemas Imunológicos Artificiais - - Agrupamento - - Otimização - - Classificação - - Aprendizado de Máquina - - Algoritmos Imunológicos ---- - -import DocCardList from '@theme/DocCardList'; - -# Teoria da Rede Imunológica - -Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, -na qual células e moléculas são capazes de se reconhecer mutuamente. [1](#1) - ---- - -A Rede Imunológica Artificial pode ser aplicada em diferentes contextos, tais como: -- **Agrupamento (Clustering)** -- **Otimização** -- **Classificação** - -## Classes: - - - -## References - ---- - -### 1 -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection.md new file mode 100644 index 000000000..d4e003b07 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection.md @@ -0,0 +1,50 @@ +--- +id: docs-nsa +keywords: + - seleção negativa + - nsa + - artificial immune systems + - detecção de anomalias + - classificação + - algoritmos bioinspirados + - computação natural +--- + +# Seleção Negativa + +Os algoritmos de **seleção negativa** inspiram-se no processo em que o sistema imunológico faz a maturação das células-T +conhecidas também por linfócitos-T, no qual as tornam aptas na detecção dos não-próprios. Assim, o Algoritmo de +seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional[^1]. + +--- + +A Seleção Negativa pode ser aplicada em diferentes contextos, tais como: +- **Detecção de anomalias** +- **Classificação** + +## Implementações do pacote: + +### Algoritmo seleção negativa binária ([BNSA](../api/nsa/bnsa.md)) + +O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por +Forrest et al. (1994)[^2], originalmente desenvolvida para segurança computacional. + +### Algoritmo seleção negativa de real valor ([RNSA](../api/nsa/rnsa.md)) + +Este algoritmo possui duas versões diferentes: uma baseada na versão canônica[^1] e outra com detectores +de raio variável.[^3] Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para +previsão de dados presentes na região não-self de todos os detectores e classes. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. + +[^3] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md deleted file mode 100644 index 9f619b1e0..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: bnsa -sidebar_label: BNSA - Algoritmo de Seleção Negativa Binária -sidebar_position: 2 -pagination_next: null -last_update: - date: 2025/05/17 - author: João Paulo -keywords: - - Binário - - classificação - - anomalias - - not self - - affinity threshold - - Algoritmo de Seleção Negativa - - Sistema Imunológico Artificial (AIS) - - Próprio e não-próprio - - Imune - - Computação Natural ---- - -# BNSA (Algoritmo de Seleção Negativa Binária) - -:::info - -**``BNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. - -::: - -## Construtor RNSA - -A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . - -```python -class BNSA( - self, - N: int = 100, - aff_thresh: float = 0.1, - max_discards: int = 1000, - seed: int = None, - no_label_sample_selection: Literal["max_average_difference", "max_nearest_difference"] = "max_average_difference" -) -``` - -**Attributes:** - -* *N* (``int``): Quantidade de detectores. Defaults to ``100``. -* *aff_thresh* (``float``): A variável ('affinity threshold') representa a porcentagem de não similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de não similaridade. - - :::note - Definir uma porcentagem de diferença muito alta pode resultar na incapacidade de gerar detectores para não-próprio. - ::: - -* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um -possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. -* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* no_label_sample_selection (``str``): Método para a seleção de rótulos para amostras designadas como não pertencentes por todos os detectores não pertencentes. **Tipos de métodos disponíveis:** - * (``max_average_difference``): Seleciona a classe com a maior diferença média entre os detectores. - * (``max_nearest_difference``): Seleciona a classe com a maior diferença entre o detector mais próximo e mais distante da amostra. - -**Outras variáveis iniciadas:** - -* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. - -* *classes* (``npt.NDArray``): lista de classes de saída. - ---- - -## Função fit(...) - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -## Função predict(...) - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**O parâmetro de entrada:** - -* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. -* ``None``: se não houver detectores. - ---- - -## Função score(...) - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - ---- - -## Função __slice_index_list_by_class(...) - -A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/README.md deleted file mode 100644 index 610f032ba..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/README.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Seleção Negativa - -A **seleção negativa** é o processo em que o sistema imunológico faz a maturação das células-T conhecidas também por linfócitos-T, no qual tornam-as aptas na detecção dos não-próprios. Assim, o Algoritmo de seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional. [1](#1) - ---- - -## classes - -> 1. **[Binary version:](BNSA.md)** -> ->> O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por [Forrest et al. (1994)](#2), originalmente desenvolvida para segurança computacional. ->>> **Exemplo:** ->>> ->>> + [Base de dados Mushrooms](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/mushrooms_dataBase_example_pt-br.ipynb) - -> 2. **[Real-Valued version:](RNSA.md)** -> ->>Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [[1]](#1) e outra com detectores de raio variável [[3]](#3). Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de dados presentes na região não-self de todos os detectores e classes. ->>> **Exemplos:** ->>> ->>> + [Base de dados Iris](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/iris_dataBase_example_pt-br.ipynb) ->>> + [Base de dados Geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/geyser_dataBase_example_pt-br.ipynb) - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). - -### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). - -### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md deleted file mode 100644 index 6f1c88e07..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -id: rnsa -sidebar_label: RNSA - Algoritmo de Seleção Negativa de Valor Real -sidebar_position: 1 -last_update: - date: 2025/05/17 - author: João Paulo -keywords: - - Valor Real - - classificação - - anomalias - - not self - - V-detector - - Algoritmo de Seleção Negativa - - Sistema Imunológico Artificial (AIS) - - Próprio e não-próprio - - Imune - - Computação Natural ---- - -# RNSA (Algoritmo de Seleção Negativa de Valor Real) - -:::info - -**``RNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. - -::: - -## Construtor RNSA - -A classe ``RNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . - -```python -class RNSA( - self, - N: int = 100, - r: float = 0.05, - r_s: float = 0.0001, - k: int = 1, - metric: Literal['manhattan', 'minkowski', 'euclidean'] = 'euclidean', - max_discards: int = 1000, - seed: int = None, - algorithm: Literal['default-NSA', 'V-detector'] ='default-NSA', - **kwargs: Dict[str, Union[bool, str, float]] -) -``` - -**Attributes:** - -* *N* (``int``): Quantidade de detectores. Defaults to ``100``. -* *r* (``float``): Raio do detector. Defaults to ``0.05``. - - :::note - É importante considerar que definir um raio muito baixo para o detector pode reduzir significativamente a taxa de detecção. Por outro lado, um raio muito grande pode inviabilizar a incorporação do detector no espaço de busca, o que também pode comprometer o desempenho da detecção. É fundamental encontrar um equilíbrio entre o tamanho do raio e a eficiência da detecção para obter os melhores resultados possíveis. - ::: - -* *k* (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. Defaults to ``1``. -* *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: - - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$. - - Defaults to ``'euclidean'``. - -* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um -possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. - -* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* *algorithm* (``str``), Definir a versão do algoritmo: - - * ``'default-NSA'``: Algoritmo padrão com raio fixo. - * ``'V-detector'``: Este algoritmo é baseado no artigo "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", de autoria de Ji, Z., Dasgupta, D. (2004), e utiliza um raio variável para a detecção de anomalias em espaços de características. - - Defaults to ``'default-NSA'``. - -* *r_s* (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``. - -* ``**kwargs``: - * *non_self_label* (``str``): Esta variável armazena o rótulo que será atribuído quando os dados possuírem - apenas uma classe de saída, e a amostra for classificada como não pertencente a essa classe. Defaults to ``'non-self'``. - - * *cell_bounds* (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço do plano compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, e esta variável é usada exclusivamente no algoritmo ``V-detector``. - * p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski. O padrão é ``2``, o que significa distância euclidiana normalizada. Diferentes valores de p levam a diferentes variantes da distância de Minkowski [saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Outras variáveis iniciadas:** - -* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. - -* *classes* (``npt.NDArray``): lista de classes de saída. - ---- - -### Função fit(...) - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -### Função predict(...) - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**O parâmetro de entrada:** - -* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. -* ``None``: se não houver detectores. - ---- - -### Função score(...) - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - ---- - -### Função __checks_valid_detector(...) - -A função ``def __checks_valid_detector(...)`` verifica se o detector possui raio ``r`` válido para o não-próprio da classe: - -```python -def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: -``` - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. - -* ``vector_x``: Detector candidato gerado aleatoriamente. - -* ``samplesIndexClass``: Array com os indexes de uma classe. - -**Retorna:** Verdadeiro (``True``) para os detectores que não possuam amostras em seu interior ou falso (``False``) se possuir. - ---- - -### Função __compare_KnearestNeighbors_List(...) - -A função ``def __compare_KnearestNeighbors_List(...)`` compara a distância dos k-vizinhos mais próximo, para isso se a distância da nova amostra for menor, substitui ``k-1`` e ordena em ordem crescente: - -```python -def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: -``` - -**Retorna:** uma lista com as distâncias dos k-vizinhos mais próximo. - ---- - -### Função __compare_sample_to_detectors(...) - -Função para comparar uma amostra com os detectores, verificando se a amostra é própria. - -Nesta função, quando possui ambiguidade de classes, retorna a classe que possuir a média de distância maior entre os detectores. - -**Os parâmetros de entrada são:** - -* line: vetor com N-características - -**Retorna:** A classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe. - ---- - -### Função __detector_is_valid_to_Vdetector(...) - -Verifique se a distância entre o detector e as amostras, descontando o raio das amostras, é maior do que o raio mínimo. - -```python -def __detector_is_valid_to_Vdetector(self, distance, vector_x): -``` - -**Os parâmetros de entrada são:** - -* distance (``float``): distância mínima calculada entre todas as amostras. -* vector_x (``numpy.ndarray``): vetor x candidato do detector gerado aleatoriamente, com valores entre 0 e 1. - -**Retorna:** - -* ``False``: caso o raio calculado seja menor do que a distância mínima ou ultrapasse a borda do espaço, caso essa opção esteja habilitada. -* ``True`` e a distância menos o raio das amostras, caso o raio seja válido. - ---- - -### Função __distance(...) - -A função ``def __distance(...)`` calcula a distância entre dois pontos utilizando a técnica definida em ``metric``, no qual são: ``'euclidiana', 'minkowski', ou 'manhattan'`` - -```python -def __distance(self, u: npt.NDArray, v: npt.NDArray): -``` - -Os parâmetros de entrada são NDArrays: ``u`` e ``v``, com as coordenadas para os pontos. - -Retorna a distancia (``double``) entre os dois pontos. - ---- - -### Função __slice_index_list_by_class(...) - -A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md new file mode 100644 index 000000000..e86d07419 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md @@ -0,0 +1,84 @@ +--- +id: api +sidebar_position: 5 +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering +--- + +# AISP - API + +Bem-vindo à API do **AISP** (Artificial Immune System Package). Esta documentação demonstra a API pública do pacote. + +## Módulos Principais ([`aisp.base`](./base/README.md)) + +Abstrações fundamentais e classes base que definem as interfaces principais do pacote. + +| Classe | Descrição | +|-----------------------------------------------|---------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base/base-clusterer.md) | Classe base abstrata para algoritmos de agrupamento. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +### Componentes do Domínio Imunológico ([`aisp.base.immune`](./base/immune/README.md)) + +Estruturas principais e utilitários de suporte para implementações imunológicas. + +| Módulo | Descrição | +|-----------------------------------------------|---------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./base/immune/mutation.md) | Funções para gerar clones mutados e simular a expansão clonal. | +| [`populations`](./base/immune/populations.md) | Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. | + +--- + +## Algoritmos + +### Algoritmos de Seleção Negativa ([`aisp.nsa`](./nsa/README.md)) + +Algoritmos de aprendizagem supervisionada baseados na seleção negativa, o processo do sistema imunológico de distinguir o próprio do não-próprio. + +| Classe | Descrição | +|-------------------------|--------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | Um algoritmo de aprendizagem supervisionada para classificação que usa detectores de valores reais. | +| [`BNSA`](./nsa/bnsa.md) | Um algoritmo de aprendizagem supervisionada para classificação que usa detectores binários. | + +### Algoritmos de Seleção Clonal ([`aisp.csa`](./csa/README.md)) + +Algoritmos inspirados no processo de proliferação de anticorpos para detectar um antígeno. + +| Classe | Descrição | +|-------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | Um algoritmo de aprendizagem supervisionada para tarefas de classificação baseado no princípio da seleção clonal. | +| [`Clonalg`](./csa/clonalg.md) | Implementação do algoritmo de seleção clonal para otimização, adaptado para problemas de minimização e maximização em domínios binários, contínuos e de permutação. | + +### Algoritmos de Redes Imunológicas ([`aisp.ina`](./ina/README.md)) + +Algoritmos baseados na Teoria de Redes Imunológicas proposta por Jerne. + +| Classe | Descrição | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | Um algoritmo de aprendizagem não supervisionada para agrupamento, baseado na teoria das redes imunológicas. | + +## Utilitários ([`aisp.utils`](./utils/README.md)) + +Funções utilitárias e auxiliares para desenvolvimento. + +| Módulo | Descrição | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Funções utilitárias para exibição de informações dos algoritmos. | +| [`distance`](./utils/distance.md) | Funções utilitárias para cálculo de distância entre arrays (com Numba). | +| [`metrics`](./utils/metrics.md) | Funções utilitárias para medição de precisão e desempenho. | +| [`multiclass`](./utils/multiclass.md) | Funções utilitárias para lidar com classes multicategorias. | +| [`sanitizers`](./utils/sanitizers.md) | Funções utilitárias para validação e tratamento de parâmetros. | +| [`types`](./utils/types.md) | Define aliases de tipos usados no projeto para melhorar a legibilidade. | +| [`validation`](./utils/validation.md) | Contém funções responsáveis pela validação de tipos de dados. | + +## Exceções ([`aisp.exceptions`](./exceptions.md)) + +Avisos e erros personalizados. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/README.md new file mode 100644 index 000000000..99b354e61 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - imune + - abstrato +--- + +# aisp.base + +Classe base e utilitários centrais + +> **Módulos:** `aisp.base` + +## Visão geral + +Este modulo fornece as classes e utilidades fundamentais para todos os algoritmos de sistemas imunológicos artificiais +implementados no AISP. + +## Classes + +| Class | Descrição | +|------------------------------------------|--------------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base-clusterer.md) | Classe base abstrata para algoritmos de clustering. | +| [`BaseOptimizer`](./base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +## Submódulos + +| Módulo | Descrição | +|--------------------------------|----------------------------------------------------------| +| [`immune`](./immune/README.md) | Módulo de suporte para sistemas imunológicos artificias. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-classifier.md new file mode 100644 index 000000000..50b174811 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-classifier.md @@ -0,0 +1,133 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classificação + - classificação interface + - pontuação de acurácia + - fit + - predict +tags: + - classificador + - classificação +--- + +# BaseClassifier + +Classe base abstrata para algoritmos de classificação. + +> **Módulo:** `aisp.base` +> **Importação:** `from aisp.base import BaseClassifier` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de classificação. +Ela define a implementação dos metodos `fit` e `predict` em todas as classes derivadas, e fornece uma implementação +do método `score`. + +Caso de uso: + +- Classe base abstrata para estender classes de algoritmos de classificação. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-----------|-------------------------|:------:|----------------------------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Rótulos das classes identificado de `y` durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Treine o modelo usando os dados de entrada X e seus rótulos correspondentes y. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada X. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|--------------------------------------------------| +| `npt.NDArray` | Array com as previsões para cada amostra de `X`. | + +--- + +## Métodos públicos + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +A função calcula o desempenho do modelo nas previsões utilizando a métrica de acurácia. + +Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. +Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|--------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos verdadeiros com dimensão (n_amostras,). | + +**Returns** + +| Tipo | Descrição | +|---------|-----------------------| +| `float` | A precisão do modelo. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-clusterer.md new file mode 100644 index 000000000..21944743d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-clusterer.md @@ -0,0 +1,123 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict + - agrupamento +tags: + - clusterer + - agrupamento +--- + +# BaseClusterer + +Classe base abstrata para algoritmos de clustering. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseClusterer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de clusterização. +Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do +método `fit_predict`. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de clusterização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|-------------------------|:------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Rótulos dos clusters encontrados durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Treinamento do modelo utilizando os dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-------------------------------------------------------------| +| `npt.NDArray` | Os labels do cluster previsto para cada amostra de entrada. | + +--- + +## Métodos públicos + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Ajusta o modelo e com os dados de X e retorna os labels para cada amostra de X. +Este é um método que combina `fit` e `predict` em uma única chamada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-------------------------------------------------------------| +| `npt.NDArray` | Os labels do cluster previsto para cada amostra de entrada. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-optimizer.md new file mode 100644 index 000000000..56281f78a --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/base-optimizer.md @@ -0,0 +1,164 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - otimizar + - otimização + - otimizar interface + - objective function + - minimization + - maximization +tags: + - otimizar + - otimização +--- + +# BaseOptimizer + +Classe base abstrata para algoritmos de otimização. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseOptimizer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de otimização. +Ela mantém o histórico de custos, soluções avaliadas, e a melhor solução encontrada durante a otimização. As classes +derivadas devem implementar os métodos ``optimize`` e ``affinity_function``. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de otimização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-------------------|:-------:|---------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | Histórico dos melhores custos encontrados em cada iteração. | +| `solution_history` | `List` | `[]` | Histórico da melhor solução encontrada em cada iteração. | +| `best_solution` | `Any` | `None` | A melhor solução global encontrada. | +| `best_cost` | `Optional[float]` | `None` | Custo da melhor solução global encontrada. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo minimiza ou maximiza a função de custo. | + +--- + +## Métodos abstratos + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Executa o processo de otimização. +Este método abstrato é implementado é responsabilidade das classes filhas, definindo a estratégia de otimização. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|----------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem atualização da melhor solução. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Avalia a afinidade (qualidade) de uma solução candidata. + +Este método deve ser implementado conforme o problema de otimização específico, definindo como a solução sera medida. +O valor retornado deve representar a qualidade da solução avaliada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|-------|:------:|--------------------------------------| +| `solution` | `Any` | - | Solução candidata que será avaliada. | + +**Returns** + +| Tipo | Descrição | +|---------|------------------------------------------------| +| `float` | Valor de custo associada a solução encontrada. | + +--- + +## Métodos públicos + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Gera um relatorio resumindo e formatado do processo de otimização. +O relatorio incluir a melhor solução, seu custo, e a evolução dos valores a cada iteração. + +**Returns** + +| Tipo | Descrição | +|-------|-------------------------------------------------------| +| `str` | Uma string formatada contendo o resumo da otimização. | + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Registra dinamicamente uma função na instância do otimizador. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|----------------------|:------:|----------------------------------------------------| +| `alias` | `str` | - | Nome usado para acessar a função como um atributo. | +| `function` | `Callable[..., Any]` | - | Função que será registrada. | + +**Exceções** + +| Exceção | Descrição | +|------------------|----------------------------------------------------------------------------------| +| `TypeError` | Se a `function` fornecida não for uma função valida. | +| `AttributeError` | Se o `alias` for protegido e não puder ser modificado, ou não existir na classe. | + + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reseta o estado interno do objeto, limpando histórico e restaurando valores iniciais. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/README.md new file mode 100644 index 000000000..82f011022 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - célula + - mutações + - populações +--- + +# aisp.base.immune + +Módulo de suporte para sistemas imunológicos artificias. + +> **Módulo:** `aisp.base.immune` + +## Submódulos + +| Módulos | Descrição | +|-----------------------------------|------------------------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./mutation.md) | Funções para gerar clones hipermutados similar a expansão clonal. | +| [`populations`](./populations.md) | Fornece funções utilitárias para gerar populações de anticorpos utilizadas em algoritmos imuno-inspirados. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/README.md new file mode 100644 index 000000000..f57ae065d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/README.md @@ -0,0 +1,32 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representação de células do sistema imunológico. + +> **Módulos:** `aisp.base.immune.cell` + +## Visão geral + +Este módulo define as representações de células dos sistemas imunológicos artificiais e as implementa como dataclass. + +## Classes + +| Class | Descrição | +|-----------------------------|----------------------------------------------------| +| [`Cell`](./c-cell.md) | Representa uma célula imune básica. | +| [`BCell`](./b-cell.md) | Representa uma célula-B de memória. | +| [`Antibody`](./antibody.md) | Representa um anticorpo. | +| [`Detector`](./detector.md) | Representa um detector não-próprio da classe rnsa. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/antibody.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/antibody.md new file mode 100644 index 000000000..79f595c84 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - anticorpo + - afinidade + - célula + - imune + - dataclass +--- + +# Antibody + +Representa um anticorpo. + +:::tip[Herança] + +Esta classe herda de [Cell](./c-cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Antibody` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|----------------------------------------| +| `vector` | `npt.NDArray` | - | Vetor com as características anticorpo | +| `affinity` | `float` | - | Valor da afinidade do anticorpo | + +--- + +## Métodos + +* `__lt__(other)`: Compara a célula atual com outra célula `Antibody` com base na afinidade. +* `__eq__(other)`: Verifica se o anticorpo possui a mesma afinidade do outro. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/b-cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/b-cell.md new file mode 100644 index 000000000..b16f40375 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/b-cell.md @@ -0,0 +1,63 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - célula-b + - memória imune + - dataclass + - mutação clonal + - expansão clonal +--- + +# BCell + +Representa uma célula-B de memória. + +:::tip[Herança] + +Esta classe herda de [Cell](./c-cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import BCell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos Públicos + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Gera **N** clones da célula atual e aplica hipermutação aos clones. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|------------------------------------------------------|:-----------------------:|-----------------------------------------------------------------| +| `n` | `int` | - | Numero de clones que serão gerados a partir da célula original. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Especifica o tipo de características da célula. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Matriz (n_features, 2) com o min e o max de cada dimensão. | + +**Returns** + +| Tipo | Descrição | +|---------------|----------------------------------------------------------| +| `npt.NDArray` | Uma matriz contendo N clones mutados da célula original. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/c-cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/c-cell.md new file mode 100644 index 000000000..0d7955c64 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/c-cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Representa uma célula imune básica. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Cell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base nos seus vetores. +* `__array__()`: Interface de array Numpy, permite que a instância seja tratada como um `np.ndarray` +* `__getitem__(item)`: Obtém um elemento do vetor com base no index. + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/detector.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/detector.md new file mode 100644 index 000000000..71fcfdc64 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - célula + - imune + - raio + - não-próprio + - nsa + - dataclass +--- + +# Detector + +Representa um detector não-próprio da classe rnsa. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Detector` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------------------|:------:|--------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Vetor com as características do detector. | +| `radius` | `float, optional` | - | Raio do detector, usado no algoritmo V-detector. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/mutation.md new file mode 100644 index 000000000..38fc658b5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/mutation.md @@ -0,0 +1,146 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutações + - expansão clonal + - sistema imune + - funções python com numba + - vetor de mutações +--- + +# mutation + +As funções utilizam decoradores do Numba para compilação Just-In-Time(JIT). + +Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o +processo +de expansão clonal dos sistemas imunológicos artificiais. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import mutation` + +## Funções + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor contínuo. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados que serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor binário. + +Esta função cria `n` clones do vetor binário de entrada e aplica mutações aos bits, simulando a expansão +clonal em sistemas imunes artificiais com representações discretas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor binário original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|-------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de uma célula representada pelo intervalo personalizados por dimensão.. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) com valor mínimo e máximo por dimensão. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_continuous + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +``` + +Gera um conjunto de clones com mutações por permutação. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-------------------------|:------:|------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | Vetor de permutação original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Probabilidade de mutação de uma característica. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/populations.md new file mode 100644 index 000000000..5f4a49ee6 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/base/immune/populations.md @@ -0,0 +1,57 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binário + - classificação + - limiar de afinidade + - real-valor + - célula-b de memória + - expansão clonal + - população +--- + +# populations + +Fornece funções utilitárias para **gerar populações** de anticorpos utilizadas em algoritmos imuno-inspirados. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import populations` + +## Funções + +### generate_random_antibodies + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +``` + +Gera uma população aleatória de anticorpos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|---------------------------------------------------------|:-----------------------:|--------------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Número de anticorpos (amostras) que serão gerados. | +| `n_features` | `int` | - | Número de características (dimensões) para cada anticorpo. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. | + + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------------------------------------------------| +| `npt.NDArray` | Array de dimensão (n_samples, n_features) contendo os anticorpos gerados. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-----------------------------------------------------------| +| `ValueError` | Se o número de características for menor ou igual a zero. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/README.md new file mode 100644 index 000000000..39f9597c9 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - sistema imunológico + - seleção clonal + - clonalg + - airsv2 + - proliferação de anticorpos + - mutações + - algoritmos de seleção clonal + - sistemas imunológicos artificiais + - classificação + - otimização +--- + +# aisp.csa + +Módulo com algoritmos de seleção clonal (ASC). + +> **Módulo:** `aisp.csa` + +## Visão geral + +Os **ASCs** são inspirados no processo de proliferação de anticorpos ao detectar o antígeno, no qual os clones gerados +passam por mutações na tentativa de melhorar o reconhecimento dos patógenos. + +## Classes + +| Class | Descrição | +|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | Um algoritmos supervisionado para tarefas de classificação. | +| [`Clonalg`](./clonalg.md) | Esta implementação do ASC para otimização, foi adaptado tanto para minimização quanto maximização de custos em problemas binários, contínuos e de permutação. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md new file mode 100644 index 000000000..c0cd9b693 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md @@ -0,0 +1,196 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classificação + - sistema imunológico artificial de reconhecimento + - células de memória + - k-nn + - aprendizado supervisionado + - AIRS2 + - seleção clonal +tags: + - classificação + - supervisionado + - seleção clonal +--- + +# AIRS + +Sistema Imunológico Artificial de Reconhecimento (AIRS) + +:::tip[Herança] + +Esta classe herda de [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Módulo:** `aisp.csa` +> **Importação:** `from aisp.csa import AIRS` + +--- + +## Visão geral + +O _Artificial Immune Recognition System_ (AIRS) é um algoritmo de classificação inspirado no processo de seleção +clonal. Esta implementação é baseada na versão simplificada (AIRS2) descrita em [^1]. O algoritmo foi adaptado +para suportar amostras com características com valores reais (contínuos) e binários (discretos). + +:::note + +Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo +adaptações para lidar com conjuntos de dados contínuos e binários. + +Baseado no Algorithm 16.5 de Brabazon et al. [^1] + +Trabalhos relacionados e notáveis: [^2]. + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Gerando dados para o treinamento +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# Instancia do AIRS +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` + +Output: + +```bash +[0 1] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-----------------------------|---------|:-------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Quantidade total de recursos disponíveis. | +| `rate_clonal` | `int` | `10` | Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * rate_hypermutation) para definir o número de clones. | +| `rate_mc_init` | `float` | `0.2` | Porcentagem de amostras usadas para inicializar a população de células de memória. | +| `rate_hypermutation` | `float` | `0.75` | Taxa de clones mutados derivada de rate_clonal como um fator escalar. | +| `affinity_threshold_scalar` | `float` | `0.75` | Limiar de afinidade normalizado. | +| `k` | `int` | `3` | Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. | +| `max_iters` | `int` | `100` | Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. | +| `resource_amplified` | `float` | `1.0` | Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. | +| `metric` | `str` | `"euclidean"` | Métrica de distância usada para calcular a afinidade entre células e amostras. | +| `seed` | `int` | `None` | Seed para geração aleatória. | +| `p` | `float` | `2` | Este parâmetro é usado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------------|-------------------------------------------|:------:|--------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Armazena as células de memória por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` + +Treina o modelo com os dados de entrada utilizando o algoritmo AIRS2. + +A função `fit(...)`, realiza o treinamento de acordo com X e y, usando o método AIRS. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-------------|---------------------------------------------------------------| +| `TypeError` | Se X ou y não forem arrays ou tiverem tamanhos incompatíveis. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prevê os rótulos dos dados de testes com base nas células de memórias criadas durante o treinamento. + +Este método utiliza as células de memórias para classificar os dados de entrada usando a abordagem dos k-vizinhos mais +próximos (K-NN). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|----------------------------------------------------------------------| +| `npt.NDArray` | Array no formato `n_samples` contendo as classes previstas para `X`. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for um ndarray ou list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de características em X não corresponder ao esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir o conjunto de células de memoria. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunologico-artificial-de-reconhecimento) + +--- + +## Referências + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md new file mode 100644 index 000000000..32114aac5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md @@ -0,0 +1,185 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - otimização + - seleção clonal + - clonalg + - população de anticorpos + - função de custo +tags: + - otimização + - seleção clonal + - minimização + - maximização + - binário + - contínuos + - permutação + - ranged +--- + +# Clonalg + +Algoritmo de Seleção Clonal (CLONALG). + +:::tip[Herança] + +Esta classe herda de [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Módulo:** `aisp.csa` +> **Importação:** `from aisp.csa import Clonalg` + +--- + +## Visão geral + +O _Clonal Selection Algorithm (CSA)_ é um algoritmo de otimização inspirado no processo biológico de seleção e expansão +clonal dos anticorpos do sistema imunológico [^1]. Esta implementação do clonalg foi adaptada para minimização e +maximização da função de custo em problemas binários, contínuos, com intervalo de valor e de permutação. + +:::note + +Esta implementação do CLONALG contem modificações para o pacote AISP, com intuito da aplicação geral em diferentes +tipos de problemas, o que pode resultar em comportamentos diferentes de implementações focada em um problema específico. +A adaptação visa generalizar o uso do CLONALG para tarefas de minimização e maximização, além de oferecer suporte +a problemas binários, contínuos, com intervalo de valor e de permutação + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.csa import Clonalg + +# Limites do espaço de busca +bounds = {'low': -5.12, 'high': 5.12} + + +# Função de custo +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x ** 2 - 10 * np.cos(2 * np.pi * x)) + + +# Instância do CLONALG +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` + +**Output:** + +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-------------------------|------------------------------------------------------|:-------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimensão do problema que será otimizado. | +| `N` | `int` | `50` | Número de células de memória (anticorpos) na população. | +| `rate_clonal` | `int` | `10` | Número máximo de clones possíveis de uma célula. Esse valor é multiplicado pela afinidade da célula para definir o número de clones. | +| `rate_hypermutation` | `float` | `1.0` | Taxa de hipermutação que controla a intensidade das mutações durante a expansão clonal. valores maiores reduzem a intensidade, enquanto menores aumentam. | +| `n_diversity_injection` | `int` | `5` | Número de novas células de mémoria aleatórias inseridas para manter a diversidade. | +| `selection_size` | `int` | `5` | Número dos melhores anticorpos selecionados para a clonagem. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Função objetiva usada para avaliar as soluções candidatas durante a otimização. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Tipo de representação das soluções: binária, contínua, com intervalo de valor e para permutação. | +| `bounds` | `Optional[Dict]` | `None` | Define os limites no espaço de busca quando ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo realiza minimização ou maximização da função de custo. | +| `seed` | `int` | `None` | Seed para geração aleatória. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------|----------------------------|:------:|--------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | População de anticorpos. | + +--- + +## Métodos Públicos + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Realiza o processo de otimização e retorna a população de anticorpos resultante. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|-------------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações na busca da melhor solução do problema usando o CLONALG. | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem melhoria na melhor solução global encontrada. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso na busca do melhor anticorpo deve ser exibido. | + +**Returns** + +| Tipo | Descrição | +|------------------|-----------------------------------------------------------| +| `List[Antibody]` | População de anticorpos após a expansão e seleção clonal. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------|----------------------------------------------------------------------| +| `NotImplementedError` | Se a função de afinidade não for fornecida para avaliar as soluções. | + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Avalia a afinidade de uma solução candidata. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|--------------------------------------| +| `solution` | `npt.NDArray` | - | Solução candidata que será avaliada. | + +**Returns** + +| Tipo | Descrição | +|--------------|---------------------------------------------------| +| `np.float64` | Valor de afinidade da solução candidata avaliada. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------|---------------------------------------------------| +| `NotImplementedError` | Se a função de afinidade não tiver sido definida. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-selecao-clonal) + +--- + +## Referências + +[^1]: BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired + Programming Recipes., 2011. Available at: + https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/exceptions.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/exceptions.md new file mode 100644 index 000000000..500c4e6a5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/exceptions.md @@ -0,0 +1,91 @@ +--- +id: exceptions +sidebar_label: aisp.exceptions +keywords: + - exceptions + - Exceções + - warnings +--- + +# aisp.exceptions + +Avisos e erros personalizados. + +> **Módulo:** `aisp.exceptions` +> **Importação:** `from aisp import exceptions` + +## Classes de exceção + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exceção lançada quando o número máximo de descartes do detector é atingido. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|---------------|-----------------|:------:|------------------------------------------| +| `object_name` | `str` | - | O nome da classe que lança a exceção. | +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exceção lançada quando o número de características (dimensões) de entrada não corresponde ao esperado. +Essa exceção é acionada durante a predição se a quantidade de características estiver incorreta. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-----------------|:------:|---------------------------------------------| +| `expected` | `int` | - | O número esperado de características. | +| `received` | `int` | - | O número real de características recebidas. | +| `variable_name` | `Optional[str]` | `None` | O nome da variável que causou o error. | + +--- + +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exceção lançada quando o tipo de dados do vetor de entrada não é suportado. +Essa exceção é lançada quando o tipo de dado do vetor não corresponde a nenhum dos suportados. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|-----------------|:------:|------------------------------------------| +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | + +--- + +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exceção lançada quando o método é chamado antes que o modelo ter sido treinado. +Essa exceção ocorre quando a instância do modelo é utilizada sem que ele tenha sido previamente treinado +por meio do método `fit`. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|---------------|-----------------|:------:|------------------------------------------| +| `object_name` | `str` | - | O nome da classe que lança a exceção. | +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/README.md new file mode 100644 index 000000000..2b737381b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/README.md @@ -0,0 +1,30 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - sistema imunológico + - seleção clonal + - rede imunológica + - ainet + - opt-ainet + - mutações + - sistemas imunológicos artificiais + - clusterização + - otimização +--- + +# aisp.ina + +Módulo com Algoritmos de Rede Imunológica (ARI). + +> **Módulo:** `aisp.ina` + +## Visão geral + +Este módulo implementa algoritmos inspirados na teoria das redes imunológicas proposta por Jerne. + +## Classes + +| Class | Descrição | +|------------------------|-------------------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | Um algoritmo não supervisionado para agrupamentos de dados, baseado na teoria das redes imunológicas. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md new file mode 100644 index 000000000..cd89715ec --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md @@ -0,0 +1,222 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - rede imunológica + - agrupamento + - compressão de dados + - aprendizado não supervisionado + - Minimum Spanning Tree +tags: + - agrupamento + - não supervisionado + - rede imunológica +--- + +# AiNet + +Rede Imunológica Artificial (AiNet) para agrupamento e compressão. + +:::tip[Herança] + +Esta classe herda de [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Módulo:** `aisp.ina` +> **Importação:** `from aisp.ina import AiNet` + +--- + +## Visão geral + +Esta classe implementa o algoritmo AiNet é projetado para tarefas de agrupamento +e compressão de dados; O algoritmo é inspirado na teoria da rede imunológica, seleção clonal e maturação por afinidade para +reduzir conjuntos de dados com muitas amostras [^1]. +No agrupamento a classe utiliza a implementação da Scipy da **Árvore geradora mínima** para separa as arestas mais +distantes em grupos de dados [^2]. + +--- + +## Exemplo + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Gerando dados de treinamento +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# Instância do AiNet +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Esperado: rótulo 0 + [0.85, 0.65], # Esperado: rótulo 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +[0 1] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|----------------------------|----------------------------------------------|:-------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Número de células de memória (anticorpos) para iniciar a população. | +| `n_clone` | `int` | `10` | Número de clones gerados para cada célula de memória selecionada. | +| `top_clonal_memory_size` | `int` | `5` | Número de anticorpos com maior afinidade que selecionados para a clonagem e mutação. | +| `n_diversity_injection` | `int` | `5` | Número de novas células de memória aleatórias que serão inseridas para manter a diversidade. | +| `affinity_threshold` | `float` | `0.5` | Limiar de afinidade (similaridade) parta determinar a supressão das células. | +| `suppression_threshold` | `float` | `0.5` | Limiar de supressão das células de memórias semelhantes. | +| `mst_inconsistency_factor` | `float` | `2.0` | Fator usado para determinar quais arestas da Árvore Geradora Mínima (MST) são consideradas inconsistentes. | +| `max_iterations` | `int` | `10` | Número máximo de iterações de treinamento. | +| `k` | `int` | `3` | Número de vizinhos mais próximos usados para predição de rótulos. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Métrica de distância utilizada para calcular a similaridade entre as células de memória. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `use_mst_clustering` | `bool` | `True` | Quando `True`, realiza o agrupamento utilizando a MST. Se `False`, o agrupamento não é executado e o método predict lança uma exceção ModelNotFittedError. | +| `p` | `float` | `2.0` | Parâmetro `p` utilizado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------------------|-------------------------|:------:|-------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | Rede imunológica que representa os clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | População de anticorpos de memória. | +| `mst` | `dict` | - | Árvore geradora minima com estatísticas (graph, mean_distance, std_distance). | + +--- + +## Métodos Públicos + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Treina o modelo com os dados de entrada utilizando o algoritmo AiNet. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------|----------------------------------------------------------| +| `TypeError` | Se `X` não for um ndarray ou list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | Se o tipo das características em X não forem suportados. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever os rótulos dos clusters para os dados de entrada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------------------| +| `npt.NDArray` | Rótulos previstos para os dados de entrada. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se X contiver valores diferentes de (0 e 1) ou (True e False), quando as características treinadas forem do tipo `'binary-features'` | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de dimensões em X não corresponder ao esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir o conjunto de células de memória. | + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` + +Agrupa os clusters com base no fator de inconsistência da MST. + +Utiliza a Árvore Geradora Mínima (MST) criada a partir da população de anticorpos para redefinir os clusters. +As arestas cujos pesos excedem a média somada ao valor de `mst_inconsistency_factor` multiplicado pelo desvio padrão +dos pesos das arestas são removidas. Cada grafo conectado após essa poda é tratado como um grupo distinto. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------------------|---------|:------:|------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | Sobrescrever o fator de inconsistência da MST. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-------------------------------------------------------------------------------| +| `ValueError` | Se a Árvore Geradora Mínima (MST) ainda não tiver sido criada. | +| `ValueError` | Se a população de anticorpos estiver vazia. | +| `ValueError` | Se as estatísticas da MST (média ou desvio padrão) não estiverem disponíveis. | + +**Updates** + +| Nome | Tipo | Descrição | +|------------------|--------------------------|---------------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dicionário de rótulos de clusters para vetores de anticorpos. | +| `labels` | `list` | Lista de rótulos de clusters. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunologica-artificial) + +--- + +## Referências + +[^1]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/README.md new file mode 100644 index 000000000..cb0335739 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/README.md @@ -0,0 +1,34 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - sistemas imunológicos artificiais + - classificação + - seleção negativa + - características binárias + - detecção de anomalias + - reconhecimento de não-próprio + - reconhecimento de padrões + - multiclasse + - valores reais + - v-detector +--- + +# aisp.nsa + +Módulo com Algoritmo de Seleção Negativa (NSA). + +> **Módulo:** `aisp.nsa` + +## Visão geral + +NSAs simulam o processo de maturação das células T no sistema imunológico, no qual essas células aprendem a distinguir +entre próprio e não-próprio. Apenas as células T capazes de reconhecer elementos não-próprios são preservadas. + +## Classes + +| Class | Descrição | +|---------------------|----------------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | Um algoritmo de aprendizado supervisionado para classificação de dados com valores reais. | +| [`BNSA`](./bnsa.md) | Um algoritmo de aprendizado supervisionado para classificação de dados com valores binárias. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md new file mode 100644 index 000000000..81f2ffed8 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md @@ -0,0 +1,192 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - seleção negativa + - características binárias + - detecção de anomalias + - reconhecimento do não-próprio + - reconhecimento de padrões + - classificação + - multiclasses +tags: + - classificação + - supervisionado + - seleção negativa + - características binárias + - detecção de anomalias +--- + +# BNSA + +Algoritmo de Seleção Negativa Binária (BNSA). + +:::tip[Herança] +Esta classe herda de [BaseClassifier](../base/base-classifier.md) +::: + + +> **Módulo:** `aisp.nsa` +> **Importação:** `from aisp.nsa import BNSA` + +--- + +## Visão geral + +Algoritmo para classificação e detecção de anomalias baseado na distinção entre próprio e não-próprio, inspirado +no algoritmo de seleção negativa. + +:::note + +O _**Binary Negative Selection Algorithm (BNSA)**_ é baseado na proposta original de Forrest et al. (1994) [^1], +desenvolvido para segurança na computação. Nesta adaptação, o algoritmo usa arrays de bits e possuir suporte para +classificação multiclasse. + +::: + +:::warning + +Valores altos de `aff_thresh` podem impedir que gere detectores válidos para a detecção do não-próprio. + +::: + +--- + +## Exemplo + +```python +from aisp.nsa import BNSA + +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ + ...[1, 1, 1, 1, 1], # Sample of Anomaly + ...[0, 1, 0, 1, 0], # self sample + ...] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` + +**Output** + +```bash +['non-self' 'self'] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-----------------------------|-----------------|:--------------------------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Quantidade de detectores. | +| `aff_thresh` | `float` | `0.1` | Representa a porcentagem de similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de similaridade. | +| `max_discards` | `int` | `1000` | Número máximo de descartes de detectores em sequência, com o objetivo de evitar um possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Método utilizado para a escolha de rótulos para amostras classificada como não-próprio por todos os detectores. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------|-----------------------------------------------------|:------:|-------------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | Conjunto de detectores, organizados por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Treinamento de acordo com X e y, utilizando o algoritmo de seleção negativa. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X ou y não forem ndarrays ou tiverem tamanhos incompatíveis. | +| `ValueError` | Se X possuir valores diferentes de (0 e 1) ou (True e False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | Se o número máximo de descartes for atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever as classes com base nos detectores gerados após o treinamento. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-----------------------------------------------------------------| +| `npt.NDArray` | Array `C` (`n_samples`), contendo as classes prevista para `X`. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se X possuir valores diferentes de (0 e 1) ou (True e False). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de característica (colunas) em X não corresponder ao valor esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir detectores ou classes definidas. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-selecao-negativa-binaria) + +--- + +## Referências + +[^1]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md new file mode 100644 index 000000000..2fee71a00 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md @@ -0,0 +1,222 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - seleção negativa + - detecção de anomalias + - reconhecimento do não-próprio + - reconhecimento de padrões + - classification + - real-valued + - v-detector + - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection +--- + +# RNSA + +Algoritmo de Seleção Negativa com valores reais (RNSA). + +:::tip[Herança] + +Esta classe herda de [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Módulo:** `aisp.nsa` +> **Importação:** `from aisp.nsa import RNSA` + +--- + +## Visão geral + +Algoritmo para classificação e detecção de anomalias baseado na distinção entre próprio e não-próprio, inspirado +no algoritmo de seleção negativa. + +:::note + +Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [^1] e outra com detectores com raio +variável [^2]. Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de +dados presentes na região não-self de todos os detectores e classes. + +::: + +:::warning + +Os parâmetros `r` e `r_s` podem impedir a geração de detectores válidos. Um valor para `r` muito pequeno pode limitar +a cobertura, enquanto muito alto pode dificultar a geração de detectores validos. Da mesma forma, um `r_s` alto +pode limitar a criação de detectores. Portanto, o ajuste adequado de `r` e `r_s` é essencial para garantir um bom +desempenho do algoritmo. + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Exemplo 1:** Classificação multiclasse (RNSA suporta duas ou mais classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +['a' 'b'] +``` + +**Exemplo 2:** Detecção de anomalias (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` + +**Output** + +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Quantidade de detectores. | +| `r` | `float` | `0.05` | Raio do detector. | +| `r_s` | `float` | `0.0001` | O valor de rₛ é o raio das amostras próprias dos dados de treinamento X. | +| `k` | `int` | `1` | Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Métrica de distância usada para calcular a distância entre o detector e a amostra. | +| `max_discards` | `int` | `1000` | Número máximo de descartes de detectores em sequência, que tem como objetivo evitar um possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Define a versão do algoritmo. | +| `non_self_label` | `str` | `'non-self'` | Rótulo atribuído quando há apenas uma classe de saída e a amostra não pertence a essa classe. | +| `cell_bounds` | `bool` | `False` | Se definido como True, esta opção limita a geração dos detectores ao espaço do plano compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, e esta variável é usada exclusivamente no algoritmo `V-detector`. | +| `p` | `float` | `2.0` | Valor de `p` utilizado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------|----------------------------------------------|:------:|-------------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | Conjunto de detectores, organizados por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Treinamento de acordo com X e y, utilizando o algoritmo de seleção negativa. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X ou y não forem ndarrays ou tiverem tamanhos incompatíveis. | +| `ValueError` | Se os valores de X estiverem fora do intervalo (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | Se o número máximo de descartes for atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever as classes com base nos detectores gerados após o treinamento. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-----------------------------------------------------------------| +| `npt.NDArray` | Array `C` (`n_samples`), contendo as classes prevista para `X`. | + +**Exceções** + + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se os valores de X estiverem fora do intervalo (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de característica (colunas) em X não corresponder ao valor esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir detectores ou classes definidas. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-selecao-negativa-de-valores-reais) + +--- + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/README.md new file mode 100644 index 000000000..5b805d884 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/README.md @@ -0,0 +1,28 @@ +--- +id: utils +sidebar_label: aisp.utils +keywords: + - functions + - helpers + - utils +--- + +# aisp.utils + +Funções utilitárias para auxiliar o desenvolvimento. + +> **Módulo:** `aisp.utils` +> **Importação:** `from aisp import utils` + +## SubMódulos + +| Módulo | Descrição | +|----------------------------------|------------------------------------------------------------------------------------| +| [`display`](./display/README.md) | Funções utilitárias para exibir informações de algoritmos. | +| [`distance`](./distance.md) | Funções utilitárias para cálculo de distância entre vetores com decoradores numba. | +| [`metrics`](./metrics.md) | Funções utilitárias para medir acurácia e desempenho. | +| [`multiclass`](./multiclass.md) | Funções utilitárias para lidar com dados com múltiplas classes. | +| [`sanitizers`](./sanitizers.md) | Funções utilitárias para validação e tratamento de parâmetros. | +| [`types`](./types.md) | Define aliases de tipos usados em todo o pacote para melhorar a legibilidade. | +| [`validation`](./validation.md) | Contém funções responsáveis pela validação de tipos de dados. | + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/README.md new file mode 100644 index 000000000..20c462cdc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/README.md @@ -0,0 +1,23 @@ +--- +id: display +sidebar_label: display +keywords: + - tabela + - progresso +--- + +# display + +Funções utilitárias para exibir informações de algoritmos. + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Descrição | +|------------------------------------------|---------------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Formata dados em tabelas para exibição no console. | +| [`ProgressTable`](./progress-table.md) | Exibe uma tabela formatada no console para acompanhar o progresso do algoritmo. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/progress-table.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/progress-table.md new file mode 100644 index 000000000..73c24ebf7 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Exibe uma tabela formatada no console para acompanhar o progresso do algoritmo. + +:::tip[Herança] + +Esta classe herda de [TableFormatter](./table-formatter.md). + +::: + + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils.display import ProgressTable` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Padrão | Descrição | +|-----------|---------------------|:------:|---------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapeamento `{nome_da_coluna: largura_da_coluna}`. | +| `verbose` | `bool` | `True` | Se False, não imprime nada no terminal. | + +--- + +## Métodos Públicos + +### update + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +``` + +Adiciona uma nova linha de valores à tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------------------|:------:|---------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | As chaves devem corresponder às colunas definidas em headers. | + +--- + +### finish + +```python +def finish(self) -> None: + ... +``` + +Finaliza a exibição da tabela, imprimindo a borda inferior e o tempo total. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/table-formatter.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/table-formatter.md new file mode 100644 index 000000000..56aaaba66 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/display/table-formatter.md @@ -0,0 +1,84 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Formata dados em tabelas para exibição no console. + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils.display import TableFormatter` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Padrão | Descrição | +|-----------|---------------------|:------:|--------------------------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapeamento dos nomes das colunas para suas respectivas larguras, no formato `{nome_da_coluna: largura_da_coluna}`. | + +--- + +## Métodos Públicos + +### get_header + +```python +def get_header(self): + ... +``` + +Gera o cabeçalho da tabela, incluindo a borda superior, os nomes das colunas e a linha separadora. + +**Returns** + +| Tipo | Descrição | +|-------|---------------------------------------| +| `str` | String formatada do header da tabela. | + +--- + +### get_row + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +``` + +Gera uma linha formatada para os dados da tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------------------|:------:|--------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dicionário com valores para cada coluna, no formato `{nome_da_coluna: valor}`. | + +**Returns** + +| Tipo | Descrição | +|-------|--------------------------------------| +| `str` | String formatada da linha da tabela. | + +--- + +### get_bottom + +```python +def get_bottom(self, new_line: bool = False): + ... +``` + +Gera a borda inferior da tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|--------|:-------:|----------------------------------------------------------------------------| +| `new_line` | `bool` | `False` | Se `True`, adiciona uma quebra de linha antes da borda (padrão é `False`). | + +**Returns** + +| Tipo | Descrição | +|-------|-------------------------------------| +| `str` | String formatada da borda inferior. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/distance.md new file mode 100644 index 000000000..784cb4faa --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/distance.md @@ -0,0 +1,241 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distância +--- + +# distance + +Funções utilitárias para cálculo de distância entre vetores com decoradores numba. + +> **Módulo:** `aisp.utils.distance` +> **Importação:** `from aisp.utils import distance` + +## Funções + +### hamming + +```python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +``` + +Calcula a distância de Hamming entre dois pontos. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|-------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-----------------------------------------| +| `float64` | Distância de Hamming entre dois pontos. | + +--- + +### euclidean + +```python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +``` + +Calcula a distância de Euclidean entre dois pontos. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Euclidean entre dois pontos. | + +--- + +### cityblock + +```python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +``` + +Calcula a distância de Manhattan entre dois pontos. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Manhattan entre dois pontos. | + +--- + +### minkowski + +```python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +``` + +Calcula a distância de Minkowski entre dois pontos. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | +| `p` | `float` | `2.0` | Parâmetro que define o tipo de distância a ser calculada. | + +:::note[Parâmetro `p`] + +- p = 1: distância **Manhattan** - soma das diferenças +- p = 2: distância **Euclidean** - soma dos quadrados (raiz quadrada). +- p > 2: distância **Minkowski** com penalização crescente conforme `p` aumenta. + +::: + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Minkowski entre dois pontos. | + +--- + +### compute_metric_distance + +```python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +``` + +Calcula a distância entre dois pontos com base na métrica escolhida. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|------------------------|:------:|------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | +| `metric` | `int` | - | Métrica de distância que será usada. Opções: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | Parâmetro que define o tipo de distância a ser calculada | + +**Returns** + +| Tipo | Descrição | +|-----------|-----------------------------------------------------------| +| `float64` | Distância entre os dois pontos com a métrica selecionada. | + +--- + +### min_distance_to_class_vectors + +```python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +``` + +Calcula distância entre um vetor de entrada e os vetores de uma classe e retorna a distância minima. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|------------------------|:------:|---------------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array contendo os vetores da classe a serem comparados com o vetor de entrada. Formato esperado: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | Vetor a ser comparado com os vetores da classe. Formato esperado: (n_features,). | +| `metric` | `int` | - | Métrica de distância a ser usada. Opções: 0 ("euclidean"), 1 ("manhattan"), 2 ("minkowski") or ("hamming") | +| `p` | `float` | `2.0` | Parâmetro da distância de Minkowski (usado apenas quando metric="minkowski"). | + +**Returns** + +| Tipo | Descrição | +|---------|--------------------------------------------------------------------------------------------------------------------------------| +| `float` | A menor distância calculada entre o vetor de entrada e os vetores da classe. Retorna -1.0 se as dimensões forem incompatíveis. | + +--- + +### get_metric_code + +```python +def get_metric_code(metric: str) -> int: + ... +``` + +Obtém o valor associado a uma métrica de distância. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|-------|:------:|---------------------------------------------------------------------------------------| +| `metric` | `str` | - | Nome da métrica. Pode ser `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Returns** + +| Tipo | Descrição | +|-------|----------------------------------| +| `int` | Número correspondente à métrica. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-------------------------------------------| +| `ValueError` | Se a métrica fornecida não for suportada. | + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/metrics.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/metrics.md new file mode 100644 index 000000000..830911a0c --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/metrics.md @@ -0,0 +1,47 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Funções utilitárias para medir acurácia e desempenho. + +> **Módulo:** `aisp.utils.metrics` +> **Importação:** `from aisp.utils import metrics` + +## Funções + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calcula a acurácia com base nos rótulos reais e previstos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------|:------:|-------------------------------------------------------------------| +| `y_true` | `Union[npt.NDArray, list]` | - | Rótulos reais (corretos). Devem ter o mesmo tamanho que `y_pred`. | +| `y_pred` | `Union[npt.NDArray, list]` | - | Rótulos previstos. Devem ter o mesmo tamanho que `y_true`. | + +**Returns** + +| Tipo | Descrição | +|---------|--------------------------------------------------------------------| +| `float` | A proporção de previsões corretas em relação ao total de previsões | + +**Exceções** + +| Exceção | Descrição | +|--------------|--------------------------------------------------------------------------| +| `ValueError` | Se y_true ou y_pred estiverem vazios ou se não tiverem o mesmo tamanho. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/multiclass.md new file mode 100644 index 000000000..d06c26dbc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/multiclass.md @@ -0,0 +1,82 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Funções utilitárias para lidar com dados com múltiplas classes. + +> **Módulo:** `aisp.utils.multiclass` +> **Importação:** `from aisp.utils import multiclass` + +## Funções + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separa os índices das amostras por classe para iteração direcionada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|--------------------------------------|:------:|-----------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | lista com classes únicas. | +| `y` | `npt.NDArray` | - | Recebe um array `y` (`n_samples`) om as classes de saída do array de amostra `X`. | + +**Returns** + +| Tipo | Descrição | +|--------|---------------------------------------------------------------------------------| +| `dict` | Um dicionário com a lista de posições do array(`y`), com as classes como chave. | + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### predict_knn_affinity + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray: + ... +``` + +Prever classes usando k-vizinhos mais próximos e células treinadas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-----------------------------------------------|:------:|-----------------------------------------------------------------| +| `X` | `npt.NDArray` | - | Dados de entrada a serem classificados. | +| `k` | `int` | - | Número de vizinhos mais próximos a considerar para a previsão. | +| `all_cell_vectors` | `List[Tuple[Union[str, int], npt.NDArray]]` | - | Lista de tuplas contendo (nome_da_classe, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Função que recebe dois vetores e retorna um valor de afinidade. | + +**Returns** + +| Tipo | Descrição | +|---------------|------------------------------------------------------------------------------------------| +| `npt.NDArray` | Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/sanitizers.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/sanitizers.md new file mode 100644 index 000000000..6636f664f --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/sanitizers.md @@ -0,0 +1,119 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Funções utilitárias para validação e tratamento de parâmetros. + +> **Módulo:** `aisp.utils.sanitizers` +> **Importação:** `from aisp.utils import sanitizers` + +## Funções + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------|:------:|-------------------------------------------------------------------------------| +| `value` | `T` | - | O valor a ser verificado. | +| `valid_choices` | `Iterable[T]` | - | Uma coleção de opções válidas. | +| `default` | `T` | - | O valor padrão a ser retornado se `'value'` não estiver em `'valid_choices'`. | + +**Returns** + +| Tipo | Descrição | +|------|---------------------------------------------------------| +| `T` | O valor original, se válido, ou o valor padrão, se não. | + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-------------|-----------------------|:------:|-----------------------------------------------------------------------------------------| +| `value` | `T` | - | O valor a ser verificado. | +| `default` | `T` | - | O valor padrão a ser retornado se a condição não for satisfeita. | +| `condition` | `Callable[[T], bool]` | - | Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. | + +**Returns** + +| Tipo | Descrição | +|------|------------------------------------------------------------------------------| +| `T` | O valor original se a condição for satisfeita, ou o valor padrão se não for. | + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------|-------|:------:|---------------------------------| +| `seed` | `Any` | - | O valor da seed a ser validado. | + +**Returns** + +| Tipo | Descrição | +|-----------------|----------------------------------------------------------------------------| +| `Optional[int]` | A seed original se for um inteiro não negativo, ou `None` se for inválido. | + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Valida e normaliza os limites das características. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|-------|:------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | Os limites de entrada, que devem ser None ou um dicionário com as chaves `'low'` e `'high'`. | +| `problem_size` | `int` | - | O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. | + +**Returns** + +| Tipo | Descrição | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dicionário `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | + +**Exceções** + +| Exceção | Descrição | +|--------------|----------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se bounds não for `None` nem um dicionário com as chaves `'low'/'high'`, ou se os valores não forem numéricos. | +| `ValueError` | Se os iteráveis fornecidos tiverem tamanho incorreto. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/types.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/types.md new file mode 100644 index 000000000..6f56b5850 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/types.md @@ -0,0 +1,60 @@ +--- +id: types +sidebar_label: types +keywords: + - tipos + - tipagem + - aliases + - type hints +--- + +# types + +Define aliases de tipos usados em todo o pacote para melhorar a legibilidade. + +> **Módulo:** `aisp.utils.types` +> **Importação:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Tipo das características de entrada + +- `"binary-features"`: Valores apenas com (0 ou 1, `False` ou `True`). +- `"continuous-features"`: Valores numéricos contínuos. +- `"ranged-features"`: Valores entre um intervalo definido. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Mesmo que `FeatureType`, mais: + +- `"permutation-features"`: valores representados como permutação. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Métrica de distância utilizada nos cálculos: + +- `"manhattan"`: distância de Manhattan entre dois pontos. +- `"minkowski"`: distância de Minkowski entre dois pontos. +- `"euclidean"`: distância de Euclidean entre dois pontos. + +--- \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/validation.md new file mode 100644 index 000000000..c8a3ba907 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/utils/validation.md @@ -0,0 +1,180 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validação +--- + +# Módulo + +Contém funções responsáveis pela validação de tipos de dados. + +> **Módulo:** `aisp.utils.validation` +> **Importação:** `from aisp.utils import validation` + +## Funções + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detecta o tipo de dado em um determinado vetor. + +Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: + +* **binário**: Valores booleanos (True/False) ou inteiro 0/1. +* **contínuo**: Valores float dentro do intervalo normalizado [0.0, 1.0]. +* **intervalo**: Valores float fora do intervalo normalizado. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|---------------|:------:|---------------------------------------------------| +| `vector` | `npt.NDArray` | - | Um array contendo os dados a serem classificados. | + +**Returns** + +| Tipo | Descrição | +|-----------------------------------------|-----------------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | O tipo de dado detectado no vetor: "binary-features", "continuous-features", or " ranged-features". | + +**Exceções** + +| Exceção | Descrição | +|------------------------|----------------------------------------------------| +| `UnsupportedTypeError` | Se o vetor contiver um tipo de dado não suportado. | + +--- + +### check_array_type + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: + ... +``` + +Garante que X seja um array numpy. Converte a partir de lista, se necessário. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------|-------|:------:|--------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array contendo as amostras e suas características. Formato: (n_samples, n_features). | +| `name` | `str` | `'X'` | Nome da variável usado em mensagens de erro. | + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------| +| `npt.NDArray` | O array convertido ou validado. | + +**Exceções** + +| Exceção | Descrição | +|-------------|---------------------------------| +| `TypeError` | Se x não for ndarray nem lista. | + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Garante que X e y tenham dimensões compatíveis. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|---------------|:------:|--------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras e suas características. Formato: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array com as classes alvo de `x`, com formato (`n_samples`). | + +**Exceções** + +| Exceção | Descrição | +|-------------|-------------------------------------------| +| `TypeError` | Se x ou y tiverem formatos incompatíveis. | + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Garante que o array possui o número esperado de características (features). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|-----------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array de entrada para predição, contendo as amostras e suas características. Formato:: (n_samples, n_features). | +| `expected` | `int` | - | Número esperado de features por amostra (colunas em X). | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de features em X não corresponder ao esperado. | + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Garante que X contenha apenas valores (0 e 1) or (`True` e `False`). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|---------------|:------:|-----------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras. | + +**Exceções** + +| Exceção | Descrição | +|--------------|---------------------------------------------------| +| `ValueError` | Se o array contiver valores diferentes de 0 e 1. | + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Garante que todos os valores do array x estejam dentro do intervalo. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-------------|---------------|:------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras. | +| `name` | `str` | `'X'` | Nome usado na mensagem de erro. | +| `min_value` | `float` | `0.0` | Valor mínimo permitido. | +| `max_value` | `float` | `1.0` | Valor máximo permitido. | + +**Exceções** + +| Exceção | Descrição | +|--------------|--------------------------------------------------------------| +| `ValueError` | Se o array estiver fora do intervalo (min_value, max_value). | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/architecture.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/architecture.md new file mode 100644 index 000000000..5c2435e78 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/architecture.md @@ -0,0 +1,76 @@ +--- +id: architecture +sidebar_position: 5 +sidebar_label: Arquitetura +keywords: + - arquitetura +--- + +# Arquitetura do AISP + +O AISP (**A**rtificial **I**mmune **S**ystems **P**ackage) é um pacote dedicado à implementação de algoritmos +inspirados no sistema imunológico dos vertebrados. Essa documentação foca na arquitetura do projeto, com o intuito de +auxiliar contribuições e manutenção. +A estrutura do pacote é modular, com separação clara entre as famílias de algoritmos e módulos de suporte para +reutilização de componente pelos algoritmos. + +## Organização dos módulos + +A hierarquia do pacote esta divida em 3 núcleos principais: base, utils e famílias de algoritmos. +O núcleo base concentra nas abstrações e modelagens imunológicas, servindo como a fundação para os algoritmos. +Já utils reúne funções que auxiliam na implementação dos algoritmos evitando redundância de código. + +O núcleo das famílias de algoritmos agrupa as diferentes metáforas dos sistemas imunológicos que os define. + +No aisp, essas famílias estão organizadas nos seguintes módulos: + +- Danger Theory Algorithms (DTA) - Previsto para versões futuras do pacote +- Clonal Selection Algorithms (CSA) +- Immune Network Algorithms (INA) +- Negative Selection Algorithms (NSA) + +### Detalhamento dos módulos + +#### Núcleo do pacote (`aisp.base`) +O módulo base é a fundação do pacote, dividido em: +1. `base.core`: Contem as classes abstratas que implementa o gerenciamento dos parâmetros e a lógica base para compatibilidade. + - `Base` (Privada): Classe abstrata estendida pelas demais classes **base** listadas abaixo. + - `BaseClassifier`: Classe abstrata para algoritmos de classificação. + - `BaseClusterer`: Classe abstrata para algoritmos de clusterização. + - `BaseOptimizer`: Classe abstrata para algoritmos de otimização. +2. `base.immune`: Define as células e processos do domínio imunoinspirados. + - `cell`: Representações de células e anticorpos do sistema imunológico. + - `mutation`: Funções de mutação das células. + - `population`: Criação de populações de células imunes. +#### Utilitários (`aisp.utils`) +Módulo de suporte com funções auxiliares reutilizáveis no pacote. +#### Famílias de algoritmos +As implementações dos algoritmos imunoinspirados no **aisp** estão organizadas em famílias, baseada na taxonomia +apresentada em Brabazon et al. [^1] + +```mermaid +flowchart TD + AIS[Artificial Immune Systems] + NSA[Negative/Positive Selection] + CSA[Clonal Expansion and Selection] + INA[Network Theory Algorithms] + DT[Danger Theory] + + AIS --- NSA + AIS --- CSA + AIS --- INA + AIS --- DT +``` +**Fonte: Adaptado de Brabazon et al. [^1], Figura 16.1.** + +Sendo estruturadas da seguinte forma: + - `aisp.nsa`: Módulo com algoritmos baseados na seleção negativa. + - `aisp.csa`: Módulo com algoritmos baseados na seleção clonal. + - `aisp.ina`: Módulo com algoritmos baseados na teoria da rede imunológica. + - `aisp.dta`: Módulo com algoritmos baseados na teoria do perigo (**Ainda não implementado**). + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/faq.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/faq.md index 218569d77..545e11c83 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/faq.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/faq.md @@ -1,6 +1,6 @@ --- +id: faq sidebar_position: 6 -title: Perguntas Frequentes sidebar_label: FAQ keywords: - FAQ @@ -9,7 +9,9 @@ keywords: - Ajuda --- -Soluções rápidas para possíveis duvidas sobre o aisp. +# Perguntas Frequentes + +Soluções rápidas para possíveis dúvidas sobre o aisp. ## Uso geral @@ -17,27 +19,30 @@ Soluções rápidas para possíveis duvidas sobre o aisp. Depende do tipo de problema: -- **Detecção de anomalias**: Use ``RNSA`` ou ``BNSA``. +- **Detecção de anomalias**: Use `RNSA` ou `BNSA`. - RNSA para problemas com dados contínuos. - BNSA para problemas com dados binários. -- **Classificação**: Use ``AIRS``, ``RNSA`` ou ``BNSA``. - - O ``RNSA`` e ``BNSA``, foram implementados para serem aplicados a classificação multiclasse. - - O ``AIRS`` é mais robusto para ruídos nos dados. -- **Otimização**: Use ``Clonalg``. +- **Classificação**: Use `AIRS`, `RNSA` ou `BNSA`. + - O `RNSA` e `BNSA`, foram implementados para serem aplicados a classificação multiclasse. + - O `AIRS` é mais robusto para dados com ruídos. +- **Otimização**: Use `Clonalg`. - A implementação pode ser aplicada à otimização (min/max) de funções objetivas. -- **Clustering/Agrupamento**: Use ``AiNet``. +- **Clustering/Agrupamento**: Use `AiNet`. - Separa grupos de dados automaticamente. - Não requer numero de grupos predefinidos. --- -### Como normalizar meus dados para utilizar o algoritmo ``RNSA``? +### Como normalizar meus dados para utilizar o algoritmo `RNSA`? -O RNSA trabalha exclusivamente com dados normalizados no intervalo entre [0, 1]. Portanto, antes de aplicá-lo, é necessário normalizar os dados se não estiver neste intervalo. Uma forma simples é fazer utilizando as ferramentas de normalização do **scikit-learn**, como o [``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). +O RNSA trabalha exclusivamente com dados normalizados no intervalo entre (0.0, 1.0). Portanto, antes de aplicá-lo, +é necessário normalizar os dados se não estiver neste intervalo. Uma forma simples é fazer utilizando as +ferramentas de normalização do **scikit-learn**, como o +[`MinMaxScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). #### Exemplo -Neste exemplo, ``X`` representa os dados de entrada não normalizados. +Neste exemplo, `X` representa os dados de entrada não normalizados. ```python from sklearn.preprocessing import MinMaxScaler @@ -55,21 +60,22 @@ rnsa.fit(x_norm, y) ## Configuração de Parâmetros -### Como escolher o numero de detectores (``N``) no ``RNSA`` ou ``BNSA``? +### Como escolher o numero de detectores (`N`) no `RNSA` ou `BNSA`? -O numero de detectores afeta diretamente a performance: +O número de detectores afeta diretamente a performance: - Um número reduzido de detectores pode não cobrir adequadamente o espaço não-próprio. - Um número muito alto de detectores pode aumentar o tempo de treinamento e pode causar overfitting. **Recomendações**: -- Teste diferentes valores para o número de detectores até encontrar um equilíbrio adequado entre tempo de treinamento e desempenho do modelo. +- Teste diferentes valores para o número de detectores até encontrar um equilíbrio adequado entre tempo de treinamento + e desempenho do modelo. - Utilize validação cruzada para identificar o valor que apresenta os melhores resultados de forma consistente. --- -### Qual raio (``r`` ou ``aff_thresh``) devo utilizar no ``BNSA`` ou ``RNSA``? +### Qual raio (`r` ou `aff_thresh`) devo utilizar no `BNSA` ou `RNSA`? O raio dos detectores depende da distribuição dos dados: @@ -78,15 +84,17 @@ O raio dos detectores depende da distribuição dos dados: --- -### O que é o parâmetro ``r_s`` no ``RNSA``? +### O que é o parâmetro `r_s` no `RNSA`? -O ``r_s`` é o raio da amostra self. Ele define uma região ao redor de cada amostra de treinamento. +O `r_s` é o raio da amostra self. Ele define uma região ao redor de cada amostra de treinamento. --- ### Clonalg: Como definir a função objetivo? -A função objetiva deve seguir o padrão da [classe base](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140), Ela deve receber uma solução como entrada e retornar um valor do custo (ou afinidade). +A função objetiva deve seguir o padrão da +[classe base](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). +Ela deve receber uma solução como entrada e retornar um valor do custo (ou afinidade). ```python def affinity_function(self, solution: Any) -> float: @@ -95,12 +103,14 @@ def affinity_function(self, solution: Any) -> float: Existem duas formas de definir a função objetivo no Clonalg. -1. Definindo a função diretamente no construtor da classe - ```python def sphere(solution): return np.sum(solution ** 2) +``` + +1. Definindo a função diretamente no construtor da classe +```python clonalg = Clonalg( problem_size=2, affinity_function=sphere @@ -110,9 +120,6 @@ clonalg = Clonalg( 2. Utilizando o registrador de funções ```python -def sphere(solution): - return np.sum(solution ** 2) - clonalg = Clonalg( problem_size=2, ) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/intro.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/intro.md index 8c57a60a0..2a4bdf8b7 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/intro.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/intro.md @@ -55,9 +55,35 @@ O AISP oferece implementações de algoritmos bio-inspirados para: - **Otimização**: Encontre soluções ótimas para funções objetivas. - **Clustering**: Agrupe dados sem supervisão. -### Algoritmos implementados +--- + +## Algoritmos Implementados + +### [Seleção Negativa](./aisp-techniques/negative-selection.md) (`aisp.nsa`) + +- [**BNSA**](./api/nsa/bnsa.md) - Algoritmo de Seleção Negativa Binária +- [**RNSA**](./api/nsa/rnsa.md) - Algoritmo de Seleção Negativa com Valores Reais + +### [Seleção Clonal](./aisp-techniques/clonal-selection-algorithms.md) (`aisp.csa`) + +- [**AIRS**](./api/csa/airs.md) - Sistema Imunológico Artificial de Reconhecimento +- [**CLONALG**](./api/csa/clonalg.md) - Algoritmo de Seleção Clonal + +### [Teoria de Redes Imunológicas](./aisp-techniques/immune-network-theory.md) (`aisp.ina`) + +- [**AiNet**](./api/ina/ai-net.md) - Rede Imunológica Artificial para Agrupamento e Compressão de Dados + +### Módulo em Desenvolvimento + +#### Teoria do Perigo (`aisp.dta`) + +- **DCA** - Algoritmo de Células Dendríticas *(planejado)* + +## Visão geral da API + +Todos os algoritmos seguem uma interface simples e consistente: -> - [x] [**Seleção Negativa.**](./aisp-techniques/negative-selection/) -> - [x] [**Algoritmos de Seleção Clonal.**](./aisp-techniques/clonal-selection-algorithms/) -> - [x] [**Teoria da Rede Imune.**](./aisp-techniques/immune-network-theory/) -> - [ ] *Teoria do Perigo.* +- `fit(X, y, verbose: bool = True)`: Treina o modelo para tarefas de classificação. +- `fit(X, verbose: bool = True)`: Treina o modelo para tarefas de agrupamento. +- `predict(X)`: Faz previsões com base em novos dados. +- `optimize(max_iters: int =..., n_iter_no_change: int =..., verbose: bool = True)`: executar os algoritmos de otimização diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json deleted file mode 100644 index 3587f3645..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "description": "As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time" -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md deleted file mode 100644 index 9041d2b26..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Seleção Negativa - -As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time. - -## Função check_detector_bnsa_validity(...) - -```python -def check_detector_bnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - aff_thresh: float -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). -* aff_thresh (``float``): Limiar de afinidade. - -**Retorna:** - -* True se o detector for válido, False caso contrário. - ---- - -## Função bnsa_class_prediction(...) - -```python -def bnsa_class_prediction( - features: npt.NDArray, - class_detectors: npt.NDArray, - aff_thresh: float -) -> int: -``` - -Define a classe de uma amostra a partir dos detectores não-próprios. - -**Os parâmetros de entrada são:** - -* features (``npt.NDArray``): amostra binária a ser classificada (shape: [n_features]). -* class_detectors (``npt.NDArray``): Matriz contendo os detectores de todas as classes (shape: [n_classes, n_detectors, n_features]). -* aff_thresh (``float``): Limiar de afinidade que determina se um detector reconhece a amostra como não-própria. - -**Retorna:** - -* int: Índice da classe predita. Retorna -1 se for não-própria para todas as classes. - ---- - -## Função check_detector_rnsa_validity(...) - -```python -def check_detector_rnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - threshold: float, - metric: int, - p: float -) -> bool: -``` - -Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. - -**Os parâmetros de entrada são:** - -* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). -* threshold (``float``): Afinidade. -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Retorna:** - -* True se o detector for válido, False caso contrário. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md deleted file mode 100644 index 5096345b3..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md +++ /dev/null @@ -1,152 +0,0 @@ -# Display - -Funções utilitárias para exibir informações de algoritmos - -## def _supports_box_drawing() - -```python -def _supports_box_drawing() -> bool -``` - -Função para verificar se o terminal suporta caracteres de borda. - -**Retorna**: - -* ***bool*** (`bool`): True se o terminal provavelmente suporta caracteres de borda, False caso contrário. - ---- - -## class TableFormatter - -Classe para formatar dados tabulares em strings para exibição no console. - -**Parâmetros**: - -* ***headers*** (`Mapping[str, int]`): Mapeamento dos nomes das colunas para suas larguras respectivas, no formato `{nome_coluna: largura_coluna}`. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -### def _border(left, middle, right, line, new_line=True) - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str -``` - -Cria uma borda horizontal para a tabela. - -**Parâmetros**: - -* ***left*** (`str`): Caractere na borda esquerda. -* ***middle*** (`str`): Caractere separador entre colunas. -* ***right*** (`str`): Caractere na borda direita. -* ***line*** (`str`): Caractere usado para preencher a borda. -* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é True). - -**Retorna**: - -* ***border*** (`str`): String representando a borda horizontal. - ---- - -### def get_header() - -```python -def get_header(self) -> str -``` - -Gera o cabeçalho da tabela, incluindo a borda superior, os títulos das colunas e a linha separadora. - -**Retorna**: - -* ***header*** (`str`): String formatada do cabeçalho da tabela. - ---- - -### def get_row(values) - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str -``` - -Gera uma linha formatada para os dados da tabela. - -**Parâmetros**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Dicionário com os valores de cada coluna, no formato `{nome_coluna: valor}`. - -**Retorna**: - -* ***row*** (`str`): String formatada da linha da tabela. - ---- - -### def get_bottom(new_line=False) - -```python -def get_bottom(self, new_line: bool = False) -> str -``` - -Gera a borda inferior da tabela. - -**Parâmetros**: - -* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é False). - -**Retorna**: - -* ***bottom*** (`str`): String formatada da borda inferior. - ---- - -## class ProgressTable(TableFormatter) - -Classe para exibir uma tabela formatada no console para acompanhar o progresso de um algoritmo. - -**Parâmetros**: - -* ***headers*** (`Mapping[str, int]`): Mapeamento `{nome_coluna: largura_coluna}`. -* ***verbose*** (`bool`, padrão=True): Se False, não imprime nada no terminal. - -**Exceções**: - -* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. - ---- - -### def _print_header() - -```python -def _print_header(self) -> None -``` - -Imprime o cabeçalho da tabela. - ---- - -### def update(values) - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None -``` - -Adiciona uma nova linha de valores à tabela. - -**Parâmetros**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): As chaves devem corresponder às colunas definidas em `headers`. - ---- - -### def finish() - -```python -def finish(self) -> None -``` - -Encerra a exibição da tabela, imprimindo a borda inferior e o tempo total. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md deleted file mode 100644 index f4b5939b0..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Distance - -Funções utilitárias para distância normalizada entre matrizes com decoradores numba. - -## def hamming(...) - -```python -def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: -``` - -Função para calcular a distância de Hamming normalizada entre dois pontos. - -$$ -\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def euclidean(...) - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Função para calcular a distância euclidiana normalizada entre dois pontos. - -$$ -\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def cityblock(...) - -```python -def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Função para calcular a distância Manhattan normalizada entre dois pontos. - -$$ -\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto -* v (``npt.NDArray``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def minkowski(...) - -```python -def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): -``` - -Função para calcular a distância de Minkowski normalizada entre dois pontos. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |X_n - Y_n|p) ¹/ₚ) / n$ - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto. -* v (``npt.NDArray``): Coordenadas do segundo ponto. -* p (``float``): O parâmetro p define o tipo de distância a ser calculada: - * p = 1: Distância **Manhattan** — soma das diferenças absolutas. - * p = 2: Distância **Euclidiana** — soma das diferenças ao quadrado (raiz quadrada). - * p > 2: Distância **Minkowski** com uma penalidade crescente à medida que p aumenta. - -**Returns:** - -* Distância (``float``) entre os dois pontos. - ---- - -## def compute_metric_distance(...) - -```python -def compute_metric_distance( - u: npt.NDArray[np.float64], - v: npt.NDArray[np.float64], - metric: int, - p: np.float64 = 2.0 -) -> np.float64: -``` - -Função para calcular a distância entre dois pontos pela ``métrica`` escolhida. - -**Parameters:** - -* u (``npt.NDArray``): Coordenadas do primeiro ponto. -* v (``npt.NDArray``): Coordenadas do segundo ponto. -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* Distância (``double``) entre os dois pontos com a métrica selecionada. - ---- - -## def min_distance_to_class_vectors(...) - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray, - vector_x: npt.NDArray, - metric: int, - p: float = 2.0 -) -> float: -``` - -Calcula a menor distância entre um vetor de entrada e os vetores de uma classe. - -**Parameters:** - -* x_class (``npt.NDArray``): Array contendo os vetores da classe com os quais o vetor de entrada será comparado. Formato esperado: (n_amostras, n_características). -* vector_x (``npt.NDArray``): Vetor a ser comparado com os vetores da classe. Formato esperado: (n_características,). -* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. -* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). - -**Returns:** - -* float: A menor distância calculada entre o vetor de entrada e os vetores da classe. -* Retorna -1.0 se as dimensões de entrada forem incompatíveis. - ---- - -## def get_metric_code(...) - -```python -def get_metric_code(metric: str) -> int: -``` - -Retorna o código numérico associado a uma métrica de distância. - -**Parameters:** - -* metric (``str``): Nome da métrica. Pode ser "euclidean", "manhattan", "minkowski" ou "hamming". - -**Raises** - -* ``ValueError``: Se a métrica informada não for suportada. - -**Returns:** - -* ``int``: Código numérico correspondente à métrica. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md deleted file mode 100644 index 1bef4601c..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -sidebar_position: 1 -title: Métricas -sidebar_label: Metrics -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -O arquivo de métricas fornece utilitários para medir, analisar e comparar o desempenho dos algoritmos do pacote de forma padronizada. - -### def accuracy_score(...) - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float -``` - -Função para calcular a acurácia de precisão com base em listas de rótulos -verdadeiros e nos rótulos previstos. - -**Parâmetros** - -* y_true (``Union[npt.NDArray, list]``): Rótulos verdadeiros (corretos).. -* y_pred (``Union[npt.NDArray, list]``): Rótulos previstos. - -**Retornos** - -* Precisão (``float``): A proporção de previsões corretas em relação -ao número total de previsões. - -**Lança** - -* ValueError: Se `y_true` ou `y_pred` estiverem vazios ou se não -tiverem o mesmo tamanho. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md deleted file mode 100644 index fbe8d25ee..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_position: 1 -title: Multiclasse -sidebar_label: Multiclass -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -Este arquivo contém funções utilitárias internas desenvolvidas para simplificar a manipulação e o processamento de dados em cenários de classificação multiclasse dentro do pacote AISP. - -### def slice_index_list_by_class(...) - -```python -def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict -``` - -A função ``slice_index_list_by_class(...)``, separa os índices das linhas conforme a \ -classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for \ -a classe que está sendo treinada. - -**Parameters:** - -* classes (``list or npt.NDArray``): lista com classes únicas. -* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saída do \ - array de amostra ``X``. - -**Returns:** - -* dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave. - ---- - -### def predict_knn_affinity(...) - -Função para prever classes usando k-vizinhos mais próximos e células treinadas. - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray -``` - -**Parâmetros:** - -* **_X_** (`npt.NDArray`): Dados de entrada a serem classificados. -* **_k_** (`int`): Número de vizinhos mais próximos a considerar para a previsão. -* **_all_cell_vectors_** (`List[Tuple[Union[str, int], npt.NDArray]]`): Lista de tuplas contendo pares (nome_da_classe, vetor_da_célula). -* **_affinity_func_** (`Callable[[npt.NDArray, npt.NDArray], float]`): Função que recebe dois vetores e retorna um valor de afinidade. - -**Retorna:** - -* `npt.NDArray`: Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md deleted file mode 100644 index b65540711..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md +++ /dev/null @@ -1,16 +0,0 @@ -# Random - -Funções utilitárias para geração e reprodutibilidade de números aleatórios. - -## Função set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Define a semente para números aleatórios usados por funções compiladas com Numba. - -**Parâmetros**: - -* **seed**: `int` - Valor inteiro usado para inicializar o gerador de números aleatórios do Numba. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md deleted file mode 100644 index 56be3c290..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Sanitizers - -## def sanitize_choice(...) - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T -``` - -A função ``sanitize_choice(...)``, retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. - -**Parameters:** - -* ***value*** (``T``): O valor a ser verificado. -* ***valid_choices*** (``Iterable[T]``): Uma coleção de opções válidas. -* ***default***: O valor padrão a ser retornado se ``value`` não estiver em ``valid_choices``. - -**Returns:** - -* `T`: O valor original, se válido, ou o valor padrão, se não. - ---- - -## def sanitize_param(...) - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -A função ``sanitize_param(...)``, retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. - -**Parameters:** - -* value (``T``): O valor a ser verificado. -* default (``T``): O valor padrão a ser retornado se a condição não for satisfeita. -* condition (``Callable[[T], bool]``): Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. - -**Returns:** - -* `T`: O valor original se a condição for satisfeita, ou o valor padrão se não for. - ---- - -## def sanitize_seed(...) - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -A função ``sanitize_param(...)``, retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. - -**Parameters:** - -* seed (``Any``): O valor da seed a ser validado. - -**Returns:** - -* ``Optional[int]``: A seed original se for um inteiro não negativo, ou ``None`` se for inválido. - ---- - -## def sanitize_bounds(...) - -```python -def sanitize_bounds(bounds: Any, problem_size: int) -> Dict[str, npt.NDArray[np.float64]] -``` - -A função `sanitize_bounds(...)` valida e normaliza os limites das características (features). - -**Parâmetros**: - -* ***bounds*** (`Any`): Os limites de entrada, que devem ser `None` ou um dicionário com as chaves `'low'` e `'high'`. -* ***problem_size*** (`int`): O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. - -**Retorna**: - -* `Dict[str, list]`: Dicionário no formato `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md deleted file mode 100644 index 030678fc5..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md +++ /dev/null @@ -1,108 +0,0 @@ -# Validation - -## def detect_vector_data_type(...) - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detecta o tipo de dado em um determinado vetor. - -Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: - -* **binário**: Valores booleanos (`True`/`False`) ou inteiro `0`/`1`. -* **contínuo**: Valores float dentro do intervalo normalizado `[0.0, 1.0]`. -* **intervalo**: Valores float fora do intervalo normalizado. - -### Parâmetros - -* `vetor` (`npt.NDArray`): Um array contendo os dados a serem classificados. - -### Retorna - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): O tipo de dado detectado no vetor. - -### Gera - -* `UnsupportedDataTypeError`: Gerado se o vetor contiver um tipo de dado não suportado. - ---- - -## def check_array_type(...) - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Garante que o parâmetro recebido é um array numpy. Converte de lista se necessário. - -**Parâmetros:** - -* `x`: Array ou lista contendo as amostras e características. -* `name`: Nome da variável para mensagens de erro. - -**Retorna:** - -* `npt.NDArray`: O array convertido ou validado. - -**Lança:** - -* `TypeError`: Se não for possível converter para ndarray. - ---- - -## def check_shape_match(...) - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Garante que os arrays `x` e `y` possuem o mesmo número de amostras (primeira dimensão). - -**Parâmetros:** - -* `x`: Array de amostras. -* `y`: Array de classes alvo. - -**Lança:** - -* `TypeError`: Se as dimensões não forem compatíveis. - ---- - -## def check_feature_dimension(...) - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Garante que o array possui o número esperado de características (features). - -**Parâmetros:** - -* `x`: Array de entrada para predição. -* `expected`: Número esperado de características por amostra. - -**Lança:** - -* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. - ---- - -## def check_binary_array(...) - -```python -def check_binary_array(x: npt.NDArray): -``` - -Garante que o array contém apenas valores 0 e 1. - -**Parâmetros:** - -* `x`: Array a ser verificado. - -**Lança:** - -* `ValueError`: Se o array contiver valores diferentes de 0 e 1. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json deleted file mode 100644 index 59b3ccf99..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "label": "Utils", - "description": "Funções utilitárias e auxiliares para o desenvolvimento." -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json deleted file mode 100644 index 871d71c3d..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Guides", - "position": 2.6, - "link": { - "type": "generated-index", - "description": "Explore a documentação avançada da biblioteca, que abrange as classes base, além das funções utilitárias do módulo utils voltadas para métricas e manipulação de classificação multiclasse." - } -} diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json deleted file mode 100644 index 8c11fd000..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "position": 1, - "description": "Classe base para algoritmo de classificação." -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md deleted file mode 100644 index bd5f0f0ef..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -sidebar_position: 1 -title: Classe Base -sidebar_label: Base -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Classe Base - - Modelo Base - - Compatibilidade com Scikit-learn - - get_params - - set_params - - Semente Aleatória - - Classes Python ---- - -Classe base para compatibilidade com a API do scikit-learn. - -Fornece os métodos `get_params` e `set_params` para compatibilidade com a API do scikit-learn, permitindo acesso aos parâmetros públicos do modelo. - -### Função set_params(...) - -```python -def set_params(self, **params) -``` - -Define os parâmetros da instância. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros**: - -* **params**: dict - Dicionário de parâmetros que serão definidos como atributos da instância. Apenas atributos públicos (que não começam com "_") são modificados. - -**Retorno**: - -* self: `Base` - Retorna a própria instância após definir os parâmetros. - ---- - -### Função get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Retorna um dicionário com os principais parâmetros do objeto. Garante compatibilidade com funções do scikit-learn. - -**Parâmetros**: - -* **deep**: `bool` (padrão=True) - Ignorado nesta implementação, mas incluído para compatibilidade com scikit-learn. - -**Retorno**: - -* params: `dict` - Dicionário contendo os atributos do objeto que não começam com "_". - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md deleted file mode 100644 index 546e22f96..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -sidebar_position: 1 -sidebar_label: BaseClassifier -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Classe base para algoritmo de classificação - -## ``class BaseClassifier(ABC)`` - -Classe base para algoritmos de classificação, definindo os métodos abstratos ``fit`` e ``predict``, e implementando o método ``get_params``. - -## Abstract methods - -### def fit(...) - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Ajusta o modelo aos dados de treinamento. - -Implementação: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-fit) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-fit) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) - -### def predict(...) - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -Realiza a previsão dos rótulos para os dados fornecidos. - -Implementação: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-predict) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-predict) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) - ---- - -## Métodos - -### def score(...) - -```python -def score(self, X: npt.NDArray, y: list) -> float -``` - -A função de pontuação (score) calcula a precisão da previsão. - -Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. -Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. - -**Parâmetros**: - -- ***X***: np.ndarray - Conjunto de características com formato (n_amostras, n_características). -- ***y***: np.ndarray - Valores verdadeiros com formato (n_amostras,). - -**Retorna**: - -- precisão: float - A precisão do modelo. - ---- - -### Método _slice_index_list_by_class(...) - -A função ``_slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -### def get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict: -``` - -A função get_params retorna um dicionário com os parâmetros principais do objeto. - -Esta função é necessária para garantir a compatibilidade com as funções do scikit-learn. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md deleted file mode 100644 index aea519ce3..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -sidebar_position: 3 -title: Base class for clustering algorithm. -sidebar_label: BaseClusterer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Clusterer - - Clustering - - Unsupervised Learning - - BaseClusterer - - Abstract Base Class - - fit Method - - predict Method - - fit_predict Method - - AiNet - - Cluster Prediction - - Python ML Classes ---- - -## ``BaseClusterer(ABC, Base)`` - -Classe base abstrata para algoritmos de clustering. - -Esta classe define a interface central para modelos de agrupamento. Ela exige -a implementação dos métodos **`fit`** e **`predict`** em todas as classes derivadas, -e fornece uma implementação padrão para **`fit_predict`** e **`get_params`**. - ---- - -### Função fit(...) - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer -``` - -Ajusta o modelo aos dados de treinamento. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada utilizados para treinar o modelo. -* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna**: - -* ***self***: `BaseClusterer` - Instância da classe que implementa este método. - -**Implementação**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) - ---- - -### Função predict(...) - -```python -def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] -``` - -Gera previsões com base nos dados de entrada. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. - -**Retorna**: - -* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. - -**Implementação**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) - ---- - -### Função fit_predict(...) - -```python -def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] -``` - -Método de conveniência que combina `fit` e `predict` em uma única chamada. - -**Parâmetros**: - -* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. -* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. - -**Retorna**: - -* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md deleted file mode 100644 index 2bbb5b15a..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -sidebar_position: 4 -title: Classe base para algoritmos de otimização. -sidebar_label: BaseOptimizer -author: João Paulo -keywords: - - BaseOptimizer - - classe base de otimização - - abstract base class - - otimização em machine learning - - função objetivo - - método optimize - - avaliação de modelos - - metaheurísticas - - algoritmos bio-inspirados - - Python ML ---- - -Esta classe define a interface central para estratégias de otimização e mantém o histórico de custos, soluções avaliadas e a melhor solução encontrada. Subclasses devem implementar os métodos `optimize` e `objective_function`. - ---- - -### Propriedades - -#### `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Retorna o histórico de custos durante a otimização. - ---- - -#### `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Retorna o histórico de soluções avaliadas. - ---- - -#### `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Retorna a melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -#### `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Retorna o custo da melhor solução encontrada até o momento, ou `None` se não disponível. - ---- - -## Funções - -### Função _record_best(...) - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Registra um novo valor de custo e atualiza a melhor solução se houver melhoria. - -**Parâmetros**: - -* ***cost***: `float` - Valor de custo a ser adicionado ao histórico. - ---- - -### Função get_report() - -```python -def get_report(self) -> str -``` - -Gera um relatório resumido e formatado do processo de otimização. O relatório inclui a melhor solução, seu custo associado e a evolução dos valores de custo por iteração. - -**Retorna**: - -* **report**: `str` - String formatada contendo o resumo da otimização. - ---- - -### Função register(...) - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Registra dinamicamente uma função na instância do otimizador. - -**Parâmetros**: - -* ***alias***: `str` - Nome usado para acessar a função como atributo. -* ***function***: `Callable[..., Any]` - Callable a ser registrado. - -**Exceções**: - -* **TypeError**: Se `function` não for chamável. -* **AttributeError**: Se `alias` for protegido e não puder ser modificado, ou se `alias` não existir na classe do otimizador. - ---- - -### Função reset() - -```python -def reset(self) -``` - -Reinicia o estado interno do objeto, limpando o histórico e resetando os valores. - ---- - -### Métodos abstratos - -#### Função optimize(...) - -```python -def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any -``` - -Executa o processo de otimização. Este método deve ser implementado pela subclasse para definir como a estratégia de otimização explora o espaço de busca. - -**Parâmetros**: - -* ***max_iters***: `int` - Número máximo de iterações. -* ***n_iter_no_change***: `int`, padrão=10 - Número máximo de iterações sem atualização da melhor solução. -* ***verbose***: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante a otimização. - -**Retorna**: - -* **best_solution**: `Any` - A melhor solução encontrada pelo algoritmo de otimização. - ---- - -#### Função affinity_function(...) - -```python -def affinity_function(self, solution: Any) -> float -``` - -Avalia a afinidade de uma solução candidata. Este método deve ser implementado pela subclasse para definir o problema específico. - -**Parâmetros**: - -* ***solution***: `Any` - Solução candidata a ser avaliada. - -**Retorna**: - -* **cost**: `float` - Valor de custo associado à solução fornecida. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md deleted file mode 100644 index ef81da74b..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Cell Classes -sidebar_label: Cell Classes -keywords: - - Binário - - classificação - - limiar de afinidade - - Valores Reais - - classificação - - anomalias - - K-Vizinhos Mais Próximos - - célula-B de memória -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -Representação de células do sistema imunológico. - -## Cell - -Representa uma célula imune básica. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Atributos - -* **vector** (`np.ndarray`): Um vetor de características da célula. - -### Métodos - -* `__eq__(other)`: Verifica se duas células são iguais com base em seus vetores. -* `__array__()`: Interface de array para NumPy, permite que a instância seja tratada como um `np.ndarray`. -* `__getitem__(item)`: Obtém elementos do vetor de características usando indexação. - ---- - -## BCell - -Representa uma célula B de memória, derivada de `Cell`. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Métodos - -### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> np.ndarray -``` - -Clona N características das características de uma célula, gerando um conjunto de vetores mutados. - -#### Parâmetros - -* **n** (`int`): Número de clones a serem gerados a partir de mutações da célula original. -* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): Especifica o tipo de características com base na natureza das características de entrada. -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) com mínimo e máximo por dimensão. - -#### Retorna - -* **npt.NDArray**: Um array contendo N vetores mutados da célula original. - ---- - -## Antibody - -Representa um anticorpo com afinidade, derivado de `Cell`. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Atributos - -* **vector** (`npt.NDArray`): Um vetor de características da célula. -* **affinity** (`float`): Valor de afinidade do anticorpo. - -### Métodos - -* `__lt__(other)`: Compara este anticorpo com outro com base na afinidade. -* `__eq__(other)`: Verifica se dois anticorpos têm a mesma afinidade. - ---- - -## Detector - -Representa um detector não-próprio da classe RNSA. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Atributos - -* **position** (`npt.NDArray[np.float64]`): Vetor de características do detector. -* **radius** (`Optional[float]`): Raio do detector, usado no algoritmo V-detector. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md deleted file mode 100644 index d9e29b669..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Mutation -sidebar_label: Mutation -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - Mutação - - Expansão Clonal - - Sistema Imunológico - - clone_and_mutate - - clone_and_mutate_continuous - - clone_and_mutate_binary - - clone_and_mutate_ranged - - Sistemas Imunológicos Artificiais - - Funções Python Numba - - Mutação Vetorial ---- - -Contém funções que geram conjuntos de clones mutados a partir de vetores contínuos ou binários, simulando o processo de expansão clonal em sistemas imunológicos artificiais. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. - -### Retorno - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int -) -> npt.NDArray[np.bool_]: -``` - -Gera um conjunto de clones mutados a partir de um vetor binário. - -Esta função cria `n` clones do vetor binário de entrada e aplica mutações aleatórias em alguns bits, simulando a expansão clonal em sistemas imunes artificiais com representações discretas. - -### Parâmetros - -* `vector` (`npt.NDArray[np.bool_]`): Vetor binário original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. - -### Retorno - -* `clone_set` (`npt.NDArray[np.bool_]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) -def clone_and_mutate_ranged( -vector: npt.NDArray[np.float64], -n: int, -bounds: npt.NDArray[np.float64] -) -> npt.NDArray[np.float64]: -``` - -Gera um conjunto de clones mutados a partir de um vetor contínuo usando limites personalizados por dimensão. - -Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. - -### Parâmetros - -* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. -* `n` (`int`): Quantidade de clones mutados a serem gerados. -* `bounds` (`npt.NDArray[np.float64]`): Um array 2D com o formato `(len(vector), 2)` contendo os valores mínimo e máximo para cada dimensão. - -### Retorna - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md deleted file mode 100644 index f3cbae8d9..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Módulo de Populações -sidebar_label: Populações -pagination_next: null -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell - - Clonal Expansion - - Immune System - - Artificial Immune Systems -lastUpdatedAt: 2025/11/21 -author: João Paulo ---- - -Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. - -## generate_random_antibodies(...) - -Gera uma população aleatória de anticorpos. - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -### Parâmetros - -* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. -* **n_features** (`int`): Número de características (dimensões) para cada anticorpo. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. - -### Retorno - -* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. - -### Exceções - -* **ValueError**: Caso o número de características seja menor ou igual a zero. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md new file mode 100644 index 000000000..c2cbcd1d2 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md @@ -0,0 +1,39 @@ +--- +id: docs-csa +keywords: + - seleção e expansão clonal + - clonalg + - artificial immune systems + - classificação + - otimização + - algoritmos bioinspirados + - computação natural +--- + +# Seleção e expansão clonal + +Os Algoritmos baseados na seleção e expansão clonal são inspirados no processo de proliferação de anticorpos +após a detecção de um antígeno, durante o qual os anticorpos gerados sofrem mutações na tentativa de aumentar +o reconhecimento do patógeno. [^1] + +--- + +A Seleção e expansão clonal pode ser aplicada em diferentes contextos, tais como: +- **Otimização** +- **Classificação** + +## Implementações do pacote + +### Sistema Imunológico Artificial de Reconhecimento ([AIRS](../api/csa/airs.md)) + +Algoritmo de classificação inspirado no processo de seleção clonal. + +### Algoritmo de Seleção Clonal ([CLONALG](../api/csa/clonalg.md)) + +Algoritmo de otimização inspirado no processo biológico de seleção clonal do sistema imunológico. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx deleted file mode 100644 index fc3db09dc..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx +++ /dev/null @@ -1,15 +0,0 @@ ---- -sidebar_position: 2 -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- -import DocCardList from '@theme/DocCardList'; - -# Algoritmos de Seleção Clonal. - -Os Algoritmos de Seleção Clonal são inspirados no processo de proliferação de anticorpos após a detecção de um antígeno, -durante o qual os anticorpos gerados sofrem mutações na tentativa de aumentar o reconhecimento do patógeno. - -## Classes: - - \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md deleted file mode 100644 index 1c5003080..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -id: airs -sidebar_label: AIRS - Sistema Imunológico Artificial de Reconhecimento -keywords: - - Binário - - Classificação - - Limiar de Afinidade - - Valores Reais - - Anomalias - - K-Vizinhos Mais Próximos -lastUpdatedAt: 2025/08/22 -author: João Paulo ---- - -# AIRS - Sistema Imunológico Artificial de Reconhecimento - -O ``AIRS`` é um algoritmo de classificação inspirado no processo de seleção clonal. A versão implementada nesta classe é inspirada na sua versão simplificada, o AIRS2, descrito em[Brabazon, O'Neill, and McGarraghy (2015)](#1) - -Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo adaptações para lidar com conjuntos de dados contínuos e binários. - -Com base no algoritmo 16.5 de Brabazon et al. [1](#1). - -:::tip Trabalhos relacionados e notáveis: - -- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) - -::: - -:::info - -**``AIRS``** estende a classe **[classe ``BaseClassifier``](../../../advanced-guides/base-module/core/Classifier.md)**, herdando sua funcionalidade base. - -::: - -## Construtor AIRS - -A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas de seleção e expansão clonal. - -**Atributos:** - -- **n_resources** (`float`): Quantidade total de recursos disponíveis. O padrão é 10. - -- **rate_clonal** (`float`): Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * taxa de hipermutação) para definir o número de clones. O padrão é 10. - -- **rate_hypermutation** (`int`): Taxa de clones mutados derivada de rate_clonal como um fator escalar. O padrão é 0,75. - -- **affinity_threshold_scalar** (`float`): Limiar de afinidade normalizado. O padrão é 0,75. - -- **k** (`int`): Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. O padrão é 10. - -- **max_iters** (`int`): Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. O padrão é 100. - -- **resource_amplified** (`float`): Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. O padrão é 1.0 (sem amplificação). - -- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$. - - Defaults to ``'euclidean'``. - -- **seed** (``Optional[int]``): Semente para geração aleatória de valores dos detectores. O padrão é None. - -- `**kwargs`: - - - **p** (`float`): Este parâmetro armazena o valor de `p` usado na distância de Minkowski. - O padrão é `2`, que corresponde à distância euclidiana normalizada. Diferentes valores de p resultam em variantes distintas da distância de Minkowski. [Saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Outras variáveis inicializadas:** - -- **cells_memory** (`dict`): Armazena uma lista de células de memória por classe. -- **affinity_threshold** (`dict`): Define o limiar de afinidade entre antígenos. -- **classes** (`npt.NDArray`): Lista de classes de saída. - ---- - -## Métodos Públicos - -### Método fit(...) - -A função `fit(...)` gera detectores para os não-pertencentes em relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray): -``` - -Realiza o treinamento conforme `X` e `y`, utilizando o método Sistema de Reconhecimento Imune Artificial (`AIRS`). - -**Parâmetros de entrada:** - -- **X**: Array com as características das amostras, com **N** amostras (linhas) e **N** características (colunas), normalizado para valores entre [0, 1]. -- **y**: Array com as classes de saída correspondentes às **N** amostras relacionadas a `X`. -- **verbose**: Booleano, padrão `True`, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -### Método predict(...) - -A função `predict(...)` realiza a predição de classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**Parâmetro de entrada:** - -- **X**: Array com as características para predição, com **N** amostras (linhas) e **N** colunas. - -**Retorna:** - -- **C**: Um array de predições com as classes de saída para as características fornecidas. -- **None**: Se não houver detectores. - ---- - -### Método score(...) - -A função `score(...)` calcula a acurácia do modelo treinado realizando predições e calculando a precisão. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -Retorna a acurácia como um `float`. - ---- - -## Métodos Privados - -### Método _refinement_arb(...) - -A função "_refinement_arb(...)" refina o conjunto ARB até que o valor médio de estímulo ultrapasse o limiar definido (`affinity_threshold_scalar`). - -Parâmetros: - -- **c_match** (`Cell`): Célula com o maior estímulo em relação a aᵢ. -- **arb_list** (`List[_ARB]`): Conjunto ARB. - -```python -def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: -``` - -Retorna a célula (_ARB) com o maior estímulo ARB. - ---- - -### Método _cells_affinity_threshold(...) - -A função "_cells_affinity_threshold(...)" calcula o limiar de afinidade com base na afinidade média entre instâncias de treinamento, onde aᵢ e aⱼ são um par de antígenos, e a afinidade é medida pela distância (Euclidiana, Manhattan, Minkowski, Hamming). -**Seguindo a fórmula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - -Parâmetros: - -- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - ---- - -### Método _affinity(...) - -A função "_affinity(...)" calcula o estímulo entre dois vetores usando métricas. - -Parâmetros: - -- **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -- **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -Retorna a taxa de estímulo entre os vetores. - ---- - -### Método _init_memory_c(...) - -A função "_init_memory_c(...)" inicializa células de memória selecionando aleatoriamente `n_antigens_selected` da lista de antígenos de treinamento. - -Parâmetros: - -- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: -``` - ---- - -## Referências - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md deleted file mode 100644 index eb0e525bd..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -id: abr -title: ABR -sidebar_label: ABR - Bolha de reconhecimento artificial -sidebar_position: 2 -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -## ABR (Artificial Recognition Ball) - -Individuo do conjunto de células reconhecedoras (ABR), herda características de uma célula-B, adicionando o consumo de recursos - -:::info - -**``ABR``** estende a classe **[``BCell``](../../../advanced-guides/base-module/immune/cell.md#BCell)**, herdando sua funcionalidade base. - -::: - -### Constructor - -Parameters: - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Function consume_resource(...) - -Parameters: - -* n_resource (```float```) : The initial amount of resources. -* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -Returns the remaining amount of resources after consumption. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md deleted file mode 100644 index 452753963..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -id: clonalg -sidebar_label: CLONALG - Algoritmo de Seleção Clonal -keywords: - - CLONALG - - algoritmo de seleção clonal - - otimização bio-inspirada - - inteligência artificial - - problemas binários - - problemas contínuos - - ranged optimization - - permutação - - metaheurísticas ---- - -# CLONALG - Algoritmo de Seleção Clonal - -A classe `Clonalg` é um **algoritmo de otimização** inspirado no processo biológico de seleção clonal do sistema imunológico. Esta implementação é projetada para minimizar ou maximizar funções de custo em diversos tipos de problemas, incluindo problemas binários, contínuos, com valores limitados (ranged) e de permutação. - -:::tip -A implementação do CLONALG foi inspirada na descrição apresentada em [1](#1). -::: - -:::info -Esta implementação do CLONALG contém algumas alterações baseadas no contexto do AISP, para aplicação geral -a diversos problemas, que podem produzir resultados diferentes da implementação padrão ou -específica. Esta adaptação visa generalizar o CLONALG para tarefas de minimização e -maximização, além de suportar problemas contínuos, discretos e de permutação. -::: - -:::info - -**``Clonalg``** estende a **[classe ``BaseOptimizer`` ](../../advanced-guides/base-module/core/Optimizer.md)**, herdando suas funcionalidades básicas. - -::: - ---- - -## CLONALG Constructor - -O construtor inicializa a instância do CLONALG com os principais parâmetros que definem o processo de otimização. - -**Atributos:** - -* **problem_size**: `int` - Dimensão do problema a ser otimizado. -* **N**: `int`, padrão=50 - Número de células de memória (anticorpos) na população. -* **rate_clonal**: `float`, padrão=10 - Número máximo de clones possíveis de uma célula. Este valor é multiplicado pela afinidade da célula para determinar o número de clones. -* **rate_hypermutation**: `float`, padrão=0.75 - Taxa de clones mutados, usada como fator escalar. -* **n_diversity_injection**: `int`, padrão=5 - Número de novas células de memória aleatórias injetadas para manter a diversidade. -* **selection_size**: `int`, padrão=5 - Número de melhores anticorpos selecionados para clonagem. -* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, padrão=None - Função objetivo usada para avaliar soluções candidatas. -* **feature_type**: `FeatureTypeAll`, padrão='ranged-features' - Tipo de amostra do problema, podendo ser `'continuous-features'`, `'binary-features'`, `'ranged-features'` ou `'permutation-features'`. -* **bounds**: `Optional[Dict]`, padrão=None - Dicionário definindo os limites de busca para problemas `'ranged-features'`. Pode ser um único intervalo ou uma lista de intervalos para cada dimensão. -* **mode**: `Literal["min", "max"]`, padrão="min" - Especifica se o algoritmo minimiza ou maximiza a função de custo. -* **seed**: `Optional[int]`, padrão=None - Semente para geração de números aleatórios. - ---- - -### Métodos Públicos - -#### Função `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -Este método executa o processo de otimização e retorna a população de anticorpos. - -**Parâmetros de entrada:** - -* **max_iters**: `int`, padrão=50 - Número máximo de interações. -* **n_iter_no_change**: `int`, padrão=10 - Número máximo de iterações sem melhoria na melhor solução. -* **verbose**: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante o processo de otimização. - -**Retorna:** - -* population : ``List[Antibody]``, A população de [anticorpos](../../advanced-guides/base-module/immune/cell.md#Antibody) após a expansão clonal. - ---- - -#### Função `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -Este método avalia a afinidade de uma solução candidata. Levanta `NotImplementedError` se nenhuma função de afinidade tiver sido fornecida à instância da classe. - -**Parâmetros de entrada:** - -* **solution**: `npt.NDArray` - Solução candidata a ser avaliada. - -**Retorna:** - -* `np.float64`: Valor de afinidade associado à solução. - ---- - -### Métodos Privados - -#### Função `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: -``` - -Seleciona os `n` melhores anticorpos com base em suas pontuações de afinidade, de acordo com o `mode` (`'min'` ou `'max'`). - -**Parâmetros de entrada:** - -* **n**: `int` - Número de anticorpos a serem selecionados. -* **antibodies**: `list[tuple]` - Lista de tuplas, onde cada tupla representa um anticorpo e sua pontuação associada. - -**Retorna:** - -* `list[tuple]`: Lista contendo os `n` anticorpos selecionados. - ---- - -#### Função `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -Inicializa aleatoriamente a população inicial de anticorpos. - -**Retorna:** - -* `npt.NDArray`: Lista com os anticorpos inicializados. - ---- - -#### Função `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -Introduz novos anticorpos aleatórios na população para manter a diversidade genética e ajudar a evitar convergência prematura. - -**Retorna:** - -* `npt.NDArray`: Array contendo os novos anticorpos aleatórios. - ---- - -#### Função `_clone_and_mutate(...)` - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: -``` - -Gera clones mutados a partir de um único anticorpo. A estratégia de mutação depende do `feature_type` especificado durante a inicialização (`'binary-features'`, `'continuous-features'`, `'ranged-features'` ou `'permutation-features'`). - -**Parâmetros de entrada:** - -* **antibody**: `npt.NDArray` - Vetor original do anticorpo a ser clonado e mutado. -* **n_clone**: `int` - Número de clones a serem gerados. -* **rate_hypermutation**: `float` - Taxa de hipermutação. - -**Retorna:** - -* `npt.NDArray`: Array contendo os clones mutados. - ---- - -#### Função `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation(self, population: list[tuple]) -> list: -``` - -Clona e aplica hipermutação a uma população de anticorpos. Retorna uma lista de todos os clones e suas afinidades em relação à função de custo. - -**Parâmetros de entrada:** - -* **population**: `list[tuple]` - Lista de anticorpos a serem avaliados e clonados. - -**Retorna:** - -* `list`: Lista contendo os clones mutados. - ---- - -## Referências - ---- - -### 1 -> -> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory.md new file mode 100644 index 000000000..55fa1162f --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory.md @@ -0,0 +1,41 @@ +--- +id: docs-ina +keywords: + - teoria da rede imunológica + - ainet + - artificial immune systems + - classificação + - clusterização + - otimização + - algoritmos bioinspirados + - computação natural +--- + +# Teoria da Rede Imunológica + +Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, +na qual células e moléculas são capazes de se reconhecer mutuamente[^1]. + +--- + +A Rede Imunológica Artificial pode ser aplicada em diferentes contextos, tais como: +- **Agrupamento (Clustering)** +- **Otimização** +- **Classificação** + +## Implementações do pacote + +### Rede Imunológica Artificial para Agrupamento e Compressão ([AiNet](../api/ina/ai-net.md)) + +AiNet é um algoritmo de clustering baseado na teoria das redes imunológicas, que utiliza seleção clonal e maturação +por afinidade para comprimir dados e identificar grupos[^2]. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md deleted file mode 100644 index 5738f143c..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md +++ /dev/null @@ -1,327 +0,0 @@ ---- -id: ainet -sidebar_label: AiNet - Agrupamento e Compressão -sidebar_position: 1 -pagination_next: null -keywords: - - Rede Imunológica Artificial - - AiNet - - Agrupamento - - Compressão de Dados - - Algoritmos Imunológicos - - Computação Bioinspirada - - Células de Memória - - Limite de Afinidade - - Limite de Supressão - - Seleção Clonal - - Expansão Clonal - - Introdução de Diversidade - - Reconhecimento de Padrões - - Detecção de Anomalias - - Agrupamento MST - - Árvore Geradora Mínima - - Aprendizado Não Supervisionado - - Algoritmos Bioinspirados - - Rede de Anticorpos -lastUpdatedAt: 2025/08/19 -author: João Paulo ---- - -# AiNet - Rede Imunológica Artificial para Agrupamento e Compressão - -A classe AiNet tem como objetivo realizar agrupamento utilizando metáforas inspiradas na teoria da rede imunológica. - -A classe AiNet implementa o algoritmo de Rede Imune Artificial para compressão e clustering. Ela utiliza princípios da teoria de redes imunes, -seleção clonal e maturação por afinidade para comprimir conjuntos de dados e encontrar clusters [1](#1). -Para clustering, pode opcionalmente utilizar uma [**Árvore Geradora Mínima** -(MST)](#2) para separar nós distantes em grupos. - -:::info - -**``AiNet``** estende a **[classe ``BaseClusterer``](../../advanced-guides/base-module/core/Clusterer.md)**, herdando sua funcionalidade básica. - -::: - -## Constructor - -```python -class AiNet( - self, - N: int = 50, - n_clone: int = 10, - top_clonal_memory_size: int = 5, - n_diversity_injection: int = 5, - affinity_threshold: float = 0.5, - suppression_threshold: float = 0.5, - mst_inconsistency_factor: float = 2.0, - max_iterations: int = 10, - k: int = 3, - metric: MetricType = "euclidean", - seed: Optional[int] = None, - use_mst_clustering: bool = True, - **kwargs -) -``` - -**Atributos:** - -* **N** (`int`): Número de células de memória (anticorpos) na população. Padrão: 50. -* **n_clone** (`int`): Número de clones gerados por célula de memória selecionada. Padrão: 10. -* **top_clonal_memory_size** (`Optional[int]`): Número de anticorpos de maior afinidade selecionados para clonagem. Padrão: 5. -* **n_diversity_injection** (`int`): Número de novos anticorpos aleatórios injetados para manter a diversidade. Padrão: 5. -* **affinity_threshold** (`float`): Limite para seleção/supressão de células. Padrão: 0.5. -* **suppression_threshold** (`float`): Limite para remoção de células de memória semelhantes. Padrão: 0.5. -* **mst_inconsistency_factor** (`float`): Fator para determinar arestas inconsistentes na MST. Padrão: 2.0. -* **max_iterations** (`int`): Número máximo de iterações de treinamento. Padrão: 10. -* **k** (`int`): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Padrão: **"Euclidean"**. - -* **seed** (`Optional[int]`): Semente para geração de números aleatórios. Padrão: None. -* **use_mst_clustering** (`bool`): Define se o clustering baseado em MST deve ser utilizado. Padrão: True. -* **kwargs**: - * **p** (`float`): Parâmetro para distância de Minkowski. Padrão: 2. - -**Outras variáveis inicializadas:** - -* **_population_antibodies** (`npt.NDArray`): Conjunto atual de anticorpos. -* **_memory_network** (`dict`): Dicionário que mapeia clusters para anticorpos. -* **_mst_structure** (`scipy.sparse.csr_matrix`): Estrutura de adjacência da MST. -* **_mst_mean_distance** (`float`): Média das distâncias das arestas da MST. -* **_mst_std_distance** (`float`): Desvio padrão das distâncias das arestas da MST. -* **classes** (`list`): Lista de rótulos dos clusters. - ---- - -## Métodos Públicos - -### Função fit(...) - -Treina o modelo AiNet com os dados de entrada: - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: -``` - -**Parâmetros de entrada:** - -* **X**: Matriz com amostras (linhas) e atributos (colunas). -* **verbose**: Booleano, padrão True, habilita feedback de progresso. - -*Retorna a instância da classe.* - ---- - -### Função predict(...) - -Prediz os rótulos dos clusters para novas amostras: - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -**Parâmetros de entrada:** - -* **X**: Matriz de atributos de entrada. - -**Retorna:** - -* **Predictions**: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado. - ---- - -### Função update_clusters(...) - -Particiona os clusters utilizando a MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parâmetros de entrada:** - -* **mst_inconsistency_factor**: Valor opcional (float) para sobrescrever o fator de inconsistência da MST. - -**Atualiza:** - -* **_memory_network**: Dicionário de rótulos de clusters para vetores de anticorpos. -* **classes**: Lista de rótulos de clusters. - ---- - -## Métodos Privados - -### Função _init_population_antibodies(...) - -Inicializa a população de anticorpos aleatoriamente. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Parâmetros de entrada:** Nenhum - -**Retorna:** Anticorpos inicializados (`npt.NDArray`). - ---- - -### Função _select_and_clone_population(...) - -Seleciona os melhores anticorpos e gera clones mutados: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Parâmetros de entrada:** - -* **antigen**: Vetor representando o antígeno para o qual as afinidades serão calculadas. -* **population**: Matriz de anticorpos a serem avaliados e clonados. - -**Retorna:** Lista de clones mutados. - ---- - -### Função _clonal_suppression(...) - -Suprime clones redundantes com base em limiares: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parâmetros de entrada:** - -* **antigen**: Vetor representando o antígeno. -* **clones**: Lista de clones candidatos a serem suprimidos. - -**Retorna:** Lista de clones não redundantes e de alta afinidade. - ---- - -### Função _memory_suppression(...) - -Remove anticorpos redundantes da memória: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parâmetros de entrada:** - -* **pool_memory**: Lista de anticorpos atualmente na memória. - -**Retorna:** Memória filtrada (`list`). - ---- - -### Função _diversity_introduction(...) - -Introduce novos anticorpos aleatórios: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Parâmetros de entrada:** Nenhum - -**Retorna:** Conjunto de novos anticorpos (`npt.NDArray`). - ---- - -### Função _affinity(...) - -Calcula o estímulo entre dois vetores: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros de entrada:** - -* **u**: Vetor representando o primeiro ponto. -* **v**: Vetor representando o segundo ponto. - -**Retorna:** Valor de afinidade (`float`) no intervalo [0,1]. - ---- - -### Função _calculate_affinities(...) - -Calcula a matriz de afinidades entre um vetor de referência e vetores-alvo: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Parâmetros de entrada:** - -* **u**: Vetor de referência (`npt.NDArray`) de formato `(n_features,)`. -* **v**: Vetores-alvo (`npt.NDArray`) de formato `(n_samples, n_features)`. - -**Retorna:** Vetor de afinidades (`npt.NDArray`) com formato `(n_samples,)`. - ---- - -### Função _clone_and_mutate(...) - -Gera clones mutados: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parâmetros de entrada:** - -* **antibody**: Vetor de anticorpo original a ser clonado e mutado. -* **n_clone**: Número de clones a serem gerados. - -**Retorna:** Matriz de clones mutados (`npt.NDArray`) de formato `(n_clone, len(antibody))`. - ---- - -### Função _build_mst(...) - -Constrói a MST e armazena estatísticas: - -```python -def _build_mst(self): -``` - -**Parâmetros de entrada:** Nenhum - -**Exceções:** ValueError se a população de anticorpos estiver vazia. - -**Atualiza variáveis internas:** - -* **_mst_structure**: Estrutura de adjacência da MST. -* **_mst_mean_distance**: Distância média das arestas. -* **_mst_std_distance**: Desvio padrão das distâncias das arestas da MST. - ---- - -## Referências - -### 1 -> -> 1. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> Disponível em: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -### 2 -> -> 2. SciPy Documentation. *Minimum Spanning Tree*. -> Disponível em: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx deleted file mode 100644 index cfa989ea5..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 3 -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Teoria da Rede Imunológica - - AiNet - - Sistemas Imunológicos Artificiais - - Agrupamento - - Otimização - - Classificação - - Aprendizado de Máquina - - Algoritmos Imunológicos ---- - -import DocCardList from '@theme/DocCardList'; - -# Teoria da Rede Imunológica - -Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, -na qual células e moléculas são capazes de se reconhecer mutuamente. [1](#1) - ---- - -A Rede Imunológica Artificial pode ser aplicada em diferentes contextos, tais como: -- **Agrupamento (Clustering)** -- **Otimização** -- **Classificação** - -## Classes: - - - -## References - ---- - -### 1 -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection.md new file mode 100644 index 000000000..d4e003b07 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection.md @@ -0,0 +1,50 @@ +--- +id: docs-nsa +keywords: + - seleção negativa + - nsa + - artificial immune systems + - detecção de anomalias + - classificação + - algoritmos bioinspirados + - computação natural +--- + +# Seleção Negativa + +Os algoritmos de **seleção negativa** inspiram-se no processo em que o sistema imunológico faz a maturação das células-T +conhecidas também por linfócitos-T, no qual as tornam aptas na detecção dos não-próprios. Assim, o Algoritmo de +seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional[^1]. + +--- + +A Seleção Negativa pode ser aplicada em diferentes contextos, tais como: +- **Detecção de anomalias** +- **Classificação** + +## Implementações do pacote: + +### Algoritmo seleção negativa binária ([BNSA](../api/nsa/bnsa.md)) + +O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por +Forrest et al. (1994)[^2], originalmente desenvolvida para segurança computacional. + +### Algoritmo seleção negativa de real valor ([RNSA](../api/nsa/rnsa.md)) + +Este algoritmo possui duas versões diferentes: uma baseada na versão canônica[^1] e outra com detectores +de raio variável.[^3] Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para +previsão de dados presentes na região não-self de todos os detectores e classes. + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. + +[^3] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md deleted file mode 100644 index 9f619b1e0..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: bnsa -sidebar_label: BNSA - Algoritmo de Seleção Negativa Binária -sidebar_position: 2 -pagination_next: null -last_update: - date: 2025/05/17 - author: João Paulo -keywords: - - Binário - - classificação - - anomalias - - not self - - affinity threshold - - Algoritmo de Seleção Negativa - - Sistema Imunológico Artificial (AIS) - - Próprio e não-próprio - - Imune - - Computação Natural ---- - -# BNSA (Algoritmo de Seleção Negativa Binária) - -:::info - -**``BNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. - -::: - -## Construtor RNSA - -A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . - -```python -class BNSA( - self, - N: int = 100, - aff_thresh: float = 0.1, - max_discards: int = 1000, - seed: int = None, - no_label_sample_selection: Literal["max_average_difference", "max_nearest_difference"] = "max_average_difference" -) -``` - -**Attributes:** - -* *N* (``int``): Quantidade de detectores. Defaults to ``100``. -* *aff_thresh* (``float``): A variável ('affinity threshold') representa a porcentagem de não similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de não similaridade. - - :::note - Definir uma porcentagem de diferença muito alta pode resultar na incapacidade de gerar detectores para não-próprio. - ::: - -* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um -possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. -* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* no_label_sample_selection (``str``): Método para a seleção de rótulos para amostras designadas como não pertencentes por todos os detectores não pertencentes. **Tipos de métodos disponíveis:** - * (``max_average_difference``): Seleciona a classe com a maior diferença média entre os detectores. - * (``max_nearest_difference``): Seleciona a classe com a maior diferença entre o detector mais próximo e mais distante da amostra. - -**Outras variáveis iniciadas:** - -* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. - -* *classes* (``npt.NDArray``): lista de classes de saída. - ---- - -## Função fit(...) - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -## Função predict(...) - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**O parâmetro de entrada:** - -* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. -* ``None``: se não houver detectores. - ---- - -## Função score(...) - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - ---- - -## Função __slice_index_list_by_class(...) - -A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md deleted file mode 100644 index 610f032ba..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Seleção Negativa - -A **seleção negativa** é o processo em que o sistema imunológico faz a maturação das células-T conhecidas também por linfócitos-T, no qual tornam-as aptas na detecção dos não-próprios. Assim, o Algoritmo de seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional. [1](#1) - ---- - -## classes - -> 1. **[Binary version:](BNSA.md)** -> ->> O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por [Forrest et al. (1994)](#2), originalmente desenvolvida para segurança computacional. ->>> **Exemplo:** ->>> ->>> + [Base de dados Mushrooms](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/mushrooms_dataBase_example_pt-br.ipynb) - -> 2. **[Real-Valued version:](RNSA.md)** -> ->>Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [[1]](#1) e outra com detectores de raio variável [[3]](#3). Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de dados presentes na região não-self de todos os detectores e classes. ->>> **Exemplos:** ->>> ->>> + [Base de dados Iris](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/iris_dataBase_example_pt-br.ipynb) ->>> + [Base de dados Geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/geyser_dataBase_example_pt-br.ipynb) - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). - -### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). - -### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md deleted file mode 100644 index 6f1c88e07..000000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -id: rnsa -sidebar_label: RNSA - Algoritmo de Seleção Negativa de Valor Real -sidebar_position: 1 -last_update: - date: 2025/05/17 - author: João Paulo -keywords: - - Valor Real - - classificação - - anomalias - - not self - - V-detector - - Algoritmo de Seleção Negativa - - Sistema Imunológico Artificial (AIS) - - Próprio e não-próprio - - Imune - - Computação Natural ---- - -# RNSA (Algoritmo de Seleção Negativa de Valor Real) - -:::info - -**``RNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. - -::: - -## Construtor RNSA - -A classe ``RNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . - -```python -class RNSA( - self, - N: int = 100, - r: float = 0.05, - r_s: float = 0.0001, - k: int = 1, - metric: Literal['manhattan', 'minkowski', 'euclidean'] = 'euclidean', - max_discards: int = 1000, - seed: int = None, - algorithm: Literal['default-NSA', 'V-detector'] ='default-NSA', - **kwargs: Dict[str, Union[bool, str, float]] -) -``` - -**Attributes:** - -* *N* (``int``): Quantidade de detectores. Defaults to ``100``. -* *r* (``float``): Raio do detector. Defaults to ``0.05``. - - :::note - É importante considerar que definir um raio muito baixo para o detector pode reduzir significativamente a taxa de detecção. Por outro lado, um raio muito grande pode inviabilizar a incorporação do detector no espaço de busca, o que também pode comprometer o desempenho da detecção. É fundamental encontrar um equilíbrio entre o tamanho do raio e a eficiência da detecção para obter os melhores resultados possíveis. - ::: - -* *k* (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. Defaults to ``1``. -* *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: - - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} - $$ - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$. - - Defaults to ``'euclidean'``. - -* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um -possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. - -* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. -* *algorithm* (``str``), Definir a versão do algoritmo: - - * ``'default-NSA'``: Algoritmo padrão com raio fixo. - * ``'V-detector'``: Este algoritmo é baseado no artigo "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", de autoria de Ji, Z., Dasgupta, D. (2004), e utiliza um raio variável para a detecção de anomalias em espaços de características. - - Defaults to ``'default-NSA'``. - -* *r_s* (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``. - -* ``**kwargs``: - * *non_self_label* (``str``): Esta variável armazena o rótulo que será atribuído quando os dados possuírem - apenas uma classe de saída, e a amostra for classificada como não pertencente a essa classe. Defaults to ``'non-self'``. - - * *cell_bounds* (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço do plano compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, e esta variável é usada exclusivamente no algoritmo ``V-detector``. - * p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski. O padrão é ``2``, o que significa distância euclidiana normalizada. Diferentes valores de p levam a diferentes variantes da distância de Minkowski [saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Outras variáveis iniciadas:** - -* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. - -* *classes* (``npt.NDArray``): lista de classes de saída. - ---- - -### Função fit(...) - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. - -*Retorna a instância da classe.* - ---- - -### Função predict(...) - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**O parâmetro de entrada:** - -* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. -* ``None``: se não houver detectores. - ---- - -### Função score(...) - -A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -retorna a acurácia, do tipo ``float``. - ---- - -## Métodos privados - ---- - -### Função __checks_valid_detector(...) - -A função ``def __checks_valid_detector(...)`` verifica se o detector possui raio ``r`` válido para o não-próprio da classe: - -```python -def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: -``` - -**Os parâmetros de entrada são:** - -* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. - -* ``vector_x``: Detector candidato gerado aleatoriamente. - -* ``samplesIndexClass``: Array com os indexes de uma classe. - -**Retorna:** Verdadeiro (``True``) para os detectores que não possuam amostras em seu interior ou falso (``False``) se possuir. - ---- - -### Função __compare_KnearestNeighbors_List(...) - -A função ``def __compare_KnearestNeighbors_List(...)`` compara a distância dos k-vizinhos mais próximo, para isso se a distância da nova amostra for menor, substitui ``k-1`` e ordena em ordem crescente: - -```python -def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: -``` - -**Retorna:** uma lista com as distâncias dos k-vizinhos mais próximo. - ---- - -### Função __compare_sample_to_detectors(...) - -Função para comparar uma amostra com os detectores, verificando se a amostra é própria. - -Nesta função, quando possui ambiguidade de classes, retorna a classe que possuir a média de distância maior entre os detectores. - -**Os parâmetros de entrada são:** - -* line: vetor com N-características - -**Retorna:** A classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe. - ---- - -### Função __detector_is_valid_to_Vdetector(...) - -Verifique se a distância entre o detector e as amostras, descontando o raio das amostras, é maior do que o raio mínimo. - -```python -def __detector_is_valid_to_Vdetector(self, distance, vector_x): -``` - -**Os parâmetros de entrada são:** - -* distance (``float``): distância mínima calculada entre todas as amostras. -* vector_x (``numpy.ndarray``): vetor x candidato do detector gerado aleatoriamente, com valores entre 0 e 1. - -**Retorna:** - -* ``False``: caso o raio calculado seja menor do que a distância mínima ou ultrapasse a borda do espaço, caso essa opção esteja habilitada. -* ``True`` e a distância menos o raio das amostras, caso o raio seja válido. - ---- - -### Função __distance(...) - -A função ``def __distance(...)`` calcula a distância entre dois pontos utilizando a técnica definida em ``metric``, no qual são: ``'euclidiana', 'minkowski', ou 'manhattan'`` - -```python -def __distance(self, u: npt.NDArray, v: npt.NDArray): -``` - -Os parâmetros de entrada são NDArrays: ``u`` e ``v``, com as coordenadas para os pontos. - -Retorna a distancia (``double``) entre os dois pontos. - ---- - -### Função __slice_index_list_by_class(...) - -A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md new file mode 100644 index 000000000..e86d07419 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md @@ -0,0 +1,84 @@ +--- +id: api +sidebar_position: 5 +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering +--- + +# AISP - API + +Bem-vindo à API do **AISP** (Artificial Immune System Package). Esta documentação demonstra a API pública do pacote. + +## Módulos Principais ([`aisp.base`](./base/README.md)) + +Abstrações fundamentais e classes base que definem as interfaces principais do pacote. + +| Classe | Descrição | +|-----------------------------------------------|---------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base/base-clusterer.md) | Classe base abstrata para algoritmos de agrupamento. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +### Componentes do Domínio Imunológico ([`aisp.base.immune`](./base/immune/README.md)) + +Estruturas principais e utilitários de suporte para implementações imunológicas. + +| Módulo | Descrição | +|-----------------------------------------------|---------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./base/immune/mutation.md) | Funções para gerar clones mutados e simular a expansão clonal. | +| [`populations`](./base/immune/populations.md) | Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. | + +--- + +## Algoritmos + +### Algoritmos de Seleção Negativa ([`aisp.nsa`](./nsa/README.md)) + +Algoritmos de aprendizagem supervisionada baseados na seleção negativa, o processo do sistema imunológico de distinguir o próprio do não-próprio. + +| Classe | Descrição | +|-------------------------|--------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | Um algoritmo de aprendizagem supervisionada para classificação que usa detectores de valores reais. | +| [`BNSA`](./nsa/bnsa.md) | Um algoritmo de aprendizagem supervisionada para classificação que usa detectores binários. | + +### Algoritmos de Seleção Clonal ([`aisp.csa`](./csa/README.md)) + +Algoritmos inspirados no processo de proliferação de anticorpos para detectar um antígeno. + +| Classe | Descrição | +|-------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | Um algoritmo de aprendizagem supervisionada para tarefas de classificação baseado no princípio da seleção clonal. | +| [`Clonalg`](./csa/clonalg.md) | Implementação do algoritmo de seleção clonal para otimização, adaptado para problemas de minimização e maximização em domínios binários, contínuos e de permutação. | + +### Algoritmos de Redes Imunológicas ([`aisp.ina`](./ina/README.md)) + +Algoritmos baseados na Teoria de Redes Imunológicas proposta por Jerne. + +| Classe | Descrição | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | Um algoritmo de aprendizagem não supervisionada para agrupamento, baseado na teoria das redes imunológicas. | + +## Utilitários ([`aisp.utils`](./utils/README.md)) + +Funções utilitárias e auxiliares para desenvolvimento. + +| Módulo | Descrição | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Funções utilitárias para exibição de informações dos algoritmos. | +| [`distance`](./utils/distance.md) | Funções utilitárias para cálculo de distância entre arrays (com Numba). | +| [`metrics`](./utils/metrics.md) | Funções utilitárias para medição de precisão e desempenho. | +| [`multiclass`](./utils/multiclass.md) | Funções utilitárias para lidar com classes multicategorias. | +| [`sanitizers`](./utils/sanitizers.md) | Funções utilitárias para validação e tratamento de parâmetros. | +| [`types`](./utils/types.md) | Define aliases de tipos usados no projeto para melhorar a legibilidade. | +| [`validation`](./utils/validation.md) | Contém funções responsáveis pela validação de tipos de dados. | + +## Exceções ([`aisp.exceptions`](./exceptions.md)) + +Avisos e erros personalizados. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/README.md new file mode 100644 index 000000000..99b354e61 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - imune + - abstrato +--- + +# aisp.base + +Classe base e utilitários centrais + +> **Módulos:** `aisp.base` + +## Visão geral + +Este modulo fornece as classes e utilidades fundamentais para todos os algoritmos de sistemas imunológicos artificiais +implementados no AISP. + +## Classes + +| Class | Descrição | +|------------------------------------------|--------------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base-clusterer.md) | Classe base abstrata para algoritmos de clustering. | +| [`BaseOptimizer`](./base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +## Submódulos + +| Módulo | Descrição | +|--------------------------------|----------------------------------------------------------| +| [`immune`](./immune/README.md) | Módulo de suporte para sistemas imunológicos artificias. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-classifier.md new file mode 100644 index 000000000..50b174811 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-classifier.md @@ -0,0 +1,133 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classificação + - classificação interface + - pontuação de acurácia + - fit + - predict +tags: + - classificador + - classificação +--- + +# BaseClassifier + +Classe base abstrata para algoritmos de classificação. + +> **Módulo:** `aisp.base` +> **Importação:** `from aisp.base import BaseClassifier` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de classificação. +Ela define a implementação dos metodos `fit` e `predict` em todas as classes derivadas, e fornece uma implementação +do método `score`. + +Caso de uso: + +- Classe base abstrata para estender classes de algoritmos de classificação. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-----------|-------------------------|:------:|----------------------------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Rótulos das classes identificado de `y` durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Treine o modelo usando os dados de entrada X e seus rótulos correspondentes y. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada X. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|--------------------------------------------------| +| `npt.NDArray` | Array com as previsões para cada amostra de `X`. | + +--- + +## Métodos públicos + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +A função calcula o desempenho do modelo nas previsões utilizando a métrica de acurácia. + +Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. +Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|--------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos verdadeiros com dimensão (n_amostras,). | + +**Returns** + +| Tipo | Descrição | +|---------|-----------------------| +| `float` | A precisão do modelo. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-clusterer.md new file mode 100644 index 000000000..21944743d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-clusterer.md @@ -0,0 +1,123 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict + - agrupamento +tags: + - clusterer + - agrupamento +--- + +# BaseClusterer + +Classe base abstrata para algoritmos de clustering. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseClusterer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de clusterização. +Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do +método `fit_predict`. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de clusterização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|-------------------------|:------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Rótulos dos clusters encontrados durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Treinamento do modelo utilizando os dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-------------------------------------------------------------| +| `npt.NDArray` | Os labels do cluster previsto para cada amostra de entrada. | + +--- + +## Métodos públicos + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Ajusta o modelo e com os dados de X e retorna os labels para cada amostra de X. +Este é um método que combina `fit` e `predict` em uma única chamada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-------------------------------------------------------------| +| `npt.NDArray` | Os labels do cluster previsto para cada amostra de entrada. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-optimizer.md new file mode 100644 index 000000000..56281f78a --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/base-optimizer.md @@ -0,0 +1,164 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - otimizar + - otimização + - otimizar interface + - objective function + - minimization + - maximization +tags: + - otimizar + - otimização +--- + +# BaseOptimizer + +Classe base abstrata para algoritmos de otimização. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseOptimizer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de otimização. +Ela mantém o histórico de custos, soluções avaliadas, e a melhor solução encontrada durante a otimização. As classes +derivadas devem implementar os métodos ``optimize`` e ``affinity_function``. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de otimização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-------------------|:-------:|---------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | Histórico dos melhores custos encontrados em cada iteração. | +| `solution_history` | `List` | `[]` | Histórico da melhor solução encontrada em cada iteração. | +| `best_solution` | `Any` | `None` | A melhor solução global encontrada. | +| `best_cost` | `Optional[float]` | `None` | Custo da melhor solução global encontrada. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo minimiza ou maximiza a função de custo. | + +--- + +## Métodos abstratos + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Executa o processo de otimização. +Este método abstrato é implementado é responsabilidade das classes filhas, definindo a estratégia de otimização. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|----------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem atualização da melhor solução. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Avalia a afinidade (qualidade) de uma solução candidata. + +Este método deve ser implementado conforme o problema de otimização específico, definindo como a solução sera medida. +O valor retornado deve representar a qualidade da solução avaliada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|-------|:------:|--------------------------------------| +| `solution` | `Any` | - | Solução candidata que será avaliada. | + +**Returns** + +| Tipo | Descrição | +|---------|------------------------------------------------| +| `float` | Valor de custo associada a solução encontrada. | + +--- + +## Métodos públicos + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Gera um relatorio resumindo e formatado do processo de otimização. +O relatorio incluir a melhor solução, seu custo, e a evolução dos valores a cada iteração. + +**Returns** + +| Tipo | Descrição | +|-------|-------------------------------------------------------| +| `str` | Uma string formatada contendo o resumo da otimização. | + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Registra dinamicamente uma função na instância do otimizador. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|----------------------|:------:|----------------------------------------------------| +| `alias` | `str` | - | Nome usado para acessar a função como um atributo. | +| `function` | `Callable[..., Any]` | - | Função que será registrada. | + +**Exceções** + +| Exceção | Descrição | +|------------------|----------------------------------------------------------------------------------| +| `TypeError` | Se a `function` fornecida não for uma função valida. | +| `AttributeError` | Se o `alias` for protegido e não puder ser modificado, ou não existir na classe. | + + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reseta o estado interno do objeto, limpando histórico e restaurando valores iniciais. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/README.md new file mode 100644 index 000000000..82f011022 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - célula + - mutações + - populações +--- + +# aisp.base.immune + +Módulo de suporte para sistemas imunológicos artificias. + +> **Módulo:** `aisp.base.immune` + +## Submódulos + +| Módulos | Descrição | +|-----------------------------------|------------------------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./mutation.md) | Funções para gerar clones hipermutados similar a expansão clonal. | +| [`populations`](./populations.md) | Fornece funções utilitárias para gerar populações de anticorpos utilizadas em algoritmos imuno-inspirados. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/README.md new file mode 100644 index 000000000..f57ae065d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/README.md @@ -0,0 +1,32 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representação de células do sistema imunológico. + +> **Módulos:** `aisp.base.immune.cell` + +## Visão geral + +Este módulo define as representações de células dos sistemas imunológicos artificiais e as implementa como dataclass. + +## Classes + +| Class | Descrição | +|-----------------------------|----------------------------------------------------| +| [`Cell`](./c-cell.md) | Representa uma célula imune básica. | +| [`BCell`](./b-cell.md) | Representa uma célula-B de memória. | +| [`Antibody`](./antibody.md) | Representa um anticorpo. | +| [`Detector`](./detector.md) | Representa um detector não-próprio da classe rnsa. | \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/antibody.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/antibody.md new file mode 100644 index 000000000..79f595c84 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - anticorpo + - afinidade + - célula + - imune + - dataclass +--- + +# Antibody + +Representa um anticorpo. + +:::tip[Herança] + +Esta classe herda de [Cell](./c-cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Antibody` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|----------------------------------------| +| `vector` | `npt.NDArray` | - | Vetor com as características anticorpo | +| `affinity` | `float` | - | Valor da afinidade do anticorpo | + +--- + +## Métodos + +* `__lt__(other)`: Compara a célula atual com outra célula `Antibody` com base na afinidade. +* `__eq__(other)`: Verifica se o anticorpo possui a mesma afinidade do outro. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/b-cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/b-cell.md new file mode 100644 index 000000000..b16f40375 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/b-cell.md @@ -0,0 +1,63 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - célula-b + - memória imune + - dataclass + - mutação clonal + - expansão clonal +--- + +# BCell + +Representa uma célula-B de memória. + +:::tip[Herança] + +Esta classe herda de [Cell](./c-cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import BCell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos Públicos + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Gera **N** clones da célula atual e aplica hipermutação aos clones. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|------------------------------------------------------|:-----------------------:|-----------------------------------------------------------------| +| `n` | `int` | - | Numero de clones que serão gerados a partir da célula original. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Especifica o tipo de características da célula. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Matriz (n_features, 2) com o min e o max de cada dimensão. | + +**Returns** + +| Tipo | Descrição | +|---------------|----------------------------------------------------------| +| `npt.NDArray` | Uma matriz contendo N clones mutados da célula original. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/c-cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/c-cell.md new file mode 100644 index 000000000..0d7955c64 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/c-cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Representa uma célula imune básica. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Cell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base nos seus vetores. +* `__array__()`: Interface de array Numpy, permite que a instância seja tratada como um `np.ndarray` +* `__getitem__(item)`: Obtém um elemento do vetor com base no index. + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/detector.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/detector.md new file mode 100644 index 000000000..71fcfdc64 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - célula + - imune + - raio + - não-próprio + - nsa + - dataclass +--- + +# Detector + +Representa um detector não-próprio da classe rnsa. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Detector` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------------------|:------:|--------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Vetor com as características do detector. | +| `radius` | `float, optional` | - | Raio do detector, usado no algoritmo V-detector. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/mutation.md new file mode 100644 index 000000000..38fc658b5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/mutation.md @@ -0,0 +1,146 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutações + - expansão clonal + - sistema imune + - funções python com numba + - vetor de mutações +--- + +# mutation + +As funções utilizam decoradores do Numba para compilação Just-In-Time(JIT). + +Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o +processo +de expansão clonal dos sistemas imunológicos artificiais. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import mutation` + +## Funções + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor contínuo. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados que serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Gera um conjunto de clones mutados a partir de um vetor binário. + +Esta função cria `n` clones do vetor binário de entrada e aplica mutações aos bits, simulando a expansão +clonal em sistemas imunes artificiais com representações discretas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor binário original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|-------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de uma célula representada pelo intervalo personalizados por dimensão.. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor contínuo original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) com valor mínimo e máximo por dimensão. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | + +### clone_and_mutate_continuous + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +``` + +Gera um conjunto de clones com mutações por permutação. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-------------------------|:------:|------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | Vetor de permutação original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Probabilidade de mutação de uma característica. | + +**Returns** + +| Tipo | Descrição | +|---------------------------|----------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/populations.md new file mode 100644 index 000000000..5f4a49ee6 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/base/immune/populations.md @@ -0,0 +1,57 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binário + - classificação + - limiar de afinidade + - real-valor + - célula-b de memória + - expansão clonal + - população +--- + +# populations + +Fornece funções utilitárias para **gerar populações** de anticorpos utilizadas em algoritmos imuno-inspirados. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import populations` + +## Funções + +### generate_random_antibodies + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +``` + +Gera uma população aleatória de anticorpos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|---------------------------------------------------------|:-----------------------:|--------------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Número de anticorpos (amostras) que serão gerados. | +| `n_features` | `int` | - | Número de características (dimensões) para cada anticorpo. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. | + + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------------------------------------------------| +| `npt.NDArray` | Array de dimensão (n_samples, n_features) contendo os anticorpos gerados. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-----------------------------------------------------------| +| `ValueError` | Se o número de características for menor ou igual a zero. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/README.md new file mode 100644 index 000000000..39f9597c9 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - sistema imunológico + - seleção clonal + - clonalg + - airsv2 + - proliferação de anticorpos + - mutações + - algoritmos de seleção clonal + - sistemas imunológicos artificiais + - classificação + - otimização +--- + +# aisp.csa + +Módulo com algoritmos de seleção clonal (ASC). + +> **Módulo:** `aisp.csa` + +## Visão geral + +Os **ASCs** são inspirados no processo de proliferação de anticorpos ao detectar o antígeno, no qual os clones gerados +passam por mutações na tentativa de melhorar o reconhecimento dos patógenos. + +## Classes + +| Class | Descrição | +|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | Um algoritmos supervisionado para tarefas de classificação. | +| [`Clonalg`](./clonalg.md) | Esta implementação do ASC para otimização, foi adaptado tanto para minimização quanto maximização de custos em problemas binários, contínuos e de permutação. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md new file mode 100644 index 000000000..c0cd9b693 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md @@ -0,0 +1,196 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classificação + - sistema imunológico artificial de reconhecimento + - células de memória + - k-nn + - aprendizado supervisionado + - AIRS2 + - seleção clonal +tags: + - classificação + - supervisionado + - seleção clonal +--- + +# AIRS + +Sistema Imunológico Artificial de Reconhecimento (AIRS) + +:::tip[Herança] + +Esta classe herda de [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Módulo:** `aisp.csa` +> **Importação:** `from aisp.csa import AIRS` + +--- + +## Visão geral + +O _Artificial Immune Recognition System_ (AIRS) é um algoritmo de classificação inspirado no processo de seleção +clonal. Esta implementação é baseada na versão simplificada (AIRS2) descrita em [^1]. O algoritmo foi adaptado +para suportar amostras com características com valores reais (contínuos) e binários (discretos). + +:::note + +Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo +adaptações para lidar com conjuntos de dados contínuos e binários. + +Baseado no Algorithm 16.5 de Brabazon et al. [^1] + +Trabalhos relacionados e notáveis: [^2]. + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Gerando dados para o treinamento +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# Instancia do AIRS +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` + +Output: + +```bash +[0 1] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-----------------------------|---------|:-------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Quantidade total de recursos disponíveis. | +| `rate_clonal` | `int` | `10` | Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * rate_hypermutation) para definir o número de clones. | +| `rate_mc_init` | `float` | `0.2` | Porcentagem de amostras usadas para inicializar a população de células de memória. | +| `rate_hypermutation` | `float` | `0.75` | Taxa de clones mutados derivada de rate_clonal como um fator escalar. | +| `affinity_threshold_scalar` | `float` | `0.75` | Limiar de afinidade normalizado. | +| `k` | `int` | `3` | Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. | +| `max_iters` | `int` | `100` | Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. | +| `resource_amplified` | `float` | `1.0` | Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. | +| `metric` | `str` | `"euclidean"` | Métrica de distância usada para calcular a afinidade entre células e amostras. | +| `seed` | `int` | `None` | Seed para geração aleatória. | +| `p` | `float` | `2` | Este parâmetro é usado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------------|-------------------------------------------|:------:|--------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Armazena as células de memória por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` + +Treina o modelo com os dados de entrada utilizando o algoritmo AIRS2. + +A função `fit(...)`, realiza o treinamento de acordo com X e y, usando o método AIRS. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-------------|---------------------------------------------------------------| +| `TypeError` | Se X ou y não forem arrays ou tiverem tamanhos incompatíveis. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prevê os rótulos dos dados de testes com base nas células de memórias criadas durante o treinamento. + +Este método utiliza as células de memórias para classificar os dados de entrada usando a abordagem dos k-vizinhos mais +próximos (K-NN). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|----------------------------------------------------------------------| +| `npt.NDArray` | Array no formato `n_samples` contendo as classes previstas para `X`. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for um ndarray ou list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de características em X não corresponder ao esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir o conjunto de células de memoria. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunologico-artificial-de-reconhecimento) + +--- + +## Referências + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md new file mode 100644 index 000000000..32114aac5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md @@ -0,0 +1,185 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - otimização + - seleção clonal + - clonalg + - população de anticorpos + - função de custo +tags: + - otimização + - seleção clonal + - minimização + - maximização + - binário + - contínuos + - permutação + - ranged +--- + +# Clonalg + +Algoritmo de Seleção Clonal (CLONALG). + +:::tip[Herança] + +Esta classe herda de [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Módulo:** `aisp.csa` +> **Importação:** `from aisp.csa import Clonalg` + +--- + +## Visão geral + +O _Clonal Selection Algorithm (CSA)_ é um algoritmo de otimização inspirado no processo biológico de seleção e expansão +clonal dos anticorpos do sistema imunológico [^1]. Esta implementação do clonalg foi adaptada para minimização e +maximização da função de custo em problemas binários, contínuos, com intervalo de valor e de permutação. + +:::note + +Esta implementação do CLONALG contem modificações para o pacote AISP, com intuito da aplicação geral em diferentes +tipos de problemas, o que pode resultar em comportamentos diferentes de implementações focada em um problema específico. +A adaptação visa generalizar o uso do CLONALG para tarefas de minimização e maximização, além de oferecer suporte +a problemas binários, contínuos, com intervalo de valor e de permutação + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.csa import Clonalg + +# Limites do espaço de busca +bounds = {'low': -5.12, 'high': 5.12} + + +# Função de custo +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x ** 2 - 10 * np.cos(2 * np.pi * x)) + + +# Instância do CLONALG +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` + +**Output:** + +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-------------------------|------------------------------------------------------|:-------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimensão do problema que será otimizado. | +| `N` | `int` | `50` | Número de células de memória (anticorpos) na população. | +| `rate_clonal` | `int` | `10` | Número máximo de clones possíveis de uma célula. Esse valor é multiplicado pela afinidade da célula para definir o número de clones. | +| `rate_hypermutation` | `float` | `1.0` | Taxa de hipermutação que controla a intensidade das mutações durante a expansão clonal. valores maiores reduzem a intensidade, enquanto menores aumentam. | +| `n_diversity_injection` | `int` | `5` | Número de novas células de mémoria aleatórias inseridas para manter a diversidade. | +| `selection_size` | `int` | `5` | Número dos melhores anticorpos selecionados para a clonagem. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Função objetiva usada para avaliar as soluções candidatas durante a otimização. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Tipo de representação das soluções: binária, contínua, com intervalo de valor e para permutação. | +| `bounds` | `Optional[Dict]` | `None` | Define os limites no espaço de busca quando ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo realiza minimização ou maximização da função de custo. | +| `seed` | `int` | `None` | Seed para geração aleatória. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------|----------------------------|:------:|--------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | População de anticorpos. | + +--- + +## Métodos Públicos + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Realiza o processo de otimização e retorna a população de anticorpos resultante. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|-------------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações na busca da melhor solução do problema usando o CLONALG. | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem melhoria na melhor solução global encontrada. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso na busca do melhor anticorpo deve ser exibido. | + +**Returns** + +| Tipo | Descrição | +|------------------|-----------------------------------------------------------| +| `List[Antibody]` | População de anticorpos após a expansão e seleção clonal. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------|----------------------------------------------------------------------| +| `NotImplementedError` | Se a função de afinidade não for fornecida para avaliar as soluções. | + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Avalia a afinidade de uma solução candidata. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|--------------------------------------| +| `solution` | `npt.NDArray` | - | Solução candidata que será avaliada. | + +**Returns** + +| Tipo | Descrição | +|--------------|---------------------------------------------------| +| `np.float64` | Valor de afinidade da solução candidata avaliada. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------|---------------------------------------------------| +| `NotImplementedError` | Se a função de afinidade não tiver sido definida. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-selecao-clonal) + +--- + +## Referências + +[^1]: BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired + Programming Recipes., 2011. Available at: + https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/exceptions.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/exceptions.md new file mode 100644 index 000000000..500c4e6a5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/exceptions.md @@ -0,0 +1,91 @@ +--- +id: exceptions +sidebar_label: aisp.exceptions +keywords: + - exceptions + - Exceções + - warnings +--- + +# aisp.exceptions + +Avisos e erros personalizados. + +> **Módulo:** `aisp.exceptions` +> **Importação:** `from aisp import exceptions` + +## Classes de exceção + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exceção lançada quando o número máximo de descartes do detector é atingido. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|---------------|-----------------|:------:|------------------------------------------| +| `object_name` | `str` | - | O nome da classe que lança a exceção. | +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exceção lançada quando o número de características (dimensões) de entrada não corresponde ao esperado. +Essa exceção é acionada durante a predição se a quantidade de características estiver incorreta. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-----------------|:------:|---------------------------------------------| +| `expected` | `int` | - | O número esperado de características. | +| `received` | `int` | - | O número real de características recebidas. | +| `variable_name` | `Optional[str]` | `None` | O nome da variável que causou o error. | + +--- + +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exceção lançada quando o tipo de dados do vetor de entrada não é suportado. +Essa exceção é lançada quando o tipo de dado do vetor não corresponde a nenhum dos suportados. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|-----------------|:------:|------------------------------------------| +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | + +--- + +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exceção lançada quando o método é chamado antes que o modelo ter sido treinado. +Essa exceção ocorre quando a instância do modelo é utilizada sem que ele tenha sido previamente treinado +por meio do método `fit`. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|---------------|-----------------|:------:|------------------------------------------| +| `object_name` | `str` | - | O nome da classe que lança a exceção. | +| `message` | `Optional[str]` | `None` | Mensagem personalizada que será exibida. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/README.md new file mode 100644 index 000000000..2b737381b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/README.md @@ -0,0 +1,30 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - sistema imunológico + - seleção clonal + - rede imunológica + - ainet + - opt-ainet + - mutações + - sistemas imunológicos artificiais + - clusterização + - otimização +--- + +# aisp.ina + +Módulo com Algoritmos de Rede Imunológica (ARI). + +> **Módulo:** `aisp.ina` + +## Visão geral + +Este módulo implementa algoritmos inspirados na teoria das redes imunológicas proposta por Jerne. + +## Classes + +| Class | Descrição | +|------------------------|-------------------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | Um algoritmo não supervisionado para agrupamentos de dados, baseado na teoria das redes imunológicas. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md new file mode 100644 index 000000000..cd89715ec --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md @@ -0,0 +1,222 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - rede imunológica + - agrupamento + - compressão de dados + - aprendizado não supervisionado + - Minimum Spanning Tree +tags: + - agrupamento + - não supervisionado + - rede imunológica +--- + +# AiNet + +Rede Imunológica Artificial (AiNet) para agrupamento e compressão. + +:::tip[Herança] + +Esta classe herda de [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Módulo:** `aisp.ina` +> **Importação:** `from aisp.ina import AiNet` + +--- + +## Visão geral + +Esta classe implementa o algoritmo AiNet é projetado para tarefas de agrupamento +e compressão de dados; O algoritmo é inspirado na teoria da rede imunológica, seleção clonal e maturação por afinidade para +reduzir conjuntos de dados com muitas amostras [^1]. +No agrupamento a classe utiliza a implementação da Scipy da **Árvore geradora mínima** para separa as arestas mais +distantes em grupos de dados [^2]. + +--- + +## Exemplo + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Gerando dados de treinamento +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# Instância do AiNet +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Esperado: rótulo 0 + [0.85, 0.65], # Esperado: rótulo 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +[0 1] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|----------------------------|----------------------------------------------|:-------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Número de células de memória (anticorpos) para iniciar a população. | +| `n_clone` | `int` | `10` | Número de clones gerados para cada célula de memória selecionada. | +| `top_clonal_memory_size` | `int` | `5` | Número de anticorpos com maior afinidade que selecionados para a clonagem e mutação. | +| `n_diversity_injection` | `int` | `5` | Número de novas células de memória aleatórias que serão inseridas para manter a diversidade. | +| `affinity_threshold` | `float` | `0.5` | Limiar de afinidade (similaridade) parta determinar a supressão das células. | +| `suppression_threshold` | `float` | `0.5` | Limiar de supressão das células de memórias semelhantes. | +| `mst_inconsistency_factor` | `float` | `2.0` | Fator usado para determinar quais arestas da Árvore Geradora Mínima (MST) são consideradas inconsistentes. | +| `max_iterations` | `int` | `10` | Número máximo de iterações de treinamento. | +| `k` | `int` | `3` | Número de vizinhos mais próximos usados para predição de rótulos. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Métrica de distância utilizada para calcular a similaridade entre as células de memória. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `use_mst_clustering` | `bool` | `True` | Quando `True`, realiza o agrupamento utilizando a MST. Se `False`, o agrupamento não é executado e o método predict lança uma exceção ModelNotFittedError. | +| `p` | `float` | `2.0` | Parâmetro `p` utilizado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------------------|-------------------------|:------:|-------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | Rede imunológica que representa os clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | População de anticorpos de memória. | +| `mst` | `dict` | - | Árvore geradora minima com estatísticas (graph, mean_distance, std_distance). | + +--- + +## Métodos Públicos + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Treina o modelo com os dados de entrada utilizando o algoritmo AiNet. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------|----------------------------------------------------------| +| `TypeError` | Se `X` não for um ndarray ou list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | Se o tipo das características em X não forem suportados. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever os rótulos dos clusters para os dados de entrada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------------------| +| `npt.NDArray` | Rótulos previstos para os dados de entrada. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se X contiver valores diferentes de (0 e 1) ou (True e False), quando as características treinadas forem do tipo `'binary-features'` | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de dimensões em X não corresponder ao esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir o conjunto de células de memória. | + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` + +Agrupa os clusters com base no fator de inconsistência da MST. + +Utiliza a Árvore Geradora Mínima (MST) criada a partir da população de anticorpos para redefinir os clusters. +As arestas cujos pesos excedem a média somada ao valor de `mst_inconsistency_factor` multiplicado pelo desvio padrão +dos pesos das arestas são removidas. Cada grafo conectado após essa poda é tratado como um grupo distinto. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------------------|---------|:------:|------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | Sobrescrever o fator de inconsistência da MST. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-------------------------------------------------------------------------------| +| `ValueError` | Se a Árvore Geradora Mínima (MST) ainda não tiver sido criada. | +| `ValueError` | Se a população de anticorpos estiver vazia. | +| `ValueError` | Se as estatísticas da MST (média ou desvio padrão) não estiverem disponíveis. | + +**Updates** + +| Nome | Tipo | Descrição | +|------------------|--------------------------|---------------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dicionário de rótulos de clusters para vetores de anticorpos. | +| `labels` | `list` | Lista de rótulos de clusters. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunologica-artificial) + +--- + +## Referências + +[^1]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/README.md new file mode 100644 index 000000000..cb0335739 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/README.md @@ -0,0 +1,34 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - sistemas imunológicos artificiais + - classificação + - seleção negativa + - características binárias + - detecção de anomalias + - reconhecimento de não-próprio + - reconhecimento de padrões + - multiclasse + - valores reais + - v-detector +--- + +# aisp.nsa + +Módulo com Algoritmo de Seleção Negativa (NSA). + +> **Módulo:** `aisp.nsa` + +## Visão geral + +NSAs simulam o processo de maturação das células T no sistema imunológico, no qual essas células aprendem a distinguir +entre próprio e não-próprio. Apenas as células T capazes de reconhecer elementos não-próprios são preservadas. + +## Classes + +| Class | Descrição | +|---------------------|----------------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | Um algoritmo de aprendizado supervisionado para classificação de dados com valores reais. | +| [`BNSA`](./bnsa.md) | Um algoritmo de aprendizado supervisionado para classificação de dados com valores binárias. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md new file mode 100644 index 000000000..81f2ffed8 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md @@ -0,0 +1,192 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - seleção negativa + - características binárias + - detecção de anomalias + - reconhecimento do não-próprio + - reconhecimento de padrões + - classificação + - multiclasses +tags: + - classificação + - supervisionado + - seleção negativa + - características binárias + - detecção de anomalias +--- + +# BNSA + +Algoritmo de Seleção Negativa Binária (BNSA). + +:::tip[Herança] +Esta classe herda de [BaseClassifier](../base/base-classifier.md) +::: + + +> **Módulo:** `aisp.nsa` +> **Importação:** `from aisp.nsa import BNSA` + +--- + +## Visão geral + +Algoritmo para classificação e detecção de anomalias baseado na distinção entre próprio e não-próprio, inspirado +no algoritmo de seleção negativa. + +:::note + +O _**Binary Negative Selection Algorithm (BNSA)**_ é baseado na proposta original de Forrest et al. (1994) [^1], +desenvolvido para segurança na computação. Nesta adaptação, o algoritmo usa arrays de bits e possuir suporte para +classificação multiclasse. + +::: + +:::warning + +Valores altos de `aff_thresh` podem impedir que gere detectores válidos para a detecção do não-próprio. + +::: + +--- + +## Exemplo + +```python +from aisp.nsa import BNSA + +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ + ...[1, 1, 1, 1, 1], # Sample of Anomaly + ...[0, 1, 0, 1, 0], # self sample + ...] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` + +**Output** + +```bash +['non-self' 'self'] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|-----------------------------|-----------------|:--------------------------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Quantidade de detectores. | +| `aff_thresh` | `float` | `0.1` | Representa a porcentagem de similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de similaridade. | +| `max_discards` | `int` | `1000` | Número máximo de descartes de detectores em sequência, com o objetivo de evitar um possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Método utilizado para a escolha de rótulos para amostras classificada como não-próprio por todos os detectores. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------|-----------------------------------------------------|:------:|-------------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | Conjunto de detectores, organizados por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Treinamento de acordo com X e y, utilizando o algoritmo de seleção negativa. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X ou y não forem ndarrays ou tiverem tamanhos incompatíveis. | +| `ValueError` | Se X possuir valores diferentes de (0 e 1) ou (True e False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | Se o número máximo de descartes for atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever as classes com base nos detectores gerados após o treinamento. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-----------------------------------------------------------------| +| `npt.NDArray` | Array `C` (`n_samples`), contendo as classes prevista para `X`. | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se X possuir valores diferentes de (0 e 1) ou (True e False). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de característica (colunas) em X não corresponder ao valor esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir detectores ou classes definidas. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-selecao-negativa-binaria) + +--- + +## Referências + +[^1]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md new file mode 100644 index 000000000..2fee71a00 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md @@ -0,0 +1,222 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - seleção negativa + - detecção de anomalias + - reconhecimento do não-próprio + - reconhecimento de padrões + - classification + - real-valued + - v-detector + - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection +--- + +# RNSA + +Algoritmo de Seleção Negativa com valores reais (RNSA). + +:::tip[Herança] + +Esta classe herda de [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Módulo:** `aisp.nsa` +> **Importação:** `from aisp.nsa import RNSA` + +--- + +## Visão geral + +Algoritmo para classificação e detecção de anomalias baseado na distinção entre próprio e não-próprio, inspirado +no algoritmo de seleção negativa. + +:::note + +Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [^1] e outra com detectores com raio +variável [^2]. Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de +dados presentes na região não-self de todos os detectores e classes. + +::: + +:::warning + +Os parâmetros `r` e `r_s` podem impedir a geração de detectores válidos. Um valor para `r` muito pequeno pode limitar +a cobertura, enquanto muito alto pode dificultar a geração de detectores validos. Da mesma forma, um `r_s` alto +pode limitar a criação de detectores. Portanto, o ajuste adequado de `r` e `r_s` é essencial para garantir um bom +desempenho do algoritmo. + +::: + +--- + +## Exemplo + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Exemplo 1:** Classificação multiclasse (RNSA suporta duas ou mais classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +['a' 'b'] +``` + +**Exemplo 2:** Detecção de anomalias (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` + +**Output** + +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Default | Descrição | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Quantidade de detectores. | +| `r` | `float` | `0.05` | Raio do detector. | +| `r_s` | `float` | `0.0001` | O valor de rₛ é o raio das amostras próprias dos dados de treinamento X. | +| `k` | `int` | `1` | Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Métrica de distância usada para calcular a distância entre o detector e a amostra. | +| `max_discards` | `int` | `1000` | Número máximo de descartes de detectores em sequência, que tem como objetivo evitar um possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. | +| `seed` | `Optional[int]` | `None` | Seed para geração aleatória. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Define a versão do algoritmo. | +| `non_self_label` | `str` | `'non-self'` | Rótulo atribuído quando há apenas uma classe de saída e a amostra não pertence a essa classe. | +| `cell_bounds` | `bool` | `False` | Se definido como True, esta opção limita a geração dos detectores ao espaço do plano compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, e esta variável é usada exclusivamente no algoritmo `V-detector`. | +| `p` | `float` | `2.0` | Valor de `p` utilizado na distância de Minkowski. | + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-------------|----------------------------------------------|:------:|-------------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | Conjunto de detectores, organizados por classe. | + +--- + +## Métodos Públicos + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Treinamento de acordo com X e y, utilizando o algoritmo de seleção negativa. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada para treinamento. Cada linha corresponde a uma amostra e cada coluna a uma característica. | +| `y` | `Union[npt.NDArray, list]` | - | Vetor alvo no formato (n_samples,). Deve conter o mesmo número de amostras que X. | +| `verbose` | `bool` | `True` | Se True, exibe informações sobre o progresso do treinamento. | + +**Returns** + +| Tipo | Descrição | +|--------|--------------------------------| +| `Self` | Retorna a instancia da classe. | + +**Exceções** + +| Exceção | Descrição | +|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se X ou y não forem ndarrays ou tiverem tamanhos incompatíveis. | +| `ValueError` | Se os valores de X estiverem fora do intervalo (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | Se o número máximo de descartes for atingido durante a maturação. Verifique o valor do raio definido e considere reduzi-lo. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prever as classes com base nos detectores gerados após o treinamento. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|----------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Amostras de entrada. Deve ter o mesmo número de características usadas no treinamento. | + +**Returns** + +| Tipo | Descrição | +|---------------|-----------------------------------------------------------------| +| `npt.NDArray` | Array `C` (`n_samples`), contendo as classes prevista para `X`. | + +**Exceções** + + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------| +| `TypeError` | Se X não for ndarray ou list. | +| `ValueError` | Se os valores de X estiverem fora do intervalo (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de característica (colunas) em X não corresponder ao valor esperado. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | Se o modelo ainda não tiver sido treinado e não possuir detectores ou classes definidas. | + +--- + +## Exemplos Estendidos + +Exemplos completos de uso estão disponíveis nos notebooks Jupyter: + +- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-selecao-negativa-de-valores-reais) + +--- + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/README.md new file mode 100644 index 000000000..5b805d884 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/README.md @@ -0,0 +1,28 @@ +--- +id: utils +sidebar_label: aisp.utils +keywords: + - functions + - helpers + - utils +--- + +# aisp.utils + +Funções utilitárias para auxiliar o desenvolvimento. + +> **Módulo:** `aisp.utils` +> **Importação:** `from aisp import utils` + +## SubMódulos + +| Módulo | Descrição | +|----------------------------------|------------------------------------------------------------------------------------| +| [`display`](./display/README.md) | Funções utilitárias para exibir informações de algoritmos. | +| [`distance`](./distance.md) | Funções utilitárias para cálculo de distância entre vetores com decoradores numba. | +| [`metrics`](./metrics.md) | Funções utilitárias para medir acurácia e desempenho. | +| [`multiclass`](./multiclass.md) | Funções utilitárias para lidar com dados com múltiplas classes. | +| [`sanitizers`](./sanitizers.md) | Funções utilitárias para validação e tratamento de parâmetros. | +| [`types`](./types.md) | Define aliases de tipos usados em todo o pacote para melhorar a legibilidade. | +| [`validation`](./validation.md) | Contém funções responsáveis pela validação de tipos de dados. | + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/README.md new file mode 100644 index 000000000..20c462cdc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/README.md @@ -0,0 +1,23 @@ +--- +id: display +sidebar_label: display +keywords: + - tabela + - progresso +--- + +# display + +Funções utilitárias para exibir informações de algoritmos. + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Descrição | +|------------------------------------------|---------------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Formata dados em tabelas para exibição no console. | +| [`ProgressTable`](./progress-table.md) | Exibe uma tabela formatada no console para acompanhar o progresso do algoritmo. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/progress-table.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/progress-table.md new file mode 100644 index 000000000..73c24ebf7 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Exibe uma tabela formatada no console para acompanhar o progresso do algoritmo. + +:::tip[Herança] + +Esta classe herda de [TableFormatter](./table-formatter.md). + +::: + + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils.display import ProgressTable` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Padrão | Descrição | +|-----------|---------------------|:------:|---------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapeamento `{nome_da_coluna: largura_da_coluna}`. | +| `verbose` | `bool` | `True` | Se False, não imprime nada no terminal. | + +--- + +## Métodos Públicos + +### update + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +``` + +Adiciona uma nova linha de valores à tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------------------|:------:|---------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | As chaves devem corresponder às colunas definidas em headers. | + +--- + +### finish + +```python +def finish(self) -> None: + ... +``` + +Finaliza a exibição da tabela, imprimindo a borda inferior e o tempo total. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/table-formatter.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/table-formatter.md new file mode 100644 index 000000000..56aaaba66 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/display/table-formatter.md @@ -0,0 +1,84 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Formata dados em tabelas para exibição no console. + +> **Módulo:** `aisp.utils.display` +> **Importação:** `from aisp.utils.display import TableFormatter` + +--- + +## Parâmetros do Construtor + +| Nome | Tipo | Padrão | Descrição | +|-----------|---------------------|:------:|--------------------------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapeamento dos nomes das colunas para suas respectivas larguras, no formato `{nome_da_coluna: largura_da_coluna}`. | + +--- + +## Métodos Públicos + +### get_header + +```python +def get_header(self): + ... +``` + +Gera o cabeçalho da tabela, incluindo a borda superior, os nomes das colunas e a linha separadora. + +**Returns** + +| Tipo | Descrição | +|-------|---------------------------------------| +| `str` | String formatada do header da tabela. | + +--- + +### get_row + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +``` + +Gera uma linha formatada para os dados da tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------------------|:------:|--------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dicionário com valores para cada coluna, no formato `{nome_da_coluna: valor}`. | + +**Returns** + +| Tipo | Descrição | +|-------|--------------------------------------| +| `str` | String formatada da linha da tabela. | + +--- + +### get_bottom + +```python +def get_bottom(self, new_line: bool = False): + ... +``` + +Gera a borda inferior da tabela. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|--------|:-------:|----------------------------------------------------------------------------| +| `new_line` | `bool` | `False` | Se `True`, adiciona uma quebra de linha antes da borda (padrão é `False`). | + +**Returns** + +| Tipo | Descrição | +|-------|-------------------------------------| +| `str` | String formatada da borda inferior. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/distance.md new file mode 100644 index 000000000..784cb4faa --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/distance.md @@ -0,0 +1,241 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distância +--- + +# distance + +Funções utilitárias para cálculo de distância entre vetores com decoradores numba. + +> **Módulo:** `aisp.utils.distance` +> **Importação:** `from aisp.utils import distance` + +## Funções + +### hamming + +```python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +``` + +Calcula a distância de Hamming entre dois pontos. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|-------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-----------------------------------------| +| `float64` | Distância de Hamming entre dois pontos. | + +--- + +### euclidean + +```python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +``` + +Calcula a distância de Euclidean entre dois pontos. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Euclidean entre dois pontos. | + +--- + +### cityblock + +```python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +``` + +Calcula a distância de Manhattan entre dois pontos. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|--------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Manhattan entre dois pontos. | + +--- + +### minkowski + +```python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +``` + +Calcula a distância de Minkowski entre dois pontos. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|------------------------|:------:|------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | +| `p` | `float` | `2.0` | Parâmetro que define o tipo de distância a ser calculada. | + +:::note[Parâmetro `p`] + +- p = 1: distância **Manhattan** - soma das diferenças +- p = 2: distância **Euclidean** - soma dos quadrados (raiz quadrada). +- p > 2: distância **Minkowski** com penalização crescente conforme `p` aumenta. + +::: + +**Returns** + +| Tipo | Descrição | +|-----------|-------------------------------------------| +| `float64` | Distância de Minkowski entre dois pontos. | + +--- + +### compute_metric_distance + +```python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +``` + +Calcula a distância entre dois pontos com base na métrica escolhida. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|------------------------|:------:|------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordenadas do primeiro ponto. | +| `v` | `npt.NDArray[float64]` | - | Coordenadas do segundo ponto. | +| `metric` | `int` | - | Métrica de distância que será usada. Opções: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | Parâmetro que define o tipo de distância a ser calculada | + +**Returns** + +| Tipo | Descrição | +|-----------|-----------------------------------------------------------| +| `float64` | Distância entre os dois pontos com a métrica selecionada. | + +--- + +### min_distance_to_class_vectors + +```python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +``` + +Calcula distância entre um vetor de entrada e os vetores de uma classe e retorna a distância minima. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|------------------------|:------:|---------------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array contendo os vetores da classe a serem comparados com o vetor de entrada. Formato esperado: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | Vetor a ser comparado com os vetores da classe. Formato esperado: (n_features,). | +| `metric` | `int` | - | Métrica de distância a ser usada. Opções: 0 ("euclidean"), 1 ("manhattan"), 2 ("minkowski") or ("hamming") | +| `p` | `float` | `2.0` | Parâmetro da distância de Minkowski (usado apenas quando metric="minkowski"). | + +**Returns** + +| Tipo | Descrição | +|---------|--------------------------------------------------------------------------------------------------------------------------------| +| `float` | A menor distância calculada entre o vetor de entrada e os vetores da classe. Retorna -1.0 se as dimensões forem incompatíveis. | + +--- + +### get_metric_code + +```python +def get_metric_code(metric: str) -> int: + ... +``` + +Obtém o valor associado a uma métrica de distância. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|-------|:------:|---------------------------------------------------------------------------------------| +| `metric` | `str` | - | Nome da métrica. Pode ser `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Returns** + +| Tipo | Descrição | +|-------|----------------------------------| +| `int` | Número correspondente à métrica. | + +**Exceções** + +| Exceção | Descrição | +|--------------|-------------------------------------------| +| `ValueError` | Se a métrica fornecida não for suportada. | + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/metrics.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/metrics.md new file mode 100644 index 000000000..830911a0c --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/metrics.md @@ -0,0 +1,47 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Funções utilitárias para medir acurácia e desempenho. + +> **Módulo:** `aisp.utils.metrics` +> **Importação:** `from aisp.utils import metrics` + +## Funções + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calcula a acurácia com base nos rótulos reais e previstos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|----------------------------|:------:|-------------------------------------------------------------------| +| `y_true` | `Union[npt.NDArray, list]` | - | Rótulos reais (corretos). Devem ter o mesmo tamanho que `y_pred`. | +| `y_pred` | `Union[npt.NDArray, list]` | - | Rótulos previstos. Devem ter o mesmo tamanho que `y_true`. | + +**Returns** + +| Tipo | Descrição | +|---------|--------------------------------------------------------------------| +| `float` | A proporção de previsões corretas em relação ao total de previsões | + +**Exceções** + +| Exceção | Descrição | +|--------------|--------------------------------------------------------------------------| +| `ValueError` | Se y_true ou y_pred estiverem vazios ou se não tiverem o mesmo tamanho. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/multiclass.md new file mode 100644 index 000000000..d06c26dbc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/multiclass.md @@ -0,0 +1,82 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Funções utilitárias para lidar com dados com múltiplas classes. + +> **Módulo:** `aisp.utils.multiclass` +> **Importação:** `from aisp.utils import multiclass` + +## Funções + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separa os índices das amostras por classe para iteração direcionada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|--------------------------------------|:------:|-----------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | lista com classes únicas. | +| `y` | `npt.NDArray` | - | Recebe um array `y` (`n_samples`) om as classes de saída do array de amostra `X`. | + +**Returns** + +| Tipo | Descrição | +|--------|---------------------------------------------------------------------------------| +| `dict` | Um dicionário com a lista de posições do array(`y`), com as classes como chave. | + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### predict_knn_affinity + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray: + ... +``` + +Prever classes usando k-vizinhos mais próximos e células treinadas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-----------------------------------------------|:------:|-----------------------------------------------------------------| +| `X` | `npt.NDArray` | - | Dados de entrada a serem classificados. | +| `k` | `int` | - | Número de vizinhos mais próximos a considerar para a previsão. | +| `all_cell_vectors` | `List[Tuple[Union[str, int], npt.NDArray]]` | - | Lista de tuplas contendo (nome_da_classe, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Função que recebe dois vetores e retorna um valor de afinidade. | + +**Returns** + +| Tipo | Descrição | +|---------------|------------------------------------------------------------------------------------------| +| `npt.NDArray` | Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/sanitizers.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/sanitizers.md new file mode 100644 index 000000000..6636f664f --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/sanitizers.md @@ -0,0 +1,119 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Funções utilitárias para validação e tratamento de parâmetros. + +> **Módulo:** `aisp.utils.sanitizers` +> **Importação:** `from aisp.utils import sanitizers` + +## Funções + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------|:------:|-------------------------------------------------------------------------------| +| `value` | `T` | - | O valor a ser verificado. | +| `valid_choices` | `Iterable[T]` | - | Uma coleção de opções válidas. | +| `default` | `T` | - | O valor padrão a ser retornado se `'value'` não estiver em `'valid_choices'`. | + +**Returns** + +| Tipo | Descrição | +|------|---------------------------------------------------------| +| `T` | O valor original, se válido, ou o valor padrão, se não. | + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-------------|-----------------------|:------:|-----------------------------------------------------------------------------------------| +| `value` | `T` | - | O valor a ser verificado. | +| `default` | `T` | - | O valor padrão a ser retornado se a condição não for satisfeita. | +| `condition` | `Callable[[T], bool]` | - | Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. | + +**Returns** + +| Tipo | Descrição | +|------|------------------------------------------------------------------------------| +| `T` | O valor original se a condição for satisfeita, ou o valor padrão se não for. | + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------|-------|:------:|---------------------------------| +| `seed` | `Any` | - | O valor da seed a ser validado. | + +**Returns** + +| Tipo | Descrição | +|-----------------|----------------------------------------------------------------------------| +| `Optional[int]` | A seed original se for um inteiro não negativo, ou `None` se for inválido. | + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Valida e normaliza os limites das características. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|-------|:------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | Os limites de entrada, que devem ser None ou um dicionário com as chaves `'low'` e `'high'`. | +| `problem_size` | `int` | - | O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. | + +**Returns** + +| Tipo | Descrição | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dicionário `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | + +**Exceções** + +| Exceção | Descrição | +|--------------|----------------------------------------------------------------------------------------------------------------| +| `TypeError` | Se bounds não for `None` nem um dicionário com as chaves `'low'/'high'`, ou se os valores não forem numéricos. | +| `ValueError` | Se os iteráveis fornecidos tiverem tamanho incorreto. | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/types.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/types.md new file mode 100644 index 000000000..6f56b5850 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/types.md @@ -0,0 +1,60 @@ +--- +id: types +sidebar_label: types +keywords: + - tipos + - tipagem + - aliases + - type hints +--- + +# types + +Define aliases de tipos usados em todo o pacote para melhorar a legibilidade. + +> **Módulo:** `aisp.utils.types` +> **Importação:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Tipo das características de entrada + +- `"binary-features"`: Valores apenas com (0 ou 1, `False` ou `True`). +- `"continuous-features"`: Valores numéricos contínuos. +- `"ranged-features"`: Valores entre um intervalo definido. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Mesmo que `FeatureType`, mais: + +- `"permutation-features"`: valores representados como permutação. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Métrica de distância utilizada nos cálculos: + +- `"manhattan"`: distância de Manhattan entre dois pontos. +- `"minkowski"`: distância de Minkowski entre dois pontos. +- `"euclidean"`: distância de Euclidean entre dois pontos. + +--- \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/validation.md new file mode 100644 index 000000000..c8a3ba907 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/utils/validation.md @@ -0,0 +1,180 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validação +--- + +# Módulo + +Contém funções responsáveis pela validação de tipos de dados. + +> **Módulo:** `aisp.utils.validation` +> **Importação:** `from aisp.utils import validation` + +## Funções + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detecta o tipo de dado em um determinado vetor. + +Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: + +* **binário**: Valores booleanos (True/False) ou inteiro 0/1. +* **contínuo**: Valores float dentro do intervalo normalizado [0.0, 1.0]. +* **intervalo**: Valores float fora do intervalo normalizado. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------|---------------|:------:|---------------------------------------------------| +| `vector` | `npt.NDArray` | - | Um array contendo os dados a serem classificados. | + +**Returns** + +| Tipo | Descrição | +|-----------------------------------------|-----------------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | O tipo de dado detectado no vetor: "binary-features", "continuous-features", or " ranged-features". | + +**Exceções** + +| Exceção | Descrição | +|------------------------|----------------------------------------------------| +| `UnsupportedTypeError` | Se o vetor contiver um tipo de dado não suportado. | + +--- + +### check_array_type + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: + ... +``` + +Garante que X seja um array numpy. Converte a partir de lista, se necessário. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------|-------|:------:|--------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array contendo as amostras e suas características. Formato: (n_samples, n_features). | +| `name` | `str` | `'X'` | Nome da variável usado em mensagens de erro. | + +**Returns** + +| Tipo | Descrição | +|---------------|---------------------------------| +| `npt.NDArray` | O array convertido ou validado. | + +**Exceções** + +| Exceção | Descrição | +|-------------|---------------------------------| +| `TypeError` | Se x não for ndarray nem lista. | + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Garante que X e y tenham dimensões compatíveis. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|---------------|:------:|--------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras e suas características. Formato: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array com as classes alvo de `x`, com formato (`n_samples`). | + +**Exceções** + +| Exceção | Descrição | +|-------------|-------------------------------------------| +| `TypeError` | Se x ou y tiverem formatos incompatíveis. | + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Garante que o array possui o número esperado de características (features). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|-----------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array de entrada para predição, contendo as amostras e suas características. Formato:: (n_samples, n_features). | +| `expected` | `int` | - | Número esperado de features por amostra (colunas em X). | + +**Exceções** + +| Exceção | Descrição | +|-------------------------------------------------------------------------|------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | Se o número de features em X não corresponder ao esperado. | + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Garante que X contenha apenas valores (0 e 1) or (`True` e `False`). + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|---------------|:------:|-----------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras. | + +**Exceções** + +| Exceção | Descrição | +|--------------|---------------------------------------------------| +| `ValueError` | Se o array contiver valores diferentes de 0 e 1. | + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Garante que todos os valores do array x estejam dentro do intervalo. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-------------|---------------|:------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array contendo as amostras. | +| `name` | `str` | `'X'` | Nome usado na mensagem de erro. | +| `min_value` | `float` | `0.0` | Valor mínimo permitido. | +| `max_value` | `float` | `1.0` | Valor máximo permitido. | + +**Exceções** + +| Exceção | Descrição | +|--------------|--------------------------------------------------------------| +| `ValueError` | Se o array estiver fora do intervalo (min_value, max_value). | diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/architecture.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/architecture.md new file mode 100644 index 000000000..5c2435e78 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/architecture.md @@ -0,0 +1,76 @@ +--- +id: architecture +sidebar_position: 5 +sidebar_label: Arquitetura +keywords: + - arquitetura +--- + +# Arquitetura do AISP + +O AISP (**A**rtificial **I**mmune **S**ystems **P**ackage) é um pacote dedicado à implementação de algoritmos +inspirados no sistema imunológico dos vertebrados. Essa documentação foca na arquitetura do projeto, com o intuito de +auxiliar contribuições e manutenção. +A estrutura do pacote é modular, com separação clara entre as famílias de algoritmos e módulos de suporte para +reutilização de componente pelos algoritmos. + +## Organização dos módulos + +A hierarquia do pacote esta divida em 3 núcleos principais: base, utils e famílias de algoritmos. +O núcleo base concentra nas abstrações e modelagens imunológicas, servindo como a fundação para os algoritmos. +Já utils reúne funções que auxiliam na implementação dos algoritmos evitando redundância de código. + +O núcleo das famílias de algoritmos agrupa as diferentes metáforas dos sistemas imunológicos que os define. + +No aisp, essas famílias estão organizadas nos seguintes módulos: + +- Danger Theory Algorithms (DTA) - Previsto para versões futuras do pacote +- Clonal Selection Algorithms (CSA) +- Immune Network Algorithms (INA) +- Negative Selection Algorithms (NSA) + +### Detalhamento dos módulos + +#### Núcleo do pacote (`aisp.base`) +O módulo base é a fundação do pacote, dividido em: +1. `base.core`: Contem as classes abstratas que implementa o gerenciamento dos parâmetros e a lógica base para compatibilidade. + - `Base` (Privada): Classe abstrata estendida pelas demais classes **base** listadas abaixo. + - `BaseClassifier`: Classe abstrata para algoritmos de classificação. + - `BaseClusterer`: Classe abstrata para algoritmos de clusterização. + - `BaseOptimizer`: Classe abstrata para algoritmos de otimização. +2. `base.immune`: Define as células e processos do domínio imunoinspirados. + - `cell`: Representações de células e anticorpos do sistema imunológico. + - `mutation`: Funções de mutação das células. + - `population`: Criação de populações de células imunes. +#### Utilitários (`aisp.utils`) +Módulo de suporte com funções auxiliares reutilizáveis no pacote. +#### Famílias de algoritmos +As implementações dos algoritmos imunoinspirados no **aisp** estão organizadas em famílias, baseada na taxonomia +apresentada em Brabazon et al. [^1] + +```mermaid +flowchart TD + AIS[Artificial Immune Systems] + NSA[Negative/Positive Selection] + CSA[Clonal Expansion and Selection] + INA[Network Theory Algorithms] + DT[Danger Theory] + + AIS --- NSA + AIS --- CSA + AIS --- INA + AIS --- DT +``` +**Fonte: Adaptado de Brabazon et al. [^1], Figura 16.1.** + +Sendo estruturadas da seguinte forma: + - `aisp.nsa`: Módulo com algoritmos baseados na seleção negativa. + - `aisp.csa`: Módulo com algoritmos baseados na seleção clonal. + - `aisp.ina`: Módulo com algoritmos baseados na teoria da rede imunológica. + - `aisp.dta`: Módulo com algoritmos baseados na teoria do perigo (**Ainda não implementado**). + +## Referências + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/faq.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/faq.md index 218569d77..545e11c83 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/faq.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/faq.md @@ -1,6 +1,6 @@ --- +id: faq sidebar_position: 6 -title: Perguntas Frequentes sidebar_label: FAQ keywords: - FAQ @@ -9,7 +9,9 @@ keywords: - Ajuda --- -Soluções rápidas para possíveis duvidas sobre o aisp. +# Perguntas Frequentes + +Soluções rápidas para possíveis dúvidas sobre o aisp. ## Uso geral @@ -17,27 +19,30 @@ Soluções rápidas para possíveis duvidas sobre o aisp. Depende do tipo de problema: -- **Detecção de anomalias**: Use ``RNSA`` ou ``BNSA``. +- **Detecção de anomalias**: Use `RNSA` ou `BNSA`. - RNSA para problemas com dados contínuos. - BNSA para problemas com dados binários. -- **Classificação**: Use ``AIRS``, ``RNSA`` ou ``BNSA``. - - O ``RNSA`` e ``BNSA``, foram implementados para serem aplicados a classificação multiclasse. - - O ``AIRS`` é mais robusto para ruídos nos dados. -- **Otimização**: Use ``Clonalg``. +- **Classificação**: Use `AIRS`, `RNSA` ou `BNSA`. + - O `RNSA` e `BNSA`, foram implementados para serem aplicados a classificação multiclasse. + - O `AIRS` é mais robusto para dados com ruídos. +- **Otimização**: Use `Clonalg`. - A implementação pode ser aplicada à otimização (min/max) de funções objetivas. -- **Clustering/Agrupamento**: Use ``AiNet``. +- **Clustering/Agrupamento**: Use `AiNet`. - Separa grupos de dados automaticamente. - Não requer numero de grupos predefinidos. --- -### Como normalizar meus dados para utilizar o algoritmo ``RNSA``? +### Como normalizar meus dados para utilizar o algoritmo `RNSA`? -O RNSA trabalha exclusivamente com dados normalizados no intervalo entre [0, 1]. Portanto, antes de aplicá-lo, é necessário normalizar os dados se não estiver neste intervalo. Uma forma simples é fazer utilizando as ferramentas de normalização do **scikit-learn**, como o [``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). +O RNSA trabalha exclusivamente com dados normalizados no intervalo entre (0.0, 1.0). Portanto, antes de aplicá-lo, +é necessário normalizar os dados se não estiver neste intervalo. Uma forma simples é fazer utilizando as +ferramentas de normalização do **scikit-learn**, como o +[`MinMaxScaler`](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). #### Exemplo -Neste exemplo, ``X`` representa os dados de entrada não normalizados. +Neste exemplo, `X` representa os dados de entrada não normalizados. ```python from sklearn.preprocessing import MinMaxScaler @@ -55,21 +60,22 @@ rnsa.fit(x_norm, y) ## Configuração de Parâmetros -### Como escolher o numero de detectores (``N``) no ``RNSA`` ou ``BNSA``? +### Como escolher o numero de detectores (`N`) no `RNSA` ou `BNSA`? -O numero de detectores afeta diretamente a performance: +O número de detectores afeta diretamente a performance: - Um número reduzido de detectores pode não cobrir adequadamente o espaço não-próprio. - Um número muito alto de detectores pode aumentar o tempo de treinamento e pode causar overfitting. **Recomendações**: -- Teste diferentes valores para o número de detectores até encontrar um equilíbrio adequado entre tempo de treinamento e desempenho do modelo. +- Teste diferentes valores para o número de detectores até encontrar um equilíbrio adequado entre tempo de treinamento + e desempenho do modelo. - Utilize validação cruzada para identificar o valor que apresenta os melhores resultados de forma consistente. --- -### Qual raio (``r`` ou ``aff_thresh``) devo utilizar no ``BNSA`` ou ``RNSA``? +### Qual raio (`r` ou `aff_thresh`) devo utilizar no `BNSA` ou `RNSA`? O raio dos detectores depende da distribuição dos dados: @@ -78,15 +84,17 @@ O raio dos detectores depende da distribuição dos dados: --- -### O que é o parâmetro ``r_s`` no ``RNSA``? +### O que é o parâmetro `r_s` no `RNSA`? -O ``r_s`` é o raio da amostra self. Ele define uma região ao redor de cada amostra de treinamento. +O `r_s` é o raio da amostra self. Ele define uma região ao redor de cada amostra de treinamento. --- ### Clonalg: Como definir a função objetivo? -A função objetiva deve seguir o padrão da [classe base](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140), Ela deve receber uma solução como entrada e retornar um valor do custo (ou afinidade). +A função objetiva deve seguir o padrão da +[classe base](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). +Ela deve receber uma solução como entrada e retornar um valor do custo (ou afinidade). ```python def affinity_function(self, solution: Any) -> float: @@ -95,12 +103,14 @@ def affinity_function(self, solution: Any) -> float: Existem duas formas de definir a função objetivo no Clonalg. -1. Definindo a função diretamente no construtor da classe - ```python def sphere(solution): return np.sum(solution ** 2) +``` + +1. Definindo a função diretamente no construtor da classe +```python clonalg = Clonalg( problem_size=2, affinity_function=sphere @@ -110,9 +120,6 @@ clonalg = Clonalg( 2. Utilizando o registrador de funções ```python -def sphere(solution): - return np.sum(solution ** 2) - clonalg = Clonalg( problem_size=2, ) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md index 8c57a60a0..2a4bdf8b7 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md @@ -55,9 +55,35 @@ O AISP oferece implementações de algoritmos bio-inspirados para: - **Otimização**: Encontre soluções ótimas para funções objetivas. - **Clustering**: Agrupe dados sem supervisão. -### Algoritmos implementados +--- + +## Algoritmos Implementados + +### [Seleção Negativa](./aisp-techniques/negative-selection.md) (`aisp.nsa`) + +- [**BNSA**](./api/nsa/bnsa.md) - Algoritmo de Seleção Negativa Binária +- [**RNSA**](./api/nsa/rnsa.md) - Algoritmo de Seleção Negativa com Valores Reais + +### [Seleção Clonal](./aisp-techniques/clonal-selection-algorithms.md) (`aisp.csa`) + +- [**AIRS**](./api/csa/airs.md) - Sistema Imunológico Artificial de Reconhecimento +- [**CLONALG**](./api/csa/clonalg.md) - Algoritmo de Seleção Clonal + +### [Teoria de Redes Imunológicas](./aisp-techniques/immune-network-theory.md) (`aisp.ina`) + +- [**AiNet**](./api/ina/ai-net.md) - Rede Imunológica Artificial para Agrupamento e Compressão de Dados + +### Módulo em Desenvolvimento + +#### Teoria do Perigo (`aisp.dta`) + +- **DCA** - Algoritmo de Células Dendríticas *(planejado)* + +## Visão geral da API + +Todos os algoritmos seguem uma interface simples e consistente: -> - [x] [**Seleção Negativa.**](./aisp-techniques/negative-selection/) -> - [x] [**Algoritmos de Seleção Clonal.**](./aisp-techniques/clonal-selection-algorithms/) -> - [x] [**Teoria da Rede Imune.**](./aisp-techniques/immune-network-theory/) -> - [ ] *Teoria do Perigo.* +- `fit(X, y, verbose: bool = True)`: Treina o modelo para tarefas de classificação. +- `fit(X, verbose: bool = True)`: Treina o modelo para tarefas de agrupamento. +- `predict(X)`: Faz previsões com base em novos dados. +- `optimize(max_iters: int =..., n_iter_no_change: int =..., verbose: bool = True)`: executar os algoritmos de otimização diff --git a/package-lock.json b/package-lock.json index 7004a35c3..13ec5a185 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,16 +1,17 @@ { "name": "ais-package-github-io", - "version": "0.4.0", + "version": "0.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ais-package-github-io", - "version": "0.4.0", + "version": "0.5.0", "dependencies": { - "@docusaurus/core": "^3.9.1", - "@docusaurus/plugin-sitemap": "^3.9.1", - "@docusaurus/preset-classic": "^3.9.1", + "@docusaurus/core": "^3.10.0", + "@docusaurus/plugin-sitemap": "^3.10.0", + "@docusaurus/preset-classic": "^3.10.0", + "@docusaurus/theme-mermaid": "^3.10.0", "@easyops-cn/docusaurus-search-local": "^0.49.2", "@mdx-js/react": "^3.0.0", "axios": "^1.9.0", @@ -22,9 +23,9 @@ "remark-math": "^6.0.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.9.1", - "@docusaurus/tsconfig": "^3.9.1", - "@docusaurus/types": "^3.9.1", + "@docusaurus/module-type-aliases": "^3.10.0", + "@docusaurus/tsconfig": "^3.10.0", + "@docusaurus/types": "^3.10.0", "@types/dotenv": "^8.2.3", "typescript": "~5.6.2" }, @@ -32,116 +33,47 @@ "node": ">=18.0" } }, - "node_modules/@ai-sdk/gateway": { - "version": "1.0.30", - "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-1.0.30.tgz", - "integrity": "sha512-QdrSUryr/CLcsCISokLHOImcHj1adGXk1yy4B3qipqLhcNc33Kj/O/3crI790Qp85oDx7sc4vm7R4raf9RA/kg==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/provider": "2.0.0", - "@ai-sdk/provider-utils": "3.0.10" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "zod": "^3.25.76 || ^4.1.8" - } - }, - "node_modules/@ai-sdk/provider": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-2.0.0.tgz", - "integrity": "sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA==", - "license": "Apache-2.0", - "dependencies": { - "json-schema": "^0.4.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@ai-sdk/provider-utils": { - "version": "3.0.10", - "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-3.0.10.tgz", - "integrity": "sha512-T1gZ76gEIwffep6MWI0QNy9jgoybUHE7TRaHB5k54K8mF91ciGFlbtCGxDYhMH3nCRergKwYFIDeFF0hJSIQHQ==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/provider": "2.0.0", - "@standard-schema/spec": "^1.0.0", - "eventsource-parser": "^3.0.5" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "zod": "^3.25.76 || ^4.1.8" - } - }, - "node_modules/@ai-sdk/react": { - "version": "2.0.56", - "resolved": "https://registry.npmjs.org/@ai-sdk/react/-/react-2.0.56.tgz", - "integrity": "sha512-7glIc65IZYFx+GZIcvMFdp+lkJnpsgRJNGRhStF6naUXtCrhjC5SyyXFMwZk+GMk3ZK9Kb83zdnWqtO7LOXGuA==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/provider-utils": "3.0.10", - "ai": "5.0.56", - "swr": "^2.2.5", - "throttleit": "2.1.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "react": "^18 || ^19 || ^19.0.0-rc", - "zod": "^3.25.76 || ^4.1.8" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, "node_modules/@algolia/abtesting": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.5.0.tgz", - "integrity": "sha512-W/ohRkbKQsqDWALJg28X15KF7Tcyg53L1MfdOkLgvkcCcofdzGHSimHHeNG05ojjFw9HK8+VPhe/Vwq4MozIJg==", + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.17.0.tgz", + "integrity": "sha512-nuhHZdTiCtRzJEe9VSNzyqE9cOQMt01UWBzymFnjbgwrxxZpbGHQde6Oa/y9zyspTCjbUtb7Q5HQek1CLiLyeg==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/autocomplete-core": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.19.2.tgz", - "integrity": "sha512-mKv7RyuAzXvwmq+0XRK8HqZXt9iZ5Kkm2huLjgn5JoCPtDy+oh9yxUMfDDaVCw0oyzZ1isdJBc7l9nuCyyR7Nw==", + "version": "1.19.8", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.19.8.tgz", + "integrity": "sha512-3YEorYg44niXcm7gkft3nXYItHd44e8tmh4D33CTszPgP0QWkaLEaFywiNyJBo7UL/mqObA/G9RYuU7R8tN1IA==", "license": "MIT", "dependencies": { - "@algolia/autocomplete-plugin-algolia-insights": "1.19.2", - "@algolia/autocomplete-shared": "1.19.2" + "@algolia/autocomplete-plugin-algolia-insights": "1.19.8", + "@algolia/autocomplete-shared": "1.19.8" } }, "node_modules/@algolia/autocomplete-plugin-algolia-insights": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.19.2.tgz", - "integrity": "sha512-TjxbcC/r4vwmnZaPwrHtkXNeqvlpdyR+oR9Wi2XyfORkiGkLTVhX2j+O9SaCCINbKoDfc+c2PB8NjfOnz7+oKg==", + "version": "1.19.8", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.19.8.tgz", + "integrity": "sha512-ZvJWO8ZZJDpc1LNM2TTBdmQsZBLMR4rU5iNR2OYvEeFBiaf/0ESnRSSLQbryarJY4SVxtoz6A2ZtDMNM+iQEAA==", "license": "MIT", "dependencies": { - "@algolia/autocomplete-shared": "1.19.2" + "@algolia/autocomplete-shared": "1.19.8" }, "peerDependencies": { "search-insights": ">= 1 < 3" } }, "node_modules/@algolia/autocomplete-shared": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.19.2.tgz", - "integrity": "sha512-jEazxZTVD2nLrC+wYlVHQgpBoBB5KPStrJxLzsIFl6Kqd1AlG9sIAGl39V5tECLpIQzB3Qa2T6ZPJ1ChkwMK/w==", + "version": "1.19.8", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.19.8.tgz", + "integrity": "sha512-h5hf2t8ejF6vlOgvLaZzQbWs5SyH2z4PAWygNAvvD/2RI29hdQ54ldUGwqVuj9Srs+n8XUKTPUqb7fvhBhQrnQ==", "license": "MIT", "peerDependencies": { "@algolia/client-search": ">= 4.9.1 < 6", @@ -149,99 +81,99 @@ } }, "node_modules/@algolia/client-abtesting": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.39.0.tgz", - "integrity": "sha512-Vf0ZVe+qo3sHDrCinouJqlg8VoxM4Qo/KxNIqMYybkuctutfnp3kIY9OmESplOQ/9NGBthU9EG+4d5fBibWK/A==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.51.0.tgz", + "integrity": "sha512-PKrKlIla1U2J7mFcIQn6N3pWP4oySmkxShnbbDsj/H7818gKbET5KsUwsVoNjWIxHKTJMCTcQ7ekAJ8Ea23NMg==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-analytics": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.39.0.tgz", - "integrity": "sha512-V16ITZxYIwcv1arNce65JZmn94Ft6vKlBZ//gXw8AvIH32glJz1KcbaVAUr9p7PYlGZ/XVHP6LxDgrpNdtwgcA==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.51.0.tgz", + "integrity": "sha512-U+HCY1K16Km91pIRL1kN6bW6BbGFAF/WhkRSCx4wyl1aFpbrlhSFQs/dAwWbmyBiHWwVWhl7stWHQ1pum5EfMw==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-common": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.39.0.tgz", - "integrity": "sha512-UCJTuwySEQeiKPWV3wruhuI/wHbDYenHzgL9pYsvh6r/u5Z+g61ip1iwdAlFp02CnywzI9O7+AQPh2ManYyHmQ==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.51.0.tgz", + "integrity": "sha512-YPJ3dEuZLCRp846Az94t6Z2gwSNRazP+SmBco7p6SCa4fYrtIE820PDXYZshbNrj2Z8Qfbmv7BQ1Lecl5L3G/w==", "license": "MIT", "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-insights": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.39.0.tgz", - "integrity": "sha512-s0ia8M/ZZR+iO2uLNTBrlQdEb6ZMAMcKMHckp5mcoglxrf8gHifL4LmdhGKdAxAn3UIagtqIP0RCnIymHUbm7A==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.51.0.tgz", + "integrity": "sha512-/gEwLlR7fQ7YjOW+ADRZ0NxLDtpTC61FSzlZ01Gdl1kTJfU0Rq3Y/TYqwxGxlQGcUiXtGzrpjxXWh3Y0TZD6NA==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-personalization": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.39.0.tgz", - "integrity": "sha512-vZPIt7Lw+toNsHZUiPhNIc1Z3vUjDp7nzn6AMOaPC73gEuTq2iLPNvM06CSB6aHePo5eMeJIP5YEKBUQUA/PJA==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.51.0.tgz", + "integrity": "sha512-nRwUN1Y2cKyOAFZyIBagkEfZSIhP05nWhT4Rjwl84lcjECssYggftrAODrZ4leakXxSGjhxs/AdaAFEIBqwVFA==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-query-suggestions": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.39.0.tgz", - "integrity": "sha512-jcPQr3iKTWNVli2NYHPv02aNLwixDjPCpOgMp9CZTvEiPI6Ec4jHX+oFr3LDZagOFY9e1xJhc/JrgMGGW1sHnw==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.51.0.tgz", + "integrity": "sha512-pybzYCG7VoQKppo+z5iZOKpW8XqtFxhsAIRgEaNboCnfypKukiBHJAwB+pmr7vMZXBsOHwklGYWwCG82e8qshA==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/client-search": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.39.0.tgz", - "integrity": "sha512-/IYpF10BpthGZEJQZMhMqV4AqWr5avcWfZm/SIKK1RvUDmzGqLoW/+xeJVX9C8ZnNkIC8hivbIQFaNaRw0BFZQ==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.51.0.tgz", + "integrity": "sha512-DWVIlj6RqcvdhwP0gBU9OpOQPnHdcAk9jlT+z8rsNb2+liWv4eUlfQZ7saGBraFsnygEHD3PtdppIHvqwBAb5w==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" @@ -254,93 +186,106 @@ "license": "MIT" }, "node_modules/@algolia/ingestion": { - "version": "1.39.0", - "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.39.0.tgz", - "integrity": "sha512-IgSHKUiuecqLfBlXiuCSdRTdsO3/yvpmXrMFz8fAJ8M4QmDtHkOuD769dmybRYqsbYMHivw+lir4BgbRGMtOIQ==", + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.51.0.tgz", + "integrity": "sha512-bA25s12iUDJi/X8M7tWlPRT8GeOhls/yDbdoUqinz27lNqsOlcM1UrAxIKdIZ6lm3sXit+ewPIz1pS2x6rXu8g==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/monitoring": { - "version": "1.39.0", - "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.39.0.tgz", - "integrity": "sha512-8Xnd4+609SKC/hqVsuFc4evFBmvA2765/4NcH+Dpr756SKPbL1BY0X8kVxlmM3YBLNqnduSQxHxpDJUK58imCA==", + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.51.0.tgz", + "integrity": "sha512-zj+RcE5e0NE0/ew6oEOTgOplPHry+w2oi7h0Y87lhdq4E0d7xLS31KVB8kKfCGkrG7AYtZvrcyvLOKS5d0no4Q==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/recommend": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.39.0.tgz", - "integrity": "sha512-D7Ye2Ss/5xqUkQUxKm/VqEJLt5kARd9IMmjdzlxaKhGgNlOemTay0lwBmOVFuJRp7UODjp5c9+K+B8g0ORObIw==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.51.0.tgz", + "integrity": "sha512-/HDgccfye1Rq3bPxaSCsvSEBHzSMmtpM9ZRGRtAuC62Cv+ql/76IWnxjGTDXtqIJ+/j7ZlFYAzq9fkp95wF2SQ==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "@algolia/client-common": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/requester-browser-xhr": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.39.0.tgz", - "integrity": "sha512-mgPte1ZJqpk9dkVs44J3wKAbHATvHZNlSpzhMdjMLIg/3qTycSZyDiomLiSlxE8CLsxyBAOJWnyKRHfom+Z1rg==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.51.0.tgz", + "integrity": "sha512-nJdW+WBwGlXWMJbxxB7/AJPvNq0lLJSudXmIQCJbmH8jsOXQhRpAtoCD4ceLyJKv3ze9JbQu4Gqu5JDLckuFcw==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0" + "@algolia/client-common": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/requester-fetch": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.39.0.tgz", - "integrity": "sha512-LIrCkrxu1WnO3ev1+w6NnZ12JZL/o+2H9w6oWnZAjQZIlA/Ym6M9QHkt+OQ/SwkuoiNkW3DAo+Pi4A2V9FPtqg==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.51.0.tgz", + "integrity": "sha512-bsBgRI/1h1mjS3eCyfGau78yGZVmiDLmT1aU6dMnk75/T0SgKqnSKNpQ53xKoDYVChGDcNnpHXWpoUSo8MH1+w==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0" + "@algolia/client-common": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/@algolia/requester-node-http": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.39.0.tgz", - "integrity": "sha512-6beG+egPwXmvhAg+m0STCj+ZssDcjrLzf4L05aKm2nGglMXSSPz0cH/rM+kVD9krNfldiMctURd4wjojW1fV0w==", + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.51.0.tgz", + "integrity": "sha512-zPrIDVPpmKWgrjmWOqpqrhqAhNjvVkjoj+mqw2NBPxEOuKNzP0H+Qz5NJLLTOepBVj1UFedFaF3AUgxLsB9ukQ==", "license": "MIT", "dependencies": { - "@algolia/client-common": "5.39.0" + "@algolia/client-common": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, + "node_modules/@antfu/install-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz", + "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==", + "license": "MIT", + "dependencies": { + "package-manager-detector": "^1.3.0", + "tinyexec": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, "node_modules/@babel/code-frame": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", - "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" }, @@ -349,29 +294,29 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.4.tgz", - "integrity": "sha512-YsmSKC29MJwf0gF8Rjjrg5LQCmyh+j/nD8/eP7f+BeoQTKYqs9RoWbjGOdy0+1Ekr68RJZMUOPVQaQisnIo4Rw==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.4.tgz", - "integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==", - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.3", - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-module-transforms": "^7.28.3", - "@babel/helpers": "^7.28.4", - "@babel/parser": "^7.28.4", - "@babel/template": "^7.27.2", - "@babel/traverse": "^7.28.4", - "@babel/types": "^7.28.4", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", @@ -397,13 +342,13 @@ } }, "node_modules/@babel/generator": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.3.tgz", - "integrity": "sha512-3lSpxGgvnmZznmBkCRnVREPUFJv2wrv9iAoFDvADJc0ypmdOxdUtcLeBgBJ6zE0PMeTKnxeQzyk0xTBq4Ep7zw==", + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", "license": "MIT", "dependencies": { - "@babel/parser": "^7.28.3", - "@babel/types": "^7.28.2", + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" @@ -425,12 +370,12 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", - "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.27.2", + "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", @@ -450,17 +395,17 @@ } }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.3.tgz", - "integrity": "sha512-V9f6ZFIYSLNEbuGA/92uOvYsGCJNsuA8ESZ4ldc09bWk/j8H8TKiPw8Mk1eG6olpnO0ALHJmYfZvF4MEE4gajg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.6.tgz", + "integrity": "sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", - "@babel/helper-member-expression-to-functions": "^7.27.1", + "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", - "@babel/helper-replace-supers": "^7.27.1", + "@babel/helper-replace-supers": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", - "@babel/traverse": "^7.28.3", + "@babel/traverse": "^7.28.6", "semver": "^6.3.1" }, "engines": { @@ -480,13 +425,13 @@ } }, "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.27.1.tgz", - "integrity": "sha512-uVDC72XVf8UbrH5qQTc18Agb8emwjTiZrQE11Nv3CuBEZmVvTwwE9CBUEvHku06gQCAyYf8Nv6ja1IN+6LMbxQ==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.28.5.tgz", + "integrity": "sha512-N1EhvLtHzOvj7QQOUCCS3NrPJP8c5W6ZXCHDn7Yialuy1iu4r5EmIYkXlKNqT99Ciw+W0mDqWoR6HWMZlFP3hw==", "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^7.27.1", - "regexpu-core": "^6.2.0", + "@babel/helper-annotate-as-pure": "^7.27.3", + "regexpu-core": "^6.3.1", "semver": "^6.3.1" }, "engines": { @@ -506,16 +451,16 @@ } }, "node_modules/@babel/helper-define-polyfill-provider": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.5.tgz", - "integrity": "sha512-uJnGFcPsWQK8fvjgGP5LZUZZsYGIoPeRjSF5PGwrelYgq7Q15/Ft9NGFp1zglwgIv//W0uG4BevRuSJRyylZPg==", + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.8.tgz", + "integrity": "sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==", "license": "MIT", "dependencies": { - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", - "debug": "^4.4.1", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "debug": "^4.4.3", "lodash.debounce": "^4.0.8", - "resolve": "^1.22.10" + "resolve": "^1.22.11" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" @@ -531,40 +476,40 @@ } }, "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.27.1.tgz", - "integrity": "sha512-E5chM8eWjTp/aNoVpcbfM7mLxu9XGLWYise2eBKGQomAk/Mb4XoxyqXTZbuTohbsl8EKqdlMhnDI2CCLfcs9wA==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.28.5.tgz", + "integrity": "sha512-cwM7SBRZcPCLgl8a7cY0soT1SptSzAlMH39vwiRpOQkJlh53r5hdHwLSCZpQdVLT39sZt+CRpNwYG4Y2v77atg==", "license": "MIT", "dependencies": { - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-imports": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", - "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", "license": "MIT", "dependencies": { - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz", - "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1", - "@babel/traverse": "^7.28.3" + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -586,9 +531,9 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz", - "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", "license": "MIT", "engines": { "node": ">=6.9.0" @@ -612,14 +557,14 @@ } }, "node_modules/@babel/helper-replace-supers": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.27.1.tgz", - "integrity": "sha512-7EHz6qDZc8RYS5ElPoShMheWvEgERonFCs7IAonWLLUTXW59DP14bCZt89/GKyreYn8g3S83m21FelHKbeDCKA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.28.6.tgz", + "integrity": "sha512-mq8e+laIk94/yFec3DxSjCRD2Z0TAjhVbEJY3UQrlwVo15Lmt7C2wAUbK4bjnTs4APkwsYLTahXRraQXhb1WCg==", "license": "MIT", "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.27.1", + "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", - "@babel/traverse": "^7.27.1" + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -651,9 +596,9 @@ } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz", - "integrity": "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", "license": "MIT", "engines": { "node": ">=6.9.0" @@ -669,39 +614,39 @@ } }, "node_modules/@babel/helper-wrap-function": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.28.3.tgz", - "integrity": "sha512-zdf983tNfLZFletc0RRXYrHrucBEg95NIFMkn6K9dbeMYnsgHaSBGcQqdsCSStG2PYwRre0Qc2NNSCXbG+xc6g==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.28.6.tgz", + "integrity": "sha512-z+PwLziMNBeSQJonizz2AGnndLsP2DeGHIxDAn+wdHOGuo4Fo1x1HBPPXeE9TAOPHNNWQKCSlA2VZyYyyibDnQ==", "license": "MIT", "dependencies": { - "@babel/template": "^7.27.2", - "@babel/traverse": "^7.28.3", - "@babel/types": "^7.28.2" + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz", - "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", "license": "MIT", "dependencies": { - "@babel/template": "^7.27.2", - "@babel/types": "^7.28.4" + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.4.tgz", - "integrity": "sha512-yZbBqeM6TkpP9du/I2pUZnJsRMGGvOuIrhjzC1AwHwW+6he4mni6Bp/m8ijn0iOuZuPI2BfkCoSRunpyjnrQKg==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", "license": "MIT", "dependencies": { - "@babel/types": "^7.28.4" + "@babel/types": "^7.29.0" }, "bin": { "parser": "bin/babel-parser.js" @@ -711,13 +656,13 @@ } }, "node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-7.27.1.tgz", - "integrity": "sha512-QPG3C9cCVRQLxAVwmefEmwdTanECuUBMQZ/ym5kiw3XKCGA7qkuQLcjWWHcrD/GKbn/WmJwaezfuuAOcyKlRPA==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-firefox-class-in-computed-class-key/-/plugin-bugfix-firefox-class-in-computed-class-key-7.28.5.tgz", + "integrity": "sha512-87GDMS3tsmMSi/3bWOte1UblL+YUTFMV8SZPZ2eSEL17s74Cw/l63rR6NmGVKMYW2GYi85nE+/d6Hw5N0bEk2Q==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", - "@babel/traverse": "^7.27.1" + "@babel/traverse": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -774,13 +719,13 @@ } }, "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.28.3.tgz", - "integrity": "sha512-b6YTX108evsvE4YgWyQ921ZAFFQm3Bn+CA3+ZXlNVnPhx+UfsVURoPjfGAPCjBgrqo30yX/C2nZGX96DxvR9Iw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.28.6.tgz", + "integrity": "sha512-a0aBScVTlNaiUe35UtfxAN7A/tehvvG4/ByO6+46VPKTRSlfnAFsgKy0FUh+qAkQrDTmhDkT+IBOKlOoMUxQ0g==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/traverse": "^7.28.3" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -814,12 +759,12 @@ } }, "node_modules/@babel/plugin-syntax-import-assertions": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.27.1.tgz", - "integrity": "sha512-UT/Jrhw57xg4ILHLFnzFpPDlMbcdEicaAtjPQpbj9wa8T4r5KVWCimHcL/460g8Ht0DMxDyjsLgiWSkVjnwPFg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.28.6.tgz", + "integrity": "sha512-pSJUpFHdx9z5nqTSirOCMtYVP2wFgoWhP0p3g8ONK/4IHhLIBd0B9NYqAvIUAhq+OkhO4VM1tENCt0cjlsNShw==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -829,12 +774,12 @@ } }, "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz", - "integrity": "sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", + "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -844,12 +789,12 @@ } }, "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.27.1.tgz", - "integrity": "sha512-y8YTNIeKoyhGd9O0Jiyzyyqk8gdjnumGTQPsz0xOZOQ2RmkVJeZ1vmmfIvFEKqucBG6axJGBZDE/7iI5suUI/w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", + "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -859,12 +804,12 @@ } }, "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.27.1.tgz", - "integrity": "sha512-xfYCBMxveHrRMnAWl1ZlPXOZjzkN82THFvLhQhFXFt81Z5HnN+EtUkZhv/zcKpmT3fzmWZB0ywiBrbC3vogbwQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.28.6.tgz", + "integrity": "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -905,14 +850,14 @@ } }, "node_modules/@babel/plugin-transform-async-generator-functions": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.28.0.tgz", - "integrity": "sha512-BEOdvX4+M765icNPZeidyADIvQ1m1gmunXufXxvRESy/jNNyfovIqUyE7MVgGBjWktCoJlzvFA1To2O4ymIO3Q==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.29.0.tgz", + "integrity": "sha512-va0VdWro4zlBr2JsXC+ofCPB2iG12wPtVGTWFx2WLDOM3nYQZZIGP82qku2eW/JR83sD+k2k+CsNtyEbUqhU6w==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-remap-async-to-generator": "^7.27.1", - "@babel/traverse": "^7.28.0" + "@babel/traverse": "^7.29.0" }, "engines": { "node": ">=6.9.0" @@ -922,13 +867,13 @@ } }, "node_modules/@babel/plugin-transform-async-to-generator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.27.1.tgz", - "integrity": "sha512-NREkZsZVJS4xmTr8qzE5y8AfIPqsdQfRuUiLRTEzb7Qii8iFWCyDKaUV2c0rCuh4ljDZ98ALHP/PetiBV2nddA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.28.6.tgz", + "integrity": "sha512-ilTRcmbuXjsMmcZ3HASTe4caH5Tpo93PkTxF9oG2VZsSWsahydmcEHhix9Ik122RcTnZnUzPbmux4wh1swfv7g==", "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-remap-async-to-generator": "^7.27.1" }, "engines": { @@ -954,12 +899,12 @@ } }, "node_modules/@babel/plugin-transform-block-scoping": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.28.4.tgz", - "integrity": "sha512-1yxmvN0MJHOhPVmAsmoW5liWwoILobu/d/ShymZmj867bAdxGbehIrew1DuLpw2Ukv+qDSSPQdYW1dLNE7t11A==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.28.6.tgz", + "integrity": "sha512-tt/7wOtBmwHPNMPu7ax4pdPz6shjFrmHDghvNC+FG9Qvj7D6mJcoRQIF5dy4njmxR941l6rgtvfSB2zX3VlUIw==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -969,13 +914,13 @@ } }, "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.27.1.tgz", - "integrity": "sha512-D0VcalChDMtuRvJIu3U/fwWjf8ZMykz5iZsg77Nuj821vCKI3zCyRLwRdWbsuJ/uRwZhZ002QtCqIkwC/ZkvbA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.28.6.tgz", + "integrity": "sha512-dY2wS3I2G7D697VHndN91TJr8/AAfXQNt5ynCTI/MpxMsSzHp+52uNivYT5wCPax3whc47DR8Ba7cmlQMg24bw==", "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -985,13 +930,13 @@ } }, "node_modules/@babel/plugin-transform-class-static-block": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.28.3.tgz", - "integrity": "sha512-LtPXlBbRoc4Njl/oh1CeD/3jC+atytbnf/UqLoqTDcEYGUPj022+rvfkbDYieUrSj3CaV4yHDByPE+T2HwfsJg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.28.6.tgz", + "integrity": "sha512-rfQ++ghVwTWTqQ7w8qyDxL1XGihjBss4CmTgGRCTAC9RIbhVpyp4fOeZtta0Lbf+dTNIVJer6ych2ibHwkZqsQ==", "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.28.3", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1001,17 +946,17 @@ } }, "node_modules/@babel/plugin-transform-classes": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.28.4.tgz", - "integrity": "sha512-cFOlhIYPBv/iBoc+KS3M6et2XPtbT2HiCRfBXWtfpc9OAyostldxIf9YAYB6ypURBBbx+Qv6nyrLzASfJe+hBA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.28.6.tgz", + "integrity": "sha512-EF5KONAqC5zAqT783iMGuM2ZtmEBy+mJMOKl2BCvPZ2lVrwvXnB6o+OBWCS+CoeCCpVRF2sA2RBKUxvT8tQT5Q==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", - "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-compilation-targets": "^7.28.6", "@babel/helper-globals": "^7.28.0", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/helper-replace-supers": "^7.27.1", - "@babel/traverse": "^7.28.4" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/helper-replace-supers": "^7.28.6", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1021,13 +966,13 @@ } }, "node_modules/@babel/plugin-transform-computed-properties": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.27.1.tgz", - "integrity": "sha512-lj9PGWvMTVksbWiDT2tW68zGS/cyo4AkZ/QTp0sQT0mjPopCmrSkzxeXkznjqBxzDI6TclZhOJbBmbBLjuOZUw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.28.6.tgz", + "integrity": "sha512-bcc3k0ijhHbc2lEfpFHgx7eYw9KNXqOerKWfzbxEHUGKnS3sz9C4CNL9OiFN1297bDNfUiSO7DaLzbvHQQQ1BQ==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/template": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/template": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1037,13 +982,13 @@ } }, "node_modules/@babel/plugin-transform-destructuring": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.28.0.tgz", - "integrity": "sha512-v1nrSMBiKcodhsyJ4Gf+Z0U/yawmJDBOTpEB3mcQY52r9RIyPneGyAS/yM6seP/8I+mWI3elOMtT5dB8GJVs+A==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.28.5.tgz", + "integrity": "sha512-Kl9Bc6D0zTUcFUvkNuQh4eGXPKKNDOJQXVyyM4ZAQPMveniJdxi8XMJwLo+xSoW3MIq81bD33lcUe9kZpl0MCw==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", - "@babel/traverse": "^7.28.0" + "@babel/traverse": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -1053,13 +998,13 @@ } }, "node_modules/@babel/plugin-transform-dotall-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.27.1.tgz", - "integrity": "sha512-gEbkDVGRvjj7+T1ivxrfgygpT7GUd4vmODtYpbs0gZATdkX8/iSnOtZSxiZnsgm1YjTgjI6VKBGSJJevkrclzw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.28.6.tgz", + "integrity": "sha512-SljjowuNKB7q5Oayv4FoPzeB74g3QgLt8IVJw9ADvWy3QnUb/01aw8I4AVv8wYnPvQz2GDDZ/g3GhcNyDBI4Bg==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1084,13 +1029,13 @@ } }, "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.27.1.tgz", - "integrity": "sha512-hkGcueTEzuhB30B3eJCbCYeCaaEQOmQR0AdvzpD4LoN0GXMWzzGSuRrxR2xTnCrvNbVwK9N6/jQ92GSLfiZWoQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.29.0.tgz", + "integrity": "sha512-zBPcW2lFGxdiD8PUnPwJjag2J9otbcLQzvbiOzDxpYXyCuYX9agOwMPGn1prVH0a4qzhCKu24rlH4c1f7yA8rw==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1115,13 +1060,13 @@ } }, "node_modules/@babel/plugin-transform-explicit-resource-management": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.28.0.tgz", - "integrity": "sha512-K8nhUcn3f6iB+P3gwCv/no7OdzOZQcKchW6N389V6PD8NUWKZHzndOd9sPDVbMoBsbmjMqlB4L9fm+fEFNVlwQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.28.6.tgz", + "integrity": "sha512-Iao5Konzx2b6g7EPqTy40UZbcdXE126tTxVFr/nAIj+WItNxjKSYTEw3RC+A2/ZetmdJsgueL1KhaMCQHkLPIg==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/plugin-transform-destructuring": "^7.28.0" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/plugin-transform-destructuring": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -1131,12 +1076,12 @@ } }, "node_modules/@babel/plugin-transform-exponentiation-operator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.27.1.tgz", - "integrity": "sha512-uspvXnhHvGKf2r4VVtBpeFnuDWsJLQ6MF6lGJLC89jBR1uoVeqM416AZtTuhTezOfgHicpJQmoD5YUakO/YmXQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.28.6.tgz", + "integrity": "sha512-WitabqiGjV/vJ0aPOLSFfNY1u9U3R7W36B03r5I2KoNix+a3sOhJ3pKFB3R5It9/UiK78NiO0KE9P21cMhlPkw==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1194,12 +1139,12 @@ } }, "node_modules/@babel/plugin-transform-json-strings": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.27.1.tgz", - "integrity": "sha512-6WVLVJiTjqcQauBhn1LkICsR2H+zm62I3h9faTDKt1qP4jn2o72tSvqMwtGFKGTpojce0gJs+76eZ2uCHRZh0Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.28.6.tgz", + "integrity": "sha512-Nr+hEN+0geQkzhbdgQVPoqr47lZbm+5fCUmO70722xJZd0Mvb59+33QLImGj6F+DkK3xgDi1YVysP8whD6FQAw==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1224,12 +1169,12 @@ } }, "node_modules/@babel/plugin-transform-logical-assignment-operators": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.27.1.tgz", - "integrity": "sha512-SJvDs5dXxiae4FbSL1aBJlG4wvl594N6YEVVn9e3JGulwioy6z3oPjx/sQBO3Y4NwUu5HNix6KJ3wBZoewcdbw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.28.6.tgz", + "integrity": "sha512-+anKKair6gpi8VsM/95kmomGNMD0eLz1NQ8+Pfw5sAwWH9fGYXT50E55ZpV0pHUHWf6IUTWPM+f/7AAff+wr9A==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1270,13 +1215,13 @@ } }, "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.27.1.tgz", - "integrity": "sha512-OJguuwlTYlN0gBZFRPqwOGNWssZjfIUdS7HMYtN8c1KmwpwHFBwTeFZrg9XZa+DFTitWOW5iTAG7tyCUPsCCyw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.28.6.tgz", + "integrity": "sha512-jppVbf8IV9iWWwWTQIxJMAJCWBuuKx71475wHwYytrRGQ2CWiDvYlADQno3tcYpS/T2UUWFQp3nVtYfK/YBQrA==", "license": "MIT", "dependencies": { - "@babel/helper-module-transforms": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1286,15 +1231,15 @@ } }, "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.27.1.tgz", - "integrity": "sha512-w5N1XzsRbc0PQStASMksmUeqECuzKuTJer7kFagK8AXgpCMkeDMO5S+aaFb7A51ZYDF7XI34qsTX+fkHiIm5yA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.0.tgz", + "integrity": "sha512-PrujnVFbOdUpw4UHiVwKvKRLMMic8+eC0CuNlxjsyZUiBjhFdPsewdXCkveh2KqBA9/waD0W1b4hXSOBQJezpQ==", "license": "MIT", "dependencies": { - "@babel/helper-module-transforms": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1", - "@babel/traverse": "^7.27.1" + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.29.0" }, "engines": { "node": ">=6.9.0" @@ -1320,13 +1265,13 @@ } }, "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.27.1.tgz", - "integrity": "sha512-SstR5JYy8ddZvD6MhV0tM/j16Qds4mIpJTOd1Yu9J9pJjH93bxHECF7pgtc28XvkzTD6Pxcm/0Z73Hvk7kb3Ng==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.29.0.tgz", + "integrity": "sha512-1CZQA5KNAD6ZYQLPw7oi5ewtDNxH/2vuCh+6SmvgDfhumForvs8a1o9n0UrEoBD8HU4djO2yWngTQlXl1NDVEQ==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1351,12 +1296,12 @@ } }, "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.27.1.tgz", - "integrity": "sha512-aGZh6xMo6q9vq1JGcw58lZ1Z0+i0xB2x0XaauNIUXd6O1xXc3RwoWEBlsTQrY4KQ9Jf0s5rgD6SiNkaUdJegTA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.28.6.tgz", + "integrity": "sha512-3wKbRgmzYbw24mDJXT7N+ADXw8BC/imU9yo9c9X9NKaLF1fW+e5H1U5QjMUBe4Qo4Ox/o++IyUkl1sVCLgevKg==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1366,12 +1311,12 @@ } }, "node_modules/@babel/plugin-transform-numeric-separator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.27.1.tgz", - "integrity": "sha512-fdPKAcujuvEChxDBJ5c+0BTaS6revLV7CJL08e4m3de8qJfNIuCc2nc7XJYOjBoTMJeqSmwXJ0ypE14RCjLwaw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.28.6.tgz", + "integrity": "sha512-SJR8hPynj8outz+SlStQSwvziMN4+Bq99it4tMIf5/Caq+3iOc0JtKyse8puvyXkk3eFRIA5ID/XfunGgO5i6w==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1381,16 +1326,16 @@ } }, "node_modules/@babel/plugin-transform-object-rest-spread": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.28.4.tgz", - "integrity": "sha512-373KA2HQzKhQCYiRVIRr+3MjpCObqzDlyrM6u4I201wL8Mp2wHf7uB8GhDwis03k2ti8Zr65Zyyqs1xOxUF/Ew==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.28.6.tgz", + "integrity": "sha512-5rh+JR4JBC4pGkXLAcYdLHZjXudVxWMXbB6u6+E9lRL5TrGVbHt1TjxGbZ8CkmYw9zjkB7jutzOROArsqtncEA==", "license": "MIT", "dependencies": { - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/plugin-transform-destructuring": "^7.28.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/plugin-transform-destructuring": "^7.28.5", "@babel/plugin-transform-parameters": "^7.27.7", - "@babel/traverse": "^7.28.4" + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1416,12 +1361,12 @@ } }, "node_modules/@babel/plugin-transform-optional-catch-binding": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.27.1.tgz", - "integrity": "sha512-txEAEKzYrHEX4xSZN4kJ+OfKXFVSWKB2ZxM9dpcE3wT7smwkNmXo5ORRlVzMVdJbD+Q8ILTgSD7959uj+3Dm3Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.28.6.tgz", + "integrity": "sha512-R8ja/Pyrv0OGAvAXQhSTmWyPJPml+0TMqXlO5w+AsMEiwb2fg3WkOvob7UxFSL3OIttFSGSRFKQsOhJ/X6HQdQ==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1431,12 +1376,12 @@ } }, "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.27.1.tgz", - "integrity": "sha512-BQmKPPIuc8EkZgNKsv0X4bPmOoayeu4F1YCwx2/CfmDSXDbp7GnzlUH+/ul5VGfRg1AoFPsrIThlEBj2xb4CAg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.28.6.tgz", + "integrity": "sha512-A4zobikRGJTsX9uqVFdafzGkqD30t26ck2LmOzAuLL8b2x6k3TIqRiT2xVvA9fNmFeTX484VpsdgmKNA0bS23w==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" }, "engines": { @@ -1462,13 +1407,13 @@ } }, "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.27.1.tgz", - "integrity": "sha512-10FVt+X55AjRAYI9BrdISN9/AQWHqldOeZDUoLyif1Kn05a56xVBXb8ZouL8pZ9jem8QpXaOt8TS7RHUIS+GPA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.28.6.tgz", + "integrity": "sha512-piiuapX9CRv7+0st8lmuUlRSmX6mBcVeNQ1b4AYzJxfCMuBfB0vBXDiGSmm03pKJw1v6cZ8KSeM+oUnM6yAExg==", "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1478,14 +1423,14 @@ } }, "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.27.1.tgz", - "integrity": "sha512-5J+IhqTi1XPa0DXF83jYOaARrX+41gOewWbkPyjMNRDqgOCqdffGh8L3f/Ek5utaEBZExjSAzcyjmV9SSAWObQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.28.6.tgz", + "integrity": "sha512-b97jvNSOb5+ehyQmBpmhOCiUC5oVK4PMnpRvO7+ymFBoqYjeDHIU9jnrNUuwHOiL9RpGDoKBpSViarV+BU+eVA==", "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^7.27.1", - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1540,16 +1485,16 @@ } }, "node_modules/@babel/plugin-transform-react-jsx": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.27.1.tgz", - "integrity": "sha512-2KH4LWGSrJIkVf5tSiBFYuXDAoWRq2MMwgivCf+93dd0GQi8RXLjKA/0EvRnVV5G0hrHczsquXuD01L8s6dmBw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.28.6.tgz", + "integrity": "sha512-61bxqhiRfAACulXSLd/GxqmAedUSrRZIu/cbaT18T1CetkTmtDN15it7i80ru4DVqRK1WMxQhXs+Lf9kajm5Ow==", "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^7.27.1", - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/plugin-syntax-jsx": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/plugin-syntax-jsx": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1590,12 +1535,12 @@ } }, "node_modules/@babel/plugin-transform-regenerator": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.28.4.tgz", - "integrity": "sha512-+ZEdQlBoRg9m2NnzvEeLgtvBMO4tkFBw5SQIUgLICgTrumLoU7lr+Oghi6km2PFj+dbUt2u1oby2w3BDO9YQnA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.0.tgz", + "integrity": "sha512-FijqlqMA7DmRdg/aINBSs04y8XNTYw/lr1gJ2WsmBnnaNw1iS43EPkJW+zK7z65auG3AWRFXWj+NcTQwYptUog==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1605,13 +1550,13 @@ } }, "node_modules/@babel/plugin-transform-regexp-modifiers": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.27.1.tgz", - "integrity": "sha512-TtEciroaiODtXvLZv4rmfMhkCv8jx3wgKpL68PuiPh2M4fvz5jhsA7697N1gMvkvr/JTF13DrFYyEbY9U7cVPA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.28.6.tgz", + "integrity": "sha512-QGWAepm9qxpaIs7UM9FvUSnCGlb8Ua1RhyM4/veAxLwt3gMat/LSGrZixyuj4I6+Kn9iwvqCyPTtbdxanYoWYg==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1636,13 +1581,13 @@ } }, "node_modules/@babel/plugin-transform-runtime": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.28.3.tgz", - "integrity": "sha512-Y6ab1kGqZ0u42Zv/4a7l0l72n9DKP/MKoKWaUSBylrhNZO2prYuqFOLbn5aW5SIFXwSH93yfjbgllL8lxuGKLg==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.29.0.tgz", + "integrity": "sha512-jlaRT5dJtMaMCV6fAuLbsQMSwz/QkvaHOHOSXRitGGwSpR1blCY4KUKoyP2tYO8vJcqYe8cEj96cqSztv3uF9w==", "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "babel-plugin-polyfill-corejs2": "^0.4.14", "babel-plugin-polyfill-corejs3": "^0.13.0", "babel-plugin-polyfill-regenerator": "^0.6.5", @@ -1680,12 +1625,12 @@ } }, "node_modules/@babel/plugin-transform-spread": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.27.1.tgz", - "integrity": "sha512-kpb3HUqaILBJcRFVhFUs6Trdd4mkrzcGXss+6/mxUd273PfbWqSDHRzMT2234gIg2QYfAjvXLSquP1xECSg09Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.28.6.tgz", + "integrity": "sha512-9U4QObUC0FtJl05AsUcodau/RWDytrU6uKgkxu09mLR9HLDAtUMoPuuskm5huQsoktmsYpI+bGmq+iapDcriKA==", "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" }, "engines": { @@ -1741,16 +1686,16 @@ } }, "node_modules/@babel/plugin-transform-typescript": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.28.0.tgz", - "integrity": "sha512-4AEiDEBPIZvLQaWlc9liCavE0xRM0dNca41WtBeM3jgFptfUOSG9z0uteLhq6+3rq+WB6jIvUwKDTpXEHPJ2Vg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.28.6.tgz", + "integrity": "sha512-0YWL2RFxOqEm9Efk5PvreamxPME8OyY0wM5wh5lHjF+VtVhdneCWGzZeSqzOfiobVqQaNCd2z0tQvnI9DaPWPw==", "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", - "@babel/plugin-syntax-typescript": "^7.27.1" + "@babel/plugin-syntax-typescript": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1775,13 +1720,13 @@ } }, "node_modules/@babel/plugin-transform-unicode-property-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.27.1.tgz", - "integrity": "sha512-uW20S39PnaTImxp39O5qFlHLS9LJEmANjMG7SxIhap8rCHqu0Ik+tLEPX5DKmHn6CsWQ7j3lix2tFOa5YtL12Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.28.6.tgz", + "integrity": "sha512-4Wlbdl/sIZjzi/8St0evF0gEZrgOswVO6aOzqxh1kDZOl9WmLrHq2HtGhnOJZmHZYKP8WZ1MDLCt5DAWwRo57A==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1807,13 +1752,13 @@ } }, "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.27.1.tgz", - "integrity": "sha512-EtkOujbc4cgvb0mlpQefi4NTPBzhSIevblFevACNLUspmrALgmEBdL/XfnyyITfd8fKBZrZys92zOWcik7j9Tw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.28.6.tgz", + "integrity": "sha512-/wHc/paTUmsDYN7SZkpWxogTOBNnlx7nBQYfy6JJlCT7G3mVhltk3e++N7zV0XfgGsrqBxd4rJQt9H16I21Y1Q==", "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1823,80 +1768,80 @@ } }, "node_modules/@babel/preset-env": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.28.3.tgz", - "integrity": "sha512-ROiDcM+GbYVPYBOeCR6uBXKkQpBExLl8k9HO1ygXEyds39j+vCCsjmj7S8GOniZQlEs81QlkdJZe76IpLSiqpg==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.29.2.tgz", + "integrity": "sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==", "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.28.0", - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/compat-data": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", - "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.27.1", + "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.28.5", "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^7.27.1", "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.27.1", "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.27.1", - "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.28.3", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.28.6", "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", - "@babel/plugin-syntax-import-assertions": "^7.27.1", - "@babel/plugin-syntax-import-attributes": "^7.27.1", + "@babel/plugin-syntax-import-assertions": "^7.28.6", + "@babel/plugin-syntax-import-attributes": "^7.28.6", "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", "@babel/plugin-transform-arrow-functions": "^7.27.1", - "@babel/plugin-transform-async-generator-functions": "^7.28.0", - "@babel/plugin-transform-async-to-generator": "^7.27.1", + "@babel/plugin-transform-async-generator-functions": "^7.29.0", + "@babel/plugin-transform-async-to-generator": "^7.28.6", "@babel/plugin-transform-block-scoped-functions": "^7.27.1", - "@babel/plugin-transform-block-scoping": "^7.28.0", - "@babel/plugin-transform-class-properties": "^7.27.1", - "@babel/plugin-transform-class-static-block": "^7.28.3", - "@babel/plugin-transform-classes": "^7.28.3", - "@babel/plugin-transform-computed-properties": "^7.27.1", - "@babel/plugin-transform-destructuring": "^7.28.0", - "@babel/plugin-transform-dotall-regex": "^7.27.1", + "@babel/plugin-transform-block-scoping": "^7.28.6", + "@babel/plugin-transform-class-properties": "^7.28.6", + "@babel/plugin-transform-class-static-block": "^7.28.6", + "@babel/plugin-transform-classes": "^7.28.6", + "@babel/plugin-transform-computed-properties": "^7.28.6", + "@babel/plugin-transform-destructuring": "^7.28.5", + "@babel/plugin-transform-dotall-regex": "^7.28.6", "@babel/plugin-transform-duplicate-keys": "^7.27.1", - "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.29.0", "@babel/plugin-transform-dynamic-import": "^7.27.1", - "@babel/plugin-transform-explicit-resource-management": "^7.28.0", - "@babel/plugin-transform-exponentiation-operator": "^7.27.1", + "@babel/plugin-transform-explicit-resource-management": "^7.28.6", + "@babel/plugin-transform-exponentiation-operator": "^7.28.6", "@babel/plugin-transform-export-namespace-from": "^7.27.1", "@babel/plugin-transform-for-of": "^7.27.1", "@babel/plugin-transform-function-name": "^7.27.1", - "@babel/plugin-transform-json-strings": "^7.27.1", + "@babel/plugin-transform-json-strings": "^7.28.6", "@babel/plugin-transform-literals": "^7.27.1", - "@babel/plugin-transform-logical-assignment-operators": "^7.27.1", + "@babel/plugin-transform-logical-assignment-operators": "^7.28.6", "@babel/plugin-transform-member-expression-literals": "^7.27.1", "@babel/plugin-transform-modules-amd": "^7.27.1", - "@babel/plugin-transform-modules-commonjs": "^7.27.1", - "@babel/plugin-transform-modules-systemjs": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.28.6", + "@babel/plugin-transform-modules-systemjs": "^7.29.0", "@babel/plugin-transform-modules-umd": "^7.27.1", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.29.0", "@babel/plugin-transform-new-target": "^7.27.1", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.27.1", - "@babel/plugin-transform-numeric-separator": "^7.27.1", - "@babel/plugin-transform-object-rest-spread": "^7.28.0", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.28.6", + "@babel/plugin-transform-numeric-separator": "^7.28.6", + "@babel/plugin-transform-object-rest-spread": "^7.28.6", "@babel/plugin-transform-object-super": "^7.27.1", - "@babel/plugin-transform-optional-catch-binding": "^7.27.1", - "@babel/plugin-transform-optional-chaining": "^7.27.1", + "@babel/plugin-transform-optional-catch-binding": "^7.28.6", + "@babel/plugin-transform-optional-chaining": "^7.28.6", "@babel/plugin-transform-parameters": "^7.27.7", - "@babel/plugin-transform-private-methods": "^7.27.1", - "@babel/plugin-transform-private-property-in-object": "^7.27.1", + "@babel/plugin-transform-private-methods": "^7.28.6", + "@babel/plugin-transform-private-property-in-object": "^7.28.6", "@babel/plugin-transform-property-literals": "^7.27.1", - "@babel/plugin-transform-regenerator": "^7.28.3", - "@babel/plugin-transform-regexp-modifiers": "^7.27.1", + "@babel/plugin-transform-regenerator": "^7.29.0", + "@babel/plugin-transform-regexp-modifiers": "^7.28.6", "@babel/plugin-transform-reserved-words": "^7.27.1", "@babel/plugin-transform-shorthand-properties": "^7.27.1", - "@babel/plugin-transform-spread": "^7.27.1", + "@babel/plugin-transform-spread": "^7.28.6", "@babel/plugin-transform-sticky-regex": "^7.27.1", "@babel/plugin-transform-template-literals": "^7.27.1", "@babel/plugin-transform-typeof-symbol": "^7.27.1", "@babel/plugin-transform-unicode-escapes": "^7.27.1", - "@babel/plugin-transform-unicode-property-regex": "^7.27.1", + "@babel/plugin-transform-unicode-property-regex": "^7.28.6", "@babel/plugin-transform-unicode-regex": "^7.27.1", - "@babel/plugin-transform-unicode-sets-regex": "^7.27.1", + "@babel/plugin-transform-unicode-sets-regex": "^7.28.6", "@babel/preset-modules": "0.1.6-no-external-plugins", - "babel-plugin-polyfill-corejs2": "^0.4.14", - "babel-plugin-polyfill-corejs3": "^0.13.0", - "babel-plugin-polyfill-regenerator": "^0.6.5", - "core-js-compat": "^3.43.0", + "babel-plugin-polyfill-corejs2": "^0.4.15", + "babel-plugin-polyfill-corejs3": "^0.14.0", + "babel-plugin-polyfill-regenerator": "^0.6.6", + "core-js-compat": "^3.48.0", "semver": "^6.3.1" }, "engines": { @@ -1906,6 +1851,19 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.14.2.tgz", + "integrity": "sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==", + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8", + "core-js-compat": "^3.48.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -1930,14 +1888,14 @@ } }, "node_modules/@babel/preset-react": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.27.1.tgz", - "integrity": "sha512-oJHWh2gLhU9dW9HHr42q0cI0/iHHXTLGe39qvpAZZzagHy0MzYLCnCVV0symeRvzmjHyVU7mw2K06E6u/JwbhA==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.28.5.tgz", + "integrity": "sha512-Z3J8vhRq7CeLjdC58jLv4lnZ5RKFUJWqH5emvxmv9Hv3BD1T9R/Im713R4MTKwvFaV74ejZ3sM01LyEKk4ugNQ==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", "@babel/helper-validator-option": "^7.27.1", - "@babel/plugin-transform-react-display-name": "^7.27.1", + "@babel/plugin-transform-react-display-name": "^7.28.0", "@babel/plugin-transform-react-jsx": "^7.27.1", "@babel/plugin-transform-react-jsx-development": "^7.27.1", "@babel/plugin-transform-react-pure-annotations": "^7.27.1" @@ -1950,16 +1908,16 @@ } }, "node_modules/@babel/preset-typescript": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.27.1.tgz", - "integrity": "sha512-l7WfQfX0WK4M0v2RudjuQK4u99BS6yLHYEmdtVPP7lKV013zr9DygFuWNlnbvQ9LR+LS0Egz/XAvGx5U9MX0fQ==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.28.5.tgz", + "integrity": "sha512-+bQy5WOI2V6LJZpPVxY+yp66XdZ2yifu0Mc1aP5CQKgjn4QM5IN2i5fAZ4xKop47pr8rpVhiAeu+nDQa12C8+g==", "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", "@babel/helper-validator-option": "^7.27.1", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-transform-modules-commonjs": "^7.27.1", - "@babel/plugin-transform-typescript": "^7.27.1" + "@babel/plugin-transform-typescript": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -1977,44 +1935,32 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/runtime-corejs3": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.28.4.tgz", - "integrity": "sha512-h7iEYiW4HebClDEhtvFObtPmIvrd1SSfpI9EhOeKk4CtIK/ngBWFpuhCzhdmRKtg71ylcue+9I6dv54XYO1epQ==", - "license": "MIT", - "dependencies": { - "core-js-pure": "^3.43.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/template": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", - "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/parser": "^7.27.2", - "@babel/types": "^7.27.1" + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.4.tgz", - "integrity": "sha512-YEzuboP2qvQavAcjgQNVgsvHIDv6ZpwXvcvjmyySP2DIMuByS/6ioU5G9pYrWHM6T2YDfc7xga9iNzYOs12CFQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.3", + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", - "@babel/parser": "^7.28.4", - "@babel/template": "^7.27.2", - "@babel/types": "^7.28.4", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", "debug": "^4.3.1" }, "engines": { @@ -2022,18 +1968,61 @@ } }, "node_modules/@babel/types": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.4.tgz", - "integrity": "sha512-bkFqkLhh3pMBUQQkpVgWDWq/lqzc2678eUyDlTBhRqhCHFguYYGM0Efga7tYk4TogG/3x0EEl66/OQ+WGbWB/Q==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1" + "@babel/helper-validator-identifier": "^7.28.5" }, "engines": { "node": ">=6.9.0" } }, + "node_modules/@braintree/sanitize-url": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz", + "integrity": "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==", + "license": "MIT" + }, + "node_modules/@chevrotain/cst-dts-gen": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-12.0.0.tgz", + "integrity": "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/gast": "12.0.0", + "@chevrotain/types": "12.0.0" + } + }, + "node_modules/@chevrotain/gast": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-12.0.0.tgz", + "integrity": "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/types": "12.0.0" + } + }, + "node_modules/@chevrotain/regexp-to-ast": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-12.0.0.tgz", + "integrity": "sha512-p+EW9MaJwgaHguhoqwOtx/FwuGr+DnNn857sXWOi/mClXIkPGl3rn7hGNWvo31HA3vyeQxjqe+H36yZJwYU8cA==", + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/types": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-12.0.0.tgz", + "integrity": "sha512-S+04vjFQKeuYw0/eW3U52LkAHQsB1ASxsPGsLPUyQgrZ2iNNibQrsidruDzjEX2JYfespXMG0eZmXlhA6z7nWA==", + "license": "Apache-2.0" + }, + "node_modules/@chevrotain/utils": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz", + "integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==", + "license": "Apache-2.0" + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -2278,9 +2267,9 @@ } }, "node_modules/@csstools/postcss-cascade-layers/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -2699,9 +2688,9 @@ } }, "node_modules/@csstools/postcss-is-pseudo-class/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -2938,9 +2927,9 @@ } }, "node_modules/@csstools/postcss-normalize-display-values": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@csstools/postcss-normalize-display-values/-/postcss-normalize-display-values-4.0.0.tgz", - "integrity": "sha512-HlEoG0IDRoHXzXnkV4in47dzsxdsjdz6+j7MLjaACABX2NfvjFS6XVAnpaDyGesz9gK2SC7MbNwdCHusObKJ9Q==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@csstools/postcss-normalize-display-values/-/postcss-normalize-display-values-4.0.1.tgz", + "integrity": "sha512-TQUGBuRvxdc7TgNSTevYqrL8oItxiwPDixk20qCB5me/W8uF7BPbhRrAvFuhEoywQp/woRsUZ6SJ+sU5idZAIA==", "funding": [ { "type": "github", @@ -2991,6 +2980,28 @@ "postcss": "^8.4" } }, + "node_modules/@csstools/postcss-position-area-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@csstools/postcss-position-area-property/-/postcss-position-area-property-1.0.0.tgz", + "integrity": "sha512-fUP6KR8qV2NuUZV3Cw8itx0Ep90aRjAZxAEzC3vrl6yjFv+pFsQbR18UuQctEKmA72K9O27CoYiKEgXxkqjg8Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, "node_modules/@csstools/postcss-progressive-custom-properties": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/@csstools/postcss-progressive-custom-properties/-/postcss-progressive-custom-properties-4.2.1.tgz", @@ -3016,6 +3027,32 @@ "postcss": "^8.4" } }, + "node_modules/@csstools/postcss-property-rule-prelude-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@csstools/postcss-property-rule-prelude-list/-/postcss-property-rule-prelude-list-1.0.0.tgz", + "integrity": "sha512-IxuQjUXq19fobgmSSvUDO7fVwijDJaZMvWQugxfEUxmjBeDCVaDuMpsZ31MsTm5xbnhA+ElDi0+rQ7sQQGisFA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "dependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, "node_modules/@csstools/postcss-random-function": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/@csstools/postcss-random-function/-/postcss-random-function-2.0.1.tgz", @@ -3098,9 +3135,9 @@ } }, "node_modules/@csstools/postcss-scope-pseudo-class/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -3164,10 +3201,10 @@ "postcss": "^8.4" } }, - "node_modules/@csstools/postcss-text-decoration-shorthand": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@csstools/postcss-text-decoration-shorthand/-/postcss-text-decoration-shorthand-4.0.3.tgz", - "integrity": "sha512-KSkGgZfx0kQjRIYnpsD7X2Om9BUXX/Kii77VBifQW9Ih929hK0KNjVngHDH0bFB9GmfWcR9vJYJJRvw/NQjkrA==", + "node_modules/@csstools/postcss-syntax-descriptor-syntax-production": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@csstools/postcss-syntax-descriptor-syntax-production/-/postcss-syntax-descriptor-syntax-production-1.0.1.tgz", + "integrity": "sha512-GneqQWefjM//f4hJ/Kbox0C6f2T7+pi4/fqTqOFGTL3EjnvOReTqO1qUQ30CaUjkwjYq9qZ41hzarrAxCc4gow==", "funding": [ { "type": "github", @@ -3180,8 +3217,59 @@ ], "license": "MIT-0", "dependencies": { - "@csstools/color-helpers": "^5.1.0", - "postcss-value-parser": "^4.2.0" + "@csstools/css-tokenizer": "^3.0.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/@csstools/postcss-system-ui-font-family": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@csstools/postcss-system-ui-font-family/-/postcss-system-ui-font-family-1.0.0.tgz", + "integrity": "sha512-s3xdBvfWYfoPSBsikDXbuorcMG1nN1M6GdU0qBsGfcmNR0A/qhloQZpTxjA3Xsyrk1VJvwb2pOfiOT3at/DuIQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "dependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "postcss": "^8.4" + } + }, + "node_modules/@csstools/postcss-text-decoration-shorthand": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@csstools/postcss-text-decoration-shorthand/-/postcss-text-decoration-shorthand-4.0.3.tgz", + "integrity": "sha512-KSkGgZfx0kQjRIYnpsD7X2Om9BUXX/Kii77VBifQW9Ih929hK0KNjVngHDH0bFB9GmfWcR9vJYJJRvw/NQjkrA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "postcss-value-parser": "^4.2.0" }, "engines": { "node": ">=18" @@ -3270,25 +3358,43 @@ "node": ">=10.0.0" } }, + "node_modules/@docsearch/core": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@docsearch/core/-/core-4.6.2.tgz", + "integrity": "sha512-/S0e6Dj7Zcm8m9Rru49YEX49dhU11be68c+S/BCyN8zQsTTgkKzXlhRbVL5mV6lOLC2+ZRRryaTdcm070Ug2oA==", + "license": "MIT", + "peerDependencies": { + "@types/react": ">= 16.8.0 < 20.0.0", + "react": ">= 16.8.0 < 20.0.0", + "react-dom": ">= 16.8.0 < 20.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/@docsearch/css": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-4.1.0.tgz", - "integrity": "sha512-nuNKGjHj/FQeWgE9t+i83QD/V67QiaAmGY7xS9TVCRUiCqSljOgIKlsLoQZKKVwEG8f+OWKdznzZkJxGZ7d06A==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-4.6.2.tgz", + "integrity": "sha512-fH/cn8BjEEdM2nJdjNMHIvOVYupG6AIDtFVDgIZrNzdCSj4KXr9kd+hsehqsNGYjpUjObeKYKvgy/IwCb1jZYQ==", "license": "MIT" }, "node_modules/@docsearch/react": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-4.1.0.tgz", - "integrity": "sha512-4GHI7TT3sJZ2Vs4Kjadv7vAkMrTsJqHvzvxO3JA7UT8iPRKaDottG5o5uNshPWhVVaBYPC35Ukf8bfCotGpjSg==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-4.6.2.tgz", + "integrity": "sha512-/BbtGFtqVOGwZx0dw/UfhN/0/DmMQYnulY4iv0tPRhC2JCXv0ka/+izwt3Jzo1ZxXS/2eMvv9zHsBJOK1I9f/w==", "license": "MIT", "dependencies": { - "@ai-sdk/react": "^2.0.30", "@algolia/autocomplete-core": "1.19.2", - "@docsearch/css": "4.1.0", - "ai": "^5.0.30", - "algoliasearch": "^5.28.0", - "marked": "^16.3.0", - "zod": "^4.1.8" + "@docsearch/core": "4.6.2", + "@docsearch/css": "4.6.2" }, "peerDependencies": { "@types/react": ">= 16.8.0 < 20.0.0", @@ -3311,10 +3417,42 @@ } } }, + "node_modules/@docsearch/react/node_modules/@algolia/autocomplete-core": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.19.2.tgz", + "integrity": "sha512-mKv7RyuAzXvwmq+0XRK8HqZXt9iZ5Kkm2huLjgn5JoCPtDy+oh9yxUMfDDaVCw0oyzZ1isdJBc7l9nuCyyR7Nw==", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-plugin-algolia-insights": "1.19.2", + "@algolia/autocomplete-shared": "1.19.2" + } + }, + "node_modules/@docsearch/react/node_modules/@algolia/autocomplete-plugin-algolia-insights": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.19.2.tgz", + "integrity": "sha512-TjxbcC/r4vwmnZaPwrHtkXNeqvlpdyR+oR9Wi2XyfORkiGkLTVhX2j+O9SaCCINbKoDfc+c2PB8NjfOnz7+oKg==", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-shared": "1.19.2" + }, + "peerDependencies": { + "search-insights": ">= 1 < 3" + } + }, + "node_modules/@docsearch/react/node_modules/@algolia/autocomplete-shared": { + "version": "1.19.2", + "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.19.2.tgz", + "integrity": "sha512-jEazxZTVD2nLrC+wYlVHQgpBoBB5KPStrJxLzsIFl6Kqd1AlG9sIAGl39V5tECLpIQzB3Qa2T6ZPJ1ChkwMK/w==", + "license": "MIT", + "peerDependencies": { + "@algolia/client-search": ">= 4.9.1 < 6", + "algoliasearch": ">= 4.9.1 < 6" + } + }, "node_modules/@docusaurus/babel": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/babel/-/babel-3.9.1.tgz", - "integrity": "sha512-/uoi3oG+wvbVWNBRfPrzrEslOSeLxrQEyWMywK51TLDFTANqIRivzkMusudh5bdDty8fXzCYUT+tg5t697jYqg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/babel/-/babel-3.10.0.tgz", + "integrity": "sha512-mqCJhCZNZUDg0zgDEaPTM4DnRsisa24HdqTy/qn/MQlbwhTb4WVaZg6ZyX6yIVKqTz8fS1hBMgM+98z+BeJJDg==", "license": "MIT", "dependencies": { "@babel/core": "^7.25.9", @@ -3325,10 +3463,9 @@ "@babel/preset-react": "^7.25.9", "@babel/preset-typescript": "^7.25.9", "@babel/runtime": "^7.25.9", - "@babel/runtime-corejs3": "^7.25.9", "@babel/traverse": "^7.25.9", - "@docusaurus/logger": "3.9.1", - "@docusaurus/utils": "3.9.1", + "@docusaurus/logger": "3.10.0", + "@docusaurus/utils": "3.10.0", "babel-plugin-dynamic-import-node": "^2.3.3", "fs-extra": "^11.1.1", "tslib": "^2.6.0" @@ -3338,17 +3475,17 @@ } }, "node_modules/@docusaurus/bundler": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/bundler/-/bundler-3.9.1.tgz", - "integrity": "sha512-E1c9DgNmAz4NqbNtiJVp4UgjLtr8O01IgtXD/NDQ4PZaK8895cMiTOgb3k7mN0qX8A3lb8vqyrPJ842+yMpuUg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/bundler/-/bundler-3.10.0.tgz", + "integrity": "sha512-iONUGZGgp+lAkw/cJZH6irONcF4p8+278IsdRlq8lYhxGjkoNUs0w7F4gVXBYSNChq5KG5/JleTSsdJySShxow==", "license": "MIT", "dependencies": { "@babel/core": "^7.25.9", - "@docusaurus/babel": "3.9.1", - "@docusaurus/cssnano-preset": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", + "@docusaurus/babel": "3.10.0", + "@docusaurus/cssnano-preset": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", "babel-loader": "^9.2.1", "clean-css": "^5.3.3", "copy-webpack-plugin": "^11.0.0", @@ -3381,18 +3518,18 @@ } }, "node_modules/@docusaurus/core": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-3.9.1.tgz", - "integrity": "sha512-FWDk1LIGD5UR5Zmm9rCrXRoxZUgbwuP6FBA7rc50DVfzqDOMkeMe3NyJhOsA2dF0zBE3VbHEIMmTjKwTZJwbaA==", - "license": "MIT", - "dependencies": { - "@docusaurus/babel": "3.9.1", - "@docusaurus/bundler": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/core/-/core-3.10.0.tgz", + "integrity": "sha512-mgLdQsO8xppnQZc3LPi+Mf+PkPeyxJeIx11AXAq/14fsaMefInQiMEZUUmrc7J+956G/f7MwE7tn8KZgi3iRcA==", + "license": "MIT", + "dependencies": { + "@docusaurus/babel": "3.10.0", + "@docusaurus/bundler": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "boxen": "^6.2.1", "chalk": "^4.1.2", "chokidar": "^3.5.3", @@ -3404,7 +3541,7 @@ "escape-html": "^1.0.3", "eta": "^2.2.0", "eval": "^0.1.8", - "execa": "5.1.1", + "execa": "^5.1.1", "fs-extra": "^11.1.1", "html-tags": "^3.3.1", "html-webpack-plugin": "^5.6.0", @@ -3415,12 +3552,12 @@ "prompts": "^2.4.2", "react-helmet-async": "npm:@slorber/react-helmet-async@1.3.0", "react-loadable": "npm:@docusaurus/react-loadable@6.0.0", - "react-loadable-ssr-addon-v5-slorber": "^1.0.1", + "react-loadable-ssr-addon-v5-slorber": "^1.0.3", "react-router": "^5.3.4", "react-router-config": "^5.1.1", "react-router-dom": "^5.3.4", "semver": "^7.5.4", - "serve-handler": "^6.1.6", + "serve-handler": "^6.1.7", "tinypool": "^1.0.2", "tslib": "^2.6.0", "update-notifier": "^6.0.2", @@ -3436,15 +3573,21 @@ "node": ">=20.0" }, "peerDependencies": { + "@docusaurus/faster": "*", "@mdx-js/react": "^3.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@docusaurus/faster": { + "optional": true + } } }, "node_modules/@docusaurus/cssnano-preset": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-3.9.1.tgz", - "integrity": "sha512-2y7+s7RWQMqBg+9ejeKwvZs7Bdw/hHIVJIodwMXbs2kr+S48AhcmAfdOh6Cwm0unJb0hJUshN0ROwRoQMwl3xg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/cssnano-preset/-/cssnano-preset-3.10.0.tgz", + "integrity": "sha512-qzSshTO1DB3TYW+dPUal5KHM7XPc5YQfzF3Kdb2NDACJUyGbNcFtw3tGkCJlYwhNCRKbZcmwraKUS1i5dcHdGg==", "license": "MIT", "dependencies": { "cssnano-preset-advanced": "^6.1.2", @@ -3457,9 +3600,9 @@ } }, "node_modules/@docusaurus/logger": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-3.9.1.tgz", - "integrity": "sha512-C9iFzXwHzwvGlisE4bZx+XQE0JIqlGAYAd5LzpR7fEDgjctu7yL8bE5U4nTNywXKHURDzMt4RJK8V6+stFHVkA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/logger/-/logger-3.10.0.tgz", + "integrity": "sha512-9jrZzFuBH1LDRlZ7cznAhCLmAZ3HSDqgwdrSSZdGHq9SPUOQgXXu8mnxe2ZRB9NS1PCpMTIOVUqDtZPIhMafZg==", "license": "MIT", "dependencies": { "chalk": "^4.1.2", @@ -3470,14 +3613,14 @@ } }, "node_modules/@docusaurus/mdx-loader": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-3.9.1.tgz", - "integrity": "sha512-/1PY8lqry8jCt0qZddJSpc0U2sH6XC27kVJZfpA7o2TiQ3mdBQyH5AVbj/B2m682B1ounE+XjI0LdpOkAQLPoA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/mdx-loader/-/mdx-loader-3.10.0.tgz", + "integrity": "sha512-mQQV97080AH4PYNs087l202NMDqRopZA4mg5W76ZZyTFrmWhJ3mHg+8A+drJVENxw5/Q+wHMHLgsx+9z1nEs0A==", "license": "MIT", "dependencies": { - "@docusaurus/logger": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/logger": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "@mdx-js/mdx": "^3.0.0", "@slorber/remark-comment": "^1.0.0", "escape-html": "^1.0.3", @@ -3509,12 +3652,12 @@ } }, "node_modules/@docusaurus/module-type-aliases": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-3.9.1.tgz", - "integrity": "sha512-YBce3GbJGGcMbJTyHcnEOMvdXqg41pa5HsrMCGA5Rm4z0h0tHS6YtEldj0mlfQRhCG7Y0VD66t2tb87Aom+11g==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/module-type-aliases/-/module-type-aliases-3.10.0.tgz", + "integrity": "sha512-/1O0Zg8w3DFrYX/I6Fbss7OJrtZw1QoyjDhegiFNHVi9A9Y0gQ3jUAytVxF6ywpAWpLyLxch8nN8H/V3XfzdJQ==", "license": "MIT", "dependencies": { - "@docusaurus/types": "3.9.1", + "@docusaurus/types": "3.10.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -3528,20 +3671,21 @@ } }, "node_modules/@docusaurus/plugin-content-blog": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-3.9.1.tgz", - "integrity": "sha512-vT6kIimpJLWvW9iuWzH4u7VpTdsGlmn4yfyhq0/Kb1h4kf9uVouGsTmrD7WgtYBUG1P+TSmQzUUQa+ALBSRTig==", - "license": "MIT", - "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/theme-common": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-blog/-/plugin-content-blog-3.10.0.tgz", + "integrity": "sha512-RuTz68DhB7CL96QO5UsFbciD7GPYq6QV+YMfF9V0+N4ZgLhJIBgpVAr8GobrKF6NRe5cyWWETU5z5T834piG9g==", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "cheerio": "1.0.0-rc.12", + "combine-promises": "^1.1.0", "feed": "^4.2.2", "fs-extra": "^11.1.1", "lodash": "^4.17.21", @@ -3562,20 +3706,20 @@ } }, "node_modules/@docusaurus/plugin-content-docs": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-3.9.1.tgz", - "integrity": "sha512-DyLk9BIA6I9gPIuia8XIL+XIEbNnExam6AHzRsfrEq4zJr7k/DsWW7oi4aJMepDnL7jMRhpVcdsCxdjb0/A9xg==", - "license": "MIT", - "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/module-type-aliases": "3.9.1", - "@docusaurus/theme-common": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-docs/-/plugin-content-docs-3.10.0.tgz", + "integrity": "sha512-9BjHhf15ct8Z7TThTC0xRndKDVvMKmVsAGAN7W9FpNRzfMdScOGcXtLmcCWtJGvAezjOJIm6CxOYCy3Io5+RnQ==", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/module-type-aliases": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "@types/react-router-config": "^5.0.7", "combine-promises": "^1.1.0", "fs-extra": "^11.1.1", @@ -3595,16 +3739,16 @@ } }, "node_modules/@docusaurus/plugin-content-pages": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-3.9.1.tgz", - "integrity": "sha512-/1wFzRnXYASI+Nv9ck9IVPIMw0O5BGQ8ZVhDzEwhkL+tl44ycvSnY6PIe6rW2HLxsw61Z3WFwAiU8+xMMtMZpg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-content-pages/-/plugin-content-pages-3.10.0.tgz", + "integrity": "sha512-5amX8kEJI+nIGtuLVjYk59Y5utEJ3CHETFOPEE4cooIRLA4xM4iBsA6zFgu4ljcopeYwvBzFEWf5g2I6Yb9SkA==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "fs-extra": "^11.1.1", "tslib": "^2.6.0", "webpack": "^5.88.1" @@ -3618,15 +3762,15 @@ } }, "node_modules/@docusaurus/plugin-css-cascade-layers": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-css-cascade-layers/-/plugin-css-cascade-layers-3.9.1.tgz", - "integrity": "sha512-/QyW2gRCk/XE3ttCK/ERIgle8KJ024dBNKMu6U5SmpJvuT2il1n5jR/48Pp/9wEwut8WVml4imNm6X8JsL5A0Q==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-css-cascade-layers/-/plugin-css-cascade-layers-3.10.0.tgz", + "integrity": "sha512-6q1vtt5FJcg5osgkHeM1euErECNqEZ5Z1j69yiNx2luEBIso+nxCkS9nqj8w+MK5X7rvKEToGhFfOFWncs51pQ==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "tslib": "^2.6.0" }, "engines": { @@ -3634,14 +3778,14 @@ } }, "node_modules/@docusaurus/plugin-debug": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-3.9.1.tgz", - "integrity": "sha512-qPeAuk0LccC251d7jg2MRhNI+o7niyqa924oEM/AxnZJvIpMa596aAxkRImiAqNN6+gtLE1Hkrz/RHUH2HDGsA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-debug/-/plugin-debug-3.10.0.tgz", + "integrity": "sha512-XcljKN+G+nmmK69uQA1d9BlYU3ZftG3T3zpK8/7Hf/wrOlV7TA4Ampdrdwkg0jElKdKAoSnPhCO0/U3bQGsVQQ==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", "fs-extra": "^11.1.1", "react-json-view-lite": "^2.3.0", "tslib": "^2.6.0" @@ -3655,14 +3799,14 @@ } }, "node_modules/@docusaurus/plugin-google-analytics": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-3.9.1.tgz", - "integrity": "sha512-k4Qq2HphqOrIU/CevGPdEO1yJnWUI8m0zOJsYt5NfMJwNsIn/gDD6gv/DKD+hxHndQT5pacsfBd4BWHZVNVroQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-analytics/-/plugin-google-analytics-3.10.0.tgz", + "integrity": "sha512-hTEoodatpBZnUat5nFExbuTGA1lhWGy7vZGuTew5Q3QDtGKFpSJLYmZJhdTjvCFwv1+qQ67hgAVlKdJOB8TXow==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "tslib": "^2.6.0" }, "engines": { @@ -3674,15 +3818,15 @@ } }, "node_modules/@docusaurus/plugin-google-gtag": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-3.9.1.tgz", - "integrity": "sha512-n9BURBiQyJKI/Ecz35IUjXYwXcgNCSq7/eA07+ZYcDiSyH2p/EjPf8q/QcZG3CyEJPZ/SzGkDHePfcVPahY4Gg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-gtag/-/plugin-google-gtag-3.10.0.tgz", + "integrity": "sha512-iB/Zzjv/eelJRbdULZqzWCbgMgJ7ht4ONVjXtN3+BI/muil6S87gQ1OJyPwlXD+ELdKkitC7bWv5eJdYOZLhrQ==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", - "@types/gtag.js": "^0.0.12", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", + "@types/gtag.js": "^0.0.20", "tslib": "^2.6.0" }, "engines": { @@ -3694,14 +3838,14 @@ } }, "node_modules/@docusaurus/plugin-google-tag-manager": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-3.9.1.tgz", - "integrity": "sha512-rZAQZ25ZuXaThBajxzLjXieTDUCMmBzfAA6ThElQ3o7Q+LEpOjCIrwGFau0KLY9HeG6x91+FwwsAM8zeApYDrg==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-google-tag-manager/-/plugin-google-tag-manager-3.10.0.tgz", + "integrity": "sha512-FEjZxqKgLHa+Wez/EgKxRwvArNCWIScfyEQD95rot7jkxp6nonjI5XIbGfO/iYhM5Qinwe8aIEQHP2KZtpqVuA==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "tslib": "^2.6.0" }, "engines": { @@ -3713,17 +3857,17 @@ } }, "node_modules/@docusaurus/plugin-sitemap": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-3.9.1.tgz", - "integrity": "sha512-k/bf5cXDxAJUYTzqatgFJwmZsLUbIgl6S8AdZMKGG2Mv2wcOHt+EQNN9qPyWZ5/9cFj+Q8f8DN+KQheBMYLong==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-sitemap/-/plugin-sitemap-3.10.0.tgz", + "integrity": "sha512-DVTSLjB97hIjmayGnGcBfognCeI7ZuUKgEnU7Oz81JYqXtVg94mVTthDjq3QHTylYNeCUbkaW8VF0FDLcc8pPw==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "fs-extra": "^11.1.1", "sitemap": "^7.1.1", "tslib": "^2.6.0" @@ -3737,15 +3881,15 @@ } }, "node_modules/@docusaurus/plugin-svgr": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/plugin-svgr/-/plugin-svgr-3.9.1.tgz", - "integrity": "sha512-TeZOXT2PSdTNR1OpDJMkYqFyX7MMhbd4t16hQByXksgZQCXNyw3Dio+KaDJ2Nj+LA4WkOvsk45bWgYG5MAaXSQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/plugin-svgr/-/plugin-svgr-3.10.0.tgz", + "integrity": "sha512-lNljBESaETZqVBMPqkrGchr+UPT1eZzEPLmJhz8I76BxbjqgsUnRvrq6lQJ9sYjgmgX52KB7kkgczqd2yzoswQ==", "license": "MIT", "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "@docusaurus/core": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "@svgr/core": "8.1.0", "@svgr/webpack": "^8.1.0", "tslib": "^2.6.0", @@ -3760,26 +3904,26 @@ } }, "node_modules/@docusaurus/preset-classic": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-3.9.1.tgz", - "integrity": "sha512-ZHga2xsxxsyd0dN1BpLj8S889Eu9eMBuj2suqxdw/vaaXu/FjJ8KEGbcaeo6nHPo8VQcBBnPEdkBtSDm2TfMNw==", - "license": "MIT", - "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/plugin-content-blog": "3.9.1", - "@docusaurus/plugin-content-docs": "3.9.1", - "@docusaurus/plugin-content-pages": "3.9.1", - "@docusaurus/plugin-css-cascade-layers": "3.9.1", - "@docusaurus/plugin-debug": "3.9.1", - "@docusaurus/plugin-google-analytics": "3.9.1", - "@docusaurus/plugin-google-gtag": "3.9.1", - "@docusaurus/plugin-google-tag-manager": "3.9.1", - "@docusaurus/plugin-sitemap": "3.9.1", - "@docusaurus/plugin-svgr": "3.9.1", - "@docusaurus/theme-classic": "3.9.1", - "@docusaurus/theme-common": "3.9.1", - "@docusaurus/theme-search-algolia": "3.9.1", - "@docusaurus/types": "3.9.1" + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/preset-classic/-/preset-classic-3.10.0.tgz", + "integrity": "sha512-kw/Ye02Hc6xP1OdTswy8yxQEHg0fdPpyWAQRxr5b2x3h7LlG2Zgbb5BDFROnXDDMpUxB7YejlocJIE5HIEfpNA==", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.10.0", + "@docusaurus/plugin-content-blog": "3.10.0", + "@docusaurus/plugin-content-docs": "3.10.0", + "@docusaurus/plugin-content-pages": "3.10.0", + "@docusaurus/plugin-css-cascade-layers": "3.10.0", + "@docusaurus/plugin-debug": "3.10.0", + "@docusaurus/plugin-google-analytics": "3.10.0", + "@docusaurus/plugin-google-gtag": "3.10.0", + "@docusaurus/plugin-google-tag-manager": "3.10.0", + "@docusaurus/plugin-sitemap": "3.10.0", + "@docusaurus/plugin-svgr": "3.10.0", + "@docusaurus/theme-classic": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/theme-search-algolia": "3.10.0", + "@docusaurus/types": "3.10.0" }, "engines": { "node": ">=20.0" @@ -3790,26 +3934,27 @@ } }, "node_modules/@docusaurus/theme-classic": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-3.9.1.tgz", - "integrity": "sha512-LrAIu/mQ04nG6s1cssC0TMmICD8twFIIn/hJ5Pd9uIPQvtKnyAKEn12RefopAul5KfMo9kixPaqogV5jIJr26w==", - "license": "MIT", - "dependencies": { - "@docusaurus/core": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/module-type-aliases": "3.9.1", - "@docusaurus/plugin-content-blog": "3.9.1", - "@docusaurus/plugin-content-docs": "3.9.1", - "@docusaurus/plugin-content-pages": "3.9.1", - "@docusaurus/theme-common": "3.9.1", - "@docusaurus/theme-translations": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-classic/-/theme-classic-3.10.0.tgz", + "integrity": "sha512-9msCAsRdN+UG+RwPwCFb0uKy4tGoPh5YfBozXeGUtIeAgsMdn6f3G/oY861luZ3t8S2ET8S9Y/1GnpJAGWytww==", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/module-type-aliases": "3.10.0", + "@docusaurus/plugin-content-blog": "3.10.0", + "@docusaurus/plugin-content-docs": "3.10.0", + "@docusaurus/plugin-content-pages": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/theme-translations": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", + "copy-text-to-clipboard": "^3.2.0", "infima": "0.2.0-alpha.45", "lodash": "^4.17.21", "nprogress": "^0.2.0", @@ -3830,15 +3975,15 @@ } }, "node_modules/@docusaurus/theme-common": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-3.9.1.tgz", - "integrity": "sha512-j9adi961F+6Ps9d0jcb5BokMcbjXAAJqKkV43eo8nh4YgmDj7KUNDX4EnOh/MjTQeO06oPY5cxp3yUXdW/8Ggw==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-common/-/theme-common-3.10.0.tgz", + "integrity": "sha512-Dkp1YXKn16ByCJAdIjbDIOpVb4Z66MsVD694/ilX1vAAHaVEMrVsf/NPd9VgreyFx08rJ9GqV1MtzsbTcU73Kg==", "license": "MIT", "dependencies": { - "@docusaurus/mdx-loader": "3.9.1", - "@docusaurus/module-type-aliases": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", + "@docusaurus/mdx-loader": "3.10.0", + "@docusaurus/module-type-aliases": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", "@types/history": "^4.7.11", "@types/react": "*", "@types/react-router-config": "*", @@ -3857,20 +4002,49 @@ "react-dom": "^18.0.0 || ^19.0.0" } }, + "node_modules/@docusaurus/theme-mermaid": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-mermaid/-/theme-mermaid-3.10.0.tgz", + "integrity": "sha512-Y2xrlwhIJ80oOZIO3PXL6A7J869splfcMI87E3NKpYsy3zJxOyV+BP1QMtGi59ajKgU868HPuyyn6J+6BZGOBg==", + "license": "MIT", + "dependencies": { + "@docusaurus/core": "3.10.0", + "@docusaurus/module-type-aliases": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", + "mermaid": ">=11.6.0", + "tslib": "^2.6.0" + }, + "engines": { + "node": ">=20.0" + }, + "peerDependencies": { + "@mermaid-js/layout-elk": "^0.1.9", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@mermaid-js/layout-elk": { + "optional": true + } + } + }, "node_modules/@docusaurus/theme-search-algolia": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-3.9.1.tgz", - "integrity": "sha512-WjM28bzlgfT6nHlEJemkwyGVpvGsZWPireV/w+wZ1Uo64xCZ8lNOb4xwQRukDaLSed3oPBN0gSnu06l5VuCXHg==", - "license": "MIT", - "dependencies": { - "@docsearch/react": "^3.9.0 || ^4.1.0", - "@docusaurus/core": "3.9.1", - "@docusaurus/logger": "3.9.1", - "@docusaurus/plugin-content-docs": "3.9.1", - "@docusaurus/theme-common": "3.9.1", - "@docusaurus/theme-translations": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-validation": "3.9.1", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-search-algolia/-/theme-search-algolia-3.10.0.tgz", + "integrity": "sha512-f5FPKI08e3JRG63vR/o4qeuUVHUHzFzM0nnF+AkB67soAZgNsKJRf2qmUZvlQkGwlV+QFkKe4D0ANMh1jToU3g==", + "license": "MIT", + "dependencies": { + "@algolia/autocomplete-core": "^1.19.2", + "@docsearch/react": "^3.9.0 || ^4.3.2", + "@docusaurus/core": "3.10.0", + "@docusaurus/logger": "3.10.0", + "@docusaurus/plugin-content-docs": "3.10.0", + "@docusaurus/theme-common": "3.10.0", + "@docusaurus/theme-translations": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-validation": "3.10.0", "algoliasearch": "^5.37.0", "algoliasearch-helper": "^3.26.0", "clsx": "^2.0.0", @@ -3889,9 +4063,9 @@ } }, "node_modules/@docusaurus/theme-translations": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-3.9.1.tgz", - "integrity": "sha512-mUQd49BSGKTiM6vP9+JFgRJL28lMIN3PUvXjF3rzuOHMByUZUBNwCt26Z23GkKiSIOrRkjKoaBNTipR/MHdYSQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/theme-translations/-/theme-translations-3.10.0.tgz", + "integrity": "sha512-L9IbFLwTc5+XdgH45iQYufLn0SVZd6BUNelDbKIFlH+E4hhjuj/XHWAFMX/w2K59rfy8wak9McOaei7BSUfRPA==", "license": "MIT", "dependencies": { "fs-extra": "^11.1.1", @@ -3902,16 +4076,16 @@ } }, "node_modules/@docusaurus/tsconfig": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/tsconfig/-/tsconfig-3.9.1.tgz", - "integrity": "sha512-stdzM1dNDgRO0OvxeznXlE3N1igUoeHPNJjiKqyffLizgpVgNXJBAWeG6fuoYiCH4udGUBqy2dyM+1+kG2/UPQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/tsconfig/-/tsconfig-3.10.0.tgz", + "integrity": "sha512-TXdC3WXuPrdQAexLvjUJfnYf3YKEgEqAs5nK0Q88pRBCW7t7oN4ILvWYb3A5Z1wlSXyXGWW/mCUmLEhdWsjnDQ==", "dev": true, "license": "MIT" }, "node_modules/@docusaurus/types": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-3.9.1.tgz", - "integrity": "sha512-ElekJ29sk39s5LTEZMByY1c2oH9FMtw7KbWFU3BtuQ1TytfIK39HhUivDEJvm5KCLyEnnfUZlvSNDXeyk0vzAA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/types/-/types-3.10.0.tgz", + "integrity": "sha512-F0dOt3FOoO20rRaFK7whGFQZ3ggyrWEdQc/c8/UiRuzhtg4y1w9FspXH5zpCT07uMnJKBPGh+qNazbNlCQqvSw==", "license": "MIT", "dependencies": { "@mdx-js/mdx": "^3.0.0", @@ -3945,16 +4119,16 @@ } }, "node_modules/@docusaurus/utils": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-3.9.1.tgz", - "integrity": "sha512-YAL4yhhWLl9DXuf5MVig260a6INz4MehrBGFU/CZu8yXmRiYEuQvRFWh9ZsjfAOyaG7za1MNmBVZ4VVAi/CiJA==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils/-/utils-3.10.0.tgz", + "integrity": "sha512-T3B0WTigsIthe0D4LQa2k+7bJY+c3WS+Wq2JhcznOSpn1lSN64yNtHQXboCj3QnUs1EuAZszQG1SHKu5w5ZrlA==", "license": "MIT", "dependencies": { - "@docusaurus/logger": "3.9.1", - "@docusaurus/types": "3.9.1", - "@docusaurus/utils-common": "3.9.1", + "@docusaurus/logger": "3.10.0", + "@docusaurus/types": "3.10.0", + "@docusaurus/utils-common": "3.10.0", "escape-string-regexp": "^4.0.0", - "execa": "5.1.1", + "execa": "^5.1.1", "file-loader": "^6.2.0", "fs-extra": "^11.1.1", "github-slugger": "^1.5.0", @@ -3977,12 +4151,12 @@ } }, "node_modules/@docusaurus/utils-common": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-3.9.1.tgz", - "integrity": "sha512-4M1u5Q8Zn2CYL2TJ864M51FV4YlxyGyfC3x+7CLuR6xsyTVNBNU4QMcPgsTHRS9J2+X6Lq7MyH6hiWXyi/sXUQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-common/-/utils-common-3.10.0.tgz", + "integrity": "sha512-JyL7sb9QVDgYvudIS81Dv0lsWm7le0vGZSDwsztxWam1SPBqrnkvBy9UYL/amh6pbybkyYTd3CMTkO24oMlCSw==", "license": "MIT", "dependencies": { - "@docusaurus/types": "3.9.1", + "@docusaurus/types": "3.10.0", "tslib": "^2.6.0" }, "engines": { @@ -3990,14 +4164,14 @@ } }, "node_modules/@docusaurus/utils-validation": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-3.9.1.tgz", - "integrity": "sha512-5bzab5si3E1udrlZuVGR17857Lfwe8iFPoy5AvMP9PXqDfoyIKT7gDQgAmxdRDMurgHaJlyhXEHHdzDKkOxxZQ==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@docusaurus/utils-validation/-/utils-validation-3.10.0.tgz", + "integrity": "sha512-c+6n2+ZPOJtWWc8Bb/EYdpSDfjYEScdCu9fB/SNjOmSCf1IdVnGf2T53o0tsz0gDRtCL90tifTL0JE/oMuP1Mw==", "license": "MIT", "dependencies": { - "@docusaurus/logger": "3.9.1", - "@docusaurus/utils": "3.9.1", - "@docusaurus/utils-common": "3.9.1", + "@docusaurus/logger": "3.10.0", + "@docusaurus/utils": "3.10.0", + "@docusaurus/utils-common": "3.10.0", "fs-extra": "^11.2.0", "joi": "^17.9.2", "js-yaml": "^4.1.0", @@ -4155,6 +4329,23 @@ "@hapi/hoek": "^9.0.0" } }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "license": "MIT" + }, + "node_modules/@iconify/utils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz", + "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==", + "license": "MIT", + "dependencies": { + "@antfu/install-pkg": "^1.1.0", + "@iconify/types": "^2.0.0", + "mlly": "^1.8.0" + } + }, "node_modules/@jest/schemas": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", @@ -4411,6 +4602,15 @@ "react": ">=16" } }, + "node_modules/@mermaid-js/parser": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.0.tgz", + "integrity": "sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==", + "license": "MIT", + "dependencies": { + "langium": "^4.0.0" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "0.2.10", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.10.tgz", @@ -4711,15 +4911,6 @@ "node": ">= 8" } }, - "node_modules/@opentelemetry/api": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", - "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", - "license": "Apache-2.0", - "engines": { - "node": ">=8.0.0" - } - }, "node_modules/@pnpm/config.env-replace": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@pnpm/config.env-replace/-/config.env-replace-1.1.0.tgz", @@ -4789,9 +4980,9 @@ "license": "BSD-3-Clause" }, "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "version": "0.27.10", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz", + "integrity": "sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA==", "license": "MIT" }, "node_modules/@sindresorhus/is": { @@ -4817,12 +5008,6 @@ "micromark-util-symbol": "^1.0.1" } }, - "node_modules/@standard-schema/spec": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz", - "integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==", - "license": "MIT" - }, "node_modules/@svgr/babel-plugin-add-jsx-attribute": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz", @@ -5092,15 +5277,6 @@ "node": ">=14.16" } }, - "node_modules/@trysound/sax": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@trysound/sax/-/sax-0.2.0.tgz", - "integrity": "sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==", - "license": "ISC", - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/@tybys/wasm-util": { "version": "0.9.0", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.9.0.tgz", @@ -5149,6 +5325,259 @@ "@types/node": "*" } }, + "node_modules/@types/d3": { + "version": "7.4.3", + "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", + "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==", + "license": "MIT", + "dependencies": { + "@types/d3-array": "*", + "@types/d3-axis": "*", + "@types/d3-brush": "*", + "@types/d3-chord": "*", + "@types/d3-color": "*", + "@types/d3-contour": "*", + "@types/d3-delaunay": "*", + "@types/d3-dispatch": "*", + "@types/d3-drag": "*", + "@types/d3-dsv": "*", + "@types/d3-ease": "*", + "@types/d3-fetch": "*", + "@types/d3-force": "*", + "@types/d3-format": "*", + "@types/d3-geo": "*", + "@types/d3-hierarchy": "*", + "@types/d3-interpolate": "*", + "@types/d3-path": "*", + "@types/d3-polygon": "*", + "@types/d3-quadtree": "*", + "@types/d3-random": "*", + "@types/d3-scale": "*", + "@types/d3-scale-chromatic": "*", + "@types/d3-selection": "*", + "@types/d3-shape": "*", + "@types/d3-time": "*", + "@types/d3-time-format": "*", + "@types/d3-timer": "*", + "@types/d3-transition": "*", + "@types/d3-zoom": "*" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", + "license": "MIT" + }, + "node_modules/@types/d3-axis": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz", + "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-brush": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz", + "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-chord": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz", + "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-contour": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz", + "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==", + "license": "MIT", + "dependencies": { + "@types/d3-array": "*", + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-delaunay": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz", + "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==", + "license": "MIT" + }, + "node_modules/@types/d3-dispatch": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz", + "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==", + "license": "MIT" + }, + "node_modules/@types/d3-drag": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz", + "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-dsv": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz", + "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-fetch": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz", + "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==", + "license": "MIT", + "dependencies": { + "@types/d3-dsv": "*" + } + }, + "node_modules/@types/d3-force": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz", + "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==", + "license": "MIT" + }, + "node_modules/@types/d3-format": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz", + "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==", + "license": "MIT" + }, + "node_modules/@types/d3-geo": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz", + "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==", + "license": "MIT", + "dependencies": { + "@types/geojson": "*" + } + }, + "node_modules/@types/d3-hierarchy": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz", + "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-polygon": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz", + "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==", + "license": "MIT" + }, + "node_modules/@types/d3-quadtree": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz", + "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==", + "license": "MIT" + }, + "node_modules/@types/d3-random": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz", + "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==", + "license": "MIT" + }, + "node_modules/@types/d3-selection": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz", + "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==", + "license": "MIT" + }, + "node_modules/@types/d3-shape": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz", + "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-time-format": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz", + "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, + "node_modules/@types/d3-transition": { + "version": "3.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz", + "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==", + "license": "MIT", + "dependencies": { + "@types/d3-selection": "*" + } + }, + "node_modules/@types/d3-zoom": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz", + "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==", + "license": "MIT", + "dependencies": { + "@types/d3-interpolate": "*", + "@types/d3-selection": "*" + } + }, "node_modules/@types/debug": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", @@ -5228,10 +5657,16 @@ "@types/send": "*" } }, + "node_modules/@types/geojson": { + "version": "7946.0.16", + "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", + "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", + "license": "MIT" + }, "node_modules/@types/gtag.js": { - "version": "0.0.12", - "resolved": "https://registry.npmjs.org/@types/gtag.js/-/gtag.js-0.0.12.tgz", - "integrity": "sha512-YQV9bUsemkzG81Ea295/nF/5GijnD2Af7QhEofh7xu+kvCN6RdodgNwwGWXB5GMI3NoyvQo0odNctoH/qLMIpg==", + "version": "0.0.20", + "resolved": "https://registry.npmjs.org/@types/gtag.js/-/gtag.js-0.0.20.tgz", + "integrity": "sha512-wwAbk3SA2QeU67unN7zPxjEHmPmlXwZXZvQEpbEUQuMCRGgKyE1m6XDuTUA9b6pCGb/GqJmdfMOY5LuDjJSbbg==", "license": "MIT" }, "node_modules/@types/hast": { @@ -5470,6 +5905,13 @@ "@types/node": "*" } }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/unist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", @@ -5486,9 +5928,9 @@ } }, "node_modules/@types/yargs": { - "version": "17.0.33", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz", - "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==", + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", "license": "MIT", "dependencies": { "@types/yargs-parser": "*" @@ -5506,6 +5948,16 @@ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==", "license": "ISC" }, + "node_modules/@upsetjs/venn.js": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@upsetjs/venn.js/-/venn.js-2.0.0.tgz", + "integrity": "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==", + "license": "MIT", + "optionalDependencies": { + "d3-selection": "^3.0.0", + "d3-transition": "^3.0.1" + } + }, "node_modules/@webassemblyjs/ast": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", @@ -5708,9 +6160,9 @@ } }, "node_modules/acorn": { - "version": "8.14.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", - "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -5762,24 +6214,6 @@ "node": ">=8" } }, - "node_modules/ai": { - "version": "5.0.56", - "resolved": "https://registry.npmjs.org/ai/-/ai-5.0.56.tgz", - "integrity": "sha512-Rl++Ogg6DxzFkVHAOJZzhqcqvqtBLGOP9mMxJOGr2EJWj5HH5zjqDcnRh6x5vBoca5kj/Gd0rvUZFMnyI+sRiw==", - "license": "Apache-2.0", - "dependencies": { - "@ai-sdk/gateway": "1.0.30", - "@ai-sdk/provider": "2.0.0", - "@ai-sdk/provider-utils": "3.0.10", - "@opentelemetry/api": "1.9.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "zod": "^3.25.76 || ^4.1.8" - } - }, "node_modules/ajv": { "version": "8.17.1", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", @@ -5826,34 +6260,34 @@ } }, "node_modules/algoliasearch": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.39.0.tgz", - "integrity": "sha512-DzTfhUxzg9QBNGzU/0kZkxEV72TeA4MmPJ7RVfLnQwHNhhliPo7ynglEWJS791rNlLFoTyrKvkapwr/P3EXV9A==", - "license": "MIT", - "dependencies": { - "@algolia/abtesting": "1.5.0", - "@algolia/client-abtesting": "5.39.0", - "@algolia/client-analytics": "5.39.0", - "@algolia/client-common": "5.39.0", - "@algolia/client-insights": "5.39.0", - "@algolia/client-personalization": "5.39.0", - "@algolia/client-query-suggestions": "5.39.0", - "@algolia/client-search": "5.39.0", - "@algolia/ingestion": "1.39.0", - "@algolia/monitoring": "1.39.0", - "@algolia/recommend": "5.39.0", - "@algolia/requester-browser-xhr": "5.39.0", - "@algolia/requester-fetch": "5.39.0", - "@algolia/requester-node-http": "5.39.0" + "version": "5.51.0", + "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.51.0.tgz", + "integrity": "sha512-u3XS8HaTzt5YN90KPsOXMRjYJUMVD1dtr6yi4NXQluMbZ5IjQNBu1MEabdAxFhYtEuexqomPMSmRIhQJUd3QSg==", + "license": "MIT", + "dependencies": { + "@algolia/abtesting": "1.17.0", + "@algolia/client-abtesting": "5.51.0", + "@algolia/client-analytics": "5.51.0", + "@algolia/client-common": "5.51.0", + "@algolia/client-insights": "5.51.0", + "@algolia/client-personalization": "5.51.0", + "@algolia/client-query-suggestions": "5.51.0", + "@algolia/client-search": "5.51.0", + "@algolia/ingestion": "1.51.0", + "@algolia/monitoring": "1.51.0", + "@algolia/recommend": "5.51.0", + "@algolia/requester-browser-xhr": "5.51.0", + "@algolia/requester-fetch": "5.51.0", + "@algolia/requester-node-http": "5.51.0" }, "engines": { "node": ">= 14.0.0" } }, "node_modules/algoliasearch-helper": { - "version": "3.26.0", - "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.26.0.tgz", - "integrity": "sha512-Rv2x3GXleQ3ygwhkhJubhhYGsICmShLAiqtUuJTUkr9uOCOXyF2E71LVT4XDnVffbknv8XgScP4U0Oxtgm+hIw==", + "version": "3.28.1", + "resolved": "https://registry.npmjs.org/algoliasearch-helper/-/algoliasearch-helper-3.28.1.tgz", + "integrity": "sha512-6iXpbkkrAI5HFpCWXlNmIDSBuoN/U1XnEvb2yJAoWfqrZ+DrybI7MQ5P5mthFaprmocq+zbi6HxnR28xnZAYBw==", "license": "MIT", "dependencies": { "@algolia/events": "^4.0.1" @@ -6010,9 +6444,9 @@ "license": "MIT" }, "node_modules/autoprefixer": { - "version": "10.4.21", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz", - "integrity": "sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ==", + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.0.tgz", + "integrity": "sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==", "funding": [ { "type": "opencollective", @@ -6029,10 +6463,9 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.24.4", - "caniuse-lite": "^1.0.30001702", - "fraction.js": "^4.3.7", - "normalize-range": "^0.1.2", + "browserslist": "^4.28.2", + "caniuse-lite": "^1.0.30001787", + "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, @@ -6084,13 +6517,13 @@ } }, "node_modules/babel-plugin-polyfill-corejs2": { - "version": "0.4.14", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.14.tgz", - "integrity": "sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg==", + "version": "0.4.17", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", + "integrity": "sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==", "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.27.7", - "@babel/helper-define-polyfill-provider": "^0.6.5", + "@babel/compat-data": "^7.28.6", + "@babel/helper-define-polyfill-provider": "^0.6.8", "semver": "^6.3.1" }, "peerDependencies": { @@ -6120,12 +6553,12 @@ } }, "node_modules/babel-plugin-polyfill-regenerator": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.5.tgz", - "integrity": "sha512-ISqQ2frbiNU9vIJkzg7dlPpznPZ4jOiUQ1uSmB0fEHeowtN3COYRsXr/xexn64NpU13P06jc/L5TgiJXOgrbEg==", + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.8.tgz", + "integrity": "sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==", "license": "MIT", "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.5" + "@babel/helper-define-polyfill-provider": "^0.6.8" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" @@ -6148,12 +6581,15 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.8.8", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.8.tgz", - "integrity": "sha512-be0PUaPsQX/gPWWgFsdD+GFzaoig5PXaUC1xLkQiYdDnANU8sMnHoQd8JhbJQuvTWrWLyeFN9Imb5Qtfvr4RrQ==", + "version": "2.10.22", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.22.tgz", + "integrity": "sha512-6qruVrb5rse6WylFkU0FhBKKGuecWseqdpQfhkawn6ztyk2QlfwSRjsDxMCLJrkfmfN21qvhl9ABgaMeRkuwww==", "license": "Apache-2.0", "bin": { - "baseline-browser-mapping": "dist/cli.js" + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" } }, "node_modules/batch": { @@ -6270,9 +6706,9 @@ } }, "node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", + "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", @@ -6292,9 +6728,9 @@ } }, "node_modules/browserslist": { - "version": "4.26.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.26.2.tgz", - "integrity": "sha512-ECFzp6uFOSB+dcZ5BK/IBaGWssbSYBHvuMeMt3MMFyhI0Z8SqGgEkBLARgpRH3hutIgPVsALcMwbDrJqPxQ65A==", + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", "funding": [ { "type": "opencollective", @@ -6311,11 +6747,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.8.3", - "caniuse-lite": "^1.0.30001741", - "electron-to-chromium": "^1.5.218", - "node-releases": "^2.0.21", - "update-browserslist-db": "^1.1.3" + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" @@ -6382,14 +6818,14 @@ } }, "node_modules/call-bind": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", - "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", "license": "MIT", "dependencies": { - "call-bind-apply-helpers": "^1.0.0", - "es-define-property": "^1.0.0", - "get-intrinsic": "^1.2.4", + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", "set-function-length": "^1.2.2" }, "engines": { @@ -6472,9 +6908,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001745", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001745.tgz", - "integrity": "sha512-ywt6i8FzvdgrrrGbr1jZVObnVv6adj+0if2/omv9cmR2oiZs30zL4DIyaptKcbOrBdOIc74QTMoJvSE2QHh5UQ==", + "version": "1.0.30001790", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001790.tgz", + "integrity": "sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw==", "funding": [ { "type": "opencollective", @@ -6604,6 +7040,34 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/chevrotain": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-12.0.0.tgz", + "integrity": "sha512-csJvb+6kEiQaqo1woTdSAuOWdN0WTLIydkKrBnS+V5gZz0oqBrp4kQ35519QgK6TpBThiG3V1vNSHlIkv4AglQ==", + "license": "Apache-2.0", + "dependencies": { + "@chevrotain/cst-dts-gen": "12.0.0", + "@chevrotain/gast": "12.0.0", + "@chevrotain/regexp-to-ast": "12.0.0", + "@chevrotain/types": "12.0.0", + "@chevrotain/utils": "12.0.0" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/chevrotain-allstar": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.4.1.tgz", + "integrity": "sha512-PvVJm3oGqrveUVW2Vt/eZGeiAIsJszYweUcYwcskg9e+IubNYKKD+rHHem7A6XVO22eDAL+inxNIGAzZ/VIWlA==", + "license": "MIT", + "dependencies": { + "lodash-es": "^4.17.21" + }, + "peerDependencies": { + "chevrotain": "^12.0.0" + } + }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", @@ -6913,6 +7377,12 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "license": "MIT" }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "license": "MIT" + }, "node_modules/config-chain": { "version": "1.1.13", "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", @@ -6999,6 +7469,18 @@ "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", "license": "MIT" }, + "node_modules/copy-text-to-clipboard": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/copy-text-to-clipboard/-/copy-text-to-clipboard-3.2.2.tgz", + "integrity": "sha512-T6SqyLd1iLuqPA90J5N4cTalrtovCySh58iiZDGJ6FGznbclKh4UI+FGacQSgFzwKG77W7XT5gwbVEbd9cIH1A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/copy-webpack-plugin": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-11.0.0.tgz", @@ -7078,35 +7560,33 @@ } }, "node_modules/core-js-compat": { - "version": "3.45.1", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.45.1.tgz", - "integrity": "sha512-tqTt5T4PzsMIZ430XGviK4vzYSoeNJ6CXODi6c/voxOT6IZqBht5/EKaSNnYiEjjRYxjVz7DQIsOsY0XNi8PIA==", + "version": "3.49.0", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.49.0.tgz", + "integrity": "sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==", "license": "MIT", "dependencies": { - "browserslist": "^4.25.3" + "browserslist": "^4.28.1" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/core-js" } }, - "node_modules/core-js-pure": { - "version": "3.45.1", - "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.45.1.tgz", - "integrity": "sha512-OHnWFKgTUshEU8MK+lOs1H8kC8GkTi9Z1tvNkxrCcw9wl3MJIO7q2ld77wjWn4/xuGrVu2X+nME1iIIPBSdyEQ==", - "hasInstallScript": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/core-js" - } - }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "license": "MIT" }, + "node_modules/cose-base": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz", + "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==", + "license": "MIT", + "dependencies": { + "layout-base": "^1.0.0" + } + }, "node_modules/cosmiconfig": { "version": "8.3.6", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.3.6.tgz", @@ -7200,9 +7680,9 @@ } }, "node_modules/css-blank-pseudo/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -7213,9 +7693,9 @@ } }, "node_modules/css-declaration-sorter": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/css-declaration-sorter/-/css-declaration-sorter-7.3.0.tgz", - "integrity": "sha512-LQF6N/3vkAMYF4xoHLJfG718HRJh34Z8BnNhd6bosOMIVjMlhuZK5++oZa3uYAgrI5+7x2o27gUqTR2U/KjUOQ==", + "version": "7.4.0", + "resolved": "https://registry.npmjs.org/css-declaration-sorter/-/css-declaration-sorter-7.4.0.tgz", + "integrity": "sha512-LTuzjPoyA2vMGKKcaOqKSp7Ub2eGrNfKiZH4LpezxpNrsICGCSFvsQOI29psISxNZtaXibkC2CXzrQ5enMeGGw==", "license": "ISC", "engines": { "node": "^14 || ^16 || >=18" @@ -7274,9 +7754,9 @@ } }, "node_modules/css-has-pseudo/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -7429,9 +7909,9 @@ } }, "node_modules/cssdb": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/cssdb/-/cssdb-8.4.2.tgz", - "integrity": "sha512-PzjkRkRUS+IHDJohtxkIczlxPPZqRo0nXplsYXOMBRPjcVRjj1W4DfvRgshUYTVuUigU7ptVYkFJQ7abUB0nyg==", + "version": "8.8.0", + "resolved": "https://registry.npmjs.org/cssdb/-/cssdb-8.8.0.tgz", + "integrity": "sha512-QbLeyz2Bgso1iRlh7IpWk6OKa3lLNGXsujVjDMPl9rOZpxKeiG69icLpbLCFxeURwmcdIfZqQyhlooKJYM4f8Q==", "funding": [ { "type": "opencollective", @@ -7535,61 +8015,587 @@ "postcss-unique-selectors": "^6.0.4" }, "engines": { - "node": "^14 || ^16 || >=18.0" - }, - "peerDependencies": { - "postcss": "^8.4.31" + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/cssnano-utils": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/cssnano-utils/-/cssnano-utils-4.0.2.tgz", + "integrity": "sha512-ZR1jHg+wZ8o4c3zqf1SIUSTIvm/9mU343FMR6Obe/unskbvpGhZOo1J6d/r8D1pzkRQYuwbcH3hToOuoA2G7oQ==", + "license": "MIT", + "engines": { + "node": "^14 || ^16 || >=18.0" + }, + "peerDependencies": { + "postcss": "^8.4.31" + } + }, + "node_modules/csso": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/csso/-/csso-5.0.5.tgz", + "integrity": "sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==", + "license": "MIT", + "dependencies": { + "css-tree": "~2.2.0" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/css-tree": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", + "integrity": "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==", + "license": "MIT", + "dependencies": { + "mdn-data": "2.0.28", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/csso/node_modules/mdn-data": { + "version": "2.0.28", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.28.tgz", + "integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==", + "license": "CC0-1.0" + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "license": "MIT" + }, + "node_modules/cytoscape": { + "version": "3.33.2", + "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.2.tgz", + "integrity": "sha512-sj4HXd3DokGhzZAdjDejGvTPLqlt84vNFN8m7bGsOzDY5DyVcxIb2ejIXat2Iy7HxWhdT/N1oKyheJ5YdpsGuw==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/cytoscape-cose-bilkent": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz", + "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==", + "license": "MIT", + "dependencies": { + "cose-base": "^1.0.0" + }, + "peerDependencies": { + "cytoscape": "^3.2.0" + } + }, + "node_modules/cytoscape-fcose": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz", + "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==", + "license": "MIT", + "dependencies": { + "cose-base": "^2.2.0" + }, + "peerDependencies": { + "cytoscape": "^3.2.0" + } + }, + "node_modules/cytoscape-fcose/node_modules/cose-base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz", + "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==", + "license": "MIT", + "dependencies": { + "layout-base": "^2.0.0" + } + }, + "node_modules/cytoscape-fcose/node_modules/layout-base": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz", + "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==", + "license": "MIT" + }, + "node_modules/d3": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz", + "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==", + "license": "ISC", + "dependencies": { + "d3-array": "3", + "d3-axis": "3", + "d3-brush": "3", + "d3-chord": "3", + "d3-color": "3", + "d3-contour": "4", + "d3-delaunay": "6", + "d3-dispatch": "3", + "d3-drag": "3", + "d3-dsv": "3", + "d3-ease": "3", + "d3-fetch": "3", + "d3-force": "3", + "d3-format": "3", + "d3-geo": "3", + "d3-hierarchy": "3", + "d3-interpolate": "3", + "d3-path": "3", + "d3-polygon": "3", + "d3-quadtree": "3", + "d3-random": "3", + "d3-scale": "4", + "d3-scale-chromatic": "3", + "d3-selection": "3", + "d3-shape": "3", + "d3-time": "3", + "d3-time-format": "4", + "d3-timer": "3", + "d3-transition": "3", + "d3-zoom": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-axis": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz", + "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-brush": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz", + "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "3", + "d3-transition": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-chord": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz", + "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==", + "license": "ISC", + "dependencies": { + "d3-path": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-contour": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz", + "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==", + "license": "ISC", + "dependencies": { + "d3-array": "^3.2.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-delaunay": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz", + "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==", + "license": "ISC", + "dependencies": { + "delaunator": "5" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dispatch": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz", + "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-drag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz", + "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-selection": "3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz", + "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==", + "license": "ISC", + "dependencies": { + "commander": "7", + "iconv-lite": "0.6", + "rw": "1" + }, + "bin": { + "csv2json": "bin/dsv2json.js", + "csv2tsv": "bin/dsv2dsv.js", + "dsv2dsv": "bin/dsv2dsv.js", + "dsv2json": "bin/dsv2json.js", + "json2csv": "bin/json2dsv.js", + "json2dsv": "bin/json2dsv.js", + "json2tsv": "bin/json2dsv.js", + "tsv2csv": "bin/dsv2dsv.js", + "tsv2json": "bin/dsv2json.js" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-dsv/node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/d3-dsv/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-fetch": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz", + "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==", + "license": "ISC", + "dependencies": { + "d3-dsv": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-force": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz", + "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==", + "license": "ISC", + "dependencies": { + "d3-dispatch": "1 - 3", + "d3-quadtree": "1 - 3", + "d3-timer": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-geo": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz", + "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2.5.0 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-hierarchy": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz", + "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-polygon": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz", + "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-quadtree": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz", + "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-random": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz", + "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-sankey": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz", + "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-array": "1 - 2", + "d3-shape": "^1.2.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-array": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz", + "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==", + "license": "BSD-3-Clause", + "dependencies": { + "internmap": "^1.0.0" + } + }, + "node_modules/d3-sankey/node_modules/d3-path": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz", + "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==", + "license": "BSD-3-Clause" + }, + "node_modules/d3-sankey/node_modules/d3-shape": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz", + "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==", + "license": "BSD-3-Clause", + "dependencies": { + "d3-path": "1" + } + }, + "node_modules/d3-sankey/node_modules/internmap": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz", + "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==", + "license": "ISC" + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale-chromatic": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", + "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3", + "d3-interpolate": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-selection": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz", + "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" } }, - "node_modules/cssnano-utils": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/cssnano-utils/-/cssnano-utils-4.0.2.tgz", - "integrity": "sha512-ZR1jHg+wZ8o4c3zqf1SIUSTIvm/9mU343FMR6Obe/unskbvpGhZOo1J6d/r8D1pzkRQYuwbcH3hToOuoA2G7oQ==", - "license": "MIT", + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", "engines": { - "node": "^14 || ^16 || >=18.0" - }, - "peerDependencies": { - "postcss": "^8.4.31" + "node": ">=12" } }, - "node_modules/csso": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/csso/-/csso-5.0.5.tgz", - "integrity": "sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ==", - "license": "MIT", + "node_modules/d3-transition": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz", + "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==", + "license": "ISC", "dependencies": { - "css-tree": "~2.2.0" + "d3-color": "1 - 3", + "d3-dispatch": "1 - 3", + "d3-ease": "1 - 3", + "d3-interpolate": "1 - 3", + "d3-timer": "1 - 3" }, "engines": { - "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", - "npm": ">=7.0.0" + "node": ">=12" + }, + "peerDependencies": { + "d3-selection": "2 - 3" } }, - "node_modules/csso/node_modules/css-tree": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", - "integrity": "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA==", - "license": "MIT", + "node_modules/d3-zoom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz", + "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==", + "license": "ISC", "dependencies": { - "mdn-data": "2.0.28", - "source-map-js": "^1.0.1" + "d3-dispatch": "1 - 3", + "d3-drag": "2 - 3", + "d3-interpolate": "1 - 3", + "d3-selection": "2 - 3", + "d3-transition": "2 - 3" }, "engines": { - "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0", - "npm": ">=7.0.0" + "node": ">=12" } }, - "node_modules/csso/node_modules/mdn-data": { - "version": "2.0.28", - "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.28.tgz", - "integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==", - "license": "CC0-1.0" + "node_modules/dagre-d3-es": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.14.tgz", + "integrity": "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==", + "license": "MIT", + "dependencies": { + "d3": "^7.9.0", + "lodash-es": "^4.17.21" + } }, - "node_modules/csstype": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", - "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "node_modules/dayjs": { + "version": "1.11.20", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.20.tgz", + "integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==", "license": "MIT" }, "node_modules/debounce": { @@ -7599,9 +8605,9 @@ "license": "MIT" }, "node_modules/debug": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", - "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -7753,6 +8759,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delaunator": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", + "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", + "license": "ISC", + "dependencies": { + "robust-predicates": "^3.0.2" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -7900,6 +8915,15 @@ "url": "https://github.com/fb55/domhandler?sponsor=1" } }, + "node_modules/dompurify": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.1.tgz", + "integrity": "sha512-JahakDAIg1gyOm7dlgWSDjV4n7Ip2PKR55NIT6jrMfIgLFgWo81vdr1/QGqWtFNRqXP9UV71oVePtjqS2ebnPw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/domutils": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", @@ -7994,9 +9018,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.227", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.227.tgz", - "integrity": "sha512-ITxuoPfJu3lsNWUi2lBM2PaBPYgH3uqmxut5vmBxgYvyI4AlJ6P3Cai1O76mOrkJCBzq0IxWg/NtqOrpu/0gKA==", + "version": "1.5.344", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.344.tgz", + "integrity": "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg==", "license": "ISC" }, "node_modules/emoji-regex": { @@ -8436,15 +9460,6 @@ "node": ">=0.8.x" } }, - "node_modules/eventsource-parser": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", - "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", - "license": "MIT", - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -8906,15 +9921,15 @@ } }, "node_modules/fraction.js": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", - "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", "license": "MIT", "engines": { "node": "*" }, "funding": { - "type": "patreon", + "type": "github", "url": "https://github.com/sponsors/rawify" } }, @@ -9219,6 +10234,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/hachure-fill": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz", + "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==", + "license": "MIT" + }, "node_modules/handle-thing": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz", @@ -10002,6 +11023,15 @@ "integrity": "sha512-0aO8FkhNZlj/ZIbNi7Lxxr12obT7cL1moPfE4tg1LkX7LlLfC6DeX4l2ZEud1ukP9jNQyNnfzQVqwbwmAATY4Q==", "license": "MIT" }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/invariant": { "version": "2.2.4", "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", @@ -10467,12 +11497,6 @@ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", "license": "MIT" }, - "node_modules/json-schema": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", - "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", - "license": "(AFL-2.1 OR BSD-3-Clause)" - }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -10504,9 +11528,9 @@ } }, "node_modules/katex": { - "version": "0.16.22", - "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz", - "integrity": "sha512-XCHRdUw4lf3SKBaJe4EvgqIuWwkPSo9XoeO8GjQW94Bp7TWv9hNhzZjZ+OH9yf1UmLygb7DIT5GSFQiyt16zYg==", + "version": "0.16.45", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.45.tgz", + "integrity": "sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==", "funding": [ "https://opencollective.com/katex", "https://github.com/sponsors/katex" @@ -10537,6 +11561,11 @@ "json-buffer": "3.0.1" } }, + "node_modules/khroma": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz", + "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==" + }, "node_modules/kind-of": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", @@ -10564,6 +11593,24 @@ "node": ">=6" } }, + "node_modules/langium": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/langium/-/langium-4.2.2.tgz", + "integrity": "sha512-JUshTRAfHI4/MF9dH2WupvjSXyn8JBuUEWazB8ZVJUtXutT0doDlAv1XKbZ1Pb5sMexa8FF4CFBc0iiul7gbUQ==", + "license": "MIT", + "dependencies": { + "@chevrotain/regexp-to-ast": "~12.0.0", + "chevrotain": "~12.0.0", + "chevrotain-allstar": "~0.4.1", + "vscode-languageserver": "~9.0.1", + "vscode-languageserver-textdocument": "~1.0.11", + "vscode-uri": "~3.1.0" + }, + "engines": { + "node": ">=20.10.0", + "npm": ">=10.2.3" + } + }, "node_modules/latest-version": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-7.0.0.tgz", @@ -10589,6 +11636,12 @@ "shell-quote": "^1.8.3" } }, + "node_modules/layout-base": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz", + "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==", + "license": "MIT" + }, "node_modules/leven": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", @@ -10660,6 +11713,12 @@ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "license": "MIT" }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, "node_modules/lodash.debounce": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", @@ -11269,6 +12328,48 @@ "node": ">= 8" } }, + "node_modules/mermaid": { + "version": "11.14.0", + "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.14.0.tgz", + "integrity": "sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==", + "license": "MIT", + "dependencies": { + "@braintree/sanitize-url": "^7.1.1", + "@iconify/utils": "^3.0.2", + "@mermaid-js/parser": "^1.1.0", + "@types/d3": "^7.4.3", + "@upsetjs/venn.js": "^2.0.0", + "cytoscape": "^3.33.1", + "cytoscape-cose-bilkent": "^4.1.0", + "cytoscape-fcose": "^2.2.0", + "d3": "^7.9.0", + "d3-sankey": "^0.12.3", + "dagre-d3-es": "7.0.14", + "dayjs": "^1.11.19", + "dompurify": "^3.3.1", + "katex": "^0.16.25", + "khroma": "^2.1.0", + "lodash-es": "^4.17.23", + "marked": "^16.3.0", + "roughjs": "^4.6.6", + "stylis": "^4.3.6", + "ts-dedent": "^2.2.0", + "uuid": "^11.1.0" + } + }, + "node_modules/mermaid/node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "node_modules/methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", @@ -13205,9 +14306,9 @@ } }, "node_modules/mini-css-extract-plugin": { - "version": "2.9.4", - "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.9.4.tgz", - "integrity": "sha512-ZWYT7ln73Hptxqxk2DxPU9MmapXRhxkJD6tkSR04dnQxm8BGu2hzgKLugK5yySD97u/8yy7Ma7E76k9ZdvtjkQ==", + "version": "2.10.2", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.10.2.tgz", + "integrity": "sha512-AOSS0IdEB95ayVkxn5oGzNQwqAi2J0Jb/kKm43t7H73s8+f5873g0yuj0PNvK4dO75mu5DHg4nlgp4k6Kga8eg==", "license": "MIT", "dependencies": { "schema-utils": "^4.0.0", @@ -13231,9 +14332,9 @@ "license": "ISC" }, "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "license": "ISC", "dependencies": { "brace-expansion": "^1.1.7" @@ -13251,6 +14352,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, "node_modules/mrmime": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", @@ -13347,9 +14460,9 @@ } }, "node_modules/node-releases": { - "version": "2.0.21", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.21.tgz", - "integrity": "sha512-5b0pgg78U3hwXkCM8Z9b2FJdPZlr9Psr9V2gQPESdGHqbntyFJKFW4r5TeWGFzafGY3hzs1JC62VEQMbl1JFkw==", + "version": "2.0.38", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz", + "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", "license": "MIT" }, "node_modules/normalize-path": { @@ -13361,15 +14474,6 @@ "node": ">=0.10.0" } }, - "node_modules/normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/normalize-url": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-8.0.1.tgz", @@ -13433,9 +14537,9 @@ } }, "node_modules/null-loader/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.1", @@ -13725,6 +14829,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-manager-detector": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz", + "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==", + "license": "MIT" + }, "node_modules/param-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz", @@ -13864,6 +14974,12 @@ "tslib": "^2.0.3" } }, + "node_modules/path-data-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz", + "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==", + "license": "MIT" + }, "node_modules/path-exists": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", @@ -13912,6 +15028,12 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -13945,10 +15067,37 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/points-on-curve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz", + "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==", + "license": "MIT" + }, + "node_modules/points-on-path": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz", + "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==", + "license": "MIT", + "dependencies": { + "path-data-parser": "0.1.0", + "points-on-curve": "0.2.0" + } + }, "node_modules/postcss": { - "version": "8.5.6", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", - "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "version": "8.5.10", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz", + "integrity": "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==", "funding": [ { "type": "opencollective", @@ -13999,9 +15148,9 @@ } }, "node_modules/postcss-attribute-case-insensitive/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14243,9 +15392,9 @@ } }, "node_modules/postcss-custom-selectors/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14281,9 +15430,9 @@ } }, "node_modules/postcss-dir-pseudo-class/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14409,9 +15558,9 @@ } }, "node_modules/postcss-focus-visible/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14447,9 +15596,9 @@ } }, "node_modules/postcss-focus-within/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14736,9 +15885,9 @@ } }, "node_modules/postcss-modules-local-by-default/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14764,9 +15913,9 @@ } }, "node_modules/postcss-modules-scope/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -14863,9 +16012,9 @@ } }, "node_modules/postcss-nesting/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -15106,9 +16255,9 @@ } }, "node_modules/postcss-preset-env": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/postcss-preset-env/-/postcss-preset-env-10.4.0.tgz", - "integrity": "sha512-2kqpOthQ6JhxqQq1FSAAZGe9COQv75Aw8WbsOvQVNJ2nSevc9Yx/IKZGuZ7XJ+iOTtVon7LfO7ELRzg8AZ+sdw==", + "version": "10.6.1", + "resolved": "https://registry.npmjs.org/postcss-preset-env/-/postcss-preset-env-10.6.1.tgz", + "integrity": "sha512-yrk74d9EvY+W7+lO9Aj1QmjWY9q5NsKjK2V9drkOPZB/X6KZ0B3igKsHUYakb7oYVhnioWypQX3xGuePf89f3g==", "funding": [ { "type": "github", @@ -15146,23 +16295,27 @@ "@csstools/postcss-media-minmax": "^2.0.9", "@csstools/postcss-media-queries-aspect-ratio-number-values": "^3.0.5", "@csstools/postcss-nested-calc": "^4.0.0", - "@csstools/postcss-normalize-display-values": "^4.0.0", + "@csstools/postcss-normalize-display-values": "^4.0.1", "@csstools/postcss-oklab-function": "^4.0.12", + "@csstools/postcss-position-area-property": "^1.0.0", "@csstools/postcss-progressive-custom-properties": "^4.2.1", + "@csstools/postcss-property-rule-prelude-list": "^1.0.0", "@csstools/postcss-random-function": "^2.0.1", "@csstools/postcss-relative-color-syntax": "^3.0.12", "@csstools/postcss-scope-pseudo-class": "^4.0.1", "@csstools/postcss-sign-functions": "^1.1.4", "@csstools/postcss-stepped-value-functions": "^4.0.9", + "@csstools/postcss-syntax-descriptor-syntax-production": "^1.0.1", + "@csstools/postcss-system-ui-font-family": "^1.0.0", "@csstools/postcss-text-decoration-shorthand": "^4.0.3", "@csstools/postcss-trigonometric-functions": "^4.0.9", "@csstools/postcss-unset-value": "^4.0.0", - "autoprefixer": "^10.4.21", - "browserslist": "^4.26.0", + "autoprefixer": "^10.4.23", + "browserslist": "^4.28.1", "css-blank-pseudo": "^7.0.1", "css-has-pseudo": "^7.0.3", "css-prefers-color-scheme": "^10.0.0", - "cssdb": "^8.4.2", + "cssdb": "^8.6.0", "postcss-attribute-case-insensitive": "^7.0.1", "postcss-clamp": "^4.1.0", "postcss-color-functional-notation": "^7.0.12", @@ -15222,9 +16375,9 @@ } }, "node_modules/postcss-pseudo-class-any-link/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -15315,9 +16468,9 @@ } }, "node_modules/postcss-selector-not/node_modules/postcss-selector-parser": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.0.tgz", - "integrity": "sha512-8sLjZwK0R+JlxlYcTuVnyT2v+htpdrjDOKuMcOVdYjt52Lh8hWRYpxBPoKx/Zg+bcjc3wx6fmQevMmUztS/ccA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", + "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "license": "MIT", "dependencies": { "cssesc": "^3.0.0", @@ -15733,9 +16886,9 @@ } }, "node_modules/react-loadable-ssr-addon-v5-slorber": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/react-loadable-ssr-addon-v5-slorber/-/react-loadable-ssr-addon-v5-slorber-1.0.1.tgz", - "integrity": "sha512-lq3Lyw1lGku8zUEJPDxsNm1AfYHBrO9Y1+olAYwpUJ2IGFBskM0DMKok97A6LWUpHm+o7IvQBOWu9MLenp9Z+A==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/react-loadable-ssr-addon-v5-slorber/-/react-loadable-ssr-addon-v5-slorber-1.0.3.tgz", + "integrity": "sha512-GXfh9VLwB5ERaCsU6RULh7tkemeX15aNh6wuMEBtfdyMa7fFG8TXrhXlx1SoEK2Ty/l6XIkzzYIQmyaWW3JgdQ==", "license": "MIT", "dependencies": { "@babel/runtime": "^7.10.3" @@ -15958,9 +17111,9 @@ "license": "MIT" }, "node_modules/regjsparser": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.0.tgz", - "integrity": "sha512-NZQZdC5wOE/H3UT28fVGL+ikOZcEzfMGk/c3iN9UGxzWHMa1op7274oyiUVrAG4B2EuFhus8SvkaYnhvW92p9Q==", + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.13.1.tgz", + "integrity": "sha512-dLsljMd9sqwRkby8zhO1gSg3PnJIBFid8f4CQj/sXx+7cKx+E7u0PKhZ+U4wmhx7EfmtvnA318oVaIkAB1lRJw==", "license": "BSD-2-Clause", "dependencies": { "jsesc": "~3.1.0" @@ -16304,12 +17457,13 @@ "license": "MIT" }, "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", "license": "MIT", "dependencies": { - "is-core-module": "^2.16.0", + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -16378,6 +17532,24 @@ "node": ">=0.10.0" } }, + "node_modules/robust-predicates": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", + "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", + "license": "Unlicense" + }, + "node_modules/roughjs": { + "version": "4.6.6", + "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz", + "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==", + "license": "MIT", + "dependencies": { + "hachure-fill": "^0.5.2", + "path-data-parser": "^0.1.0", + "points-on-curve": "^0.2.0", + "points-on-path": "^0.2.1" + } + }, "node_modules/rtlcss": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/rtlcss/-/rtlcss-4.3.0.tgz", @@ -16431,6 +17603,12 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rw": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz", + "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==", + "license": "BSD-3-Clause" + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -16458,10 +17636,13 @@ "license": "MIT" }, "node_modules/sax": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz", - "integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==", - "license": "ISC" + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz", + "integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } }, "node_modules/scheduler": { "version": "0.26.0", @@ -16627,15 +17808,15 @@ } }, "node_modules/serve-handler": { - "version": "6.1.6", - "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.6.tgz", - "integrity": "sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==", + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.7.tgz", + "integrity": "sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg==", "license": "MIT", "dependencies": { "bytes": "3.0.0", "content-disposition": "0.5.2", "mime-types": "2.1.18", - "minimatch": "3.1.2", + "minimatch": "3.1.5", "path-is-inside": "1.0.2", "path-to-regexp": "3.3.0", "range-parser": "1.2.0" @@ -17093,9 +18274,9 @@ } }, "node_modules/std-env": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.9.0.tgz", - "integrity": "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", "license": "MIT" }, "node_modules/string_decoder": { @@ -17255,6 +18436,12 @@ "postcss": "^8.4.31" } }, + "node_modules/stylis": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.4.0.tgz", + "integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==", + "license": "MIT" + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -17286,18 +18473,18 @@ "license": "MIT" }, "node_modules/svgo": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.3.2.tgz", - "integrity": "sha512-OoohrmuUlBs8B8o6MB2Aevn+pRIH9zDALSR+6hhqVfa6fRwG/Qw9VUMSMW9VNg2CFc/MTIfabtdOVl9ODIJjpw==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.3.3.tgz", + "integrity": "sha512-+wn7I4p7YgJhHs38k2TNjy1vCfPIfLIJWR5MnCStsN8WuuTcBnRKcMHQLMM2ijxGZmDoZwNv8ipl5aTTen62ng==", "license": "MIT", "dependencies": { - "@trysound/sax": "0.2.0", "commander": "^7.2.0", "css-select": "^5.1.0", "css-tree": "^2.3.1", "css-what": "^6.1.0", "csso": "^5.0.5", - "picocolors": "^1.0.0" + "picocolors": "^1.0.0", + "sax": "^1.5.0" }, "bin": { "svgo": "bin/svgo" @@ -17319,19 +18506,6 @@ "node": ">= 10" } }, - "node_modules/swr": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.6.tgz", - "integrity": "sha512-wfHRmHWk/isGNMwlLGlZX5Gzz/uTgo0o2IRuTMcf4CPuPFJZlq0rDaKUx+ozB5nBOReNV1kiOyzMfj+MBMikLw==", - "license": "MIT", - "dependencies": { - "dequal": "^2.0.3", - "use-sync-external-store": "^1.4.0" - }, - "peerDependencies": { - "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, "node_modules/tapable": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.2.1.tgz", @@ -17444,18 +18618,6 @@ "tslib": "^2" } }, - "node_modules/throttleit": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz", - "integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/thunky": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", @@ -17474,6 +18636,15 @@ "integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==", "license": "MIT" }, + "node_modules/tinyexec": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.1.tgz", + "integrity": "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinypool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.0.tgz", @@ -17549,6 +18720,15 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/ts-dedent": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz", + "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==", + "license": "MIT", + "engines": { + "node": ">=6.10" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -17624,6 +18804,12 @@ "node": ">=14.17" } }, + "node_modules/ufo": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz", + "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==", + "license": "MIT" + }, "node_modules/undici": { "version": "6.21.3", "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz", @@ -17850,9 +19036,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", - "integrity": "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "funding": [ { "type": "opencollective", @@ -18059,15 +19245,6 @@ "url": "https://opencollective.com/webpack" } }, - "node_modules/use-sync-external-store": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz", - "integrity": "sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==", - "license": "MIT", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -18164,6 +19341,55 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/vscode-jsonrpc": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", + "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageserver": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz", + "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==", + "license": "MIT", + "dependencies": { + "vscode-languageserver-protocol": "3.17.5" + }, + "bin": { + "installServerIntoExtension": "bin/installServerIntoExtension" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", + "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "8.2.0", + "vscode-languageserver-types": "3.17.5" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", + "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", + "license": "MIT" + }, "node_modules/watchpack": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", @@ -18803,9 +20029,9 @@ "license": "ISC" }, "node_modules/yocto-queue": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.1.tgz", - "integrity": "sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz", + "integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==", "license": "MIT", "engines": { "node": ">=12.20" @@ -18814,15 +20040,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/zod": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.11.tgz", - "integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/package.json b/package.json index 9268bf8ba..9ef992e1c 100644 --- a/package.json +++ b/package.json @@ -16,9 +16,10 @@ "build:changelog": "node scripts/build-changelog.js" }, "dependencies": { - "@docusaurus/core": "^3.9.1", - "@docusaurus/plugin-sitemap": "^3.9.1", - "@docusaurus/preset-classic": "^3.9.1", + "@docusaurus/core": "^3.10.0", + "@docusaurus/plugin-sitemap": "^3.10.0", + "@docusaurus/preset-classic": "^3.10.0", + "@docusaurus/theme-mermaid": "^3.10.0", "@easyops-cn/docusaurus-search-local": "^0.49.2", "@mdx-js/react": "^3.0.0", "axios": "^1.9.0", @@ -30,9 +31,9 @@ "remark-math": "^6.0.0" }, "devDependencies": { - "@docusaurus/module-type-aliases": "^3.9.1", - "@docusaurus/tsconfig": "^3.9.1", - "@docusaurus/types": "^3.9.1", + "@docusaurus/module-type-aliases": "^3.10.0", + "@docusaurus/tsconfig": "^3.10.0", + "@docusaurus/types": "^3.10.0", "@types/dotenv": "^8.2.3", "typescript": "~5.6.2" }, diff --git a/sidebars.ts b/sidebars.ts index 0286e8634..f9cd2bd55 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -6,6 +6,12 @@ const sidebars: SidebarsConfig = { type: 'autogenerated', dirName: '.' } + ], + api: [ + { + type: 'autogenerated', + dirName: 'api' + } ] }; diff --git a/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json deleted file mode 100644 index 650683c42..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "description": "The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation" -} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md b/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md deleted file mode 100644 index a85f9771f..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Negative Selection - -The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation - -## Function check_detector_bnsa_validity(...) - -```python -def check_detector_bnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - aff_thresh: float -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters**: - -* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). -* aff_thresh (``float``): Affinity threshold. - -**returns**: - -* True if the detector is valid, False otherwise. - ---- - -## Function bnsa_class_prediction(...) - -```python -def bnsa_class_prediction( - features: npt.NDArray, - class_detectors: npt.NDArray, - aff_thresh: float -) -> int: -``` - -Defines the class of a sample from the non-self detectors. - -**Parameters**: - -* features (``npt.NDArray``): binary sample to be classified (shape: [n_features]). -* class_detectors (``npt.NDArray``): Array containing the detectors of all classes -(shape: [n_classes, n_detectors, n_features]). -* aff_thresh (``float``): Affinity threshold that determines whether a detector recognizes the sample as non-self. - -**returns**: - -* int: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- - -## Function check_detector_rnsa_validity(...) - -```python -def check_detector_rnsa_validity( - x_class: npt.NDArray, - vector_x: npt.NDArray, - threshold: float, - metric: int, - p: float -) -> bool: -``` - -Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. - -**Parameters**: - -* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). -* threshold (``float``): threshold. -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**returns**: - -* int: Index of the predicted class. Returns -1 if it is non-self for all classes. - ---- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md deleted file mode 100644 index 51c3bbdb3..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md +++ /dev/null @@ -1,152 +0,0 @@ -# Display - -Utility Functions for Displaying Algorithm Information - -## def _supports_box_drawing() - -```python -def _supports_box_drawing() -> bool -``` - -Function to check if the terminal supports boxed characters. - -**Returns**: - -* ***bool*** (`bool`): True if the terminal likely supports boxed characters, False otherwise. - ---- - -## class TableFormatter - -Class to format tabular data into strings for display in the console. - -**Parameters**: - -* ***headers*** (`Mapping[str, int]`): Mapping of column names to their respective widths, in the format `{column_name: column_width}`. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -### def _border(left, middle, right, line, new_line=True) - -```python -def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str -``` - -Create a horizontal border for the table. - -**Parameters**: - -* ***left*** (`str`): Character on the left side of the border. -* ***middle*** (`str`): Character separator between columns. -* ***right*** (`str`): Character on the right side of the border. -* ***line*** (`str`): Character used to fill the border. -* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is True). - -**Returns**: - -* ***border*** (`str`): String representing the horizontal border. - ---- - -### def get_header() - -```python -def get_header(self) -> str -``` - -Generate the table header, including the top border, column headings, and separator line. - -**Returns**: - -* ***header*** (`str`): Formatted string of the table header. - ---- - -### def get_row(values) - -```python -def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str -``` - -Generate a formatted row for the table data. - -**Parameters**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Dictionary with values for each column, in the format `{column_name: value}`. - -**Returns**: - -* ***row*** (`str`): Formatted string of the table row. - ---- - -### def get_bottom(new_line=False) - -```python -def get_bottom(self, new_line: bool = False) -> str -``` - -Generate the table's bottom border. - -**Parameters**: - -* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is False). - -**Returns**: - -* ***bottom*** (`str`): Formatted string for the bottom border. - ---- - -## class ProgressTable(TableFormatter) - -Class to display a formatted table in the console to track the algorithm's progress. - -**Parameters**: - -* ***headers*** (`Mapping[str, int]`): Mapping `{column_name: column_width}`. -* ***verbose*** (`bool`): If False, prints nothing to the terminal. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -### def _print_header() - -```python -def _print_header(self) -> None -``` - -Print the table header. - ---- - -### def update(values) - -```python -def update(self, values: Mapping[str, Union[str, int, float]]) -> None -``` - -Add a new row of values to the table. - -**Parameters**: - -* ***values*** (`Mapping[str, Union[str, int, float]]`): Keys must match the columns defined in headers. - ---- - -### def finish() - -```python -def finish(self) -> None -``` - -End the table display, printing the bottom border and total time. - ---- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md deleted file mode 100644 index 1ac5aba8b..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -last_update: - date: 2025/08/28 - author: João Paulo ---- - -# Distance - -Utility functions for normalized distance between arrays with numba decorators. - -## def hamming(...) - -```python -def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: -``` - -The function to calculate the normalized Hamming distance between two points. - -$$ -\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def euclidean(...) - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Function to calculate the normalized Euclidean distance between two points. - -$$ -\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def cityblock(...) - -```python -def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: -``` - -Function to calculate the normalized Manhattan distance between two points. - -$$ -\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def minkowski(...) - -```python -def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): -``` - -Function to calculate the normalized Minkowski distance between two points. - -$$ -\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} -$$ - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. -* p float: The p parameter defines the type of distance to be calculated: - * p = 1: **Manhattan** distance — sum of absolute differences. - * p = 2: **Euclidean** distance — sum of squared differences (square root). - * p > 2: **Minkowski** distance with an increasing penalty as p increases. - -**Returns:** - -* Distance (``float``) between the two points. - ---- - -## def compute_metric_distance(...) - -```python -def compute_metric_distance( - u: npt.NDArray[np.float64], - v: npt.NDArray[np.float64], - metric: int, - p: np.float64 = 2.0 -) -> np.float64: -``` - -Function to calculate the distance between two points by the chosen ``metric``. - -**Parameters:** - -* u (``npt.NDArray``): Coordinates of the first point. -* v (``npt.NDArray``): Coordinates of the second point. -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* Distance (``double``) between the two points with the selected metric. - ---- - -## def min_distance_to_class_vectors(...) - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray, - vector_x: npt.NDArray, - metric: int, - p: float = 2.0 -) -> float: -``` - -Calculates the minimum distance between an input vector and the vectors of a class. - -**Parameters:** - -* x_class (``npt.NDArray``): Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). -* vector_x (``npt.NDArray``): Vector to be compared with the class vectors. Expected shape: (n_features,). -* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] -* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). - -**Returns:** - -* float: The minimum distance calculated between the input vector and the class vectors. -* Returns -1.0 if the input dimensions are incompatible. - ---- - -## def get_metric_code(...) - -```python -def get_metric_code(metric: str) -> int: -``` - -Returns the numeric code associated with a distance metric. - -**Parameters:** - -* metric (str): Name of the metric. Can be "euclidean", "manhattan", "minkowski" or "hamming". - -**Raises** - -* ``ValueError``: If the metric provided is not supported - -**Returns:** - -* ``int``: Numeric code corresponding to the metric. - ---- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md deleted file mode 100644 index d65da92c8..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 1 -title: Metrics -sidebar_label: Metrics -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -The metrics file provides utilities to measure, analyze, and compare the performance of the package's algorithms in a standardized way. - -#### def accuracy_score(...) - -```python -def accuracy_score( - y_true: Union[npt.NDArray, list], - y_pred: Union[npt.NDArray, list] -) -> float -``` - -Function to calculate precision accuracy based on lists of true labels and -predicted labels. - -**Parameters**: - -* **_y_true_** (``Union[npt.NDArray, list]``): Ground truth (correct) labels. - Expected to be of the same length as `y_pred`. -* **_y_pred_** (``Union[npt.NDArray, list]``): Predicted labels. Expected to - be of the same length as `y_true`. - -Returns: - -* **_Accuracy_** (``float``): The ratio of correct predictions to the total -number of predictions. - -**Raises**: - -* `ValueError`: If `y_true` or `y_pred` are empty or if they do not have the same length. - ---- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md deleted file mode 100644 index dc919f82a..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -sidebar_position: 1 -title: Multiclass -sidebar_label: Multiclass -lastUpdatedAt: 2025/04/04 -author: João Paulo ---- - -This file contains internal utility functions designed to simplify data manipulation and processing in multiclass classification scenarios within the AISP package. - -## def slice_index_list_by_class(...) - -```python -def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict -``` - -The function ``slice_index_list_by_class(...)``, separates the indices of the lines \ -according to the output class, to loop through the sample array, only in positions where \ -the output is the class being trained. - -**Parameters**: - -* ***classes*** (``list or npt.NDArray``): list with unique classes. -* ***y*** (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array. - -**returns**: - -* dict: A dictionary with the list of array positions(``y``), with the classes as key. - ---- - -## def predict_knn_affinity(...) - -```python -def predict_knn_affinity( - X: npt.NDArray, - k: int, - all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], - affinity_func: Callable[[npt.NDArray, npt.NDArray], float] -) -> npt.NDArray -``` - -Function to predict classes using k-nearest neighbors and trained cells. - -**Parameters:** - -* ***X*** (`npt.NDArray`): Input data to be classified. -* ***k*** (`int`): Number of nearest neighbors to consider for prediction. -* ***all_cell_vectors*** (`List[Tuple[Union[str, int], npt.NDArray]]`): List of tuples containing (class_name, cell vector) pairs. -* ***affinity_func*** (`Callable[[npt.NDArray, npt.NDArray], float]`): Function that takes two vectors and returns an affinity value. - -**Returns:** - -* `npt.NDArray`: Array of predicted labels for each sample in X, based on the k nearest neighbors. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md deleted file mode 100644 index 8bcd03930..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md +++ /dev/null @@ -1,17 +0,0 @@ -# Random - -Utility functions for random number generation and reproducibility. - -## Function set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Set the seed for random numbers used by functions compiled with Numba. - -**Parameters**: - -* **seed**: `int` - Integer value used to initialize Numba's random number generator. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md deleted file mode 100644 index b57a80539..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# Sanitizers - -## def sanitize_choice(...) - -```python -def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T -``` - -The function ``sanitize_choice(...)``, returns the value if it is present in the set of valid choices; otherwise, returns the default value. - -**Parameters:** - -* ***value*** (``T``): The value to be checked. -* ***valid_choices*** (``Iterable[T]``): A collection of valid choices. -* ***default***: The default value to be returned if ``value`` is not in ``valid_choices``. - -**Returns:** - -* `T`: The original value if valid, or the default value if not. - ---- - -## def sanitize_param(...) - -```python -def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: -``` - -The function ``sanitize_param(...)``, returns the value if it satisfies the specified condition; otherwise, returns the default value. - -**Parameters:** - -* value (``T``): The value to be checked. -* default (``T``): The default value to be returned if the condition is not satisfied. -* condition (``Callable[[T], bool]``): A function that takes a value and returns a boolean, determining if the value is valid. - -**Returns:** - -* `T`: The original value if the condition is satisfied, or the default value if not. - ---- - -## def sanitize_seed(...) - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -The function ``sanitize_param(...)``, returns the seed if it is a non-negative integer; otherwise, returns None. - -**Parameters:** - -* seed (``Any``): The seed value to be validated. - -**Returns:** - -* ``Optional[int]``: The original seed if it is a non-negative integer, or ``None`` if it is invalid. - ---- - -## def sanitize_bounds(...) - -```python -def sanitize_bounds( - bounds: Any, - problem_size: int -) -> Dict[str, npt.NDArray[np.float64]] -``` - -The function ``sanitize_bounds(...)``, validate and normalize feature bounds. - -**Parameters:** - -* ***bounds*** (``Any``): he input bounds, which must be either None or a dictionary with 'low' and 'high' keys. -* ***problem_size*** (``int``): The expected length for the normalized bounds lists, corresponding to the number of features in the problem. - -**Returns:** - -* `Dict[str, list]`: Dictionary ``{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}``. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md deleted file mode 100644 index c0d5bba6b..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md +++ /dev/null @@ -1,104 +0,0 @@ -# Validation - -## def detect_vector_data_type(...) - -```python -def detect_vector_data_type( - vector: npt.NDArray -) -> FeatureType: -``` - -Detects the type of data in a given vector. - -This function analyzes the input vector and classifies its data as one of the supported types: - -* **binary**: Boolean values (`True`/`False`) or integer `0`/`1`. -* **continuous**: Float values within the normalized range `[0.0, 1.0]`. -* **ranged**: Float values outside the normalized range. - -### Parameters - -* `vector` (`npt.NDArray`): An array containing the data to be classified. - -### Returns - -* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): The detected type of data in the vector. - -### Raises - -* `UnsupportedDataTypeError`: Raised if the vector contains an unsupported data type. - ---- - -## def check_array_type(...) - -```python -def check_array_type(x, name: str = "X") -> npt.NDArray: -``` - -Ensure X is a numpy array. Convert from list if needed. - -### Parameters - -* `x` (`Any`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `name` (`str`, default='X'): Variable name used in error messages. - -### Returns - -* `npt.NDArray`: The converted or validated array. - -### Raises - -* `TypeError`: If X or y are not ndarrays or have incompatible shapes. - ---- - -## def check_shape_match(...) - -```python -def check_shape_match(x: npt.NDArray, y: npt.NDArray): -``` - -Ensure X and y have compatible first dimensions. - -### Parameters - -* `x` (`npt.NDArray`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `y` (`npt.NDArray`): Array of target classes of `x` with [`N samples` (lines)]. - -### Raises - -* `TypeError`: If x or y are not ndarrays or have incompatible shapes. - ---- - -## def check_feature_dimension(...) - -```python -def check_feature_dimension(x: npt.NDArray, expected: int): -``` - -Ensure X has the expected number of features. - -### Parameters - -* `x` (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. -* `expected` (`int`): Expected number of features per sample (columns in X). - -### Raises - -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. - ---- - -## def check_binary_array(...) - -```python -def check_binary_array(x: npt.NDArray): -``` - -Ensure X contains only 0 and 1. - -### Raises - -* `ValueError`: If feature_type is binary-features and X contains values that are not composed only of 0 and 1. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json deleted file mode 100644 index c57d4b807..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "label": "Utils", - "description": "Utility functions and helpers for development." -} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/_category_.json deleted file mode 100644 index 020788b9f..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Guides", - "position": 2.6, - "link": { - "type": "generated-index", - "description": "Explore the advanced documentation of the library, covering the base classes and the utility functions in utils for metrics and multiclass classification handling." - } -} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json deleted file mode 100644 index d6566b364..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Base module", - "position": 1, - "description": "Base class for classification algorithm." -} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md deleted file mode 100644 index 2d458c1b8..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -sidebar_position: 1 -title: Base class -sidebar_label: Base -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Class - - Model Base - - Scikit-learn Compatibility - - get_params - - set_params - - Random Seed - - Python Classes ---- - -Base class for scikit-learn API compatibility. - -Provides the `get_params` and `set_params` methods for compatibility with the scikit-learn API, allowing access to the model's public parameters. - -### Function set_params(...) - -```python -def set_params(self, **params) -``` - -Set the parameters of the instance. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **params**: ``dict`` - Dictionary of parameters to set as attributes on the instance. Only public attributes (not starting with "_") are modified. - -**Returns**: - -* self: `Base` - Returns the instance itself after setting the parameters. - ---- - -### Function get_params(...) - -```python -def get_params(self, deep: bool = True) -> dict -``` - -Return a dictionary with the object's main parameters. Ensures compatibility with scikit-learn functions. - -**Parameters**: - -* **deep**: `bool` - Ignored in this implementation but included for scikit-learn compatibility. - -**Returns**: - -* params: `dict` - Dictionary containing the object's attributes that do not start with "_". diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md deleted file mode 100644 index 86baa60f3..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -sidebar_position: 2 -title: Base class for classification algorithm. -sidebar_label: BaseClassifier -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Classifier - - Classification - - Abstract Base Class - - BaseClassifier - - Machine Learning - - Supervised Learning - - fit Method - - predict Method - - score Method - - Model Evaluation - - Accuracy - - Python ML Classes - - RNSA - - BNSA ---- - -## ``class BaseClassifier(ABC, Base)`` - -Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``, and implementing the ``get_params`` method. - -## Abstract methods - -### def fit(...) - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -Fit the model to the training data. - -Implementation: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-fit) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-fit) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) - -### def predict(...) - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -Performs label prediction for the given data. - -Implementation: - -- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-predict) -- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-predict) -- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) - ---- - -## Methods - -### def score(...) - -```python -def score(self, X: npt.NDArray, y: list) -> float -``` - -Score function calculates forecast accuracy. - -This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. -This function was added for compatibility with some scikit-learn functions. - -**Parameters**: - -- ***X***: ``np.ndarray`` - Feature set with shape (n_samples, n_features). -- ***y***: ``np.ndarray`` - True values with shape (n_samples,). - -**Returns**: - -- accuracy: ``float`` The accuracy of the model. - -### Function _slice_index_list_by_class(...) - -The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class, to go through the sample array, only in the positions that the output is the class that is being trained: - -```python -def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Returns a dictionary with the classes as key and the indices in ``X`` of the samples. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md deleted file mode 100644 index 559c30499..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -sidebar_position: 3 -title: Base class for clustering algorithm. -sidebar_label: BaseClusterer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Base Clusterer - - Clustering - - Unsupervised Learning - - BaseClusterer - - Abstract Base Class - - fit Method - - predict Method - - fit_predict Method - - AiNet - - Cluster Prediction - - Python ML Classes ---- - - -## ``BaseClusterer(ABC, Base)`` - -Abstract base class for clustering algorithms. - -This class defines the core interface for clustering models. It enforces -the implementation of the **`fit`** and **`predict`** methods in all derived classes, -and provides a default implementation for **`fit_predict`** and **`get_params`**. - ---- - -### Function fit(...) - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer -``` - -Fit the model to the training data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data used for training the model. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during training. - -**Returns**: - -* ***self***: - Instance of the class that implements this method. - -**Implementation**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) - ---- - -### Function predict(...) - -```python -def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] -``` - -Generate predictions based on the input data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data for which predictions will be generated. - -**Returns**: - -* ***predictions***: `Optional[npt.NDArray]` - Predicted cluster labels for each input sample, or `None` if prediction is not possible. - -**Implementation**: - -* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) - ---- - -### Function fit_predict(...) - -```python -def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] -``` - -Convenience method that combines `fit` and `predict` in a single call. - -**Parameters**: - -* ***X***: `npt.NDArray` - Input data for which predictions will be generated. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during training. - -**Returns**: - -* ***predictions***: `Optional[npt.NDArray]` - Predicted cluster labels for each input sample, or `None` if prediction is not possible. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md deleted file mode 100644 index aa33b86cf..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -sidebar_position: 4 -title: Base class for optimization algorithms. -sidebar_label: BaseOptimizer -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - BaseOptimizer - - base class - - optimization algorithms - - abstract base class - - machine learning optimization - - supervised learning - - optimize method - - objective function - - model evaluation - - Python ML classes - - Clonalg - - metaheuristics ---- - - -This class defines the core interface for optimization strategies and -keeps track of the cost history, evaluated solutions, and the best solution found. Subclasses must implement -``optimize`` and ``objective_function``. - ---- - -### Properties - -#### `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Returns the history of costs during optimization. - ---- - -#### `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Returns the history of evaluated solutions. - ---- - -#### `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Returns the best solution found so far, or `None` if unavailable. - ---- - -#### `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Returns the cost of the best solution found so far, or `None` if unavailable. - ---- - -## Functions - -### Function _record_best(...) - -```python -def _record_best(self, cost: float, best_solution: Any) -> None -``` - -Record a new cost value and update the best solution if improved. - -**Parameters**: - -* ***cost***: `float` - Cost value to be added to the history. - ---- - -### Function get_report() - -```python -def get_report(self) -> str -``` - -Generate a formatted summary report of the optimization process. The report includes the best solution, -its associated cost, and the evolution of cost values per iteration. - -**Returns**: - -* **report**: `str` - A formatted string containing the optimization summary. - ---- - -### Function register(...) - -```python -def register(self, alias: str, function: Callable[..., Any]) -> None -``` - -Register a function dynamically in the optimizer instance. - -**Parameters**: - -* ***alias***: `str` - Name used to access the function as an attribute. -* ***function***: `Callable[..., Any]` - Callable to be registered. - -**Raises**: - -* **TypeError**: If `function` is not callable. -* **AttributeError**: If `alias` is protected and cannot be modified, or if `alias` does not exist in the - optimizer class. - ---- - -### Function reset() - -```python -def reset(self) -``` - -Reset the object's internal state, clearing history and resetting values. - ---- - -### Abstract methods - -#### Function optimize(...) - -```python -def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any -``` - -Execute the optimization process. This method must be implemented by the subclass to define how the optimization strategy explores the search space. - -**Parameters**: - -* ***max_iters***: `int` - Maximum number of iterations. -* ***n_iter_no_change***: `int`, default=10 - The maximum number of iterations without updating the best solution. -* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during optimization. - -**Implementation**: - -* [Clonalg](../../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) - ---- - -#### Function affinity_function(...) - -```python -def affinity_function(self, solution: Any) -> float -``` - -Evaluate the affinity of a candidate solution. This method must be implemented by the subclass to define the problem-specific. - -**Parameters**: - -* ***solution***: `Any` - Candidate solution to be evaluated. - -**Returns**: - -* **cost**: `float` - Cost value associated with the given solution. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md deleted file mode 100644 index 1ceacb91b..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Cell Classes -sidebar_label: Cell Classes -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -Representation of immune system cells. - -## Cell - -Represents a basic immune cell. - -```python -@dataclass(slots=True) -class Cell: - vector: np.ndarray -``` - -### Attributes - -* **vector** (`np.ndarray`): A vector of cell features. - -### Methods - -* `__eq__(other)`: Check if two cells are equal based on their vectors. -* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. -* `__getitem__(item)`: Get elements from the feature vector using indexing. - ---- - -## BCell - -Represents a memory B-cell. - -```python -@dataclass(slots=True, eq=False) -class BCell(Cell): - vector: np.ndarray -``` - -### Methods - -#### hyper_clonal_mutate(...) - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> np.ndarray -``` - -Clones N features from a cell's features, generating a set of mutated vectors. - -##### Parameters - -* **n** (`int`): Number of clones to be generated from mutations of the original cell. -* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): - Specifies the type of feature_type to use based on the nature of the input features -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -##### Returns - -* **npt.NDArray**: An array containing N mutated vectors from the original cell. - ---- - -## Antibody - -Represent an antibody. - -```python -@dataclass(slots=True) -class Antibody(Cell): - vector: np.ndarray - affinity: float -``` - -### Attributes - -* **vector** (`npt.NDArray`): A vector of cell features. -* **affinity** (`float`): Affinity value for the antibody. - -### Methods - -* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. -* `__eq__(other)`: Check if this cell has the same affinity as another cell. - ---- - -## Detector - -Represents a non-self detector of the RNSA class. - -```python -@dataclass(slots=True) -class Detector: - position: npt.NDArray[np.float64] - radius: Optional[float] = None -``` - -### Attributes - -* **position** (`npt.NDArray[np.float64]`): Detector feature vector. -* **radius** (`Optional[float]`): Detector radius, used in the V-detector algorithm. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md deleted file mode 100644 index d6c3082cd..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutation -sidebar_label: Mutation -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - Mutation - - Clonal Expansion - - Immune System - - clone_and_mutate - - clone_and_mutate_continuous - - clone_and_mutate_binary - - clone_and_mutate_ranged - - Artificial Immune Systems - - Python Numba Functions - - Vector Mutation ---- - -Contains functions that generate sets of mutated clones from continuous or binary vectors, simulating the clonal expansion process in artificial immune systems. - -## clone_and_mutate_continuous - -```python -@njit([(types.float64[:], types.int64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector. - -This function creates `n` clones of the input vector and applies random mutations to each one, simulating the clonal expansion process in artificial immune systems. Each clone receives a random number of mutations at distinct positions of the original vector. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_binary - -```python -@njit([(types.boolean[:], types.int64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int -) -> npt.NDArray[np.bool_]: -``` - -Generates a set of mutated clones from a binary vector. - -This function creates `n` clones of the input binary vector and applies random mutations to some bits, simulating clonal expansion in artificial immune systems with discrete representations. - -### Parameters - -* `vector` (`npt.NDArray[np.bool_]`): The original immune cell with binary values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. - -### Returns - -* `clone_set` (`npt.NDArray[np.bool_]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_ranged - -```python -@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64] -) -> npt.NDArray[np.float64]: -``` - -Generates a set of mutated clones from a continuous vector using custom bounds per dimension. - -This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied to distinct positions of the original vector, respecting the mutation bounds defined per dimension. - -### Parameters - -* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `bounds` (`npt.NDArray[np.float64]`): A 2D array with shape `(len(vector), 2)` containing the minimum and maximum values for each dimension. - -### Returns - -* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. - ---- - -## clone_and_mutate_permutation - -```python -@njit([(types.int64[:], types.int64, types.float64)], cache=True) -def clone___and_mutate_permutation( - vector: npt.NDArray[np.int64], - n: int, - mutation_rate: float -) -> npt.NDArray[np.int64]: -``` - -Generates a set of mutated clones from a permutation vector. - -This function creates `n` clones of the input permutation vector and applies random mutations to each one, simulating clonal expansion in artificial immune systems with discrete permutations. Each clone receives a random number of swaps according to the mutation rate. - -### Parameters - -* `vector` (`npt.NDArray[np.int64]`): The original immune cell with permutation values to be cloned and mutated. -* `n` (`int`): Number of mutated clones to be generated. -* `mutation_rate` (`float`): Probability of mutating each component ($$0 <= mutation\_rate < 1$$). - -### Returns - -* `clone_set` (`npt.NDArray[np.int64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md deleted file mode 100644 index 3944371fc..000000000 --- a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Populations Module -sidebar_label: Populations -pagination_next: null -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell - - Clonal Expansion - - Immune System - - Artificial Immune Systems -lastUpdatedAt: 2025/11/21 -author: João Paulo ---- - -Utility functions for generating antibody populations in immunological algorithms. - -## generate_random_antibodies(...) - -```python -def generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureTypeAll = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -Generate a random antibody population. - -### Parameters - -* **n_samples** (`int`): Number of antibodies (samples) to generate. -* **n_features** (`int`): Number of features (dimensions) for each antibody. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. - -### Returns - -* **npt.NDArray**: Array of shape (n_samples, n_features) containing the generated antibodies. - -### Raises - -* **ValueError**: If the number of features is less than or equal to zero. \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md new file mode 100644 index 000000000..669d832a9 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms.md @@ -0,0 +1,39 @@ +--- +id: docs-csa +keywords: + - clonal selection and expansion + - clonalg + - artificial immune systems + - classification + - optimization + - bio-inspired algorithms + - natural computing +--- + +# Clonal selection and expansion + +Algorithms based on clonal selection and expansion are inspired by the process of antibody proliferation after the +detection of an antigen, during which the generated antibodies undergo mutations in an attempt to improve pathogen +recognition. [^1] + +--- + +Clonal selection and expansion can be applied in different contexts, such as: +- **Optimization** +- **Classification** + +## Package implementation + +### Artificial Immune Recognition System ([AIRS](../api/csa/airs.md)) + +Classification algorithm inspired by the clonal selection process. + +### Clonal Selection Algorithm ([CLONALG](../api/csa/clonalg.md)) + +Optimization algorithm inspired by the biological process of clonal selection of the immune system. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Available at: https://dx.doi.org/10.1007/978-3-662-43631-8. \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx deleted file mode 100644 index 79e838162..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx +++ /dev/null @@ -1,16 +0,0 @@ ---- -sidebar_position: 2 -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- -import DocCardList from '@theme/DocCardList'; - -# Clonal Selection Algorithm. - - -Clonal Selection Algorithms are inspired by the process of antibody proliferation upon detecting an antigen, during which -the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. - -## Classes: - - \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md deleted file mode 100644 index 9e5231210..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ /dev/null @@ -1,210 +0,0 @@ ---- -id: airs -sidebar_label: AIRS - Artificial Immune Recognition System -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -# AIRS - Artificial Immune Recognition System - -The ``AIRS`` class aims to perform classification using metaphors of selection and clonal expansion. - -This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. -Introducing adaptations to handle continuous and binary datasets. - -Based on Algorithm 16.5 from Brabazon et al. [1](#1). - -:::tip Related and noteworthy works: - -- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) - -::: - -:::info - -**``AIRS``** extends the **[``BaseClassifier`` class](../../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## AIRS Constructor - -**Attributes:** - -- **n_resources** (``float``): Total amount of available resources. Defaults to 10. -- **rate_clonal** (``float``): Maximum number of possible clones of a class. This quantity is multiplied by (cell stimulus * rate_hypermutation) to define the number of clones. Defaults to 10. -- **rate_hypermutation** (``int``): The rate of mutated clones derived from rate_clonal as a scalar factor. Defaults to 0.75. -- **affinity_threshold_scalar** (``float``): Normalized affinity threshold. Defaults to 0.75. -- **k** (``int``): The number of K nearest neighbors that will be used to choose a label in the prediction. Defaults to 10. -- **max_iters** (``int``): Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. Defaults to 100. -- **resource_amplified** (``float``): Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. -- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - - ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - - ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - - ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to **"Euclidean"**. - -- **seed** (``Optional[int]``): Seed for the random generation of detector values. Defaults to None. - -- ``**kwargs``: - - **p** (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. - The default is ``2``, which means normalized Euclidean distance. Different values of p lead to different variants of the Minkowski distance. [Learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Other initialized variables:** - -- **cells_memory** (``dict``): This variable stores a list of memory cells by class. -- **affinity_threshold** (``dict``): Defines the affinity threshold between antigens. -- **classes** (``npt.NDArray``): List of output classes. - ---- - -## Public Methods - -### Function fit(...) - -The ``fit(...)`` function generates detectors for the non-owners relative to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -> AIRS: -``` - -It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). - -**Input parameters:** - -- **X**: Array with sample features, with **N** samples (rows) and **N** features (columns), normalized to values between [0, 1]. -- **y**: Array with output classes corresponding to **N** samples related to ``X``. -- **verbose**: Boolean, default ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the class instance.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**Input parameter:** - -- **X**: Array with the features for prediction, with **N** samples (rows) and **N** columns. - -**Returns:** - -- **C**: An array of predictions with the output classes for the given features. -- **None**: If there are no detectors. - ---- - -### Function score(...) - -The ``score(...)`` function calculates the accuracy of the trained model by making predictions and calculating the accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -Returns accuracy as a ``float``. - ---- - -## Private Methods - -### Function _refinement_arb(...) - -The function "_refinement_arb(...)" refines the ARB set until the average stimulation value exceeds the defined threshold (``affinity_threshold_scalar``). - -```python -def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: -``` - -Parameters: - -- **c_match** (``Cell``): Cell with the highest stimulation relative to aᵢ. -- **arb_list** (``List[_ARB]``): ARB set. - -Returns the cell (_ARB) with the highest ARB stimulation. - ---- - -### Function _cells_affinity_threshold(...) - -The function "_cells_affinity_threshold(...)" calculates the affinity threshold based on the average affinity between training instances, where aᵢ and aⱼ are a pair of antigens, and affinity is measured by distance (Euclidean, Manhattan, Minkowski, Hamming). -**Following the formula:** - -$$ -\text{affinity}_{\text{threshold}} = \frac{ -\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} -$$ - -Parameters: - -- **antigens_list** (``NDArray``): List of training antigens. - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - ---- - -### Function _affinity(...) - -The function "_affinity(...)" calculates the stimulus between two vectors using metrics. - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -Parameters: - -- **u** (``npt.NDArray``): Coordinates of the first point. -- **v** (``npt.NDArray``): Coordinates of the second point. - -Returns the stimulus rate between the vectors. - ---- - -### Function _init_memory_c(...) - -The function "_init_memory_c(...)" initializes memory cells by randomly selecting `n_antigens_selected` from the list of training antigens. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[BCell]: -``` - -Parameters: - -- **antigens_list** (``NDArray``): List of training antigens. - -Returns - -- ``List[BCell]``: List of initialized memories. - ---- - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md deleted file mode 100644 index bf2bcf614..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -id: abr -title: ABR -sidebar_label: ABR - Artificial Recognition Ball -sidebar_position: 2 -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -## ABR (Artificial Recognition Ball) - -Individual from the set of recognizing cells (ABR), inherits characteristics from a B-cell, adding resource consumption - -:::info - -**``ABR``** extends the **[``BCell`` class](../../../advanced-guides/base-module/immune/cell.md#BCell)**, inheriting its base functionality. - -::: - -### Constructor - -Parameters: - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Function consume_resource(...) - -Parameters: - -* n_resource (```float```) : The initial amount of resources. -* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -Returns the remaining amount of resources after consumption. diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md deleted file mode 100644 index 7ee8a2daf..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -id: clonalg -sidebar_label: CLONALG - Clonal Selection Algorithm -keywords: - - CLONALG - - clonal selection algorithm - - optimization - - binary optimization - - real-valued optimization - - ranged-value problems - - permutation problems - - metaheuristics - - bio-inspired algorithms - - machine learning optimization -lastUpdatedAt: 2025/09/21 -author: João Paulo ---- - -# CLONALG - Clonal Selection Algorithm - -The `Clonalg` class is an **optimization algorithm** inspired by the biological process of clonal selection in the immune system. This implementation is designed for minimizing or maximizing cost functions in various problem types, including binary, continuous, ranged-value, and permutation problems. - -:::tip -The CLONALG implementation was inspired by the description presented in [1](#1). -::: - -:::info -This CLONALG implementation contains some changes based on the AISP context, for general -application to various problems, which may produce results different from the standard or -specific implementation. This adaptation aims to generalize CLONALG to minimization and -maximization tasks, in addition to supporting continuous, discrete, and permutation problems. -::: - -:::info - -**``Clonalg``** extends the **[``BaseOptimizer`` class](../../advanced-guides/base-module/core/Optimizer.md)**, inheriting its base functionality. - -::: - ---- - -## CLONALG Constructor - -The constructor initializes the CLONALG instance with key parameters that define the optimization process. - -**Attributes:** - -* **problem_size**: `int` - The dimension of the problem to be optimized. -* **N**: `int`, default=50 - The number of memory cells (antibodies) in the population. -* **rate_clonal**: `float`, default=10 - The maximum number of possible clones of a cell. This value is multiplied by the cell's affinity to determine the number of clones. -* **rate_hypermutation**: `float`, default=0.75 - The rate of mutated clones, used as a scalar factor. -* **n_diversity_injection**: `int`, default=5 - The number of new random memory cells injected to maintain diversity. -* **selection_size**: `int`, default=5 - The number of best antibodies selected for cloning. -* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, default=None - The objective function used to evaluate candidate solutions. -* **feature_type**: `FeatureTypeAll`, default='ranged-features' - The type of problem samples, which can be `'continuous-features'`, `'binary-features'`, `'ranged-features'`, or `'permutation-features'`. -* **bounds**: `Optional[Dict]`, default=None - A dictionary defining the search limits for `'ranged-features'` problems. Can be a single fixed range or a list of ranges for each dimension. -* **mode**: `Literal["min", "max"]`, default="min" - Specifies whether the algorithm minimizes or maximizes the cost function. -* **seed**: `Optional[int]`, default=None - A seed for random number generation. - ---- - -## Public Methods - -### Function `optimize(...)` - -```python -def optimize( - self, - max_iters: int = 50, - n_iter_no_change=10, - verbose: bool = True -) -> List[Antibody]: -``` - -This method execute the optimization process and return the population. - -**Input parameters:** - -* **max_iters**: `int`, default=50 - The maximum number of interactions. -* **n_iter_no_change**: `int`, default=10 - The maximum number of iterations without an improvement in the best solution. -* **verbose**: `bool`, default=True - A flag to enable or disable detailed output during the optimization process. - -**Returns:** - -* population : ``List[Antibody]``, [Antibody](../../advanced-guides/base-module/immune/cell.md#Antibody) population after clonal expansion. - ---- - -### Function `affinity_function(...)` - -```python -def affinity_function(self, solution: npt.NDArray) -> np.float64: -``` - -This method evaluates the affinity of a candidate solution. It raises a `NotImplementedError` if no affinity function has been provided to the class instance. - -**Input parameters:** - -* **solution**: `npt.NDArray` - The candidate solution to be evaluated. - -**Returns:** - -* `np.float64`: The affinity value associated with the solution. - ---- - -## Private Methods - -### Function `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: -``` - -This method selects the top `n` antibodies based on their affinity scores, according to the `mode` (`'min'` or `'max'`). - -**Input parameters:** - -* **n**: `int` - The number of antibodies to select. -* **antibodies**: `list[tuple]` - A list of tuples, where each tuple represents an antibody and its associated score. - -**Returns:** - -* `list[tuple]`: A list containing the `n` selected antibodies. - ---- - -### Function `_init_population_antibodies(...)` - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -This method initializes the initial population of antibodies randomly. - -**Returns:** - -* `npt.NDArray`: A list of the initialized antibodies. - ---- - -### Function `_diversity_introduction(...)` - -```python -def _diversity_introduction(self): -``` - -This method introduces new random antibodies into the population to maintain genetic diversity and help prevent premature convergence. - -**Returns:** - -* `npt.NDArray`: An array of new random antibodies. - ---- - -### Function `_clone_and_mutate(...)` - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: -``` - -This method generates mutated clones from a single antibody. The mutation strategy depends on the `feature_type` specified during initialization (`'binary-features'`, `'continuous-features'`, `'ranged-features'`, or `'permutation-features'`). - -**Input parameters:** - -* **antibody**: `npt.NDArray` - The original antibody vector to be cloned and mutated. -* **n_clone**: `int` - The number of clones to generate. -* **rate_hypermutation**: `float` - The hypermutation rate. - -**Returns:** - -* `npt.NDArray`: An array containing the mutated clones. - ---- - -### Function `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation(self, population: list[tuple]) -> list: -``` - -This method clones and hypermutates a population of antibodies. It returns a list of all clones and their affinities with respect to the cost function. - -**Input parameters:** - -* **population**: `list[tuple]` - The list of antibodies to be evaluated and cloned. - -**Returns:** - -* `list`: A list of mutated clones. - ---- - -## References - -### 1 -> -> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory.md b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory.md new file mode 100644 index 000000000..065a2f852 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory.md @@ -0,0 +1,41 @@ +--- +id: docs-ina +keywords: + - immune network theory + - ainet + - artificial immune systems + - classification + - clustering + - optimization + - bio-inspired algorithms + - natural computing +--- + +# Immune network theory + +This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, in which +cells and molecules are capable of recognizing each other. [^1] + +--- + +The Artificial Immune Network can be applied in different contexts, such as: +- **Clustering** +- **Optimization** +- **Classification** + +## Package implementation + +### Artificial Immune Network for clustering and compression ([AiNet](../api/ina/ai-net.md)) + +AiNet is a clustering algorithm based on immune network theory that uses clonal selection and affinity maturation +to compress data and identify groups [^2]. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for + Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis diff --git a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md deleted file mode 100644 index 5f6807b93..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -id: ainet -sidebar_label: AiNet - Clustering and Compression -sidebar_position: 1 -pagination_next: null -keywords: - - Artificial Immune Network - - AiNet - - Clustering - - Data Compression - - Immune Algorithms - - Bioinspired Computing - - Memory Cells - - Affinity Threshold - - Suppression Threshold - - Clonal Selection - - Clonal Expansion - - Diversity Introduction - - Pattern Recognition - - Anomaly Detection - - MST Clustering - - Minimum Spanning Tree - - Unsupervised Learning - - Bioinspired Algorithms - - Antibody Network -lastUpdatedAt: 2025/08/19 -author: João Paulo ---- - -# AiNet - Artificial Immune Network para Clustering and Compression - -The AiNet class aims to perform clustering using metaphors inspired by immune network theory. - -This class implements the aiNet algorithm, an artificial immune network model designed for -clustering and data compression tasks. The aiNet algorithm uses principles from immune -network theory, clonal selection, and affinity maturation to compress high-dimensional -datasets [1](#1). -For clustering, the class uses SciPy's implementation of the [**Minimum Spanning Tree** -(MST)](#2) to remove the most distant nodes and separate the groups - -:::info - -**``AiNet``** extends the **[``BaseClusterer`` class](../../advanced-guides/base-module/core/Clusterer.md)**, inheriting its base functionality. - -::: - -## Constructor - -```python -class AiNet( - self, - N: int = 50, - n_clone: int = 10, - top_clonal_memory_size: int = 5, - n_diversity_injection: int = 5, - affinity_threshold: float = 0.5, - suppression_threshold: float = 0.5, - mst_inconsistency_factor: float = 2.0, - max_iterations: int = 10, - k: int = 3, - metric: MetricType = "euclidean", - seed: Optional[int] = None, - use_mst_clustering: bool = True, - **kwargs -) -``` - -**Attributes:** - -* **N** (``int``): Number of memory cells (antibodies) in the population. Defaults to 50. -* **n_clone** (``int``): Number of clones generated per selected memory cell. Defaults to 10. -* **top_clonal_memory_size** (``Optional[int]``): Number of highest-affinity antibodies selected for cloning. Defaults to 5. -* **n_diversity_injection** (``int``): Number of new random antibodies injected to maintain diversity. Defaults to 5. -* **affinity_threshold** (``float``): Threshold for cell selection/suppression. Defaults to 0.5. -* **suppression_threshold** (``float``): Threshold for removing similar memory cells. Defaults to 0.5. -* **mst_inconsistency_factor** (``float``): Factor to determine inconsistent MST edges. Defaults to 2.0. -* **max_iterations** (``int``): Maximum number of training iterations. Defaults to 10. -* **k** (``int``): Number of nearest neighbors used for label prediction. Defaults to 3. -* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to **"Euclidean"**. - -* **seed** (``Optional[int]``): Seed for random number generation. Defaults to None. -* **use_mst_clustering** (``bool``): Whether to perform MST-based clustering. Defaults to True. -* **kwargs**: - * **p** (``float``): Parameter for Minkowski distance. Defaults to 2. - -**Other initialized variables:** - -* **_population_antibodies** (``npt.NDArray``): Stores the current set of antibodies. -* **_memory_network** (``dict``): Dictionary mapping clusters to antibodies. -* **_mst_structure** (``scipy.sparse.csr_matrix``): MST adjacency structure. -* **_mst_mean_distance** (``float``): Mean of MST edge distances. -* **_mst_std_distance** (``float``): Standard deviation of MST edge distances. -* **classes** (``list``): List of cluster labels. - ---- - -## Public Methods - -### Function fit(...) - -Trains the AiNet model on input data: - -```python -def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: -``` - -**Input parameters:** - -* **X**: Array with input samples (rows) and features (columns). -* **verbose**: Boolean, default True, enables progress feedback. - -*Returns the class instance.* - ---- - -### Function predict(...) - -Predicts cluster labels for new samples: - -```python -def predict(self, X) -> Optional[npt.NDArray]: -``` - -**Input parameters:** - -* **X**: Array of input features. - -**Returns:** - -* **Predictions**: Array of cluster labels, or None if clustering is disabled. - ---- - -### Function update_clusters(...) - -Partitions clusters using the MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Input parameters:** - -* **mst_inconsistency_factor**: Optional float to override the MST inconsistency factor. - -**Updates:** - -* **_memory_network**: Dictionary of cluster labels to antibody arrays. -* **classes**: List of cluster labels. - ---- - -## Private Methods - -### Function _init_population_antibodies(...) - -Initializes antibody population randomly. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Returns:** Initialized antibodies (`npt.NDArray`). - ---- - -### Function _select_and_clone_population(...) - -Selects top antibodies and generates mutated clones: - -```python -def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: -``` - -**Input parameters:** - -* **antigen**: Array representing the antigen to which affinities will be computed. -* **population**: Array of antibodies to be evaluated and cloned. - -**Returns:** List of mutated clones. - ---- - -### Function _clonal_suppression(...) - -Suppresses redundant clones based on thresholds: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Input parameters:** - -* **antigen**: Array representing the antigen. -* **clones**: List of candidate clones to be suppressed. - -**Returns:** List of non-redundant, high-affinity clones. - ---- - -### Function _memory_suppression(...) - -Removes redundant antibodies from memory pool: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Input parameters:** - -* **pool_memory**: List of antibodies currently in memory. - -**Returns:** Cleaned memory pool (`list`). - ---- - -### Function _diversity_introduction(...) - -Introduces new random antibodies: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Returns:** Array of new antibodies (`npt.NDArray`). - ---- - -### Function _affinity(...) - -Calculates stimulus between two vectors: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Input parameters:** - -* **u**: Array representing the first point. -* **v**: Array representing the second point. - -**Returns:** Affinity score (`float`) in [0,1]. - ---- - -### Function _calculate_affinities(...) - -Calculates affinity matrix between reference and target vectors: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Input parameters:** - -* **u**: Reference vector (`npt.NDArray`) of shape `(n_features,)`. -* **v**: Target vectors (`npt.NDArray`) of shape `(n_samples, n_features)`. - -**Returns:** Array of affinities (`npt.NDArray`) with shape `(n_samples,)`. - ---- - -### Function _clone_and_mutate(...) - -Generates mutated clones: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Input parameters:** - -* **antibody**: Original antibody vector to clone and mutate. -* **n_clone**: Number of clones to generate. - -**Returns:** Array of mutated clones (`npt.NDArray`) of shape `(n_clone, len(antibody))`. - ---- - -### Function _build_mst(...) - -Constructs the MST and stores statistics. - -```python -def _build_mst(self): -``` - -**Raises:** ValueError if antibody population is empty. - -**Updates internal variables:** - -* **_mst_structure**: MST adjacency structure. -* **_mst_mean_distance**: Mean edge distance. -* **_mst_std_distance**: Standard deviation of MST edge distances. - ---- - -## References - -### 1 -> -> De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> Available at: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) - -### 2 -> -> SciPy Documentation. *Minimum Spanning Tree*. -> Available at: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx deleted file mode 100644 index 148e0fbe0..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx +++ /dev/null @@ -1,39 +0,0 @@ ---- -sidebar_position: 3 -lastUpdatedAt: 2025/08/19 -author: João Paulo -keywords: - - Immune Network Theory - - AiNet - - Artificial Immune Systems - - Clustering - - Optimization - - Classification - - Machine Learning - - Immune Algorithms ---- - -import DocCardList from '@theme/DocCardList'; - -# Immune Network Theory - -This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, -in which cells and molecules are capable of recognizing each other. [1](#1) - ---- - -The Artificial Immune Network can be applied in different contexts, such as: -- **Clustering** -- **Optimization** -- **Classification** - -## Classes: - - - -## References - ---- - -### 1 -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md new file mode 100644 index 000000000..29a68b9b0 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md @@ -0,0 +1,50 @@ +--- +id: docs-nsa +keywords: + - negative selection + - nsa + - artificial immune systems + - anomaly detection + - classification + - bio-inspired algorithms + - natural computing +--- + +# Seleção Negativa + +Os algoritmos de **seleção negativa** is the process in which the immune system maturates T-cells, also known as +T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) +uses hyperspheres symbolizing the detectors in an N-dimensional data space. [^1] + +--- + +Negative Selection can be applied in different contexts, such as: +- **Anomaly detection** +- **Classification** + +## Package implementation + +### Binary Negative Selection Algorithm ([BNSA](../api/nsa/bnsa.md)) + +The binary algorithm adapted for multiple classes in this project is based on the version proposed by +Forrest et al. (1994)[^2], originally developed for computer security. + +### Real-Valued Negative Selection Algorithm ([RNSA](../api/nsa/rnsa.md)) + +This algorithm has two different versions: one based on the canonical version [^1] and another with variable +radius detectors.[^3] Both are adapted to work with multiple classes and have methods for predicting data +present in the non-self region of all detectors and classes. + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Available at: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. + +[^3] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md deleted file mode 100644 index a8f7cd82c..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -id: bnsa -sidebar_label: BNSA - Binary Negative Selection Algorithm -sidebar_position: 2 -pagination_next: null -keywords: - - Binary - - classifying - - anomalies - - not self - - affinity threshold - - Negative Selection Algorithm - - Artificial Immune System (AIS) - - Self and non-self - - Immune - - Computação Natural - - Real-Valued - - V-detector -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# BNSA (Binary Negative Selection Algorithm) - -:::info - -**``BNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## Constructor RNSA - -The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -``` python -class BNSA( - self, - N: int = 100, - aff_thresh: float = 0.1, - max_discards: int = 1000, - seed: int = None, - no_label_sample_selection: Literal[ - "max_average_difference", "max_nearest_difference" - ] = "max_average_difference", -) -``` - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *aff_thresh* (``float``): The variable ('affinity threshold') represents the percentage of dissimilarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. - - :::note - Setting the difference percentage too high can result in the inability to generate detectors for non-self. - ::: - -* *max_discards* (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a -possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``1000``. -* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. -* no_label_sample_selection (``str``): Method for selecting labels for samples designated as non-members by all non-member detectors. **Available method types:** - * (``max_average_difference``): Selects the class with the highest average difference among the detectors. - * (``max_nearest_difference``): Selects the class with the highest difference between the nearest and farthest detector from the sample. - -**Other variables initiated:** - -* *detectors* (``dict``): This variable stores a list of detectors by class. - -* *classes* (``npt.NDArray``): list of output classes. - ---- - -### Function fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -**The input parameters are:** - -* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. - -* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the instance of the class.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**The input parameter is:** - -* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Returns:** - -* ``C``: prediction array, with the output classes for the given characteristics. -* ``None``: if there are no detectors. - ---- - -### Function score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Function __assign_class_to_non_self_sample(...) - -The function ``__assign_class_to_non_self_sample(...)``, determines the class of a sample when all detectors classify it as "non-self". Classification is performed using the ``max_average_difference`` and ``max_nearest_difference`` methods. - -```python -def __assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): -``` - -**The input parameter is:** - -* ***line*** (``npt.NDArray``): Sample to be classified. -* ***c*** (``list``): List of predictions to be updated with the new classification. - ---- diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md deleted file mode 100644 index be74a4825..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Negative selection - -**Negative selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [[1]](#1) - -## classes - -> 1. **[Binary version:](BNSA.md)** -> ->> The binary algorithm adapted for multiple classes in this project is based on the version proposed by [Forrest et al. (1994)](#2), originally developed for computer security. ->>> **Example:** ->>> ->>> + [Mushrooms Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) - -> 2. **[Real-Valued version:](RNSA.md)** -> ->>This algorithm has two different versions: one based on the canonical version [[1]](#1) and another with variable radius detectors [[3]](#3). Both are adapted to work with multiple classes and have methods for predicting data present in the non-self region of all detectors and classes. ->>> **Examples:** ->>> ->>> + [Iris Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) ->>> + [Geyser Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) - -## References - ---- - -### 1 -> -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). - -### 2 -> -> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). - -### 3 -> -> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). - ---- diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md deleted file mode 100644 index 3c102d26a..000000000 --- a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -id: rnsa -sidebar_label: RNSA - Real-Valued Negative Selection Algorithm -sidebar_position: 1 -keywords: - - Real-Valued - - classifying - - anomalies - - not self - - V-detector - - Negative Selection Algorithm - - Artificial Immune System (AIS) - - Self and non-self - - Immune - - Computação Natural -last_update: - date: 2025/05/17 - author: João Paulo ---- - -# RNSA (Real-Valued Negative Selection Algorithm) - -:::info - -**``RNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. - -::: - -## Constructor RNSA - -The ``RNSA`` (Real-Valued Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -```python -class RNSA( - self, - N: int = 100, - r: float = 0.05, - r_s: float = 0.0001, - k: int = 1, - metric: Literal["manhattan", "minkowski", "euclidean"] = "euclidean", - max_discards: int = 1000, - seed: int = None, - algorithm: Literal["default-NSA", "V-detector"] = "default-NSA", - **kwargs: Dict[str, Union[bool, str, float]], -) -``` - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *r* (``float``): Radius of the detector. Defaults to ``0.05``. - - :::note - it is important to consider that setting a very low radius for the detector can significantly reduce the detection rate. On the other hand, a very large radius can make it impossible to incorporate the detector into the search space, which can also compromise detection performance. It is essential to find a balance between the radius size and detection efficiency to achieve the best possible results. - ::: - -* *k* (``int``): Number of neighbors near the randomly generated detectors to perform the distance average calculation. Defaults to ``1``. -* *metric* (``str``): Way to calculate the distance between the detector and the sample: - - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$ - \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} - $$ - - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} - $$ - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - $$ - \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} - $$ - - Defaults to ``'euclidean'``. - -* *max_discards* (``int``): This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. Defaults to ``1000``. -* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. - -* *algorithm* (``str``), Set the algorithm version: - - * ``'default-NSA'``: Default algorithm with fixed radius. - * ``'V-detector'``: This algorithm is based on the article "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", by Ji, Z., Dasgupta, D. (2004), and uses a variable radius for anomaly detection in feature spaces. - - Defaults to ``'default-NSA'``. - -* *r_s* (``float``): rₛ Radius of the ``X`` own samples. - -* ``**kwargs``: - * *non_self_label* (``str``): This variable stores the label that will be assigned when the data has only one - output class, and the sample is classified as not belonging to that class. Defaults to ``'non-self'``. - * *cell_bounds* (``bool``): If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. - * p (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. The default is ``2``, which represents normalized Euclidean distance. Different values of p lead to different variants of the Minkowski - distance [learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). - -**Other variables initiated:** - -* *detectors* (``dict``): This variable stores a list of detectors by class. - -* *classes* (``npt.NDArray``): list of output classes. - ---- - -### Function fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -The input parameters are: - -* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. - -* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the instance of the class.* - ---- - -### Function predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: npt.NDArray) -> npt.NDArray: -``` - -**The input parameter is:** - -* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Returns:** - -* ``C``: prediction array, with the output classes for the given characteristics. -* ``None``: if there are no detectors. - ---- - -### Function score(...) - -The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. - -```python -def score(self, X: npt.NDArray, y: list) -> float: -``` - -It returns the accuracy as a float type. - ---- - -## Private Methods - ---- - -### Function __checks_valid_detector(...) - -The ``def __checks_valid_detector(...)`` function checks if the detector has a valid ``r`` radius for the non-self of the class: - -```python -def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: -``` - -**The input parameters are:** - -* ``X``: array with sample characteristics with **N** samples (rows) and **N** characteristics (columns), normalized to values between [0, 1]. - -* ``vector_x``: Randomly generated candidate detector. - -* ``samplesIndexClass``: Array with the indexes of a class. - -**Returns:** ``True`` for detectors that do not have samples inside or ``False`` if they do. - ---- - -### Function __compare_KnearestNeighbors_List(...) - -The ``def __compare_KnearestNeighbors_List(...)`` function compares the distance of the k-nearest neighbors, so if the distance of the new sample is smaller, replaces ``k-1`` and sorts in ascending order: - -```python -def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: -``` - -Returns a list of k-nearest neighbor distances. - ---- - -### Function __compare_sample_to_detectors(...) - -Function to compare a sample with the detectors, verifying if the sample is proper. -In this function, when there is class ambiguity, it returns the class that has the greatest average distance between the detectors. - -```python -def __compare_sample_to_detectors(self, line): -``` - -**The input parameters are:** - -* line: vector with N-features - -**Returns:** The predicted class with the detectors or None if the sample does not qualify for any class. - ---- - -### Function __detector_is_valid_to_Vdetector(...) - -Check if the distance between the detector and the samples, minus the radius of the samples, is greater than the minimum radius. - -```python -def __detector_is_valid_to_Vdetector(self, distance, vector_x): -``` - -**The input parameters are:** - -* distance (``float``): minimum distance calculated between all samples. -* vector_x (``numpy.ndarray``): randomly generated candidate detector vector x with values between 0 and 1. - -**Returns:** - -* ``False``: if the calculated radius is smaller than the minimum distance or exceeds the edge of the space, if this option is enabled. -* ``True`` and the distance minus the radius of the samples, if the radius is valid.` - ---- - -### Function __distance(...) - -The function ``def __distance(...)`` calculates the distance between two points using the technique defined in ``metric``, which are: ``'euclidean', 'norm_euclidean', or 'manhattan'`` - -```python -def __distance(self, u: npt.NDArray, v: npt.NDArray): -``` - -The input parameters are ``u`` and ``v`` NDArrays, with the coordinates for the points. - -**Returns:** the distance (``double``) between the two points. - ---- diff --git a/versioned_docs/version-0.5.x/api/README.md b/versioned_docs/version-0.5.x/api/README.md new file mode 100644 index 000000000..8d775063a --- /dev/null +++ b/versioned_docs/version-0.5.x/api/README.md @@ -0,0 +1,85 @@ +--- +id: api +sidebar_position: 5 +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering +--- + +# AISP - API + +Welcome to the **AISP** (Artificial Immune System Package) api. This documentation demonstrates the package public API. + +## Core Modules ([`aisp.base`](./base/README.md)) + +Fundamental abstractions and base classes that define core interfaces of package. + +| Class | Description | +|-----------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base/base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Abstract base class for optimization algorithms. | + +### Immune Domain components ([`aisp.base.immune`](./base/immune/README.md)) + +Core structures and support utilities for implementations immune. + +| Module | Description | +|-----------------------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representation of immune system cells. | +| [`mutation`](./base/immune/mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./base/immune/populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | + +--- + +## Algorithms + +### Negative Selection Algorithms ([`aisp.nsa`](./nsa/README.md)) + +supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from +not-self. + +| Class | Description | +|-------------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./nsa/bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | + +### Clonal Selection Algorithms ([`aisp.csa`](./csa/README.md)) + +Algorithms inspired by the process of antibody proliferation to detecting an antigen. + +| Class | Description | +|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./csa/clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | + +### Immune Network Algorithms ([`aisp.ina`](./ina/README.md)) + +Algorithms based on Network Theory Algorithms proposed by Jerne. + +| Class | Description | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | + +## Utils ([`aisp.utils`](./utils/README.md)) + +Utility functions and helpers for development. + +| Module | Description | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./utils/distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./utils/metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./utils/multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./utils/sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | + +## Exceptions ([`aisp.exceptions`](./exceptions.md)) + +Custom warnings and errors. diff --git a/versioned_docs/version-0.5.x/api/base/README.md b/versioned_docs/version-0.5.x/api/base/README.md new file mode 100644 index 000000000..631dcb4cb --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - immune + - abstract +--- + +# aisp.base + +Base Classes and Core Utilities. + +> **Module:** `aisp.base` + +## Overview + +This module provides the fundamental classes and utilities that serve as the basis for all +Artificial Immune Systems algorithms implemented in the AISP package. + +## Classes + +| Class | Description | +|------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base-optimizer.md) | Abstract base class for optimization algorithms. | + +## Submodules + +| Module | Description | +|--------------------------------|-----------------------------------------------| +| [`immune`](./immune/README.md) | Support Module for Artificial Immune Systems. | \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/api/base/base-classifier.md b/versioned_docs/version-0.5.x/api/base/base-classifier.md new file mode 100644 index 000000000..115053d64 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/base-classifier.md @@ -0,0 +1,133 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classifier + - classifier interface + - accuracy score + - fit + - predict +tags: + - classifier + - classification +--- + +# BaseClassifier + +Abstract base class for classification algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClassifier` + +--- + +## Overview + +This class defines the core interface for classification models. It enforces the implementation of the `fit` +and `predict` methods in all derived classes, and provides a default implementation of the `score` method. + +Use cases: + +- Abstract base class for extending classification algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|-----------|-------------------------|:-------:|------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Train the model using the input data X and corresponding labels y. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------| +| `npt.NDArray` | Predicted values for each input sample. | + +--- + +## Public Methods + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +Score function calculates forecast accuracy. + +This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. +This function was added for compatibility with some scikit-learn functions. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | + +**Returns** + +| Type | Description | +|---------|----------------------------| +| `float` | The accuracy of the model. | + diff --git a/versioned_docs/version-0.5.x/api/base/base-clusterer.md b/versioned_docs/version-0.5.x/api/base/base-clusterer.md new file mode 100644 index 000000000..0e554068b --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/base-clusterer.md @@ -0,0 +1,122 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict +tags: + - clusterer + - clustering +--- + +# BaseClusterer + +Abstract base class for clustering algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClusterer` + +--- + +## Overview + +This class defines the core interface for clustering models. It enforces the implementation of the `fit` and +`predict` methods in all derived classes, and provides a default implementation for `fit_predict` and `get_params`. + +Use cases: + +- Abstract base class for extending clustering algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|-------------------------|:-------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Labels for the clusters generated during model fitting. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Train the model using the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | + +--- + +## Public Methods + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Fit the clustering model to the data and return cluster labels. + +This is a convenience method that combines `fit` and `predict` into a single call. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|-----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | diff --git a/versioned_docs/version-0.5.x/api/base/base-optimizer.md b/versioned_docs/version-0.5.x/api/base/base-optimizer.md new file mode 100644 index 000000000..f3bde23a1 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/base-optimizer.md @@ -0,0 +1,165 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - optimizer + - optimization + - optimizer interface + - objective function + - minimization + - maximization +tags: + - optimizer + - optimization +--- + +# BaseOptimizer + +Abstract base class for optimization algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseOptimizer` + +--- + +## Overview + +This class defines the core interface for optimization strategies. It keeps track of cost history, evaluated +solutions, and the best solution found during the optimization process. Subclasses must implement ``optimize`` +and ``affinity_function``. + +Use cases: + +- Abstract base class for extending optimization algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|--------------------|-------------------|:-------:|-------------------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | History of best costs found at each iteration. | +| `solution_history` | `List` | `[]` | History of the best solution found at each iteration. | +| `best_solution` | `Any` | `None` | The best solution found. | +| `best_cost` | `Optional[float]` | `None` | Cost of the best solution found. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | + +--- + +## Abstract Methods + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Execute the optimization process. +This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search +space. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations | +| `n_iter_no_change` | `int` | `10` | the maximum number of iterations without updating the best | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Evaluate the affinity of a candidate solution. + +This method must be implemented according to the specific optimization problem, defining how the solution will be +evaluated. +The returned value should represent the quality of the evaluated solution. + +**Parameters** + +| Name | Type | Default | Description | +|------------|-------|:-------:|-------------------------------------| +| `solution` | `Any` | - | Candidate solution to be evaluated. | + +**Returns** + +| Type | Description | +|---------|------------------------------------------------| +| `float` | Cost value associated with the given solution. | + +--- + +## Public Methods + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Generate a formatted summary report of the optimization process. +The report includes the best solution, its associated cost, and the evolution of cost values per iteration. + +**Returns** + +| Type | Description | +|-------|---------------------------------------------------------| +| `str` | A formatted string containing the optimization summary. | + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Register a function dynamically in the optimizer instance. + +**Parameters** + +| Name | Type | Default | Description | +|------------|----------------------|:-------:|---------------------------------------------------| +| `alias` | `str` | - | Name used to access the function as an attribute. | +| `function` | `Callable[..., Any]` | - | Callable to be registered. | + +**Raises** + +| Exception | Description | +|------------------|---------------------------------------------------------------------------------| +| `TypeError` | If the provided `function` is not callable. | +| `AttributeError` | If `alias` is protected and cannot be modified, or does not exist in the class. | + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reset the object's internal state, clearing history and resetting values. diff --git a/versioned_docs/version-0.5.x/api/base/immune/README.md b/versioned_docs/version-0.5.x/api/base/immune/README.md new file mode 100644 index 000000000..5e196cbca --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - cell + - mutation + - population +--- + +# aisp.base.immune + +Support Module for Artificial Immune Systems. + +> **Module:** `aisp.base.immune` + +## Submodules + +| Module | Description | +|-----------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representation of immune system cells. | +| [`mutation`](./mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/api/base/immune/cell/README.md b/versioned_docs/version-0.5.x/api/base/immune/cell/README.md new file mode 100644 index 000000000..2aede005f --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/cell/README.md @@ -0,0 +1,33 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representation of immune system cells. + +> **Module:** `aisp.base.immune.cell` + +## Overview + +This module defines the representation of cells in artificial immune systems, +implements as dataclass. + +## Classes + +| Class | Description | +|-----------------------------|---------------------------------------------------| +| [`Cell`](./c-cell.md) | Represents a basic immune cell. | +| [`BCell`](./b-cell.md) | Represents a memory B-cell. | +| [`Antibody`](./antibody.md) | Represent an antibody. | +| [`Detector`](./detector.md) | Represents a non-self detector of the RNSA class. | \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/api/base/immune/cell/antibody.md b/versioned_docs/version-0.5.x/api/base/immune/cell/antibody.md new file mode 100644 index 000000000..6f0f72021 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - antibody + - affinity + - cell + - immune + - dataclass +--- + +# Antibody + +Represent an antibody. + +:::tip[Inheritance] + +This class extends [Cell](./c-cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Antibody` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------|:-------:|----------------------------------| +| `vector` | `npt.NDArray` | - | A vector of cell features. | +| `affinity` | `float` | - | Affinity value for the antibody. | + +--- + +## Methods + +* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. +* `__eq__(other)`: Check if this cell has the same affinity as another cell. diff --git a/versioned_docs/version-0.5.x/api/base/immune/cell/b-cell.md b/versioned_docs/version-0.5.x/api/base/immune/cell/b-cell.md new file mode 100644 index 000000000..6eff1ab58 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/cell/b-cell.md @@ -0,0 +1,63 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - B-cell + - immune memory + - dataclass + - clonal mutation + - clonal expansion +--- + +# BCell + +Represents a memory B-cell. + +:::tip[Inheritance] + +This class extends [Cell](./c-cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import BCell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Public Methods + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Generate **N** clones of the current cell and apply hypermutation to the clones. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|------------------------------------------------------|:-----------------------:|--------------------------------------------------------| +| `n` | `int` | - | Number of clones to generate from the original b-cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of features of the cell. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|---------------------------------------------------------------| +| `npt.NDArray` | An array containing N mutated vectors from the original cell. | diff --git a/versioned_docs/version-0.5.x/api/base/immune/cell/c-cell.md b/versioned_docs/version-0.5.x/api/base/immune/cell/c-cell.md new file mode 100644 index 000000000..ff94da948 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/cell/c-cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Represents a basic immune cell. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Cell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Methods + +* `__eq__(other)`: Check if two cells are equal based on their vectors. +* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. +* `__getitem__(item)`: Get elements from the feature vector using indexing. + diff --git a/versioned_docs/version-0.5.x/api/base/immune/cell/detector.md b/versioned_docs/version-0.5.x/api/base/immune/cell/detector.md new file mode 100644 index 000000000..520294da7 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - cell + - immune + - radius + - non-self + - nsa + - dataclass +--- + +# Detector + +Represents a non-self detector of the RNSA class. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Detector` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------------------|:-------:|----------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Detector feature vector. | +| `radius` | `float, optional` | - | Detector radius, used in the V-detector algorithm. | diff --git a/versioned_docs/version-0.5.x/api/base/immune/mutation.md b/versioned_docs/version-0.5.x/api/base/immune/mutation.md new file mode 100644 index 000000000..c0d34a919 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/mutation.md @@ -0,0 +1,145 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutation + - clonal expansion + - immune system + - python numba functions + - vector mutation +--- + +# mutation + +The functions perform utilize Numba decorators for Just-In-Time compilation. + +Contains functions that generate sets of mutated clones from continuous or binary vectors, +simulating the clonal expansion process in artificial immune systems. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import mutation` + +## Functions + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by a continuous vector. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Generate a set of mutated clones from a cell represented by a binary vector. + +This function creates `n` clones of the input binary vector and applies mutations to the +bits, simulating clonal expansion in artificial immune systems with discrete representations. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|-------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by custom ranges per dimension. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_continuous + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: + ... +``` + +Generate a set of mutated clones by permutation. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | Probability of mutating each feature 0 ≤ mutation_rate < 1. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | diff --git a/versioned_docs/version-0.5.x/api/base/immune/populations.md b/versioned_docs/version-0.5.x/api/base/immune/populations.md new file mode 100644 index 000000000..0126de2d5 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/base/immune/populations.md @@ -0,0 +1,56 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binary + - classifying + - affinity threshold + - real-Valued + - memory B-cell + - clonal Expansion + - populations +--- + +# populations + +Provide utility functions for generating antibody populations in immunological algorithms. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import populations` + +## Functions + +### generate_random_antibodies + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None, +) -> npt.NDArray: + ... +``` + +Generate a random antibody population. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|---------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------| +| `npt.NDArray` | Array of shape (n_samples, n_features) containing the generated antibodies. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------| +| `ValueError` | If the number of features is less than or equal to zero. | diff --git a/versioned_docs/version-0.5.x/api/csa/README.md b/versioned_docs/version-0.5.x/api/csa/README.md new file mode 100644 index 000000000..e2872edeb --- /dev/null +++ b/versioned_docs/version-0.5.x/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - immune + - clonal selection + - clonalg + - airsv2 + - antibody proliferation + - mutations + - clonal selection algorithm + - artificial immune systems + - classification + - optimization +--- + +# aisp.csa + +Module (CSA) Clonal Selection Algorithm. + +> **Module:** `aisp.csa` + +## Overview + +CSAs are inspired by the process of antibody proliferation upon detecting an antigen, during which +the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. + +## Classes + +| Class | Description | +|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | diff --git a/versioned_docs/version-0.5.x/api/csa/airs.md b/versioned_docs/version-0.5.x/api/csa/airs.md new file mode 100644 index 000000000..777623883 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/csa/airs.md @@ -0,0 +1,197 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classification + - artificial immune recognition system + - memory cells + - k-nn + - supervised learning + - AIRS2 +tags: + - classification + - supervised + - clonal selection +--- + +# AIRS + +Artificial Immune Recognition System (AIRS) + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import AIRS` + +--- + +## Overview + +The Artificial Immune Recognition System (AIRS) is a classification algorithm inspired by the +clonal selection process of the biological immune system. This implementation is based on the +simplified AIRS2 version described in [^1]. The algorithm has been adapted to support both +real-valued (continuous) and binary feature datasets. + +:::note + +This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. +Introducing adaptations to handle continuous and binary datasets. + +Based on Algorithm 16.5 from Brabazon et al. [^1] + +Related and noteworthy works: access here [^2]. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# AIRS Instance +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` + +Output: + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|---------|:-------------:|---------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Total amount of available resources. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a class. This quantity is multiplied by (cell_stimulus * rate_hypermutation) to define the number of clones. | +| `rate_mc_init` | `float` | `0.2` | Percentage of samples used to initialize memory cells. | +| `rate_hypermutation` | `float` | `0.75` | The rate of mutated clones derived from rate_clonal as a scalar factor. | +| `affinity_threshold_scalar` | `float` | `0.75` | Normalized affinity threshold. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `max_iters` | `int` | `100` | Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. | +| `resource_amplified` | `float` | `1.0` | Resource consumption amplifier is multiplied with the incentive to subtract resources. | +| `metric` | `str` | `"euclidean"` | Distance metric used to compute affinity between cells and samples. | +| `seed` | `int` | `None` | Seed for random generation. | +| `p` | `float` | `2` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|----------------|-------------------------------------------|:-------:|---------------------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` + +Fit the model to the training data using the AIRS. + +The function ``fit(...)``, performs the training according to `X` and `y`, using the +method AIRS. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + +**Raises** + +| Exception | Description | +|-------------|---------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict class labels based on the memory cells created during training. + +This method uses the trained memory cells to perform classification of the input data +using the k-nearest neighbors approach. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/csa.md#airs-artificial-immune-recognition-system) + +--- + +## References + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/versioned_docs/version-0.5.x/api/csa/clonalg.md b/versioned_docs/version-0.5.x/api/csa/clonalg.md new file mode 100644 index 000000000..81811d38d --- /dev/null +++ b/versioned_docs/version-0.5.x/api/csa/clonalg.md @@ -0,0 +1,183 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - optimization + - clonal selection + - clonalg + - antibody population + - objective function +tags: + - optimization + - clonal selection + - minimization + - maximization + - binary + - continuous + - permutation + - ranged +--- + +# Clonalg + +Clonal Selection Algorithm (CLONALG). + +:::tip[Inheritance] + +This class extends [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import Clonalg` + +--- + +## Overview + +The Clonal Selection Algorithm (CSA) is an optimization algorithm inspired by the biological +process of clonal selection and expansion of antibodies in the immune system [^1]. This +implementation of CLONALG has been adapted for the minimization or maximization of cost +functions in binary, continuous, ranged-value, and permutation problems. + +:::note + +This CLONALG implementation contains some changes based on the AISP context, for general +application to various problems, which may produce results different from the standard or +specific implementation. This adaptation aims to generalize CLONALG to minimization and +maximization tasks, in addition to supporting continuous, discrete, and permutation problems. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import Clonalg +# Search space limits +bounds = {'low': -5.12, 'high': 5.12} +# Objective function +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x)) +# CLONALG Instance +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` + +**Output:** + +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-------------------------|------------------------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimension of the problem to be minimized. | +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | +| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | +| `seed` | `int` | `None` | Seed for random generation. | + +## Attributes + +| Name | Type | Default | Description | +|--------------|----------------------------|:-------:|---------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | Population of antibodies. | + +--- + +## Public Methods + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Execute the optimization process and return the population. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|----------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | +| `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | +| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | + +**Returns** + +| Type | Description | +|------------------|---------------------------------------------| +| `List[Antibody]` | Antibody population after clonal expansion. | + + +**Raises** + +| Exception | Description | +|-----------------------|----------------------------------------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided to evaluate candidate solutions. | + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Evaluate the affinity of a candidate cell. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------| +| `solution` | `npt.NDArray` | - | Candidate solution to evaluate. | + +**Returns** + +| Type | Description | +|--------------|------------------------------------------------| +| `np.float64` | Affinity value associated with the given cell. | + + +**Raises** + +| Exception | Description | +|-----------------------|--------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Optimization/csa.md#clonalg-clonal-selection-algorithm) + +--- + +## References + +[^1]: BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired + Programming Recipes., 2011. Available at: + https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html diff --git a/versioned_docs/version-0.5.x/api/exceptions.md b/versioned_docs/version-0.5.x/api/exceptions.md new file mode 100644 index 000000000..688c12e1a --- /dev/null +++ b/versioned_docs/version-0.5.x/api/exceptions.md @@ -0,0 +1,91 @@ +--- +id: exceptions +sidebar_label: aisp.exceptions +keywords: + - exceptions + - raises + - warnings +--- + +# aisp.exceptions + +Custom warnings and errors. + +> **Module:** `aisp.exceptions` +> **Import:** `from aisp import exceptions` + +## Exception classes + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exception thrown when the maximum number of detector discards is reached. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exception raised when the number of input features does not match the expected number. +This exception is triggered during prediction if the input features' dimension is incorrect. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-----------------|:-------:|-----------------------------------------------------| +| `expected` | `int` | - | The expected number of features | +| `received` | `int` | - | The actual number of features received. | +| `variable_name` | `Optional[str]` | `None` | The name of the variable that caused this mismatch. | + +--- + +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exception raised when the input vector type is not supported. +This exception is thrown when the vector data type does not match any of the supported. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|-----------------|:-------:|----------------------------| +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exception raised when a method is called before the model has been fit. +This exception is thrown when the model instance is being used without first training +it via the `fit` method. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | diff --git a/versioned_docs/version-0.5.x/api/ina/README.md b/versioned_docs/version-0.5.x/api/ina/README.md new file mode 100644 index 000000000..59c20b75f --- /dev/null +++ b/versioned_docs/version-0.5.x/api/ina/README.md @@ -0,0 +1,31 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - immune + - clonal selection + - immune networks + - ainet + - opt-ainet + - mutations + - clonal selection + - artificial immune systems + - clustering + - optimization +--- + +# aisp.ina + +Module (ina) Immune Network Algorithm. + +> **Module:** `aisp.ina` + +## Overview + +This module implements algorithms based on Network Theory Algorithms proposed by Jerne. + +## Classes + +| Class | Description | +|------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | diff --git a/versioned_docs/version-0.5.x/api/ina/ai-net.md b/versioned_docs/version-0.5.x/api/ina/ai-net.md new file mode 100644 index 000000000..be83b3e04 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/ina/ai-net.md @@ -0,0 +1,227 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - immune network + - clustering + - data compression + - unsupervised learning + - Minimum Spanning Tree +tags: + - clustering + - unsupervised + - immune network + - data compression +--- + +# AiNet + +Artificial Immune Network (AiNet) for Compression and Clustering. + +:::tip[Inheritance] + +This class extends [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Module:** `aisp.ina` +> **Import:** `from aisp.ina import AiNet` + +--- + +## Overview + +This class implements the aiNet algorithm, an artificial immune network model designed for +clustering and data compression tasks. The aiNet algorithm uses principles from immune +network theory, clonal selection, and affinity maturation to compress high-dimensional +datasets [^1]. +For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** +(MST) to remove the most distant nodes and separate the groups [^2]. + +--- + +## Example + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# AiNet Instance +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Expected: label 0 + [0.85, 0.65], # Expected: label 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|----------------------------|----------------------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells. | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells. | +| `seed` | `Optional[int]` | `None` | Seed for random generation. | +| `use_mst_clustering` | `bool` | `True` | If `True`, performs clustering using the MST. If `False`, clustering is not performed and the predict method raises a ModelNotFittedError. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------------------|-------------------------|:-------:|------------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | The immune network representing clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | The set of memory antibodies. | +| `mst` | `dict` | - | The Minimum Spanning Tree and its statistics (graph, mean_distance, std_distance). | + +--- + +## Public Methods + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Train the AiNet model on input data. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|----------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------|--------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | If the data type of the feature on X is not supported. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict cluster labels for input data. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|--------------------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels, or None if clustering is disabled. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If X contains values other than (0 and 1) or (True and False) when the trained features are of type `"binary-features"`. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions. | + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` + +Partition the clusters based on the MST inconsistency factor. + +Uses the precomputed Minimum Spanning Tree (MST) of the antibody population +to redefine clusters. Edges whose weights exceed the mean plus the +`mst_inconsistency_factor` multiplied by the standard deviation of MST edge +weights are removed. Each connected component after pruning is treated as a +distinct cluster. + +**Parameters** + +| Name | Type | Default | Description | +|----------------------------|---------|:-------:|----------------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | If provided, overrides the current inconsistency factor. | + +**Raises** + +| Exception | Description | +|--------------|--------------------------------------------------------------| +| `ValueError` | If the Minimum Spanning Tree (MST) has not yet been created. | +| `ValueError` | If Population of antibodies is empty. | +| `ValueError` | If MST statistics (mean or std) are not available. | + +**Updates** + +| Name | Type | Description | +|------------------|--------------------------|-------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dictionary mapping cluster labels to antibody arrays. | +| `labels` | `list` | List of cluster labels. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Clustering/ina.md#ainet-artificial-immune-network) + +--- + +## References + +[^1]: De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. + Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree diff --git a/versioned_docs/version-0.5.x/api/nsa/README.md b/versioned_docs/version-0.5.x/api/nsa/README.md new file mode 100644 index 000000000..0b354be2e --- /dev/null +++ b/versioned_docs/version-0.5.x/api/nsa/README.md @@ -0,0 +1,35 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - artificial immune systems + - classification + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - multiclass + - real-valued + - v-detector +--- + +# aisp.nsa + +Module (NSA) Negative Selection Algorithm. + +> **Module:** `aisp.nsa` + +## Overview + +NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to +distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are +preserved. + +## Classes + +| Class | Description | +|---------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | diff --git a/versioned_docs/version-0.5.x/api/nsa/bnsa.md b/versioned_docs/version-0.5.x/api/nsa/bnsa.md new file mode 100644 index 000000000..6bec1fb6c --- /dev/null +++ b/versioned_docs/version-0.5.x/api/nsa/bnsa.md @@ -0,0 +1,193 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - multiclass +tags: + - classification + - supervised + - negative selection + - binary-features + - anomaly detection +--- + +# BNSA + +Binary Negative Selection Algorithm (BNSA). + +:::tip[Inheritance] +This class extends [BaseClassifier](../base/base-classifier.md) +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import BNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +The **Binary Negative Selection Algorithm (BNSA)** is based on the original proposal by +Forrest et al. (1994) [^1], originally developed for computer security. In the adaptation, the +algorithm use bits arrays, and it has support for multiclass classification. + +::: + +:::warning + +High `aff_thresh` values may prevent the generation of valid non-self detectors + +::: + +--- + +## Example + +```python +from aisp.nsa import BNSA +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ +... [1, 1, 1, 1, 1], # Sample of Anomaly +... [0, 1, 0, 1, 0], # self sample +... ] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` + +**Output** + +```bash +['non-self' 'self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|-----------------|:--------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `aff_thresh` | `float` | `0.1` | The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% similarity. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Method for selecting labels for samples designated as non-self by all detectors. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|-----------------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Training according to X and y, using the method negative selection method. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X contains any values other than (0 and 1) or (True and False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/nsa.md#bnsa-binary-negative-selection-algorithm) + +--- + +## References + +[^1]: S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in + a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security + and Privacy, Oakland, CA, USA, 1994, pp. 202-212, + doi: https://dx.doi.org/10.1109/RISP.1994.296580. diff --git a/versioned_docs/version-0.5.x/api/nsa/rnsa.md b/versioned_docs/version-0.5.x/api/nsa/rnsa.md new file mode 100644 index 000000000..ddc07e414 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/nsa/rnsa.md @@ -0,0 +1,222 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - negative selection + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - real-valued + - v-detector + - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection +--- + +# RNSA + +Real-Valued Negative Selection Algorithm (RNSA). + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import RNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +This algorithm has two different versions: one based on the canonical version [^1] and another +with variable radius detectors [^2]. Both are adapted to work with multiple classes and have +methods for predicting data present in the non-self region of all detectors and classes. + +::: + +:::warning + +The parameters `r` and `r_s` can prevent the generation of valid detectors. A very small `r` +value can limit coverage, while a very high one can hinder the generation of valid detectors. +Similarly, a high r_s can restrict detector creation. Thus, proper adjustment of `r` and `r_s` +is essential to ensure good model performance. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Example 1:** Multiclass classification (RNSA supports two or more classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +['a' 'b'] +``` + +**Example 2:** Anomaly Detection (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` + +**Output** + +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `r` | `float` | `0.05` | Radius of the detector. | +| `r_s` | `float` | `0.0001` | rₛ Radius of the `X` own samples. | +| `k` | `int` | `1` | Number of neighbors near the randomly generated detectors to perform the distance average calculation. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Distance metric used to compute the distance between the detector and the sample. | +| `max_discards` | `int` | `1000` | This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | +| `non_self_label` | `str` | `'non-self'` | This variable stores the label that will be assigned when the data has only one output class, and the sample is classified as not belonging to that class. | +| `cell_bounds` | `bool` | `False` | If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|----------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Perform training according to X and y, using the negative selection method (NegativeSelect). + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|--------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training input samples. Each row corresponds to a samples and column to feature. | +| `y` | `Union[npt.NDArray, list]` | - | Target vector of shape (n_samples,). Must contain the same number of samples as `X`. | +| `verbose` | `bool` | `True` | If True, prints training progress information. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|----------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input samples. Must have the same number of features used during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Examples**](../../examples/Classification/nsa.md#rnsa-real-valued-negative-selection-algorithm) + +--- + +## References + +[^1]: BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing + Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. + Disponível em: https://dx.doi.org/10.1007/978-3-662-43631-8. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/versioned_docs/version-0.5.x/api/utils/README.md b/versioned_docs/version-0.5.x/api/utils/README.md new file mode 100644 index 000000000..a0467faa1 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/README.md @@ -0,0 +1,28 @@ +--- +id: utils +sidebar_label: aisp.utils +keywords: + - functions + - helpers + - utils +--- + +# aisp.utils + +Utility functions and helpers for development. + +> **Module:** `aisp.utils` +> **Import:** `from aisp import utils` + +## Submodules + +| Module | Description | +|----------------------------------|--------------------------------------------------------------------------| +| [`display`](./display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./validation.md) | Contains functions responsible for validating data types. | + diff --git a/versioned_docs/version-0.5.x/api/utils/display/README.md b/versioned_docs/version-0.5.x/api/utils/display/README.md new file mode 100644 index 000000000..6625dc77f --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/display/README.md @@ -0,0 +1,23 @@ +--- +id: display +sidebar_label: display +keywords: + - table + - progress +--- + +# display + +Utility functions for displaying algorithm information. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Description | +|------------------------------------------|-----------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Format tabular data into strings for display in the console. | +| [`ProgressTable`](./progress-table.md) | Display a formatted table in the console to track the algorithm's progress. | diff --git a/versioned_docs/version-0.5.x/api/utils/display/progress-table.md b/versioned_docs/version-0.5.x/api/utils/display/progress-table.md new file mode 100644 index 000000000..7823ef2e3 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Display a formatted table in the console to track the algorithm's progress. + +:::tip[Inheritance] + +This class extends [TableFormatter](./table-formatter.md). + +::: + + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import ProgressTable` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|-------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping `{column_name: column_width}`. | +| `verbose` | `bool` | `True` | If False, prints nothing to the terminal. | + +--- + +## Public Methods + +### update + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +``` + +Add a new row of values to the table. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Keys must match the columns defined in headers. | + +--- + +### finish + +```python +def finish(self) -> None: + ... +``` + +End the table display, printing the bottom border and total time. diff --git a/versioned_docs/version-0.5.x/api/utils/display/table-formatter.md b/versioned_docs/version-0.5.x/api/utils/display/table-formatter.md new file mode 100644 index 000000000..c1c893186 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/display/table-formatter.md @@ -0,0 +1,85 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Format tabular data into strings for display in the console. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import TableFormatter` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|--------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format `{column_name: column_width}`. | + +--- + +## Public Methods + +### get_header + +```python +def get_header(self): + ... +``` + +Generate the table header, including the top border, column headings, and separator line. + +**Returns** + +| Type | Description | +|-------|---------------------------------------| +| `str` | Formatted string of the table header. | + + +--- + +### get_row + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +``` + +Generate a formatted row for the table data. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format `{column_name: value}`. | + +**Returns** + +| Type | Description | +|-------|------------------------------------| +| `str` | Formatted string of the table row. | + +--- + +### get_bottom + +```python +def get_bottom(self, new_line: bool = False): + ... +``` + +Generate the table's bottom border. + +**Parameters** + +| Name | Type | Default | Description | +|------------|--------|:-------:|------------------------------------------------------------------| +| `new_line` | `bool` | `False` | If True, adds a line break before the border (default is False). | + +**Returns** + +| Type | Description | +|-------|-----------------------------------------| +| `str` | Formatted string for the bottom border. | diff --git a/versioned_docs/version-0.5.x/api/utils/distance.md b/versioned_docs/version-0.5.x/api/utils/distance.md new file mode 100644 index 000000000..fc827f683 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/distance.md @@ -0,0 +1,243 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distance +--- + +# distance + +Utility functions for distance between arrays with numba decorators. + +> **Module:** `aisp.utils.distance` +> **Import:** `from aisp.utils import distance` + +## Functions + +### hamming + +```python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +``` + +Calculate the Hamming distance between two points. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|-------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordinates of the second point. | + + +**Returns** + +| Type | Description | +|-----------|--------------------------------------| +| `float64` | Hamming distance between two points. | + +--- + +### euclidean + +```python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +``` + +Calculate the Euclidean distance between two points. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Euclidean distance between two points. | + +--- + +### cityblock + +```python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +``` + +Calculate the Manhattan distance between two points. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Manhattan distance between two points. | + +--- + +### minkowski + +```python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the Minkowski distance between two points. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +:::note[Parameter `p`] + +- p = 1: **Manhattan** distance - sum of absolute differences. +- p = 2: **Euclidean** distance - sum of squared differences (square root). +- p > 2: **Minkowski** distance with an increasing penalty as p increases. + +::: + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Minkowski distance between two points. | + +--- + +### compute_metric_distance + +```python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the distance between two points by the chosen metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|------------------------|:-------:|--------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +**Returns** + +| Type | Description | +|-----------|-----------------------------------------------------------| +| `float64` | Distance between the two points with the selected metric. | + +--- + +### min_distance_to_class_vectors + +```python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +``` + +Calculate the minimum distance between an input vector and the vectors of a class. + +**Parameters** + +| Name | Type | Default | Description | +|------------|------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | Vector to be compared with the class vectors. Expected shape: (n_features,). | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 ("euclidean"), 1 ("manhattan"), 2 ("minkowski") or ("hamming") | +| `p` | `float` | `2.0` | Parameter for the Minkowski distance (used only if `metric` is "minkowski"). | + +**Returns** + +| Type | Description | +|---------|----------------------------------------------------------------------------------------------------------------------------------------| +| `float` | The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. | + +--- + +### get_metric_code + +```python +def get_metric_code(metric: str) -> int: + ... +``` + +Get the numeric code associated with a distance metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|-------|:-------:|----------------------------------------------------------------------------------------| +| `metric` | `str` | - | Name of the metric. Can be `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Returns** + +| Type | Description | +|-------|-------------------------------------------| +| `int` | Numeric code corresponding to the metric. | + + +**Raises** + +| Exception | Description | +|--------------|------------------------------------------| +| `ValueError` | If the metric provided is not supported. | + diff --git a/versioned_docs/version-0.5.x/api/utils/metrics.md b/versioned_docs/version-0.5.x/api/utils/metrics.md new file mode 100644 index 000000000..14e8ff389 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/metrics.md @@ -0,0 +1,47 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Utility functions for measuring accuracy and performance. + +> **Module:** `aisp.utils.metrics` +> **Import:** `from aisp.utils import metrics` + +## Functions + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calculate the accuracy score based on true and predicted labels. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------|:-------:|-------------------------------------------------------------------------------| +| `y_true` | `Union[npt.NDArray, list]` | - | Ground truth (correct) labels. Expected to be of the same length as `y_pred`. | +| `y_pred` | `Union[npt.NDArray, list]` | - | Predicted labels. Expected to be of the same length as `y_true`. | + +**Returns** + +| Type | Description | +|---------|----------------------------------------------------------------------| +| `float` | The ratio of correct predictions to the total number of predictions. | + +**Raises** + +| Exception | Description | +|--------------|---------------------------------------------------------------------------| +| `ValueError` | If `y_true` or `y_pred` are empty or if they do not have the same length. | diff --git a/versioned_docs/version-0.5.x/api/utils/multiclass.md b/versioned_docs/version-0.5.x/api/utils/multiclass.md new file mode 100644 index 000000000..367c641f4 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/multiclass.md @@ -0,0 +1,82 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Utility functions for handling classes with multiple categories. + +> **Module:** `aisp.utils.multiclass` +> **Import:** `from aisp.utils import multiclass` + +## Functions + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separate indices of samples by class for targeted iteration. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------------------------------------|:-------:|-------------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | list with unique classes. | +| `y` | `npt.NDArray` | - | Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. | + +**Returns** + +| Type | Description | +|--------|------------------------------------------------------------------------------| +| `dict` | A dictionary with the list of array positions(`y`), with the classes as key. | + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### predict_knn_affinity + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray: + ... +``` + +Predict classes using k-nearest neighbors and trained cells. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|-----------------------------------------------|:-------:|----------------------------------------------------------------| +| `X` | `npt.NDArray` | - | Input data to be classified. | +| `k` | `int` | - | Number of nearest neighbors to consider for prediction. | +| `all_cell_vectors` | `List[Tuple[Union[str, int], npt.NDArray]]` | - | List of tuples (class_name, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Function that takes two vectors and returns an affinity value. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------------| +| `npt.NDArray` | Array of predicted labels for each sample in X, based on the k nearest neighbors. | diff --git a/versioned_docs/version-0.5.x/api/utils/sanitizers.md b/versioned_docs/version-0.5.x/api/utils/sanitizers.md new file mode 100644 index 000000000..7f01210cf --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/sanitizers.md @@ -0,0 +1,119 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Utility functions for validation and treatment of parameters. + +> **Module:** `aisp.utils.sanitizers` +> **Import:** `from aisp.utils import sanitizers` + +## Functions + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Value if present in the set of valid choices; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------|:-------:|------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `valid_choices` | `Iterable[T]` | - | A collection of valid choices. | +| `default` | `T` | - | The default value to be returned if 'value' is not in 'valid_choices'. | + +**Returns** + +| Type | Description | +|------|-----------------------------------------------------------| +| `T` | The original value if valid, or the default value if not. | + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Value if it satisfies the specified condition; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|-----------------------|:-------:|-----------------------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `default` | `T` | - | The default value to be returned if the condition is not satisfied. | +| `condition` | `Callable[[T], bool]` | - | A function that takes a value and returns a boolean, determining if the value is valid. | + +**Returns** + +| Type | Description | +|------|--------------------------------------------------------------------------------| +| `T` | The original value if the condition is satisfied, or the default value if not. | + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Seed if it is a non-negative integer; otherwise, None. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|---------------------------------| +| `seed` | `Any` | - | The seed value to be validated. | + +**Returns** + +| Type | Description | +|-----------------|------------------------------------------------------------------------------| +| `Optional[int]` | The original seed if it is a non-negative integer, or None if it is invalid. | + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Validate and normalize feature bounds. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|-------|:-------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | The input bounds, which must be either None or a dictionary with 'low' and 'high' keys. | +| `problem_size` | `int` | - | The expected length for the normalized bounds lists, corresponding to the number of features in the problem. | + +**Returns** + +| Type | Description | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------------------------------| +| `TypeError` | If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. | +| `ValueError` | If provided iterables have the wrong length. | diff --git a/versioned_docs/version-0.5.x/api/utils/types.md b/versioned_docs/version-0.5.x/api/utils/types.md new file mode 100644 index 000000000..3df506673 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/types.md @@ -0,0 +1,60 @@ +--- +id: types +sidebar_label: types +keywords: + - types + - typing + - aliases + - type hints +--- + +# types + +Defines type aliases used throughout the project to improve readability. + +> **Module:** `aisp.utils.types` +> **Import:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Type of input features: + +- `"binary-features"`: values like 0 or 1. +- `"continuous-features"`: numeric continuous values. +- `"ranged-features"`: values defined by intervals. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Same as ``FeatureType``, plus: + +- `"permutation-features"`: values represented as permutation. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Distance metric used in calculations: + +- `"manhattan"`: the Manhattan distance between two points +- `"minkowski"`: the Minkowski distance between two points. +- `"euclidean"`: the Euclidean distance between two points. + +--- \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/api/utils/validation.md b/versioned_docs/version-0.5.x/api/utils/validation.md new file mode 100644 index 000000000..e224c3461 --- /dev/null +++ b/versioned_docs/version-0.5.x/api/utils/validation.md @@ -0,0 +1,180 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validation +--- + +# module + +Contains functions responsible for validating data types. + +> **Module:** `aisp.utils.validation` +> **Import:** `from aisp.utils import validation` + +## Functions + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detect the type of data in a vector. + +The function detects if the vector contains data of type: + +- Binary features: boolean values or integers restricted to 0 and 1. +- Continuous features: floating-point values in the normalized range [0.0, 1.0]. +- Ranged features: floating-point values outside the normalized range. + +**Parameters** + +| Name | Type | Default | Description | +|----------|---------------|:-------:|------------------------------------------------| +| `vector` | `npt.NDArray` | - | An array containing the data to be classified. | + +**Returns** + +| Type | Description | +|-----------------------------------------|-----------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | The data type of the vector: "binary-features", "continuous-features", or " ranged-features". | + +**Raises** + +| Exception | Description | +|------------------------|------------------------------------------------------------------| +| `UnsupportedTypeError` | If the data type of the vector is not supported by the function. | + +--- + +### check_array_type + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: + ... +``` + +Ensure X is a numpy array. Convert from list if needed. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `name` | `str` | `'X'` | Variable name used in error messages. | + +**Returns** + +| Type | Description | +|---------------|----------------------------------| +| `npt.NDArray` | The converted or validated array | + +**Raises** + +| Exception | Description | +|-------------|--------------------------------| +| `TypeError` | If X is not ndarray or a list. | + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Ensure X and y have compatible first dimensions. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array of target classes of `x` with (`n_samples`). | + +**Raises** + +| Exception | Description | +|-------------|-------------------------------------| +| `TypeError` | If x or y have incompatible shapes. | + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Ensure X has the expected number of features. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Input array for prediction, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `expected` | `int` | - | Expected number of features per sample (columns in X). | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Ensure X contains only 0 and 1. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|--------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | + +**Raises** + +| Exception | Description | +|--------------|--------------------------------------------------| +| `ValueError` | If the array contains values other than 0 and 1. | + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Ensure all values in the x array fall within a range. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|---------------|:-------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | +| `name` | `str` | `'X'` | Name used in the error message. | +| `min_value` | `float` | `0.0` | Minimum allowed value. | +| `max_value` | `float` | `1.0` | Maximum allowed value. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------| +| `ValueError` | If the array fall outside the interval (min_value, max_value). | diff --git a/versioned_docs/version-0.5.x/faq.md b/versioned_docs/version-0.5.x/faq.md index 759ea5ff4..7f392f9cb 100644 --- a/versioned_docs/version-0.5.x/faq.md +++ b/versioned_docs/version-0.5.x/faq.md @@ -1,6 +1,6 @@ --- +id: faq sidebar_position: 6 -title: Frequently Asked Questions sidebar_label: FAQ keywords: - FAQ @@ -9,6 +9,8 @@ keywords: - Help --- +# Frequently Asked Questions + Quick solutions for possible questions about aisp. ## General usage @@ -17,27 +19,30 @@ Quick solutions for possible questions about aisp. It depends on the type of problem: -- **Anomaly detection**: Use ``RNSA`` or ``BNSA``. +- **Anomaly detection**: Use `RNSA` or `BNSA`. - RNSA for problems with continuous data. - BNSA for problems with binary data. -- **Classification**: Use ``AIRS``, ``RNSA``, or ``BNSA``. - - ``RNSA`` and ``BNSA`` were implemented to be applied to multiclass classification. - - ``AIRS`` is more robust to noise in the data. -- **Optimization**: Use ``Clonalg``. +- **Classification**: Use `AIRS`, `RNSA`, or `BNSA`. + - `RNSA` and `BNSA` were implemented to be applied to multiclass classification. + - `AIRS` is more robust to noise in the data. +- **Optimization**: Use `Clonalg`. - The implementation can be applied to objective function optimization (min/max). -- **Clustering**: Use ``AiNet``. +- **Clustering**: Use `AiNet`. - Automatically separates data into groups. - Does not require a predefined number of clusters. --- -### How do I normalize my data to use the ``RNSA`` algorithm? +### How do I normalize my data to use the `RNSA` algorithm? -RNSA works exclusively with data normalized in the range [0, 1]. Therefore, before applying it, the data must be normalized if they are not already in this range. A simple way to do this is by using normalization tools from **scikit-learn**, such as [``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). +RNSA works exclusively with data normalized in the range (0.0, 1.0). Therefore, before applying it, the data must be +normalized if they are not already in this range. A simple way to do this is by using normalization tools from +**scikit-learn**, such as +[``MinMaxScaler``](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html). #### Example -In this example, ``X`` represents the non-normalized input data. +In this example, `X` represents the non-normalized input data. ```python from sklearn.preprocessing import MinMaxScaler @@ -55,7 +60,7 @@ rnsa.fit(x_norm, y) ## Parameter configuration -### How do I choose the number of detectors (``N``) in ``RNSA`` or ``BNSA``? +### How do I choose the number of detectors (`N`) in `RNSA` or `BNSA`? The number of detectors directly affects performance: @@ -69,7 +74,7 @@ The number of detectors directly affects performance: --- -### Which radius (``r`` or ``aff_thresh``) should I use in ``BNSA`` or ``RNSA``? +### Which radius (`r` or `aff_thresh`) should I use in `BNSA` or `RNSA`? The detector radius depends on the data distribution: @@ -78,15 +83,17 @@ The detector radius depends on the data distribution: --- -### What is the ``r_s`` parameter in ``RNSA``? +### What is the `r_s` parameter in `RNSA`? -``r_s`` is the radius of the self sample. It defines a region around each training sample. +`r_s` is the radius of the self sample. It defines a region around each training sample. --- ### Clonalg: How do I define the objective function? -The objective function must follow the pattern of the [base class](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). It must receive a solution as input and return a cost (or affinity) value. +The objective function must follow the pattern of the +[base class](https://github.com/AIS-Package/aisp/blob/main/aisp/base/core/_optimizer.py#L140). +It must receive a solution as input and return a cost (or affinity) value. ```python def affinity_function(self, solution: Any) -> float: @@ -95,12 +102,14 @@ def affinity_function(self, solution: Any) -> float: There are two ways to define the objective function in Clonalg. -1. Defining the function directly in the class constructor - ```python def sphere(solution): - return np.sum(solution *- 2) + return np.sum(solution ** 2) +``` +1. Defining the function directly in the class constructor + +```python clonalg = Clonalg( problem_size=2, affinity_function=sphere @@ -110,9 +119,6 @@ clonalg = Clonalg( 2. Using the function registry ```python -def sphere(solution): - return np.sum(solution *- 2) - clonalg = Clonalg( problem_size=2, ) diff --git a/versioned_docs/version-0.5.x/intro.md b/versioned_docs/version-0.5.x/intro.md index e4bc38d6d..c7d0664ca 100644 --- a/versioned_docs/version-0.5.x/intro.md +++ b/versioned_docs/version-0.5.x/intro.md @@ -52,9 +52,35 @@ AISP provides implementations of bio-inspired algorithms for: - **Optmization**: Find optimal solutions for objective functions. - **Clustering**: Group data without supervision. -### Algorithms implemented +--- + +## Implemented Algorithms + +### [Negative Selection](./aisp-techniques/negative-selection.md) (`aisp.nsa`) + +- [**BNSA**](./api/nsa/bnsa.md) - Binary Negative Selection Algorithm +- [**RNSA**](./api/nsa/rnsa.md) - Real-Valued Negative Selection Algorithm + +### [Clonal Selection](./aisp-techniques/clonal-selection-algorithms.md) (`aisp.csa`) + +- [**AIRS**](./api/csa/airs.md) - Artificial Immune Recognition System +- [**CLONALG**](./api/csa/clonalg.md) - Clonal Selection Algorithm + +### [Immune Network Theory](./aisp-techniques/immune-network-theory.md) (`aisp.ina`) + +- [**AiNet**](./api/ina/ai-net.md) - Artificial Immune Network for clustering and data compression + +### Module in Development + +#### Danger Theory (`aisp.dta`) + +- **DCA** - Dendritic Cell Algorithm *(planned)* + +## API overview + +All algorithms follow a simple and consistent interface: -> - [x] [**Negative Selection.**](./aisp-techniques/negative-selection/) -> - [x] [**Clonal Selection Algorithms.**](./aisp-techniques/clonal-selection-algorithms/) -> - [x] [**Immune Network Theory.**](./aisp-techniques/immune-network-theory/) -> - [ ] *Danger Theory* +- `fit(X, y, verbose: bool = True)`: trains the model for classification tasks. +- `fit(X, verbose: bool = True)`: trains the model for clustering tasks. +- `predict(X)`: makes predictions based on new data. +- `optimize(max_iters: int =..., n_iter_no_change: int =..., verbose: bool = True)`: run the optimization algorithms diff --git a/versioned_sidebars/version-0.5.x-sidebars.json b/versioned_sidebars/version-0.5.x-sidebars.json index 1fd014a28..ff4d9d6ba 100644 --- a/versioned_sidebars/version-0.5.x-sidebars.json +++ b/versioned_sidebars/version-0.5.x-sidebars.json @@ -4,5 +4,11 @@ "type": "autogenerated", "dirName": "." } + ], + "api": [ + { + "type": "autogenerated", + "dirName": "api" + } ] } From 0018625db14c7f2e9697775f24b6ac6ff20e7eb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 25 Apr 2026 18:34:00 -0300 Subject: [PATCH 2/3] fix: corrige links que geravam avisos durante o build --- .../current/api/csa/airs.md | 2 +- .../current/api/csa/clonalg.md | 2 +- .../current/api/ina/ai-net.md | 2 +- .../current/api/nsa/bnsa.md | 2 +- .../current/api/nsa/rnsa.md | 2 +- .../advanced-guides/Base module/Classifier.md | 8 ++++---- .../advanced-guides/Base module/Classifier.md | 8 ++++---- .../advanced-guides/base-module/Classifier.md | 12 ++++++------ .../advanced-guides/base-module/Clusterer.md | 4 ++-- .../advanced-guides/base-module/Classifier.md | 12 ++++++------ .../advanced-guides/base-module/Clusterer.md | 4 ++-- .../version-0.5.x/api/csa/airs.md | 2 +- .../version-0.5.x/api/csa/clonalg.md | 2 +- .../version-0.5.x/api/ina/ai-net.md | 2 +- .../version-0.5.x/api/nsa/bnsa.md | 2 +- .../version-0.5.x/api/nsa/rnsa.md | 2 +- .../advanced-guides/Base module/Classifier.md | 8 ++++---- .../advanced-guides/Base module/Classifier.md | 8 ++++---- .../advanced-guides/base-module/Classifier.md | 12 ++++++------ .../advanced-guides/base-module/Clusterer.md | 4 ++-- .../advanced-guides/base-module/Classifier.md | 12 ++++++------ .../advanced-guides/base-module/Clusterer.md | 4 ++-- .../advanced-guides/base-module/Optimizer.md | 2 +- 23 files changed, 59 insertions(+), 59 deletions(-) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md index c0cd9b693..849c86cc5 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/airs.md @@ -183,7 +183,7 @@ próximos (K-NN). Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunologico-artificial-de-reconhecimento) +- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunológico-artificial-de-reconhecimento) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md index 32114aac5..9fd9e7135 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/csa/clonalg.md @@ -174,7 +174,7 @@ Avalia a afinidade de uma solução candidata. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-selecao-clonal) +- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-seleção-clonal) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md index cd89715ec..9215808c1 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/ina/ai-net.md @@ -208,7 +208,7 @@ dos pesos das arestas são removidas. Cada grafo conectado após essa poda é tr Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunologica-artificial) +- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunológica-artificial) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md index 81f2ffed8..ff28ea7d5 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/bnsa.md @@ -180,7 +180,7 @@ Prever as classes com base nos detectores gerados após o treinamento. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-selecao-negativa-binaria) +- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-seleção-negativa-binária) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md index 2fee71a00..7eb0d86f1 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/nsa/rnsa.md @@ -208,7 +208,7 @@ Prever as classes com base nos detectores gerados após o treinamento. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-selecao-negativa-de-valores-reais) +- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-seleção-negativa-de-valores-reais) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Base module/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Base module/Classifier.md index 859b9c2d4..cdad0d98e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Base module/Classifier.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Base module/Classifier.md @@ -24,8 +24,8 @@ Ajusta o modelo aos dados de treinamento. Implementação: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Função-fit) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Função-fit) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#função-fit) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#função-fit) ### def predict(...) @@ -37,8 +37,8 @@ Realiza a previsão dos rótulos para os dados fornecidos. Implementação: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Função-predict) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Função-predict) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#função-predict) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#função-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Base module/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Base module/Classifier.md index 859b9c2d4..cdad0d98e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Base module/Classifier.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Base module/Classifier.md @@ -24,8 +24,8 @@ Ajusta o modelo aos dados de treinamento. Implementação: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Função-fit) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Função-fit) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#função-fit) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#função-fit) ### def predict(...) @@ -37,8 +37,8 @@ Realiza a previsão dos rótulos para os dados fornecidos. Implementação: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Função-predict) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Função-predict) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#função-predict) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#função-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Classifier.md index eef99a116..c1739799e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Classifier.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Classifier.md @@ -24,9 +24,9 @@ Ajusta o modelo aos dados de treinamento. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#função-fit) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#função-fit) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#método-fit) ### def predict(...) @@ -38,9 +38,9 @@ Realiza a previsão dos rótulos para os dados fornecidos. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#função-predict) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#função-predict) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#método-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Clusterer.md index ced74add2..4ecc96752 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Clusterer.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/base-module/Clusterer.md @@ -48,7 +48,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#função-fit) --- @@ -71,7 +71,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#função-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Classifier.md index eef99a116..c1739799e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Classifier.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Classifier.md @@ -24,9 +24,9 @@ Ajusta o modelo aos dados de treinamento. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#função-fit) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#função-fit) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#método-fit) ### def predict(...) @@ -38,9 +38,9 @@ Realiza a previsão dos rótulos para os dados fornecidos. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#função-predict) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#função-predict) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#método-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Clusterer.md index ced74add2..4ecc96752 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Clusterer.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/base-module/Clusterer.md @@ -48,7 +48,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#função-fit) --- @@ -71,7 +71,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#função-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md index c0cd9b693..849c86cc5 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/airs.md @@ -183,7 +183,7 @@ próximos (K-NN). Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunologico-artificial-de-reconhecimento) +- [**Exemplos**](../../examples/Classification/csa.md#airs-sistema-imunológico-artificial-de-reconhecimento) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md index 32114aac5..9fd9e7135 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/csa/clonalg.md @@ -174,7 +174,7 @@ Avalia a afinidade de uma solução candidata. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-selecao-clonal) +- [**Exemplos**](../../examples/Optimization/csa.md#clonalg-algoritmo-de-seleção-clonal) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md index cd89715ec..9215808c1 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/ina/ai-net.md @@ -208,7 +208,7 @@ dos pesos das arestas são removidas. Cada grafo conectado após essa poda é tr Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunologica-artificial) +- [**Exemplos**](../../examples/Clustering/ina.md#ainet-rede-imunológica-artificial) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md index 81f2ffed8..ff28ea7d5 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/bnsa.md @@ -180,7 +180,7 @@ Prever as classes com base nos detectores gerados após o treinamento. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-selecao-negativa-binaria) +- [**Exemplos**](../../examples/Classification/nsa.md#bnsa-algoritmo-de-seleção-negativa-binária) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md index 2fee71a00..7eb0d86f1 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/nsa/rnsa.md @@ -208,7 +208,7 @@ Prever as classes com base nos detectores gerados após o treinamento. Exemplos completos de uso estão disponíveis nos notebooks Jupyter: -- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-selecao-negativa-de-valores-reais) +- [**Exemplos**](../../examples/Classification/nsa.md#rnsa-algoritmo-de-seleção-negativa-de-valores-reais) --- diff --git a/versioned_docs/version-0.1.x/advanced-guides/Base module/Classifier.md b/versioned_docs/version-0.1.x/advanced-guides/Base module/Classifier.md index 412208ef4..9b8529344 100644 --- a/versioned_docs/version-0.1.x/advanced-guides/Base module/Classifier.md +++ b/versioned_docs/version-0.1.x/advanced-guides/Base module/Classifier.md @@ -23,8 +23,8 @@ Fit the model to the training data. Implementation: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Function-fit) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Function-fit) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#function-fit) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#function-fit) ### def predict(...) @@ -36,8 +36,8 @@ Performs label prediction for the given data. Implementation: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Function-predict) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Function-predict) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#function-predict) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#function-predict) --- diff --git a/versioned_docs/version-0.2.x/advanced-guides/Base module/Classifier.md b/versioned_docs/version-0.2.x/advanced-guides/Base module/Classifier.md index 412208ef4..9b8529344 100644 --- a/versioned_docs/version-0.2.x/advanced-guides/Base module/Classifier.md +++ b/versioned_docs/version-0.2.x/advanced-guides/Base module/Classifier.md @@ -23,8 +23,8 @@ Fit the model to the training data. Implementation: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Function-fit) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Function-fit) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#function-fit) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#function-fit) ### def predict(...) @@ -36,8 +36,8 @@ Performs label prediction for the given data. Implementation: -- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#Function-predict) -- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#Function-predict) +- [RNSA](../../aisp-techniques/Negative%20Selection/RNSA.md#function-predict) +- [BNSA](../../aisp-techniques/Negative%20Selection/BNSA.md#function-predict) --- diff --git a/versioned_docs/version-0.3.x/advanced-guides/base-module/Classifier.md b/versioned_docs/version-0.3.x/advanced-guides/base-module/Classifier.md index 697cd21bc..0c5497fca 100644 --- a/versioned_docs/version-0.3.x/advanced-guides/base-module/Classifier.md +++ b/versioned_docs/version-0.3.x/advanced-guides/base-module/Classifier.md @@ -37,9 +37,9 @@ Fit the model to the training data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#function-fit) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#function-fit) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#function-fit) ### def predict(...) @@ -51,9 +51,9 @@ Performs label prediction for the given data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#function-predict) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#function-predict) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#function-predict) --- diff --git a/versioned_docs/version-0.3.x/advanced-guides/base-module/Clusterer.md b/versioned_docs/version-0.3.x/advanced-guides/base-module/Clusterer.md index 565b9c964..a6ca71db2 100644 --- a/versioned_docs/version-0.3.x/advanced-guides/base-module/Clusterer.md +++ b/versioned_docs/version-0.3.x/advanced-guides/base-module/Clusterer.md @@ -52,7 +52,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#function-fit) --- @@ -77,7 +77,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#function-predict) --- diff --git a/versioned_docs/version-0.4.x/advanced-guides/base-module/Classifier.md b/versioned_docs/version-0.4.x/advanced-guides/base-module/Classifier.md index 697cd21bc..0c5497fca 100644 --- a/versioned_docs/version-0.4.x/advanced-guides/base-module/Classifier.md +++ b/versioned_docs/version-0.4.x/advanced-guides/base-module/Classifier.md @@ -37,9 +37,9 @@ Fit the model to the training data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#function-fit) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#function-fit) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#function-fit) ### def predict(...) @@ -51,9 +51,9 @@ Performs label prediction for the given data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) +- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#function-predict) +- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#function-predict) +- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#function-predict) --- diff --git a/versioned_docs/version-0.4.x/advanced-guides/base-module/Clusterer.md b/versioned_docs/version-0.4.x/advanced-guides/base-module/Clusterer.md index 565b9c964..a6ca71db2 100644 --- a/versioned_docs/version-0.4.x/advanced-guides/base-module/Clusterer.md +++ b/versioned_docs/version-0.4.x/advanced-guides/base-module/Clusterer.md @@ -52,7 +52,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#function-fit) --- @@ -77,7 +77,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) +* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#function-predict) --- diff --git a/versioned_docs/version-0.4.x/advanced-guides/base-module/Optimizer.md b/versioned_docs/version-0.4.x/advanced-guides/base-module/Optimizer.md index 3e0d99cfc..78655cfcd 100644 --- a/versioned_docs/version-0.4.x/advanced-guides/base-module/Optimizer.md +++ b/versioned_docs/version-0.4.x/advanced-guides/base-module/Optimizer.md @@ -152,7 +152,7 @@ Execute the optimization process. This method must be implemented by the subclas **Implementation**: -* [Clonalg](../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) +* [Clonalg](../../aisp-techniques/clonal-selection-algorithms/clonalg.md#function-optimize) --- From 7004413a3aa048ef9169fcde8b008728add2bea0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo?= <88985821+Joao-Paulo-Silva@users.noreply.github.com> Date: Sat, 25 Apr 2026 23:21:37 -0300 Subject: [PATCH 3/3] fix: corrige o idioma dos arquivos Markdown --- docs/aisp-techniques/negative-selection.md | 4 ++-- .../docusaurus-plugin-content-docs/current/api/README.md | 3 +++ .../version-0.5.x/api/README.md | 3 +++ .../version-0.5.x/aisp-techniques/negative-selection.md | 4 ++-- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/aisp-techniques/negative-selection.md b/docs/aisp-techniques/negative-selection.md index 29a68b9b0..54026fb35 100644 --- a/docs/aisp-techniques/negative-selection.md +++ b/docs/aisp-techniques/negative-selection.md @@ -10,9 +10,9 @@ keywords: - natural computing --- -# Seleção Negativa +# Negative Selection -Os algoritmos de **seleção negativa** is the process in which the immune system maturates T-cells, also known as +**Negative Selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [^1] diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md index e86d07419..21dac1e1c 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/api/README.md @@ -9,6 +9,9 @@ keywords: - classification - optimization - clustering + - classificação + - otimização + - clusterização --- # AISP - API diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md index e86d07419..21dac1e1c 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/api/README.md @@ -9,6 +9,9 @@ keywords: - classification - optimization - clustering + - classificação + - otimização + - clusterização --- # AISP - API diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md index 29a68b9b0..437667e96 100644 --- a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md +++ b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection.md @@ -10,9 +10,9 @@ keywords: - natural computing --- -# Seleção Negativa +# Negative Selection -Os algoritmos de **seleção negativa** is the process in which the immune system maturates T-cells, also known as +**Negative Selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [^1]