crca 1.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- .github/ISSUE_TEMPLATE/bug_report.md +65 -0
- .github/ISSUE_TEMPLATE/feature_request.md +41 -0
- .github/PULL_REQUEST_TEMPLATE.md +20 -0
- .github/workflows/publish-manual.yml +61 -0
- .github/workflows/publish.yml +64 -0
- .gitignore +214 -0
- CRCA.py +4156 -0
- LICENSE +201 -0
- MANIFEST.in +43 -0
- PKG-INFO +5035 -0
- README.md +4959 -0
- __init__.py +17 -0
- branches/CRCA-Q.py +2728 -0
- branches/crca_cg/corposwarm.py +9065 -0
- branches/crca_cg/fix_rancher_docker_creds.ps1 +155 -0
- branches/crca_cg/package.json +5 -0
- branches/crca_cg/test_bolt_integration.py +446 -0
- branches/crca_cg/test_corposwarm_comprehensive.py +773 -0
- branches/crca_cg/test_new_features.py +163 -0
- branches/crca_sd/__init__.py +149 -0
- branches/crca_sd/crca_sd_core.py +770 -0
- branches/crca_sd/crca_sd_governance.py +1325 -0
- branches/crca_sd/crca_sd_mpc.py +1130 -0
- branches/crca_sd/crca_sd_realtime.py +1844 -0
- branches/crca_sd/crca_sd_tui.py +1133 -0
- crca-1.4.0.dist-info/METADATA +5035 -0
- crca-1.4.0.dist-info/RECORD +501 -0
- crca-1.4.0.dist-info/WHEEL +4 -0
- crca-1.4.0.dist-info/licenses/LICENSE +201 -0
- docs/CRCA-Q.md +2333 -0
- examples/config.yaml.example +25 -0
- examples/crca_sd_example.py +513 -0
- examples/data_broker_example.py +294 -0
- examples/logistics_corporation.py +861 -0
- examples/palantir_example.py +299 -0
- examples/policy_bench.py +934 -0
- examples/pridnestrovia-sd.py +705 -0
- examples/pridnestrovia_realtime.py +1902 -0
- prompts/__init__.py +10 -0
- prompts/default_crca.py +101 -0
- pyproject.toml +151 -0
- requirements.txt +76 -0
- schemas/__init__.py +43 -0
- schemas/mcpSchemas.py +51 -0
- schemas/policy.py +458 -0
- templates/__init__.py +38 -0
- templates/base_specialized_agent.py +195 -0
- templates/drift_detection.py +325 -0
- templates/examples/causal_agent_template.py +309 -0
- templates/examples/drag_drop_example.py +213 -0
- templates/examples/logistics_agent_template.py +207 -0
- templates/examples/trading_agent_template.py +206 -0
- templates/feature_mixins.py +253 -0
- templates/graph_management.py +442 -0
- templates/llm_integration.py +194 -0
- templates/module_registry.py +276 -0
- templates/mpc_planner.py +280 -0
- templates/policy_loop.py +1168 -0
- templates/prediction_framework.py +448 -0
- templates/statistical_methods.py +778 -0
- tests/sanity.yml +31 -0
- tests/sanity_check +406 -0
- tests/test_core.py +47 -0
- tests/test_crca_excel.py +166 -0
- tests/test_crca_sd.py +780 -0
- tests/test_data_broker.py +424 -0
- tests/test_palantir.py +349 -0
- tools/__init__.py +38 -0
- tools/actuators.py +437 -0
- tools/bolt.diy/Dockerfile +103 -0
- tools/bolt.diy/app/components/@settings/core/AvatarDropdown.tsx +175 -0
- tools/bolt.diy/app/components/@settings/core/ControlPanel.tsx +345 -0
- tools/bolt.diy/app/components/@settings/core/constants.tsx +108 -0
- tools/bolt.diy/app/components/@settings/core/types.ts +114 -0
- tools/bolt.diy/app/components/@settings/index.ts +12 -0
- tools/bolt.diy/app/components/@settings/shared/components/TabTile.tsx +151 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionForm.tsx +193 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ConnectionTestIndicator.tsx +60 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ErrorState.tsx +102 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/LoadingState.tsx +94 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/ServiceHeader.tsx +72 -0
- tools/bolt.diy/app/components/@settings/shared/service-integration/index.ts +6 -0
- tools/bolt.diy/app/components/@settings/tabs/data/DataTab.tsx +721 -0
- tools/bolt.diy/app/components/@settings/tabs/data/DataVisualization.tsx +384 -0
- tools/bolt.diy/app/components/@settings/tabs/event-logs/EventLogsTab.tsx +1013 -0
- tools/bolt.diy/app/components/@settings/tabs/features/FeaturesTab.tsx +295 -0
- tools/bolt.diy/app/components/@settings/tabs/github/GitHubTab.tsx +281 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubAuthDialog.tsx +173 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubCacheManager.tsx +367 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubConnection.tsx +233 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubErrorBoundary.tsx +105 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubProgressiveLoader.tsx +266 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositoryCard.tsx +121 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubRepositorySelector.tsx +312 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubStats.tsx +291 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/GitHubUserProfile.tsx +46 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/GitHubStateIndicators.tsx +264 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/RepositoryCard.tsx +361 -0
- tools/bolt.diy/app/components/@settings/tabs/github/components/shared/index.ts +11 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/GitLabTab.tsx +305 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabAuthDialog.tsx +186 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabConnection.tsx +253 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/GitLabRepositorySelector.tsx +358 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryCard.tsx +79 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/RepositoryList.tsx +142 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/StatsDisplay.tsx +91 -0
- tools/bolt.diy/app/components/@settings/tabs/gitlab/components/index.ts +4 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerList.tsx +99 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpServerListItem.tsx +70 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpStatusBadge.tsx +37 -0
- tools/bolt.diy/app/components/@settings/tabs/mcp/McpTab.tsx +239 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/NetlifyTab.tsx +1393 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/components/NetlifyConnection.tsx +990 -0
- tools/bolt.diy/app/components/@settings/tabs/netlify/components/index.ts +1 -0
- tools/bolt.diy/app/components/@settings/tabs/notifications/NotificationsTab.tsx +300 -0
- tools/bolt.diy/app/components/@settings/tabs/profile/ProfileTab.tsx +181 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/cloud/CloudProvidersTab.tsx +308 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ErrorBoundary.tsx +68 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/HealthStatusBadge.tsx +64 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/LoadingSkeleton.tsx +107 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/LocalProvidersTab.tsx +556 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ModelCard.tsx +106 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/ProviderCard.tsx +120 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/SetupGuide.tsx +671 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/StatusDashboard.tsx +91 -0
- tools/bolt.diy/app/components/@settings/tabs/providers/local/types.ts +44 -0
- tools/bolt.diy/app/components/@settings/tabs/settings/SettingsTab.tsx +215 -0
- tools/bolt.diy/app/components/@settings/tabs/supabase/SupabaseTab.tsx +1089 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/VercelTab.tsx +909 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/components/VercelConnection.tsx +368 -0
- tools/bolt.diy/app/components/@settings/tabs/vercel/components/index.ts +1 -0
- tools/bolt.diy/app/components/@settings/utils/tab-helpers.ts +54 -0
- tools/bolt.diy/app/components/chat/APIKeyManager.tsx +169 -0
- tools/bolt.diy/app/components/chat/Artifact.tsx +296 -0
- tools/bolt.diy/app/components/chat/AssistantMessage.tsx +192 -0
- tools/bolt.diy/app/components/chat/BaseChat.module.scss +47 -0
- tools/bolt.diy/app/components/chat/BaseChat.tsx +522 -0
- tools/bolt.diy/app/components/chat/Chat.client.tsx +670 -0
- tools/bolt.diy/app/components/chat/ChatAlert.tsx +108 -0
- tools/bolt.diy/app/components/chat/ChatBox.tsx +334 -0
- tools/bolt.diy/app/components/chat/CodeBlock.module.scss +10 -0
- tools/bolt.diy/app/components/chat/CodeBlock.tsx +85 -0
- tools/bolt.diy/app/components/chat/DicussMode.tsx +17 -0
- tools/bolt.diy/app/components/chat/ExamplePrompts.tsx +37 -0
- tools/bolt.diy/app/components/chat/FilePreview.tsx +38 -0
- tools/bolt.diy/app/components/chat/GitCloneButton.tsx +327 -0
- tools/bolt.diy/app/components/chat/ImportFolderButton.tsx +141 -0
- tools/bolt.diy/app/components/chat/LLMApiAlert.tsx +109 -0
- tools/bolt.diy/app/components/chat/MCPTools.tsx +129 -0
- tools/bolt.diy/app/components/chat/Markdown.module.scss +171 -0
- tools/bolt.diy/app/components/chat/Markdown.spec.ts +48 -0
- tools/bolt.diy/app/components/chat/Markdown.tsx +252 -0
- tools/bolt.diy/app/components/chat/Messages.client.tsx +102 -0
- tools/bolt.diy/app/components/chat/ModelSelector.tsx +797 -0
- tools/bolt.diy/app/components/chat/NetlifyDeploymentLink.client.tsx +51 -0
- tools/bolt.diy/app/components/chat/ProgressCompilation.tsx +110 -0
- tools/bolt.diy/app/components/chat/ScreenshotStateManager.tsx +33 -0
- tools/bolt.diy/app/components/chat/SendButton.client.tsx +39 -0
- tools/bolt.diy/app/components/chat/SpeechRecognition.tsx +28 -0
- tools/bolt.diy/app/components/chat/StarterTemplates.tsx +38 -0
- tools/bolt.diy/app/components/chat/SupabaseAlert.tsx +199 -0
- tools/bolt.diy/app/components/chat/SupabaseConnection.tsx +339 -0
- tools/bolt.diy/app/components/chat/ThoughtBox.tsx +43 -0
- tools/bolt.diy/app/components/chat/ToolInvocations.tsx +409 -0
- tools/bolt.diy/app/components/chat/UserMessage.tsx +101 -0
- tools/bolt.diy/app/components/chat/VercelDeploymentLink.client.tsx +158 -0
- tools/bolt.diy/app/components/chat/chatExportAndImport/ExportChatButton.tsx +49 -0
- tools/bolt.diy/app/components/chat/chatExportAndImport/ImportButtons.tsx +96 -0
- tools/bolt.diy/app/components/deploy/DeployAlert.tsx +197 -0
- tools/bolt.diy/app/components/deploy/DeployButton.tsx +277 -0
- tools/bolt.diy/app/components/deploy/GitHubDeploy.client.tsx +171 -0
- tools/bolt.diy/app/components/deploy/GitHubDeploymentDialog.tsx +1041 -0
- tools/bolt.diy/app/components/deploy/GitLabDeploy.client.tsx +171 -0
- tools/bolt.diy/app/components/deploy/GitLabDeploymentDialog.tsx +764 -0
- tools/bolt.diy/app/components/deploy/NetlifyDeploy.client.tsx +246 -0
- tools/bolt.diy/app/components/deploy/VercelDeploy.client.tsx +235 -0
- tools/bolt.diy/app/components/editor/codemirror/BinaryContent.tsx +7 -0
- tools/bolt.diy/app/components/editor/codemirror/CodeMirrorEditor.tsx +555 -0
- tools/bolt.diy/app/components/editor/codemirror/EnvMasking.ts +80 -0
- tools/bolt.diy/app/components/editor/codemirror/cm-theme.ts +192 -0
- tools/bolt.diy/app/components/editor/codemirror/indent.ts +68 -0
- tools/bolt.diy/app/components/editor/codemirror/languages.ts +112 -0
- tools/bolt.diy/app/components/git/GitUrlImport.client.tsx +147 -0
- tools/bolt.diy/app/components/header/Header.tsx +42 -0
- tools/bolt.diy/app/components/header/HeaderActionButtons.client.tsx +54 -0
- tools/bolt.diy/app/components/mandate/MandateSubmission.tsx +167 -0
- tools/bolt.diy/app/components/observability/DeploymentStatus.tsx +168 -0
- tools/bolt.diy/app/components/observability/EventTimeline.tsx +119 -0
- tools/bolt.diy/app/components/observability/FileDiffViewer.tsx +121 -0
- tools/bolt.diy/app/components/observability/GovernanceStatus.tsx +197 -0
- tools/bolt.diy/app/components/observability/GovernorMetrics.tsx +246 -0
- tools/bolt.diy/app/components/observability/LogStream.tsx +244 -0
- tools/bolt.diy/app/components/observability/MandateDetails.tsx +201 -0
- tools/bolt.diy/app/components/observability/ObservabilityDashboard.tsx +200 -0
- tools/bolt.diy/app/components/sidebar/HistoryItem.tsx +187 -0
- tools/bolt.diy/app/components/sidebar/Menu.client.tsx +536 -0
- tools/bolt.diy/app/components/sidebar/date-binning.ts +59 -0
- tools/bolt.diy/app/components/txt +1 -0
- tools/bolt.diy/app/components/ui/BackgroundRays/index.tsx +18 -0
- tools/bolt.diy/app/components/ui/BackgroundRays/styles.module.scss +246 -0
- tools/bolt.diy/app/components/ui/Badge.tsx +53 -0
- tools/bolt.diy/app/components/ui/BranchSelector.tsx +270 -0
- tools/bolt.diy/app/components/ui/Breadcrumbs.tsx +101 -0
- tools/bolt.diy/app/components/ui/Button.tsx +46 -0
- tools/bolt.diy/app/components/ui/Card.tsx +55 -0
- tools/bolt.diy/app/components/ui/Checkbox.tsx +32 -0
- tools/bolt.diy/app/components/ui/CloseButton.tsx +49 -0
- tools/bolt.diy/app/components/ui/CodeBlock.tsx +103 -0
- tools/bolt.diy/app/components/ui/Collapsible.tsx +9 -0
- tools/bolt.diy/app/components/ui/ColorSchemeDialog.tsx +378 -0
- tools/bolt.diy/app/components/ui/Dialog.tsx +449 -0
- tools/bolt.diy/app/components/ui/Dropdown.tsx +63 -0
- tools/bolt.diy/app/components/ui/EmptyState.tsx +154 -0
- tools/bolt.diy/app/components/ui/FileIcon.tsx +346 -0
- tools/bolt.diy/app/components/ui/FilterChip.tsx +92 -0
- tools/bolt.diy/app/components/ui/GlowingEffect.tsx +192 -0
- tools/bolt.diy/app/components/ui/GradientCard.tsx +100 -0
- tools/bolt.diy/app/components/ui/IconButton.tsx +84 -0
- tools/bolt.diy/app/components/ui/Input.tsx +22 -0
- tools/bolt.diy/app/components/ui/Label.tsx +20 -0
- tools/bolt.diy/app/components/ui/LoadingDots.tsx +27 -0
- tools/bolt.diy/app/components/ui/LoadingOverlay.tsx +32 -0
- tools/bolt.diy/app/components/ui/PanelHeader.tsx +20 -0
- tools/bolt.diy/app/components/ui/PanelHeaderButton.tsx +36 -0
- tools/bolt.diy/app/components/ui/Popover.tsx +29 -0
- tools/bolt.diy/app/components/ui/Progress.tsx +22 -0
- tools/bolt.diy/app/components/ui/RepositoryStats.tsx +87 -0
- tools/bolt.diy/app/components/ui/ScrollArea.tsx +41 -0
- tools/bolt.diy/app/components/ui/SearchInput.tsx +80 -0
- tools/bolt.diy/app/components/ui/SearchResultItem.tsx +134 -0
- tools/bolt.diy/app/components/ui/Separator.tsx +22 -0
- tools/bolt.diy/app/components/ui/SettingsButton.tsx +35 -0
- tools/bolt.diy/app/components/ui/Slider.tsx +73 -0
- tools/bolt.diy/app/components/ui/StatusIndicator.tsx +90 -0
- tools/bolt.diy/app/components/ui/Switch.tsx +37 -0
- tools/bolt.diy/app/components/ui/Tabs.tsx +52 -0
- tools/bolt.diy/app/components/ui/TabsWithSlider.tsx +112 -0
- tools/bolt.diy/app/components/ui/ThemeSwitch.tsx +29 -0
- tools/bolt.diy/app/components/ui/Tooltip.tsx +122 -0
- tools/bolt.diy/app/components/ui/index.ts +38 -0
- tools/bolt.diy/app/components/ui/use-toast.ts +66 -0
- tools/bolt.diy/app/components/workbench/DiffView.tsx +796 -0
- tools/bolt.diy/app/components/workbench/EditorPanel.tsx +174 -0
- tools/bolt.diy/app/components/workbench/ExpoQrModal.tsx +55 -0
- tools/bolt.diy/app/components/workbench/FileBreadcrumb.tsx +150 -0
- tools/bolt.diy/app/components/workbench/FileTree.tsx +565 -0
- tools/bolt.diy/app/components/workbench/Inspector.tsx +126 -0
- tools/bolt.diy/app/components/workbench/InspectorPanel.tsx +146 -0
- tools/bolt.diy/app/components/workbench/LockManager.tsx +262 -0
- tools/bolt.diy/app/components/workbench/PortDropdown.tsx +91 -0
- tools/bolt.diy/app/components/workbench/Preview.tsx +1049 -0
- tools/bolt.diy/app/components/workbench/ScreenshotSelector.tsx +293 -0
- tools/bolt.diy/app/components/workbench/Search.tsx +257 -0
- tools/bolt.diy/app/components/workbench/Workbench.client.tsx +506 -0
- tools/bolt.diy/app/components/workbench/terminal/Terminal.tsx +131 -0
- tools/bolt.diy/app/components/workbench/terminal/TerminalManager.tsx +68 -0
- tools/bolt.diy/app/components/workbench/terminal/TerminalTabs.tsx +277 -0
- tools/bolt.diy/app/components/workbench/terminal/theme.ts +36 -0
- tools/bolt.diy/app/components/workflow/WorkflowPhase.tsx +109 -0
- tools/bolt.diy/app/components/workflow/WorkflowStatus.tsx +60 -0
- tools/bolt.diy/app/components/workflow/WorkflowTimeline.tsx +150 -0
- tools/bolt.diy/app/entry.client.tsx +7 -0
- tools/bolt.diy/app/entry.server.tsx +80 -0
- tools/bolt.diy/app/root.tsx +156 -0
- tools/bolt.diy/app/routes/_index.tsx +175 -0
- tools/bolt.diy/app/routes/api.bug-report.ts +254 -0
- tools/bolt.diy/app/routes/api.chat.ts +463 -0
- tools/bolt.diy/app/routes/api.check-env-key.ts +41 -0
- tools/bolt.diy/app/routes/api.configured-providers.ts +110 -0
- tools/bolt.diy/app/routes/api.corporate-swarm-status.ts +55 -0
- tools/bolt.diy/app/routes/api.enhancer.ts +137 -0
- tools/bolt.diy/app/routes/api.export-api-keys.ts +44 -0
- tools/bolt.diy/app/routes/api.git-info.ts +69 -0
- tools/bolt.diy/app/routes/api.git-proxy.$.ts +178 -0
- tools/bolt.diy/app/routes/api.github-branches.ts +166 -0
- tools/bolt.diy/app/routes/api.github-deploy.ts +67 -0
- tools/bolt.diy/app/routes/api.github-stats.ts +198 -0
- tools/bolt.diy/app/routes/api.github-template.ts +242 -0
- tools/bolt.diy/app/routes/api.github-user.ts +287 -0
- tools/bolt.diy/app/routes/api.gitlab-branches.ts +143 -0
- tools/bolt.diy/app/routes/api.gitlab-deploy.ts +67 -0
- tools/bolt.diy/app/routes/api.gitlab-projects.ts +105 -0
- tools/bolt.diy/app/routes/api.health.ts +8 -0
- tools/bolt.diy/app/routes/api.llmcall.ts +298 -0
- tools/bolt.diy/app/routes/api.mandate.ts +351 -0
- tools/bolt.diy/app/routes/api.mcp-check.ts +16 -0
- tools/bolt.diy/app/routes/api.mcp-update-config.ts +23 -0
- tools/bolt.diy/app/routes/api.models.$provider.ts +2 -0
- tools/bolt.diy/app/routes/api.models.ts +90 -0
- tools/bolt.diy/app/routes/api.netlify-deploy.ts +240 -0
- tools/bolt.diy/app/routes/api.netlify-user.ts +142 -0
- tools/bolt.diy/app/routes/api.supabase-user.ts +199 -0
- tools/bolt.diy/app/routes/api.supabase.query.ts +92 -0
- tools/bolt.diy/app/routes/api.supabase.ts +56 -0
- tools/bolt.diy/app/routes/api.supabase.variables.ts +32 -0
- tools/bolt.diy/app/routes/api.system.diagnostics.ts +142 -0
- tools/bolt.diy/app/routes/api.system.disk-info.ts +311 -0
- tools/bolt.diy/app/routes/api.system.git-info.ts +332 -0
- tools/bolt.diy/app/routes/api.update.ts +21 -0
- tools/bolt.diy/app/routes/api.vercel-deploy.ts +497 -0
- tools/bolt.diy/app/routes/api.vercel-user.ts +161 -0
- tools/bolt.diy/app/routes/api.workflow-status.$proposalId.ts +309 -0
- tools/bolt.diy/app/routes/chat.$id.tsx +8 -0
- tools/bolt.diy/app/routes/execute.$mandateId.tsx +432 -0
- tools/bolt.diy/app/routes/git.tsx +25 -0
- tools/bolt.diy/app/routes/observability.$mandateId.tsx +50 -0
- tools/bolt.diy/app/routes/webcontainer.connect.$id.tsx +32 -0
- tools/bolt.diy/app/routes/webcontainer.preview.$id.tsx +97 -0
- tools/bolt.diy/app/routes/workflow.$proposalId.tsx +170 -0
- tools/bolt.diy/app/styles/animations.scss +49 -0
- tools/bolt.diy/app/styles/components/code.scss +9 -0
- tools/bolt.diy/app/styles/components/editor.scss +135 -0
- tools/bolt.diy/app/styles/components/resize-handle.scss +30 -0
- tools/bolt.diy/app/styles/components/terminal.scss +3 -0
- tools/bolt.diy/app/styles/components/toast.scss +23 -0
- tools/bolt.diy/app/styles/diff-view.css +72 -0
- tools/bolt.diy/app/styles/index.scss +73 -0
- tools/bolt.diy/app/styles/variables.scss +255 -0
- tools/bolt.diy/app/styles/z-index.scss +37 -0
- tools/bolt.diy/app/types/GitHub.ts +182 -0
- tools/bolt.diy/app/types/GitLab.ts +103 -0
- tools/bolt.diy/app/types/actions.ts +85 -0
- tools/bolt.diy/app/types/artifact.ts +5 -0
- tools/bolt.diy/app/types/context.ts +26 -0
- tools/bolt.diy/app/types/design-scheme.ts +93 -0
- tools/bolt.diy/app/types/global.d.ts +13 -0
- tools/bolt.diy/app/types/mandate.ts +333 -0
- tools/bolt.diy/app/types/model.ts +25 -0
- tools/bolt.diy/app/types/netlify.ts +94 -0
- tools/bolt.diy/app/types/supabase.ts +54 -0
- tools/bolt.diy/app/types/template.ts +8 -0
- tools/bolt.diy/app/types/terminal.ts +9 -0
- tools/bolt.diy/app/types/theme.ts +1 -0
- tools/bolt.diy/app/types/vercel.ts +67 -0
- tools/bolt.diy/app/utils/buffer.ts +29 -0
- tools/bolt.diy/app/utils/classNames.ts +65 -0
- tools/bolt.diy/app/utils/constants.ts +147 -0
- tools/bolt.diy/app/utils/debounce.ts +13 -0
- tools/bolt.diy/app/utils/debugLogger.ts +1284 -0
- tools/bolt.diy/app/utils/diff.spec.ts +11 -0
- tools/bolt.diy/app/utils/diff.ts +117 -0
- tools/bolt.diy/app/utils/easings.ts +3 -0
- tools/bolt.diy/app/utils/fileLocks.ts +96 -0
- tools/bolt.diy/app/utils/fileUtils.ts +121 -0
- tools/bolt.diy/app/utils/folderImport.ts +73 -0
- tools/bolt.diy/app/utils/formatSize.ts +12 -0
- tools/bolt.diy/app/utils/getLanguageFromExtension.ts +24 -0
- tools/bolt.diy/app/utils/githubStats.ts +9 -0
- tools/bolt.diy/app/utils/gitlabStats.ts +54 -0
- tools/bolt.diy/app/utils/logger.ts +162 -0
- tools/bolt.diy/app/utils/markdown.ts +155 -0
- tools/bolt.diy/app/utils/mobile.ts +4 -0
- tools/bolt.diy/app/utils/os.ts +4 -0
- tools/bolt.diy/app/utils/path.ts +19 -0
- tools/bolt.diy/app/utils/projectCommands.ts +197 -0
- tools/bolt.diy/app/utils/promises.ts +19 -0
- tools/bolt.diy/app/utils/react.ts +6 -0
- tools/bolt.diy/app/utils/sampler.ts +49 -0
- tools/bolt.diy/app/utils/selectStarterTemplate.ts +255 -0
- tools/bolt.diy/app/utils/shell.ts +384 -0
- tools/bolt.diy/app/utils/stacktrace.ts +27 -0
- tools/bolt.diy/app/utils/stripIndent.ts +23 -0
- tools/bolt.diy/app/utils/terminal.ts +11 -0
- tools/bolt.diy/app/utils/unreachable.ts +3 -0
- tools/bolt.diy/app/vite-env.d.ts +2 -0
- tools/bolt.diy/assets/entitlements.mac.plist +25 -0
- tools/bolt.diy/assets/icons/icon.icns +0 -0
- tools/bolt.diy/assets/icons/icon.ico +0 -0
- tools/bolt.diy/assets/icons/icon.png +0 -0
- tools/bolt.diy/bindings.js +78 -0
- tools/bolt.diy/bindings.sh +33 -0
- tools/bolt.diy/docker-compose.yaml +145 -0
- tools/bolt.diy/electron/main/index.ts +201 -0
- tools/bolt.diy/electron/main/tsconfig.json +30 -0
- tools/bolt.diy/electron/main/ui/menu.ts +29 -0
- tools/bolt.diy/electron/main/ui/window.ts +54 -0
- tools/bolt.diy/electron/main/utils/auto-update.ts +110 -0
- tools/bolt.diy/electron/main/utils/constants.ts +4 -0
- tools/bolt.diy/electron/main/utils/cookie.ts +40 -0
- tools/bolt.diy/electron/main/utils/reload.ts +35 -0
- tools/bolt.diy/electron/main/utils/serve.ts +71 -0
- tools/bolt.diy/electron/main/utils/store.ts +3 -0
- tools/bolt.diy/electron/main/utils/vite-server.ts +44 -0
- tools/bolt.diy/electron/main/vite.config.ts +44 -0
- tools/bolt.diy/electron/preload/index.ts +22 -0
- tools/bolt.diy/electron/preload/tsconfig.json +7 -0
- tools/bolt.diy/electron/preload/vite.config.ts +31 -0
- tools/bolt.diy/electron-builder.yml +64 -0
- tools/bolt.diy/electron-update.yml +4 -0
- tools/bolt.diy/eslint.config.mjs +57 -0
- tools/bolt.diy/functions/[[path]].ts +12 -0
- tools/bolt.diy/icons/angular.svg +1 -0
- tools/bolt.diy/icons/astro.svg +8 -0
- tools/bolt.diy/icons/chat.svg +1 -0
- tools/bolt.diy/icons/expo-brand.svg +1 -0
- tools/bolt.diy/icons/expo.svg +4 -0
- tools/bolt.diy/icons/logo-text.svg +1 -0
- tools/bolt.diy/icons/logo.svg +4 -0
- tools/bolt.diy/icons/mcp.svg +1 -0
- tools/bolt.diy/icons/nativescript.svg +1 -0
- tools/bolt.diy/icons/netlify.svg +10 -0
- tools/bolt.diy/icons/nextjs.svg +1 -0
- tools/bolt.diy/icons/nuxt.svg +1 -0
- tools/bolt.diy/icons/qwik.svg +1 -0
- tools/bolt.diy/icons/react.svg +1 -0
- tools/bolt.diy/icons/remix.svg +24 -0
- tools/bolt.diy/icons/remotion.svg +1 -0
- tools/bolt.diy/icons/shadcn.svg +21 -0
- tools/bolt.diy/icons/slidev.svg +60 -0
- tools/bolt.diy/icons/solidjs.svg +1 -0
- tools/bolt.diy/icons/stars.svg +1 -0
- tools/bolt.diy/icons/svelte.svg +1 -0
- tools/bolt.diy/icons/typescript.svg +1 -0
- tools/bolt.diy/icons/vite.svg +1 -0
- tools/bolt.diy/icons/vue.svg +1 -0
- tools/bolt.diy/load-context.ts +9 -0
- tools/bolt.diy/notarize.cjs +31 -0
- tools/bolt.diy/package.json +218 -0
- tools/bolt.diy/playwright.config.preview.ts +35 -0
- tools/bolt.diy/pre-start.cjs +26 -0
- tools/bolt.diy/public/apple-touch-icon-precomposed.png +0 -0
- tools/bolt.diy/public/apple-touch-icon.png +0 -0
- tools/bolt.diy/public/favicon.ico +0 -0
- tools/bolt.diy/public/favicon.svg +4 -0
- tools/bolt.diy/public/icons/AmazonBedrock.svg +1 -0
- tools/bolt.diy/public/icons/Anthropic.svg +4 -0
- tools/bolt.diy/public/icons/Cohere.svg +4 -0
- tools/bolt.diy/public/icons/Deepseek.svg +5 -0
- tools/bolt.diy/public/icons/Default.svg +4 -0
- tools/bolt.diy/public/icons/Google.svg +4 -0
- tools/bolt.diy/public/icons/Groq.svg +4 -0
- tools/bolt.diy/public/icons/HuggingFace.svg +4 -0
- tools/bolt.diy/public/icons/Hyperbolic.svg +3 -0
- tools/bolt.diy/public/icons/LMStudio.svg +5 -0
- tools/bolt.diy/public/icons/Mistral.svg +4 -0
- tools/bolt.diy/public/icons/Ollama.svg +4 -0
- tools/bolt.diy/public/icons/OpenAI.svg +4 -0
- tools/bolt.diy/public/icons/OpenAILike.svg +4 -0
- tools/bolt.diy/public/icons/OpenRouter.svg +4 -0
- tools/bolt.diy/public/icons/Perplexity.svg +4 -0
- tools/bolt.diy/public/icons/Together.svg +4 -0
- tools/bolt.diy/public/icons/xAI.svg +5 -0
- tools/bolt.diy/public/inspector-script.js +292 -0
- tools/bolt.diy/public/logo-dark-styled.png +0 -0
- tools/bolt.diy/public/logo-dark.png +0 -0
- tools/bolt.diy/public/logo-light-styled.png +0 -0
- tools/bolt.diy/public/logo-light.png +0 -0
- tools/bolt.diy/public/logo.svg +15 -0
- tools/bolt.diy/public/social_preview_index.jpg +0 -0
- tools/bolt.diy/scripts/clean.js +45 -0
- tools/bolt.diy/scripts/electron-dev.mjs +181 -0
- tools/bolt.diy/scripts/setup-env.sh +41 -0
- tools/bolt.diy/scripts/update-imports.sh +7 -0
- tools/bolt.diy/scripts/update.sh +52 -0
- tools/bolt.diy/services/execution-governor/Dockerfile +41 -0
- tools/bolt.diy/services/execution-governor/config.ts +42 -0
- tools/bolt.diy/services/execution-governor/index.ts +683 -0
- tools/bolt.diy/services/execution-governor/metrics.ts +141 -0
- tools/bolt.diy/services/execution-governor/package.json +31 -0
- tools/bolt.diy/services/execution-governor/priority-queue.ts +139 -0
- tools/bolt.diy/services/execution-governor/tsconfig.json +21 -0
- tools/bolt.diy/services/execution-governor/types.ts +145 -0
- tools/bolt.diy/services/headless-executor/Dockerfile +43 -0
- tools/bolt.diy/services/headless-executor/executor.ts +210 -0
- tools/bolt.diy/services/headless-executor/index.ts +323 -0
- tools/bolt.diy/services/headless-executor/package.json +27 -0
- tools/bolt.diy/services/headless-executor/tsconfig.json +21 -0
- tools/bolt.diy/services/headless-executor/types.ts +38 -0
- tools/bolt.diy/test-workflows.sh +240 -0
- tools/bolt.diy/tests/integration/corporate-swarm.test.ts +208 -0
- tools/bolt.diy/tests/mandates/budget-limited.json +34 -0
- tools/bolt.diy/tests/mandates/complex.json +53 -0
- tools/bolt.diy/tests/mandates/constraint-enforced.json +36 -0
- tools/bolt.diy/tests/mandates/simple.json +35 -0
- tools/bolt.diy/tsconfig.json +37 -0
- tools/bolt.diy/types/istextorbinary.d.ts +15 -0
- tools/bolt.diy/uno.config.ts +279 -0
- tools/bolt.diy/vite-electron.config.ts +76 -0
- tools/bolt.diy/vite.config.ts +112 -0
- tools/bolt.diy/worker-configuration.d.ts +22 -0
- tools/bolt.diy/wrangler.toml +6 -0
- tools/code_generator.py +461 -0
- tools/file_operations.py +465 -0
- tools/mandate_generator.py +337 -0
- tools/mcpClientUtils.py +1216 -0
- tools/sensors.py +285 -0
- utils/Agent_types.py +15 -0
- utils/AnyToStr.py +0 -0
- utils/HHCS.py +277 -0
- utils/__init__.py +30 -0
- utils/agent.py +3627 -0
- utils/aop.py +2948 -0
- utils/canonical.py +143 -0
- utils/conversation.py +1195 -0
- utils/doctrine_versioning +230 -0
- utils/formatter.py +474 -0
- utils/ledger.py +311 -0
- utils/out_types.py +16 -0
- utils/rollback.py +339 -0
- utils/router.py +929 -0
- utils/tui.py +1908 -0
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Statistical methods module for specialized agents.
|
|
3
|
+
|
|
4
|
+
Provides data-driven fitting, uncertainty quantification, time-series analysis,
|
|
5
|
+
Bayesian inference, sensitivity analysis, and attribution methods.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, List, Tuple, Optional, Any, Callable
|
|
9
|
+
import numpy as np
|
|
10
|
+
import math
|
|
11
|
+
import logging
|
|
12
|
+
import concurrent.futures
|
|
13
|
+
|
|
14
|
+
# Optional dependencies
|
|
15
|
+
try:
|
|
16
|
+
import pandas as pd # type: ignore
|
|
17
|
+
PANDAS_AVAILABLE = True
|
|
18
|
+
except ImportError:
|
|
19
|
+
PANDAS_AVAILABLE = False
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from scipy import stats as scipy_stats # type: ignore
|
|
23
|
+
from scipy.optimize import minimize # type: ignore
|
|
24
|
+
SCIPY_AVAILABLE = True
|
|
25
|
+
except ImportError:
|
|
26
|
+
SCIPY_AVAILABLE = False
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class StatisticalMethods:
|
|
32
|
+
"""
|
|
33
|
+
Statistical analysis methods for specialized agents.
|
|
34
|
+
|
|
35
|
+
Provides methods for:
|
|
36
|
+
- Data-driven model fitting
|
|
37
|
+
- Uncertainty quantification
|
|
38
|
+
- Time-series causality testing
|
|
39
|
+
- Bayesian inference
|
|
40
|
+
- Sensitivity analysis
|
|
41
|
+
- Attribution methods
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
graph_manager: Any, # GraphManager instance
|
|
47
|
+
prediction_framework: Any, # PredictionFramework instance
|
|
48
|
+
standardization_stats: Optional[Dict[str, Dict[str, float]]] = None,
|
|
49
|
+
edge_sign_constraints: Optional[Dict[Tuple[str, str], int]] = None,
|
|
50
|
+
bayesian_priors: Optional[Dict[Tuple[str, str], Dict[str, float]]] = None,
|
|
51
|
+
seed: int = 42,
|
|
52
|
+
bootstrap_workers: int = 0,
|
|
53
|
+
):
|
|
54
|
+
"""
|
|
55
|
+
Initialize statistical methods.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
graph_manager: GraphManager instance
|
|
59
|
+
prediction_framework: PredictionFramework instance
|
|
60
|
+
standardization_stats: Standardization statistics
|
|
61
|
+
edge_sign_constraints: Edge sign constraints
|
|
62
|
+
bayesian_priors: Bayesian priors for edges
|
|
63
|
+
seed: Random seed
|
|
64
|
+
bootstrap_workers: Number of workers for bootstrap
|
|
65
|
+
"""
|
|
66
|
+
self.graph_manager = graph_manager
|
|
67
|
+
self.prediction_framework = prediction_framework
|
|
68
|
+
self.standardization_stats = standardization_stats or {}
|
|
69
|
+
self.edge_sign_constraints = edge_sign_constraints or {}
|
|
70
|
+
self.bayesian_priors = bayesian_priors or {}
|
|
71
|
+
self.seed = seed
|
|
72
|
+
self.bootstrap_workers = bootstrap_workers
|
|
73
|
+
self._rng = np.random.default_rng(seed)
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _require_pandas() -> None:
|
|
77
|
+
"""Raise ImportError if pandas is not available."""
|
|
78
|
+
if not PANDAS_AVAILABLE:
|
|
79
|
+
raise ImportError("pandas is required for this operation. Install pandas to proceed.")
|
|
80
|
+
|
|
81
|
+
@staticmethod
|
|
82
|
+
def _require_scipy() -> None:
|
|
83
|
+
"""Raise ImportError if scipy is not available."""
|
|
84
|
+
if not SCIPY_AVAILABLE:
|
|
85
|
+
raise ImportError("scipy is required for this operation. Install scipy to proceed.")
|
|
86
|
+
|
|
87
|
+
def fit_from_dataframe(
|
|
88
|
+
self,
|
|
89
|
+
df: Any,
|
|
90
|
+
variables: List[str],
|
|
91
|
+
window: int = 30,
|
|
92
|
+
decay_alpha: float = 0.9,
|
|
93
|
+
ridge_lambda: float = 0.0,
|
|
94
|
+
enforce_signs: bool = True
|
|
95
|
+
) -> None:
|
|
96
|
+
"""
|
|
97
|
+
Fit edge strengths and standardization stats from a rolling window with recency weighting.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
df: pandas DataFrame
|
|
101
|
+
variables: List of variable names
|
|
102
|
+
window: Rolling window size
|
|
103
|
+
decay_alpha: Decay factor for recency weighting
|
|
104
|
+
ridge_lambda: Ridge regularization parameter
|
|
105
|
+
enforce_signs: Whether to enforce edge sign constraints
|
|
106
|
+
"""
|
|
107
|
+
self._require_pandas()
|
|
108
|
+
if df is None:
|
|
109
|
+
return
|
|
110
|
+
if not isinstance(df, pd.DataFrame):
|
|
111
|
+
raise TypeError(f"df must be a pandas DataFrame, got {type(df)}")
|
|
112
|
+
if not variables:
|
|
113
|
+
return
|
|
114
|
+
missing = [v for v in variables if v not in df.columns]
|
|
115
|
+
if missing:
|
|
116
|
+
raise ValueError(f"Variables not in DataFrame: {missing}")
|
|
117
|
+
window = max(1, int(window))
|
|
118
|
+
if not (0 < decay_alpha <= 1):
|
|
119
|
+
raise ValueError("decay_alpha must be in (0,1]")
|
|
120
|
+
|
|
121
|
+
df_local = df[variables].dropna().copy()
|
|
122
|
+
if df_local.empty:
|
|
123
|
+
return
|
|
124
|
+
window_df = df_local.tail(window)
|
|
125
|
+
n = len(window_df)
|
|
126
|
+
weights = np.array([decay_alpha ** (n - 1 - i) for i in range(n)], dtype=float)
|
|
127
|
+
weights = weights / (weights.sum() if weights.sum() != 0 else 1.0)
|
|
128
|
+
|
|
129
|
+
# Standardization stats
|
|
130
|
+
self.standardization_stats = {}
|
|
131
|
+
for v in variables:
|
|
132
|
+
m = float(window_df[v].mean())
|
|
133
|
+
s = float(window_df[v].std(ddof=0))
|
|
134
|
+
if s == 0:
|
|
135
|
+
s = 1.0
|
|
136
|
+
self.standardization_stats[v] = {"mean": m, "std": s}
|
|
137
|
+
for node in self.graph_manager.get_nodes():
|
|
138
|
+
if node not in self.standardization_stats:
|
|
139
|
+
self.standardization_stats[node] = {"mean": 0.0, "std": 1.0}
|
|
140
|
+
|
|
141
|
+
# Estimate edge strengths
|
|
142
|
+
for child in self.graph_manager.get_nodes():
|
|
143
|
+
parents = self.graph_manager.get_parents(child)
|
|
144
|
+
if not parents:
|
|
145
|
+
continue
|
|
146
|
+
if child not in window_df.columns:
|
|
147
|
+
continue
|
|
148
|
+
parent_vals = []
|
|
149
|
+
for p in parents:
|
|
150
|
+
if p in window_df.columns:
|
|
151
|
+
stats = self.standardization_stats.get(p, {"mean": 0.0, "std": 1.0})
|
|
152
|
+
parent_vals.append(((window_df[p] - stats["mean"]) / stats["std"]).values)
|
|
153
|
+
if not parent_vals:
|
|
154
|
+
continue
|
|
155
|
+
X = np.vstack(parent_vals).T
|
|
156
|
+
y_stats = self.standardization_stats.get(child, {"mean": 0.0, "std": 1.0})
|
|
157
|
+
y = ((window_df[child] - y_stats["mean"]) / y_stats["std"]).values
|
|
158
|
+
W = np.diag(weights)
|
|
159
|
+
XtW = X.T @ W
|
|
160
|
+
XtWX = XtW @ X
|
|
161
|
+
if ridge_lambda > 0 and XtWX.size > 0:
|
|
162
|
+
k = XtWX.shape[0]
|
|
163
|
+
XtWX = XtWX + ridge_lambda * np.eye(k)
|
|
164
|
+
try:
|
|
165
|
+
XtWX_inv = np.linalg.pinv(XtWX)
|
|
166
|
+
beta = XtWX_inv @ (XtW @ y)
|
|
167
|
+
except Exception:
|
|
168
|
+
beta = np.zeros(X.shape[1])
|
|
169
|
+
beta = np.asarray(beta)
|
|
170
|
+
for idx, p in enumerate(parents):
|
|
171
|
+
strength = float(beta[idx]) if idx < len(beta) else 0.0
|
|
172
|
+
if enforce_signs:
|
|
173
|
+
sign = self.edge_sign_constraints.get((p, child))
|
|
174
|
+
if sign == 1 and strength < 0:
|
|
175
|
+
strength = 0.0
|
|
176
|
+
elif sign == -1 and strength > 0:
|
|
177
|
+
strength = 0.0
|
|
178
|
+
self.graph_manager.add_relationship(p, child, strength=strength, confidence=1.0)
|
|
179
|
+
|
|
180
|
+
def quantify_uncertainty(
|
|
181
|
+
self,
|
|
182
|
+
df: Any,
|
|
183
|
+
variables: List[str],
|
|
184
|
+
windows: int = 200,
|
|
185
|
+
alpha: float = 0.95,
|
|
186
|
+
agent_clone_factory: Optional[Callable] = None,
|
|
187
|
+
) -> Dict[str, Any]:
|
|
188
|
+
"""
|
|
189
|
+
Quantify uncertainty using bootstrap resampling.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
df: pandas DataFrame
|
|
193
|
+
variables: List of variable names
|
|
194
|
+
windows: Number of bootstrap samples
|
|
195
|
+
alpha: Confidence level
|
|
196
|
+
agent_clone_factory: Optional factory function to create agent clones
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
Dictionary with edge confidence intervals
|
|
200
|
+
"""
|
|
201
|
+
self._require_pandas()
|
|
202
|
+
if df is None or not isinstance(df, pd.DataFrame):
|
|
203
|
+
return {"edge_cis": {}, "samples": 0}
|
|
204
|
+
usable = df[variables].dropna()
|
|
205
|
+
if len(usable) < 10:
|
|
206
|
+
return {"edge_cis": {}, "samples": 0}
|
|
207
|
+
windows = max(1, int(windows))
|
|
208
|
+
samples: Dict[Tuple[str, str], List[float]] = {}
|
|
209
|
+
|
|
210
|
+
# Snapshot current strengths
|
|
211
|
+
baseline_strengths: Dict[Tuple[str, str], float] = {}
|
|
212
|
+
for u, targets in self.graph_manager.graph.items():
|
|
213
|
+
for v, meta in targets.items():
|
|
214
|
+
try:
|
|
215
|
+
baseline_strengths[(u, v)] = float(meta.get("strength", 0.0)) if isinstance(meta, dict) else float(meta)
|
|
216
|
+
except Exception:
|
|
217
|
+
baseline_strengths[(u, v)] = 0.0
|
|
218
|
+
baseline_stats = dict(self.standardization_stats)
|
|
219
|
+
|
|
220
|
+
def _snapshot_strengths() -> Dict[Tuple[str, str], float]:
|
|
221
|
+
snap: Dict[Tuple[str, str], float] = {}
|
|
222
|
+
for u, targets in self.graph_manager.graph.items():
|
|
223
|
+
for v, meta in targets.items():
|
|
224
|
+
try:
|
|
225
|
+
snap[(u, v)] = float(meta.get("strength", 0.0)) if isinstance(meta, dict) else float(meta)
|
|
226
|
+
except Exception:
|
|
227
|
+
snap[(u, v)] = 0.0
|
|
228
|
+
return snap
|
|
229
|
+
|
|
230
|
+
def _bootstrap_single(df_sample: "pd.DataFrame") -> Dict[Tuple[str, str], float]:
|
|
231
|
+
if agent_clone_factory:
|
|
232
|
+
clone = agent_clone_factory()
|
|
233
|
+
clone.fit_from_dataframe(
|
|
234
|
+
df=df_sample,
|
|
235
|
+
variables=variables,
|
|
236
|
+
window=min(30, len(df_sample)),
|
|
237
|
+
decay_alpha=0.9,
|
|
238
|
+
ridge_lambda=0.0,
|
|
239
|
+
enforce_signs=True,
|
|
240
|
+
)
|
|
241
|
+
return _snapshot_strengths_from_graph(clone.graph_manager.graph)
|
|
242
|
+
else:
|
|
243
|
+
# Fallback: fit on current instance (not recommended for parallel)
|
|
244
|
+
self.fit_from_dataframe(
|
|
245
|
+
df=df_sample,
|
|
246
|
+
variables=variables,
|
|
247
|
+
window=min(30, len(df_sample)),
|
|
248
|
+
decay_alpha=0.9,
|
|
249
|
+
ridge_lambda=0.0,
|
|
250
|
+
enforce_signs=True,
|
|
251
|
+
)
|
|
252
|
+
return _snapshot_strengths()
|
|
253
|
+
|
|
254
|
+
def _snapshot_strengths_from_graph(graph: Dict[str, Dict[str, Any]]) -> Dict[Tuple[str, str], float]:
|
|
255
|
+
res: Dict[Tuple[str, str], float] = {}
|
|
256
|
+
for u, targets in graph.items():
|
|
257
|
+
for v, meta in targets.items():
|
|
258
|
+
try:
|
|
259
|
+
res[(u, v)] = float(meta.get("strength", 0.0)) if isinstance(meta, dict) else float(meta)
|
|
260
|
+
except Exception:
|
|
261
|
+
res[(u, v)] = 0.0
|
|
262
|
+
return res
|
|
263
|
+
|
|
264
|
+
use_parallel = self.bootstrap_workers > 0 and agent_clone_factory is not None
|
|
265
|
+
if use_parallel:
|
|
266
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=self.bootstrap_workers) as executor:
|
|
267
|
+
futures = []
|
|
268
|
+
for i in range(windows):
|
|
269
|
+
boot_df = usable.sample(n=len(usable), replace=True, random_state=self.seed + i)
|
|
270
|
+
futures.append(executor.submit(_bootstrap_single, boot_df))
|
|
271
|
+
for fut in futures:
|
|
272
|
+
try:
|
|
273
|
+
res_strengths = fut.result()
|
|
274
|
+
for (u, v), w in res_strengths.items():
|
|
275
|
+
samples.setdefault((u, v), []).append(w)
|
|
276
|
+
except Exception:
|
|
277
|
+
continue
|
|
278
|
+
else:
|
|
279
|
+
for i in range(windows):
|
|
280
|
+
boot_df = usable.sample(n=len(usable), replace=True, random_state=self.seed + i)
|
|
281
|
+
try:
|
|
282
|
+
self.fit_from_dataframe(
|
|
283
|
+
df=boot_df,
|
|
284
|
+
variables=variables,
|
|
285
|
+
window=min(30, len(boot_df)),
|
|
286
|
+
decay_alpha=0.9,
|
|
287
|
+
ridge_lambda=0.0,
|
|
288
|
+
enforce_signs=True,
|
|
289
|
+
)
|
|
290
|
+
for (u, v), w in _snapshot_strengths().items():
|
|
291
|
+
samples.setdefault((u, v), []).append(w)
|
|
292
|
+
except Exception:
|
|
293
|
+
continue
|
|
294
|
+
|
|
295
|
+
# Restore baseline strengths and stats
|
|
296
|
+
for (u, v), w in baseline_strengths.items():
|
|
297
|
+
if u in self.graph_manager.graph and v in self.graph_manager.graph[u]:
|
|
298
|
+
self.graph_manager.graph[u][v]["strength"] = w
|
|
299
|
+
self.standardization_stats = baseline_stats
|
|
300
|
+
|
|
301
|
+
edge_cis: Dict[str, Tuple[float, float]] = {}
|
|
302
|
+
for (u, v), arr in samples.items():
|
|
303
|
+
arr_np = np.array(arr)
|
|
304
|
+
lo = float(np.quantile(arr_np, (1 - alpha) / 2))
|
|
305
|
+
hi = float(np.quantile(arr_np, 1 - (1 - alpha) / 2))
|
|
306
|
+
edge_cis[f"{u}->{v}"] = (lo, hi)
|
|
307
|
+
return {"edge_cis": edge_cis, "samples": windows}
|
|
308
|
+
|
|
309
|
+
def granger_causality_test(
|
|
310
|
+
self,
|
|
311
|
+
df: Any,
|
|
312
|
+
var1: str,
|
|
313
|
+
var2: str,
|
|
314
|
+
max_lag: int = 4,
|
|
315
|
+
) -> Dict[str, Any]:
|
|
316
|
+
"""
|
|
317
|
+
Perform Granger causality test.
|
|
318
|
+
|
|
319
|
+
Args:
|
|
320
|
+
df: pandas DataFrame
|
|
321
|
+
var1: First variable (potential cause)
|
|
322
|
+
var2: Second variable (potential effect)
|
|
323
|
+
max_lag: Maximum lag to test
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
Dictionary with test results
|
|
327
|
+
"""
|
|
328
|
+
self._require_pandas()
|
|
329
|
+
if df is None or not isinstance(df, pd.DataFrame):
|
|
330
|
+
return {"error": "Invalid data or variables"}
|
|
331
|
+
data = df[[var1, var2]].dropna()
|
|
332
|
+
if len(data) < max_lag * 2 + 5:
|
|
333
|
+
return {"error": "Insufficient data"}
|
|
334
|
+
try:
|
|
335
|
+
from scipy.stats import f as f_dist # type: ignore
|
|
336
|
+
except Exception:
|
|
337
|
+
return {"error": "scipy f distribution not available"}
|
|
338
|
+
|
|
339
|
+
n = len(data)
|
|
340
|
+
y = data[var2].values
|
|
341
|
+
Xr = []
|
|
342
|
+
Xu = []
|
|
343
|
+
for t in range(max_lag, n):
|
|
344
|
+
lags_var2 = [data[var2].iloc[t - i] for i in range(1, max_lag + 1)]
|
|
345
|
+
lags_var1 = [data[var1].iloc[t - i] for i in range(1, max_lag + 1)]
|
|
346
|
+
Xr.append(lags_var2)
|
|
347
|
+
Xu.append(lags_var2 + lags_var1)
|
|
348
|
+
y_vec = np.array(y[max_lag:], dtype=float)
|
|
349
|
+
Xr = np.array(Xr, dtype=float)
|
|
350
|
+
Xu = np.array(Xu, dtype=float)
|
|
351
|
+
|
|
352
|
+
def ols(X: np.ndarray, yv: np.ndarray) -> Tuple[np.ndarray, float]:
|
|
353
|
+
beta = np.linalg.pinv(X) @ yv
|
|
354
|
+
y_pred = X @ beta
|
|
355
|
+
rss = float(np.sum((yv - y_pred) ** 2))
|
|
356
|
+
return beta, rss
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
_, rss_r = ols(Xr, y_vec)
|
|
360
|
+
_, rss_u = ols(Xu, y_vec)
|
|
361
|
+
m = max_lag
|
|
362
|
+
df2 = len(y_vec) - 2 * m - 1
|
|
363
|
+
if df2 <= 0 or rss_u <= 1e-12:
|
|
364
|
+
return {"error": "Degenerate case in F-test"}
|
|
365
|
+
f_stat = ((rss_r - rss_u) / m) / (rss_u / df2)
|
|
366
|
+
p_value = float(1.0 - f_dist.cdf(f_stat, m, df2))
|
|
367
|
+
return {
|
|
368
|
+
"f_statistic": float(f_stat),
|
|
369
|
+
"p_value": p_value,
|
|
370
|
+
"granger_causes": p_value < 0.05,
|
|
371
|
+
"max_lag": max_lag,
|
|
372
|
+
"restricted_rss": rss_r,
|
|
373
|
+
"unrestricted_rss": rss_u,
|
|
374
|
+
}
|
|
375
|
+
except Exception as e:
|
|
376
|
+
return {"error": str(e)}
|
|
377
|
+
|
|
378
|
+
def vector_autoregression_estimation(
|
|
379
|
+
self,
|
|
380
|
+
df: Any,
|
|
381
|
+
variables: List[str],
|
|
382
|
+
max_lag: int = 2,
|
|
383
|
+
) -> Dict[str, Any]:
|
|
384
|
+
"""
|
|
385
|
+
Estimate vector autoregression model.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
df: pandas DataFrame
|
|
389
|
+
variables: List of variable names
|
|
390
|
+
max_lag: Maximum lag
|
|
391
|
+
|
|
392
|
+
Returns:
|
|
393
|
+
Dictionary with VAR coefficients and residuals
|
|
394
|
+
"""
|
|
395
|
+
self._require_pandas()
|
|
396
|
+
if df is None or not isinstance(df, pd.DataFrame):
|
|
397
|
+
return {"error": "Invalid data"}
|
|
398
|
+
data = df[variables].dropna()
|
|
399
|
+
if len(data) < max_lag * len(variables) + 5:
|
|
400
|
+
return {"error": "Insufficient data"}
|
|
401
|
+
n_vars = len(variables)
|
|
402
|
+
X_lag = []
|
|
403
|
+
y_mat = []
|
|
404
|
+
for t in range(max_lag, len(data)):
|
|
405
|
+
y_row = [data[var].iloc[t] for var in variables]
|
|
406
|
+
y_mat.append(y_row)
|
|
407
|
+
lag_row = []
|
|
408
|
+
for lag in range(1, max_lag + 1):
|
|
409
|
+
for var in variables:
|
|
410
|
+
lag_row.append(data[var].iloc[t - lag])
|
|
411
|
+
X_lag.append(lag_row)
|
|
412
|
+
X = np.array(X_lag, dtype=float)
|
|
413
|
+
Y = np.array(y_mat, dtype=float)
|
|
414
|
+
coefficients: Dict[str, Any] = {}
|
|
415
|
+
residuals = []
|
|
416
|
+
for idx, var in enumerate(variables):
|
|
417
|
+
y_vec = Y[:, idx]
|
|
418
|
+
beta = np.linalg.pinv(X) @ y_vec
|
|
419
|
+
y_pred = X @ beta
|
|
420
|
+
res = y_vec - y_pred
|
|
421
|
+
residuals.append(res)
|
|
422
|
+
coefficients[var] = {"coefficients": beta.tolist()}
|
|
423
|
+
residuals = np.array(residuals).T
|
|
424
|
+
return {
|
|
425
|
+
"coefficient_matrices": coefficients,
|
|
426
|
+
"residuals": residuals.tolist(),
|
|
427
|
+
"n_observations": len(Y),
|
|
428
|
+
"n_variables": n_vars,
|
|
429
|
+
"max_lag": max_lag,
|
|
430
|
+
"variables": variables,
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
def compute_information_theoretic_measures(
|
|
434
|
+
self,
|
|
435
|
+
df: Any,
|
|
436
|
+
variables: List[str],
|
|
437
|
+
) -> Dict[str, Any]:
|
|
438
|
+
"""
|
|
439
|
+
Compute entropy and mutual information estimates.
|
|
440
|
+
|
|
441
|
+
Args:
|
|
442
|
+
df: pandas DataFrame
|
|
443
|
+
variables: List of variable names
|
|
444
|
+
|
|
445
|
+
Returns:
|
|
446
|
+
Dictionary with entropies and mutual information
|
|
447
|
+
"""
|
|
448
|
+
self._require_pandas()
|
|
449
|
+
if df is None or not isinstance(df, pd.DataFrame):
|
|
450
|
+
return {"error": "Invalid data"}
|
|
451
|
+
data = df[variables].dropna()
|
|
452
|
+
if len(data) < 10:
|
|
453
|
+
return {"error": "Insufficient data"}
|
|
454
|
+
|
|
455
|
+
results: Dict[str, Any] = {"entropies": {}, "mutual_information": {}}
|
|
456
|
+
for var in variables:
|
|
457
|
+
if var not in data.columns:
|
|
458
|
+
continue
|
|
459
|
+
series = data[var].dropna()
|
|
460
|
+
if len(series) < 5:
|
|
461
|
+
continue
|
|
462
|
+
n_bins = min(20, max(5, int(np.sqrt(len(series)))))
|
|
463
|
+
hist, _ = np.histogram(series, bins=n_bins)
|
|
464
|
+
hist = hist[hist > 0]
|
|
465
|
+
probs = hist / hist.sum()
|
|
466
|
+
entropy = -np.sum(probs * np.log2(probs))
|
|
467
|
+
results["entropies"][var] = float(entropy)
|
|
468
|
+
|
|
469
|
+
# Pairwise mutual information
|
|
470
|
+
for i, var1 in enumerate(variables):
|
|
471
|
+
if var1 not in results["entropies"]:
|
|
472
|
+
continue
|
|
473
|
+
for var2 in variables[i + 1:]:
|
|
474
|
+
if var2 not in results["entropies"]:
|
|
475
|
+
continue
|
|
476
|
+
joint = data[[var1, var2]].dropna()
|
|
477
|
+
if len(joint) < 5:
|
|
478
|
+
continue
|
|
479
|
+
n_bins = min(10, max(3, int(np.cbrt(len(joint)))))
|
|
480
|
+
hist2d, _, _ = np.histogram2d(joint[var1], joint[var2], bins=n_bins)
|
|
481
|
+
hist2d = hist2d[hist2d > 0]
|
|
482
|
+
probs_joint = hist2d / hist2d.sum()
|
|
483
|
+
h_joint = -np.sum(probs_joint * np.log2(probs_joint))
|
|
484
|
+
mi = results["entropies"][var1] + results["entropies"][var2] - float(h_joint)
|
|
485
|
+
results["mutual_information"][f"{var1};{var2}"] = float(max(0.0, mi))
|
|
486
|
+
|
|
487
|
+
return results
|
|
488
|
+
|
|
489
|
+
def bayesian_edge_inference(
|
|
490
|
+
self,
|
|
491
|
+
df: Any,
|
|
492
|
+
parent: str,
|
|
493
|
+
child: str,
|
|
494
|
+
prior_mu: float = 0.0,
|
|
495
|
+
prior_sigma: float = 1.0,
|
|
496
|
+
) -> Dict[str, Any]:
|
|
497
|
+
"""
|
|
498
|
+
Perform Bayesian inference for edge strength.
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
df: pandas DataFrame
|
|
502
|
+
parent: Parent variable
|
|
503
|
+
child: Child variable
|
|
504
|
+
prior_mu: Prior mean
|
|
505
|
+
prior_sigma: Prior standard deviation
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
Dictionary with posterior distribution parameters
|
|
509
|
+
"""
|
|
510
|
+
self._require_pandas()
|
|
511
|
+
if df is None or not isinstance(df, pd.DataFrame):
|
|
512
|
+
return {"error": "Invalid data"}
|
|
513
|
+
if parent not in df.columns or child not in df.columns:
|
|
514
|
+
return {"error": "Variables not found"}
|
|
515
|
+
data = df[[parent, child]].dropna()
|
|
516
|
+
if len(data) < 5:
|
|
517
|
+
return {"error": "Insufficient data"}
|
|
518
|
+
X = data[parent].values.reshape(-1, 1)
|
|
519
|
+
y = data[child].values
|
|
520
|
+
X_mean, X_std = X.mean(), X.std() or 1.0
|
|
521
|
+
y_mean, y_std = y.mean(), y.std() or 1.0
|
|
522
|
+
X_norm = (X - X_mean) / X_std
|
|
523
|
+
y_norm = (y - y_mean) / y_std
|
|
524
|
+
XtX = X_norm.T @ X_norm
|
|
525
|
+
Xty = X_norm.T @ y_norm
|
|
526
|
+
beta_ols = float((np.linalg.pinv(XtX) @ Xty)[0])
|
|
527
|
+
residuals = y_norm - X_norm @ np.array([beta_ols])
|
|
528
|
+
sigma_sq = float(np.var(residuals))
|
|
529
|
+
tau_likelihood = 1.0 / (sigma_sq + 1e-6)
|
|
530
|
+
tau_prior = 1.0 / (prior_sigma ** 2)
|
|
531
|
+
tau_post = tau_prior + tau_likelihood * len(data)
|
|
532
|
+
mu_post = (tau_prior * prior_mu + tau_likelihood * len(data) * beta_ols) / tau_post
|
|
533
|
+
sigma_post = math.sqrt(1.0 / tau_post)
|
|
534
|
+
ci_lower = mu_post - 1.96 * sigma_post
|
|
535
|
+
ci_upper = mu_post + 1.96 * sigma_post
|
|
536
|
+
self.bayesian_priors[(parent, child)] = {"mu": prior_mu, "sigma": prior_sigma}
|
|
537
|
+
return {
|
|
538
|
+
"posterior_mean": float(mu_post),
|
|
539
|
+
"posterior_std": float(sigma_post),
|
|
540
|
+
"posterior_variance": float(sigma_post ** 2),
|
|
541
|
+
"credible_interval_95": (float(ci_lower), float(ci_upper)),
|
|
542
|
+
"ols_estimate": float(beta_ols),
|
|
543
|
+
"prior_mu": float(prior_mu),
|
|
544
|
+
"prior_sigma": float(prior_sigma),
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
def sensitivity_analysis(
|
|
548
|
+
self,
|
|
549
|
+
intervention: Dict[str, float],
|
|
550
|
+
target: str,
|
|
551
|
+
perturbation_size: float = 0.01,
|
|
552
|
+
) -> Dict[str, Any]:
|
|
553
|
+
"""
|
|
554
|
+
Perform sensitivity analysis.
|
|
555
|
+
|
|
556
|
+
Args:
|
|
557
|
+
intervention: Intervention dictionary
|
|
558
|
+
target: Target variable
|
|
559
|
+
perturbation_size: Size of perturbation
|
|
560
|
+
|
|
561
|
+
Returns:
|
|
562
|
+
Dictionary with sensitivities and elasticities
|
|
563
|
+
"""
|
|
564
|
+
base_outcome = self.prediction_framework.predict_outcomes({}, intervention)
|
|
565
|
+
base_target = base_outcome.get(target, 0.0)
|
|
566
|
+
sensitivities: Dict[str, float] = {}
|
|
567
|
+
elasticities: Dict[str, float] = {}
|
|
568
|
+
for var, val in intervention.items():
|
|
569
|
+
perturbed = dict(intervention)
|
|
570
|
+
perturbed[var] = val + perturbation_size
|
|
571
|
+
perturbed_outcome = self.prediction_framework.predict_outcomes({}, perturbed)
|
|
572
|
+
pert_target = perturbed_outcome.get(target, 0.0)
|
|
573
|
+
sensitivity = (pert_target - base_target) / perturbation_size
|
|
574
|
+
sensitivities[var] = float(sensitivity)
|
|
575
|
+
if abs(base_target) > 1e-6 and abs(val) > 1e-6:
|
|
576
|
+
elasticities[var] = float(sensitivity * (val / base_target))
|
|
577
|
+
else:
|
|
578
|
+
elasticities[var] = 0.0
|
|
579
|
+
most_inf = max(sensitivities.items(), key=lambda x: abs(x[1])) if sensitivities else (None, 0.0)
|
|
580
|
+
total_sens = float(np.linalg.norm(list(sensitivities.values()))) if sensitivities else 0.0
|
|
581
|
+
return {
|
|
582
|
+
"sensitivities": sensitivities,
|
|
583
|
+
"elasticities": elasticities,
|
|
584
|
+
"total_sensitivity": total_sens,
|
|
585
|
+
"most_influential_variable": most_inf[0],
|
|
586
|
+
"most_influential_sensitivity": float(most_inf[1]),
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
def deep_root_cause_analysis(
|
|
590
|
+
self,
|
|
591
|
+
problem_variable: str,
|
|
592
|
+
max_depth: int = 20,
|
|
593
|
+
min_path_strength: float = 0.01,
|
|
594
|
+
) -> Dict[str, Any]:
|
|
595
|
+
"""
|
|
596
|
+
Perform deep root cause analysis.
|
|
597
|
+
|
|
598
|
+
Args:
|
|
599
|
+
problem_variable: Variable to analyze
|
|
600
|
+
max_depth: Maximum search depth
|
|
601
|
+
min_path_strength: Minimum path strength threshold
|
|
602
|
+
|
|
603
|
+
Returns:
|
|
604
|
+
Dictionary with root causes and paths
|
|
605
|
+
"""
|
|
606
|
+
if problem_variable not in self.graph_manager.get_nodes():
|
|
607
|
+
return {"error": f"Variable {problem_variable} not in graph"}
|
|
608
|
+
all_ancestors = list(self.graph_manager.graph_reverse.get(problem_variable, []))
|
|
609
|
+
root_causes: List[Dict[str, Any]] = []
|
|
610
|
+
paths_to_problem: List[Dict[str, Any]] = []
|
|
611
|
+
|
|
612
|
+
def path_strength(path: List[str]) -> float:
|
|
613
|
+
prod = 1.0
|
|
614
|
+
for i in range(len(path) - 1):
|
|
615
|
+
u, v = path[i], path[i + 1]
|
|
616
|
+
prod *= self.graph_manager.edge_strength(u, v)
|
|
617
|
+
if abs(prod) < min_path_strength:
|
|
618
|
+
return 0.0
|
|
619
|
+
return prod
|
|
620
|
+
|
|
621
|
+
for anc in all_ancestors:
|
|
622
|
+
try:
|
|
623
|
+
queue = [(anc, [anc])]
|
|
624
|
+
visited = set()
|
|
625
|
+
while queue:
|
|
626
|
+
node, path = queue.pop(0)
|
|
627
|
+
if len(path) - 1 > max_depth:
|
|
628
|
+
continue
|
|
629
|
+
if node == problem_variable and len(path) > 1:
|
|
630
|
+
ps = path_strength(path)
|
|
631
|
+
if abs(ps) > 0:
|
|
632
|
+
root_causes.append({
|
|
633
|
+
"root_cause": path[0],
|
|
634
|
+
"path_to_problem": path,
|
|
635
|
+
"path_string": " -> ".join(path),
|
|
636
|
+
"path_strength": float(ps),
|
|
637
|
+
"depth": len(path) - 1,
|
|
638
|
+
"is_exogenous": len(self.graph_manager.get_parents(path[0])) == 0,
|
|
639
|
+
})
|
|
640
|
+
paths_to_problem.append({
|
|
641
|
+
"from": path[0],
|
|
642
|
+
"to": problem_variable,
|
|
643
|
+
"path": path,
|
|
644
|
+
"strength": float(ps),
|
|
645
|
+
})
|
|
646
|
+
continue
|
|
647
|
+
for child in self.graph_manager.get_children(node):
|
|
648
|
+
if child not in visited:
|
|
649
|
+
visited.add(child)
|
|
650
|
+
queue.append((child, path + [child]))
|
|
651
|
+
except Exception:
|
|
652
|
+
continue
|
|
653
|
+
|
|
654
|
+
root_causes.sort(key=lambda x: (-x["is_exogenous"], -abs(x["path_strength"]), x["depth"]))
|
|
655
|
+
ultimate_roots = [rc for rc in root_causes if rc.get("is_exogenous")]
|
|
656
|
+
return {
|
|
657
|
+
"problem_variable": problem_variable,
|
|
658
|
+
"all_root_causes": root_causes[:20],
|
|
659
|
+
"ultimate_root_causes": ultimate_roots[:10],
|
|
660
|
+
"total_paths_found": len(paths_to_problem),
|
|
661
|
+
"max_depth_reached": max([rc["depth"] for rc in root_causes] + [0]),
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
def shapley_value_attribution(
|
|
665
|
+
self,
|
|
666
|
+
baseline_state: Dict[str, float],
|
|
667
|
+
target_state: Dict[str, float],
|
|
668
|
+
target: str,
|
|
669
|
+
samples: int = 100,
|
|
670
|
+
) -> Dict[str, Any]:
|
|
671
|
+
"""
|
|
672
|
+
Compute Shapley value attribution.
|
|
673
|
+
|
|
674
|
+
Args:
|
|
675
|
+
baseline_state: Baseline state
|
|
676
|
+
target_state: Target state
|
|
677
|
+
target: Target variable
|
|
678
|
+
samples: Number of samples
|
|
679
|
+
|
|
680
|
+
Returns:
|
|
681
|
+
Dictionary with Shapley values
|
|
682
|
+
"""
|
|
683
|
+
variables = list(set(list(baseline_state.keys()) + list(target_state.keys())))
|
|
684
|
+
n = len(variables)
|
|
685
|
+
if n == 0:
|
|
686
|
+
return {"shapley_values": {}, "normalized": {}, "total_attribution": 0.0}
|
|
687
|
+
contributions: Dict[str, float] = {v: 0.0 for v in variables}
|
|
688
|
+
|
|
689
|
+
def value(subset: List[str]) -> float:
|
|
690
|
+
state = dict(baseline_state)
|
|
691
|
+
for var in subset:
|
|
692
|
+
if var in target_state:
|
|
693
|
+
state[var] = target_state[var]
|
|
694
|
+
outcome = self.prediction_framework.predict_outcomes({}, state)
|
|
695
|
+
return float(outcome.get(target, 0.0))
|
|
696
|
+
|
|
697
|
+
for _ in range(max(1, samples)):
|
|
698
|
+
perm = list(variables)
|
|
699
|
+
self._rng.shuffle(perm)
|
|
700
|
+
cur_set: List[str] = []
|
|
701
|
+
prev_val = value(cur_set)
|
|
702
|
+
for v in perm:
|
|
703
|
+
cur_set.append(v)
|
|
704
|
+
new_val = value(cur_set)
|
|
705
|
+
contributions[v] += new_val - prev_val
|
|
706
|
+
prev_val = new_val
|
|
707
|
+
|
|
708
|
+
shapley_values = {k: v / float(samples) for k, v in contributions.items()}
|
|
709
|
+
total = sum(abs(v) for v in shapley_values.values()) or 1.0
|
|
710
|
+
normalized = {k: v / total for k, v in shapley_values.items()}
|
|
711
|
+
return {
|
|
712
|
+
"shapley_values": shapley_values,
|
|
713
|
+
"normalized": normalized,
|
|
714
|
+
"total_attribution": float(sum(abs(v) for v in shapley_values.values())),
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
def gradient_based_intervention_optimization(
|
|
718
|
+
self,
|
|
719
|
+
initial_state: Dict[str, float],
|
|
720
|
+
target: str,
|
|
721
|
+
intervention_vars: List[str],
|
|
722
|
+
constraints: Optional[Dict[str, Tuple[float, float]]] = None,
|
|
723
|
+
method: str = "L-BFGS-B",
|
|
724
|
+
) -> Dict[str, Any]:
|
|
725
|
+
"""
|
|
726
|
+
Optimize interventions using gradient-based optimization.
|
|
727
|
+
|
|
728
|
+
Args:
|
|
729
|
+
initial_state: Initial state
|
|
730
|
+
target: Target variable
|
|
731
|
+
intervention_vars: Variables that can be intervened on
|
|
732
|
+
constraints: Optional bounds for interventions
|
|
733
|
+
method: Optimization method
|
|
734
|
+
|
|
735
|
+
Returns:
|
|
736
|
+
Dictionary with optimal intervention and results
|
|
737
|
+
"""
|
|
738
|
+
self._require_scipy()
|
|
739
|
+
if not intervention_vars:
|
|
740
|
+
return {"error": "intervention_vars cannot be empty", "optimal_intervention": {}, "success": False}
|
|
741
|
+
|
|
742
|
+
bounds = []
|
|
743
|
+
x0 = []
|
|
744
|
+
for var in intervention_vars:
|
|
745
|
+
cur = float(initial_state.get(var, 0.0))
|
|
746
|
+
x0.append(cur)
|
|
747
|
+
if constraints and var in constraints:
|
|
748
|
+
bounds.append(constraints[var])
|
|
749
|
+
else:
|
|
750
|
+
bounds.append((cur - 3.0, cur + 3.0))
|
|
751
|
+
|
|
752
|
+
def objective(x: np.ndarray) -> float:
|
|
753
|
+
intervention = {intervention_vars[i]: float(x[i]) for i in range(len(x))}
|
|
754
|
+
outcome = self.prediction_framework.predict_outcomes(initial_state, intervention)
|
|
755
|
+
return -float(outcome.get(target, 0.0))
|
|
756
|
+
|
|
757
|
+
try:
|
|
758
|
+
result = minimize(
|
|
759
|
+
objective,
|
|
760
|
+
x0=np.array(x0, dtype=float),
|
|
761
|
+
method=method,
|
|
762
|
+
bounds=bounds,
|
|
763
|
+
options={"maxiter": 100, "ftol": 1e-6},
|
|
764
|
+
)
|
|
765
|
+
optimal_intervention = {intervention_vars[i]: float(result.x[i]) for i in range(len(result.x))}
|
|
766
|
+
optimal_outcome = self.prediction_framework.predict_outcomes(initial_state, optimal_intervention)
|
|
767
|
+
return {
|
|
768
|
+
"optimal_intervention": optimal_intervention,
|
|
769
|
+
"optimal_target_value": float(optimal_outcome.get(target, 0.0)),
|
|
770
|
+
"objective_value": float(result.fun),
|
|
771
|
+
"success": bool(result.success),
|
|
772
|
+
"iterations": int(getattr(result, "nit", 0)),
|
|
773
|
+
"convergence_message": str(result.message),
|
|
774
|
+
}
|
|
775
|
+
except Exception as e:
|
|
776
|
+
logger.debug(f"gradient_based_intervention_optimization failed: {e}")
|
|
777
|
+
return {"error": str(e), "optimal_intervention": {}, "success": False}
|
|
778
|
+
|