quantnodes 3.0.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.
- QuantNodes/__init__.py +15 -0
- QuantNodes/__main__.py +14 -0
- QuantNodes/agent/__init__.py +158 -0
- QuantNodes/agent/agents/__init__.py +13 -0
- QuantNodes/agent/agents/definition.py +180 -0
- QuantNodes/agent/agents/manager.py +73 -0
- QuantNodes/agent/config/__init__.py +34 -0
- QuantNodes/agent/config/executor.py +958 -0
- QuantNodes/agent/config/loader.py +427 -0
- QuantNodes/agent/config/templates/bollinger_bands.yaml +84 -0
- QuantNodes/agent/config/templates/dual_ma.yaml +72 -0
- QuantNodes/agent/config/templates/empty.yaml +56 -0
- QuantNodes/agent/config/templates/mean_reversion.yaml +47 -0
- QuantNodes/agent/config/templates/mean_reversion_zscore.yaml +90 -0
- QuantNodes/agent/config/templates/momentum.yaml +81 -0
- QuantNodes/agent/config/templates/momentum_breakout.yaml +84 -0
- QuantNodes/agent/config/templates/rsi_strategy.yaml +72 -0
- QuantNodes/agent/config/templates/volume_price.yaml +86 -0
- QuantNodes/agent/config/types.py +156 -0
- QuantNodes/agent/config_mapper.py +293 -0
- QuantNodes/agent/core/__init__.py +19 -0
- QuantNodes/agent/core/dream.py +47 -0
- QuantNodes/agent/core/quant_dream.py +274 -0
- QuantNodes/agent/cron_jobs.py +314 -0
- QuantNodes/agent/nanobot_bridge.py +242 -0
- QuantNodes/agent/permission/__init__.py +30 -0
- QuantNodes/agent/permission/defaults.py +36 -0
- QuantNodes/agent/permission/evaluate.py +41 -0
- QuantNodes/agent/permission/models.py +59 -0
- QuantNodes/agent/permission/service.py +133 -0
- QuantNodes/agent/providers/__init__.py +11 -0
- QuantNodes/agent/providers/base.py +102 -0
- QuantNodes/agent/providers/quantnodes.py +610 -0
- QuantNodes/agent/providers/rate_limiter.py +326 -0
- QuantNodes/agent/providers/registry.py +163 -0
- QuantNodes/agent/skills/__init__.py +20 -0
- QuantNodes/agent/skills/base.py +118 -0
- QuantNodes/agent/skills/bridge.py +73 -0
- QuantNodes/agent/skills/factor/__init__.py +14 -0
- QuantNodes/agent/skills/factor/correlation.py +99 -0
- QuantNodes/agent/skills/factor/group_backtest.py +114 -0
- QuantNodes/agent/skills/factor/ic_analysis.py +106 -0
- QuantNodes/agent/skills/loader.py +107 -0
- QuantNodes/agent/skills/registry.py +105 -0
- QuantNodes/agent/skills/strategy/__init__.py +16 -0
- QuantNodes/agent/skills/strategy/bollinger.py +86 -0
- QuantNodes/agent/skills/strategy/dual_ma.py +82 -0
- QuantNodes/agent/skills/strategy/momentum.py +74 -0
- QuantNodes/agent/skills/strategy/rsi_reversal.py +99 -0
- QuantNodes/agent/skills_quant/__init__.py +14 -0
- QuantNodes/agent/skills_quant/backtest-analyze/SKILL.md +42 -0
- QuantNodes/agent/skills_quant/config-driven/SKILL.md +72 -0
- QuantNodes/agent/skills_quant/factor-research/SKILL.md +40 -0
- QuantNodes/agent/skills_quant/quant-dream/SKILL.md +55 -0
- QuantNodes/agent/skills_quant/risk-management/SKILL.md +45 -0
- QuantNodes/agent/skills_quant/strategy-design/SKILL.md +43 -0
- QuantNodes/agent/templates/__init__.py +4 -0
- QuantNodes/agent/tools/__init__.py +173 -0
- QuantNodes/agent/tools/_workspace.py +51 -0
- QuantNodes/agent/tools/alpha_backtest.py +328 -0
- QuantNodes/agent/tools/alpha_evaluate.py +493 -0
- QuantNodes/agent/tools/backtest.py +226 -0
- QuantNodes/agent/tools/base.py +133 -0
- QuantNodes/agent/tools/code_search.py +207 -0
- QuantNodes/agent/tools/config_backtest.py +401 -0
- QuantNodes/agent/tools/context.py +97 -0
- QuantNodes/agent/tools/dream_skill.py +77 -0
- QuantNodes/agent/tools/echo.py +38 -0
- QuantNodes/agent/tools/factor.py +231 -0
- QuantNodes/agent/tools/file_ops.py +201 -0
- QuantNodes/agent/tools/git_ops.py +190 -0
- QuantNodes/agent/tools/operator_lookup.py +218 -0
- QuantNodes/agent/tools/output_truncation.py +77 -0
- QuantNodes/agent/tools/path_check.py +43 -0
- QuantNodes/agent/tools/pipeline.py +62 -0
- QuantNodes/agent/tools/registry.py +150 -0
- QuantNodes/agent/tools/sandbox.py +62 -0
- QuantNodes/agent/tools/shell_safety.py +63 -0
- QuantNodes/agent/tools/strategy.py +106 -0
- QuantNodes/agent/tools/task.py +171 -0
- QuantNodes/agent/tools/web_fetch.py +142 -0
- QuantNodes/agent/tools/web_search.py +114 -0
- QuantNodes/agent/tools/wiki.py +370 -0
- QuantNodes/agent/utils/__init__.py +11 -0
- QuantNodes/agent/utils/helpers.py +43 -0
- QuantNodes/agent/utils/prompt_templates.py +30 -0
- QuantNodes/agent/workflows/__init__.py +20 -0
- QuantNodes/agent/workflows/implementations/__init__.py +8 -0
- QuantNodes/agent/workflows/implementations/alpha_gpt.py +508 -0
- QuantNodes/agent/workflows/implementations/mcts.py +442 -0
- QuantNodes/agent/workflows/parsers.py +44 -0
- QuantNodes/agent/workflows/registry.py +119 -0
- QuantNodes/agent/workflows/step_agent.py +219 -0
- QuantNodes/agent/workflows/tool.py +198 -0
- QuantNodes/ai/__init__.py +93 -0
- QuantNodes/ai/llm/__init__.py +75 -0
- QuantNodes/ai/llm/base.py +233 -0
- QuantNodes/ai/llm/decorators.py +281 -0
- QuantNodes/ai/llm/gateway.py +571 -0
- QuantNodes/ai/llm/null.py +76 -0
- QuantNodes/ai/llm/openai.py +435 -0
- QuantNodes/ai/optimizer.py +405 -0
- QuantNodes/ai/prompts/__init__.py +229 -0
- QuantNodes/ai/sandbox.py +371 -0
- QuantNodes/ai/sandbox_pandas_bridge.py +150 -0
- QuantNodes/ai/strategy_gen.py +396 -0
- QuantNodes/backtest/__init__.py +64 -0
- QuantNodes/backtest/backtest_node.py +188 -0
- QuantNodes/backtest/broker_node.py +378 -0
- QuantNodes/backtest/config_runner.py +397 -0
- QuantNodes/backtest/config_strategy.py +64 -0
- QuantNodes/backtest/risk_node.py +360 -0
- QuantNodes/backtest/strategy_node.py +268 -0
- QuantNodes/cache_node/__init__.py +19 -0
- QuantNodes/cache_node/base.py +244 -0
- QuantNodes/cache_node/cache_store.py +99 -0
- QuantNodes/cache_node/metadata.py +100 -0
- QuantNodes/cli/__init__.py +109 -0
- QuantNodes/cli/_helpers.py +511 -0
- QuantNodes/cli/command.py +110 -0
- QuantNodes/cli/commands/__init__.py +69 -0
- QuantNodes/cli/commands/agent.py +158 -0
- QuantNodes/cli/commands/alpha.py +951 -0
- QuantNodes/cli/commands/chat.py +38 -0
- QuantNodes/cli/commands/evolve.py +120 -0
- QuantNodes/cli/commands/factor.py +569 -0
- QuantNodes/cli/commands/init.py +190 -0
- QuantNodes/cli/commands/run.py +259 -0
- QuantNodes/cli/commands/serve.py +398 -0
- QuantNodes/cli/commands/version.py +120 -0
- QuantNodes/cli/enhanced.py +146 -0
- QuantNodes/conf_node/__init__.py +37 -0
- QuantNodes/conf_node/base.py +120 -0
- QuantNodes/conf_node/env_config.py +132 -0
- QuantNodes/conf_node/ini_config.py +70 -0
- QuantNodes/conf_node/json_config.py +69 -0
- QuantNodes/conf_node/yaml_config.py +78 -0
- QuantNodes/constants.py +17 -0
- QuantNodes/core/__init__.py +196 -0
- QuantNodes/core/_lookback_helpers.py +49 -0
- QuantNodes/core/ast_parser.py +198 -0
- QuantNodes/core/base.py +61 -0
- QuantNodes/core/cache_manager.py +344 -0
- QuantNodes/core/cache_utils.py +150 -0
- QuantNodes/core/cond_builder.py +53 -0
- QuantNodes/core/config.py +170 -0
- QuantNodes/core/constants.py +48 -0
- QuantNodes/core/control.py +412 -0
- QuantNodes/core/data_preprocessing.py +453 -0
- QuantNodes/core/data_source.py +46 -0
- QuantNodes/core/events.py +178 -0
- QuantNodes/core/evolution/__init__.py +22 -0
- QuantNodes/core/evolution/loop.py +583 -0
- QuantNodes/core/evolution/operators.py +289 -0
- QuantNodes/core/evolution/settings.py +44 -0
- QuantNodes/core/expression.py +841 -0
- QuantNodes/core/feedback/__init__.py +38 -0
- QuantNodes/core/feedback/channels.py +182 -0
- QuantNodes/core/feedback/collector.py +91 -0
- QuantNodes/core/feedback/dataclass.py +239 -0
- QuantNodes/core/feedback/llm_judge.py +138 -0
- QuantNodes/core/knowledge/__init__.py +69 -0
- QuantNodes/core/knowledge/knowledge_base.py +217 -0
- QuantNodes/core/knowledge/lineage_compress.py +196 -0
- QuantNodes/core/knowledge/lineage_expand.py +123 -0
- QuantNodes/core/knowledge/metrics/__init__.py +43 -0
- QuantNodes/core/knowledge/metrics/evaluator.py +176 -0
- QuantNodes/core/knowledge/metrics/metrics.py +220 -0
- QuantNodes/core/knowledge/rag_prompt.py +196 -0
- QuantNodes/core/knowledge/retriever.py +209 -0
- QuantNodes/core/lambda_node.py +81 -0
- QuantNodes/core/monitoring/__init__.py +22 -0
- QuantNodes/core/monitoring/collector.py +292 -0
- QuantNodes/core/monitoring/dashboard.py +365 -0
- QuantNodes/core/node.py +375 -0
- QuantNodes/core/pandas_utils.py +504 -0
- QuantNodes/core/parallel/__init__.py +15 -0
- QuantNodes/core/parallel/worker.py +140 -0
- QuantNodes/core/parallel/worker_process.py +265 -0
- QuantNodes/core/path_utils.py +73 -0
- QuantNodes/core/pipeline.py +328 -0
- QuantNodes/core/plugin.py +135 -0
- QuantNodes/core/quality_gate/__init__.py +32 -0
- QuantNodes/core/quality_gate/complexity.py +94 -0
- QuantNodes/core/quality_gate/consistency.py +26 -0
- QuantNodes/core/quality_gate/node.py +97 -0
- QuantNodes/core/quality_gate/redundancy.py +51 -0
- QuantNodes/core/quality_gate/settings.py +43 -0
- QuantNodes/core/quality_gate/zoo.py +98 -0
- QuantNodes/core/serializable.py +116 -0
- QuantNodes/core/serialization.py +673 -0
- QuantNodes/core/tools.py +333 -0
- QuantNodes/core/trajectory/__init__.py +25 -0
- QuantNodes/core/trajectory/entry.py +116 -0
- QuantNodes/core/trajectory/lineage.py +67 -0
- QuantNodes/core/trajectory/pool.py +211 -0
- QuantNodes/core/trajectory/selector.py +140 -0
- QuantNodes/core/visualization/__init__.py +33 -0
- QuantNodes/core/visualization/builder.py +233 -0
- QuantNodes/core/visualization/gate_breakdown.py +140 -0
- QuantNodes/core/visualization/lineage_dag.py +203 -0
- QuantNodes/core/visualization/metric_distribution.py +125 -0
- QuantNodes/core/visualization/report.py +68 -0
- QuantNodes/database_node/__init__.py +69 -0
- QuantNodes/database_node/base.py +135 -0
- QuantNodes/database_node/clickhouse_node.py +272 -0
- QuantNodes/database_node/csv_node.py +83 -0
- QuantNodes/database_node/duckdb_node.py +86 -0
- QuantNodes/database_node/factory.py +83 -0
- QuantNodes/database_node/mysql_node.py +100 -0
- QuantNodes/database_node/parquet_node.py +75 -0
- QuantNodes/database_node/sqlite_node.py +67 -0
- QuantNodes/factor_node/__init__.py +50 -0
- QuantNodes/factor_node/factor.py +563 -0
- QuantNodes/factor_node/factor_db.py +421 -0
- QuantNodes/factor_node/factor_functions/__init__.py +252 -0
- QuantNodes/factor_node/factor_functions/_helpers.py +358 -0
- QuantNodes/factor_node/factor_functions/_helpers_debug.py +317 -0
- QuantNodes/factor_node/factor_functions/composite_ops.py +136 -0
- QuantNodes/factor_node/factor_functions/math_ops.py +433 -0
- QuantNodes/factor_node/factor_functions/section_ops.py +290 -0
- QuantNodes/factor_node/factor_functions/talib_ops.py +1293 -0
- QuantNodes/factor_node/factor_functions/time_ops.py +535 -0
- QuantNodes/factor_node/factor_operation.py +1115 -0
- QuantNodes/factor_node/factor_table.py +1073 -0
- QuantNodes/factor_node/quant_nodes_object.py +60 -0
- QuantNodes/mcp_server/__init__.py +27 -0
- QuantNodes/mcp_server/__main__.py +4 -0
- QuantNodes/mcp_server/server.py +272 -0
- QuantNodes/methods/__init__.py +28 -0
- QuantNodes/methods/pipeline.py +100 -0
- QuantNodes/methods/sandbox.py +102 -0
- QuantNodes/monitor/__init__.py +27 -0
- QuantNodes/monitor/agent_tools/__init__.py +5 -0
- QuantNodes/monitor/agent_tools/monitor_tool.py +98 -0
- QuantNodes/monitor/agent_tools/schedule_tool.py +98 -0
- QuantNodes/monitor/agent_tools/version_tool.py +133 -0
- QuantNodes/monitor/monitor/__init__.py +6 -0
- QuantNodes/monitor/monitor/alerter.py +60 -0
- QuantNodes/monitor/monitor/collector.py +164 -0
- QuantNodes/monitor/monitor/dashboard.py +115 -0
- QuantNodes/monitor/monitor/drift.py +190 -0
- QuantNodes/monitor/scheduler/__init__.py +4 -0
- QuantNodes/monitor/scheduler/runner.py +133 -0
- QuantNodes/monitor/scheduler/scheduler.py +184 -0
- QuantNodes/monitor/storage/__init__.py +16 -0
- QuantNodes/monitor/storage/models.py +70 -0
- QuantNodes/monitor/storage/repository.py +407 -0
- QuantNodes/monitor/version/__init__.py +4 -0
- QuantNodes/monitor/version/diff.py +81 -0
- QuantNodes/monitor/version/version_manager.py +182 -0
- QuantNodes/operator_node/__init__.py +28 -0
- QuantNodes/operator_node/base.py +97 -0
- QuantNodes/operator_node/query_node.py +129 -0
- QuantNodes/operator_node/sql_builder.py +125 -0
- QuantNodes/operator_node/sql_utils.py +172 -0
- QuantNodes/operator_node/transform.py +130 -0
- QuantNodes/operators/__init__.py +90 -0
- QuantNodes/operators/_engine.py +108 -0
- QuantNodes/operators/composite.py +161 -0
- QuantNodes/operators/composite_dag.py +667 -0
- QuantNodes/operators/composite_dag_ops.py +343 -0
- QuantNodes/operators/composite_dag_pandas_ops.py +382 -0
- QuantNodes/operators/custom.py +408 -0
- QuantNodes/operators/facade.py +164 -0
- QuantNodes/operators/math.py +163 -0
- QuantNodes/operators/proxy.py +29 -0
- QuantNodes/operators/registry.py +144 -0
- QuantNodes/operators/section.py +99 -0
- QuantNodes/operators/talib.py +757 -0
- QuantNodes/operators/templates.py +95 -0
- QuantNodes/operators/time_series.py +136 -0
- QuantNodes/prompts/__init__.py +20 -0
- QuantNodes/prompts/backtest/__init__.py +12 -0
- QuantNodes/prompts/backtest/factor_based.py +86 -0
- QuantNodes/prompts/backtest/standard.py +73 -0
- QuantNodes/prompts/factor/__init__.py +14 -0
- QuantNodes/prompts/factor/correlation.py +77 -0
- QuantNodes/prompts/factor/group_backtest.py +86 -0
- QuantNodes/prompts/factor/ic_analysis.py +91 -0
- QuantNodes/prompts/strategy/__init__.py +18 -0
- QuantNodes/prompts/strategy/market_neutral.py +96 -0
- QuantNodes/prompts/strategy/mean_reversion.py +107 -0
- QuantNodes/prompts/strategy/momentum.py +160 -0
- QuantNodes/prompts/strategy/pairs_trading.py +107 -0
- QuantNodes/prompts/strategy/trend_following.py +96 -0
- QuantNodes/research/README.md +106 -0
- QuantNodes/research/__init__.py +154 -0
- QuantNodes/research/_legacy_3c/__init__.py +61 -0
- QuantNodes/research/_legacy_3c/auto_researcher.py +289 -0
- QuantNodes/research/_legacy_3c/factor_evaluator.py +560 -0
- QuantNodes/research/_legacy_3c/factor_miner.py +318 -0
- QuantNodes/research/_legacy_3c/mcts_search.py +324 -0
- QuantNodes/research/factor_test/__init__.py +25 -0
- QuantNodes/research/factor_test/config.py +184 -0
- QuantNodes/research/factor_test/config_builder.py +276 -0
- QuantNodes/research/factor_test/e2e/data_prep.py +163 -0
- QuantNodes/research/factor_test/e2e/run_evolution_e2e.py +309 -0
- QuantNodes/research/factor_test/evolution_adapter.py +231 -0
- QuantNodes/research/factor_test/feedback_wrapper.py +102 -0
- QuantNodes/research/factor_test/ifind_db/__init__.py +7 -0
- QuantNodes/research/factor_test/ifind_db/fetcher.py +224 -0
- QuantNodes/research/factor_test/ifind_db/ifind_database.py +689 -0
- QuantNodes/research/factor_test/nodes/__init__.py +1 -0
- QuantNodes/research/factor_test/nodes/_base.py +91 -0
- QuantNodes/research/factor_test/nodes/adjust_date_node.py +48 -0
- QuantNodes/research/factor_test/nodes/configs.py +240 -0
- QuantNodes/research/factor_test/nodes/factor_neutralize_node.py +87 -0
- QuantNodes/research/factor_test/nodes/factor_preprocess_node.py +222 -0
- QuantNodes/research/factor_test/nodes/factor_score_node.py +141 -0
- QuantNodes/research/factor_test/nodes/factor_test_report_node.py +153 -0
- QuantNodes/research/factor_test/nodes/group_analyzer_node.py +317 -0
- QuantNodes/research/factor_test/nodes/ic_analyzer_node.py +112 -0
- QuantNodes/research/factor_test/nodes/load_data_node.py +100 -0
- QuantNodes/research/factor_test/nodes/long_short_node.py +93 -0
- QuantNodes/research/factor_test/nodes/neutralizers.py +222 -0
- QuantNodes/research/factor_test/nodes/preprocess_strategies.py +277 -0
- QuantNodes/research/factor_test/nodes/risk_correlation_node.py +112 -0
- QuantNodes/research/factor_test/nodes/sample_pool_filter_node.py +110 -0
- QuantNodes/research/factor_test/nodes/tradability_filter_node.py +92 -0
- QuantNodes/research/factor_test/pipeline_runner.py +305 -0
- QuantNodes/research/factor_test/pipeline_spec.py +216 -0
- QuantNodes/research/factor_test/utils/__init__.py +26 -0
- QuantNodes/research/factor_test/utils/constants.py +86 -0
- QuantNodes/research/factor_test/utils/data_loader.py +141 -0
- QuantNodes/research/factor_test/utils/date_utils.py +232 -0
- QuantNodes/research/factor_test/utils/file_loaders.py +150 -0
- QuantNodes/research/factor_test/utils/labels.py +37 -0
- QuantNodes/research/factor_test/utils/metrics_extractor.py +55 -0
- QuantNodes/research/factor_test/utils/performance_metrics.py +175 -0
- QuantNodes/research/factor_test/utils/safe_load.py +106 -0
- QuantNodes/research/quant_alpha/CHANGELOG.md +80 -0
- QuantNodes/research/quant_alpha/README.md +142 -0
- QuantNodes/research/quant_alpha/__init__.py +45 -0
- QuantNodes/research/quant_alpha/adapters/__init__.py +99 -0
- QuantNodes/research/quant_alpha/adapters/calculator.py +503 -0
- QuantNodes/research/quant_alpha/adapters/expression.py +387 -0
- QuantNodes/research/quant_alpha/alpha101_design/__init__.py +50 -0
- QuantNodes/research/quant_alpha/alpha101_design/few_shot_examples.py +243 -0
- QuantNodes/research/quant_alpha/alpha101_design/philosophy.py +474 -0
- QuantNodes/research/quant_alpha/alpha158_design/__init__.py +63 -0
- QuantNodes/research/quant_alpha/alpha158_design/few_shot_examples.py +219 -0
- QuantNodes/research/quant_alpha/alpha158_design/philosophy.py +240 -0
- QuantNodes/research/quant_alpha/evaluation/__init__.py +47 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/__init__.py +8 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g1_handcrafted.py +135 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g2_llm_only.py +269 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g3_alpha_gpt.py +152 -0
- QuantNodes/research/quant_alpha/evaluation/clickhouse_data_loader.py +227 -0
- QuantNodes/research/quant_alpha/evaluation/contracts.py +376 -0
- QuantNodes/research/quant_alpha/evaluation/evaluators/__init__.py +6 -0
- QuantNodes/research/quant_alpha/evaluation/evaluators/polars_evaluator.py +545 -0
- QuantNodes/research/quant_alpha/evaluation/mock_data_loader.py +226 -0
- QuantNodes/research/quant_alpha/evaluation/runner.py +243 -0
- QuantNodes/research/quant_alpha/llm/__init__.py +38 -0
- QuantNodes/research/quant_alpha/llm/parser.py +681 -0
- QuantNodes/research/quant_alpha/logic_driven_pipeline.py +411 -0
- QuantNodes/research/quant_alpha/logic_mining/__init__.py +74 -0
- QuantNodes/research/quant_alpha/logic_mining/compiler.py +457 -0
- QuantNodes/research/quant_alpha/logic_mining/generator.py +366 -0
- QuantNodes/research/quant_alpha/logic_mining/models.py +252 -0
- QuantNodes/research/quant_alpha/logic_mining/parser.py +287 -0
- QuantNodes/research/quant_alpha/logic_mining/pipelines.py +297 -0
- QuantNodes/research/quant_alpha/logic_mining/sources.py +149 -0
- QuantNodes/research/quant_alpha/mcts/__init__.py +66 -0
- QuantNodes/research/quant_alpha/mcts/cache.py +262 -0
- QuantNodes/research/quant_alpha/mcts/extension_ops.py +320 -0
- QuantNodes/research/quant_alpha/mcts/feedback.py +825 -0
- QuantNodes/research/quant_alpha/mcts/op_prior.py +180 -0
- QuantNodes/research/quant_alpha/mcts/search.py +540 -0
- QuantNodes/research/quant_alpha/mcts/tree.py +201 -0
- QuantNodes/research/quant_alpha/operator_vocab/__init__.py +50 -0
- QuantNodes/research/quant_alpha/operator_vocab/config.py +54 -0
- QuantNodes/research/quant_alpha/operator_vocab/metadata.py +263 -0
- QuantNodes/research/quant_alpha/operator_vocab/vocabulary.py +481 -0
- QuantNodes/research/quant_alpha/pipeline.py +1027 -0
- QuantNodes/research/quant_alpha/types/__init__.py +27 -0
- QuantNodes/research/quant_alpha/types/constants.py +28 -0
- QuantNodes/research/quant_alpha/types/state.py +205 -0
- QuantNodes/research/quant_alpha/workflow/__init__.py +32 -0
- QuantNodes/research/quant_alpha/workflow/alpha_gpt.py +911 -0
- QuantNodes/research/quant_alpha/workflow/alpha_logics.py +416 -0
- QuantNodes/research/quant_alpha/workflow/state.py +27 -0
- QuantNodes/research/report_reproducer.py +485 -0
- QuantNodes/research/wiki.py +1155 -0
- QuantNodes/symbolic/__init__.py +51 -0
- QuantNodes/symbolic/compiler.py +113 -0
- QuantNodes/symbolic/dialect.py +260 -0
- QuantNodes/symbolic/executor.py +147 -0
- QuantNodes/symbolic/expression.py +234 -0
- QuantNodes/symbolic/functions.py +433 -0
- QuantNodes/symbolic/optimizer.py +165 -0
- QuantNodes/ui_node/__init__.py +30 -0
- QuantNodes/ui_node/base.py +222 -0
- quantnodes-3.0.0.dist-info/METADATA +463 -0
- quantnodes-3.0.0.dist-info/RECORD +399 -0
- quantnodes-3.0.0.dist-info/WHEEL +5 -0
- quantnodes-3.0.0.dist-info/entry_points.txt +24 -0
- quantnodes-3.0.0.dist-info/top_level.txt +1 -0
QuantNodes/core/tools.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# coding=utf-8
|
|
2
|
+
"""
|
|
3
|
+
工具函数
|
|
4
|
+
|
|
5
|
+
替代 QuantStudio.Tools 中的工具函数
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import multiprocessing as mp
|
|
9
|
+
import tempfile
|
|
10
|
+
import uuid
|
|
11
|
+
from typing import Any, Callable, Iterator, List, Optional, TypeVar, Union
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def gen_available_name(base: str = "Temp", used_names: Optional[set] = None) -> str:
|
|
19
|
+
"""
|
|
20
|
+
生成唯一可用的名称
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
base: 名称基础前缀
|
|
24
|
+
used_names: 已使用的名称集合
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
唯一的名称字符串
|
|
28
|
+
"""
|
|
29
|
+
used = used_names or set()
|
|
30
|
+
while True:
|
|
31
|
+
name = f"{base}_{uuid.uuid4().hex[:8]}"
|
|
32
|
+
if name not in used:
|
|
33
|
+
used.add(name)
|
|
34
|
+
return name
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def partition_list(data: List[T], n_parts: int) -> List[List[T]]:
|
|
38
|
+
"""
|
|
39
|
+
将列表分割为 n 个大致相等的部分
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
data: 要分割的列表
|
|
43
|
+
n_parts: 分割数量
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
分割后的子列表
|
|
47
|
+
"""
|
|
48
|
+
if n_parts <= 0:
|
|
49
|
+
return [data]
|
|
50
|
+
if n_parts >= len(data):
|
|
51
|
+
return [[x] for x in data]
|
|
52
|
+
|
|
53
|
+
part_size = len(data) // n_parts
|
|
54
|
+
remainder = len(data) % n_parts
|
|
55
|
+
|
|
56
|
+
result = []
|
|
57
|
+
start = 0
|
|
58
|
+
for i in range(n_parts):
|
|
59
|
+
end = start + part_size + (1 if i < remainder else 0)
|
|
60
|
+
result.append(data[start:end])
|
|
61
|
+
start = end
|
|
62
|
+
|
|
63
|
+
return result
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def partition_list_moving_sampling(
|
|
67
|
+
data: List[Any],
|
|
68
|
+
n_parts: int,
|
|
69
|
+
step: Optional[int] = None,
|
|
70
|
+
) -> List[List[Any]]:
|
|
71
|
+
"""
|
|
72
|
+
将列表分割为 n 个部分,支持移动采样
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
data: 要分割的列表
|
|
76
|
+
n_parts: 分割数量
|
|
77
|
+
step: 采样步长(可选)
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
分割后的子列表
|
|
81
|
+
"""
|
|
82
|
+
if n_parts <= 0:
|
|
83
|
+
return [data]
|
|
84
|
+
if n_parts >= len(data):
|
|
85
|
+
return [[x] for x in data]
|
|
86
|
+
|
|
87
|
+
if step is None:
|
|
88
|
+
step = max(1, len(data) // n_parts)
|
|
89
|
+
|
|
90
|
+
result = []
|
|
91
|
+
for i in range(n_parts):
|
|
92
|
+
start = i * step
|
|
93
|
+
end = min(start + step + (len(data) % n_parts if i < len(data) % n_parts else 0), len(data))
|
|
94
|
+
if start < len(data):
|
|
95
|
+
result.append(data[start:end])
|
|
96
|
+
else:
|
|
97
|
+
result.append([])
|
|
98
|
+
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def start_multi_process(
|
|
103
|
+
func: Callable,
|
|
104
|
+
args_list: List[tuple],
|
|
105
|
+
n_processes: Optional[int] = None,
|
|
106
|
+
daemon: bool = True,
|
|
107
|
+
) -> List[Any]:
|
|
108
|
+
"""
|
|
109
|
+
启动多进程执行任务
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
func: 要执行的函数
|
|
113
|
+
args_list: 参数列表,每个元素是一个 tuple
|
|
114
|
+
n_processes: 进程数,None 则使用 CPU 核心数
|
|
115
|
+
daemon: 是否守护进程
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
结果列表
|
|
119
|
+
"""
|
|
120
|
+
if n_processes is None:
|
|
121
|
+
n_processes = mp.cpu_count()
|
|
122
|
+
|
|
123
|
+
n_processes = min(n_processes, len(args_list)) if args_list else 1
|
|
124
|
+
|
|
125
|
+
if n_processes == 1:
|
|
126
|
+
return [func(*args) for args in args_list]
|
|
127
|
+
|
|
128
|
+
with mp.Pool(processes=n_processes, maxtasksperchild=1) as pool:
|
|
129
|
+
results = pool.starmap(func, args_list)
|
|
130
|
+
|
|
131
|
+
return results
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def fill_na_by_lookback(
|
|
135
|
+
data: Union[pd.DataFrame, pd.Series],
|
|
136
|
+
lookback: int = 1,
|
|
137
|
+
method: str = "ffill",
|
|
138
|
+
) -> Union[pd.DataFrame, pd.Series]:
|
|
139
|
+
"""
|
|
140
|
+
通过回溯填充 NaN 值
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
data: 数据 DataFrame 或 Series
|
|
144
|
+
lookback: 回溯期数
|
|
145
|
+
method: 填充方法,"ffill"(前向填充)或 "bfill"(后向填充)
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
填充后的数据
|
|
149
|
+
"""
|
|
150
|
+
if lookback <= 0:
|
|
151
|
+
return data
|
|
152
|
+
|
|
153
|
+
if isinstance(data, pd.DataFrame):
|
|
154
|
+
result = data.copy()
|
|
155
|
+
for _ in range(lookback):
|
|
156
|
+
result = result.ffill()
|
|
157
|
+
return result
|
|
158
|
+
else:
|
|
159
|
+
result = data.copy()
|
|
160
|
+
for _ in range(lookback):
|
|
161
|
+
result = result.ffill()
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def get_shelve_file_suffix() -> str:
|
|
166
|
+
"""
|
|
167
|
+
获取 shelve 数据库文件后缀
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
文件后缀字符串
|
|
171
|
+
"""
|
|
172
|
+
return ".db"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def compile_id_filter_str(
|
|
176
|
+
filter_str: str,
|
|
177
|
+
factor_names: List[str],
|
|
178
|
+
) -> tuple:
|
|
179
|
+
"""
|
|
180
|
+
测试并编译 ID 过滤字符串
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
filter_str: 过滤条件字符串
|
|
184
|
+
factor_names: 可用的因子名列表
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
(编译后的字符串, 涉及的因子列表) 或 (None, None) 如果失败
|
|
188
|
+
"""
|
|
189
|
+
if not filter_str:
|
|
190
|
+
return None, None
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
valid_names = set(factor_names)
|
|
194
|
+
if "@" in filter_str:
|
|
195
|
+
factors = []
|
|
196
|
+
normalized = (
|
|
197
|
+
filter_str.replace("=", "==")
|
|
198
|
+
.replace(">", " > ")
|
|
199
|
+
.replace("<", " < ")
|
|
200
|
+
.replace("&", " & ")
|
|
201
|
+
.replace("|", " | ")
|
|
202
|
+
)
|
|
203
|
+
parts = normalized.split()
|
|
204
|
+
for part in parts:
|
|
205
|
+
part = part.strip()
|
|
206
|
+
if part.startswith("@") and part[1:] in valid_names:
|
|
207
|
+
factors.append(part[1:])
|
|
208
|
+
return filter_str, list(set(factors))
|
|
209
|
+
return filter_str, []
|
|
210
|
+
except Exception:
|
|
211
|
+
return None, None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def create_temp_dir(prefix: str = "quantnodes_") -> str:
|
|
215
|
+
"""
|
|
216
|
+
创建临时目录
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
prefix: 目录名前缀
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
临时目录路径
|
|
223
|
+
"""
|
|
224
|
+
temp_dir = tempfile.mkdtemp(prefix=prefix)
|
|
225
|
+
return temp_dir
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def merge_data_frames(
|
|
229
|
+
dfs: List[pd.DataFrame],
|
|
230
|
+
how: str = "inner",
|
|
231
|
+
on: Optional[str] = None,
|
|
232
|
+
left_index: bool = False,
|
|
233
|
+
right_index: bool = False,
|
|
234
|
+
) -> pd.DataFrame:
|
|
235
|
+
"""
|
|
236
|
+
合并多个 DataFrame
|
|
237
|
+
|
|
238
|
+
Args:
|
|
239
|
+
dfs: DataFrame 列表
|
|
240
|
+
how: 合并方式 ("inner", "outer", "left", "right")
|
|
241
|
+
on: 合并键
|
|
242
|
+
left_index: 左侧使用索引
|
|
243
|
+
right_index: 右侧使用索引
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
合并后的 DataFrame
|
|
247
|
+
"""
|
|
248
|
+
if not dfs:
|
|
249
|
+
return pd.DataFrame()
|
|
250
|
+
if len(dfs) == 1:
|
|
251
|
+
return dfs[0]
|
|
252
|
+
|
|
253
|
+
result = dfs[0]
|
|
254
|
+
for df in dfs[1:]:
|
|
255
|
+
result = pd.merge(
|
|
256
|
+
result, df, how=how, on=on,
|
|
257
|
+
left_index=left_index, right_index=right_index,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
return result
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def chunk_iterable(iterable: Iterator[T], chunk_size: int) -> Iterator[List[T]]:
|
|
264
|
+
"""
|
|
265
|
+
将迭代器分块
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
iterable: 可迭代对象
|
|
269
|
+
chunk_size: 块大小
|
|
270
|
+
|
|
271
|
+
Yields:
|
|
272
|
+
块列表
|
|
273
|
+
"""
|
|
274
|
+
chunk = []
|
|
275
|
+
for item in iterable:
|
|
276
|
+
chunk.append(item)
|
|
277
|
+
if len(chunk) >= chunk_size:
|
|
278
|
+
yield chunk
|
|
279
|
+
chunk = []
|
|
280
|
+
if chunk:
|
|
281
|
+
yield chunk
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
__all__ = [
|
|
285
|
+
"gen_available_name",
|
|
286
|
+
"partition_list",
|
|
287
|
+
"partition_list_moving_sampling",
|
|
288
|
+
"start_multi_process",
|
|
289
|
+
"fill_na_by_lookback",
|
|
290
|
+
"get_shelve_file_suffix",
|
|
291
|
+
"compile_id_filter_str",
|
|
292
|
+
"create_temp_dir",
|
|
293
|
+
"merge_data_frames",
|
|
294
|
+
"chunk_iterable",
|
|
295
|
+
"timer",
|
|
296
|
+
"retry",
|
|
297
|
+
]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def timer(func):
|
|
301
|
+
"""计时器装饰器"""
|
|
302
|
+
from functools import wraps
|
|
303
|
+
import time
|
|
304
|
+
|
|
305
|
+
@wraps(func)
|
|
306
|
+
def wrapper(*args, **kwargs):
|
|
307
|
+
start = time.time()
|
|
308
|
+
res = func(*args, **kwargs)
|
|
309
|
+
end = time.time()
|
|
310
|
+
print(f"{func.__name__} spend: {end - start:.4f}s")
|
|
311
|
+
return res
|
|
312
|
+
|
|
313
|
+
return wrapper
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def retry(max_attempts: int = 3, delay: float = 1.0):
|
|
317
|
+
"""重试装饰器"""
|
|
318
|
+
from functools import wraps
|
|
319
|
+
import time
|
|
320
|
+
|
|
321
|
+
def decorator(func):
|
|
322
|
+
@wraps(func)
|
|
323
|
+
def wrapper(*args, **kwargs):
|
|
324
|
+
for attempt in range(max_attempts):
|
|
325
|
+
try:
|
|
326
|
+
return func(*args, **kwargs)
|
|
327
|
+
except Exception:
|
|
328
|
+
if attempt == max_attempts - 1:
|
|
329
|
+
raise
|
|
330
|
+
time.sleep(delay)
|
|
331
|
+
return None
|
|
332
|
+
return wrapper
|
|
333
|
+
return decorator
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""TrajectoryPool — 演化轨迹池。
|
|
2
|
+
|
|
3
|
+
公开 API:
|
|
4
|
+
- TrajectoryEntry (dataclass): 单条轨迹
|
|
5
|
+
- Operation (str Enum): 演化操作类型 (M1)
|
|
6
|
+
- TrajectoryPool (class): 池子 + CRUD + 过滤 + 谱系 + 双层持久化
|
|
7
|
+
- ParentSelector (class): 5 种选择策略
|
|
8
|
+
- SelectionStrategy (Enum): 5 种策略枚举
|
|
9
|
+
- children_of / lineage / descendants: 谱系工具函数
|
|
10
|
+
"""
|
|
11
|
+
from .entry import Operation, TrajectoryEntry
|
|
12
|
+
from .pool import TrajectoryPool
|
|
13
|
+
from .selector import ParentSelector, SelectionStrategy
|
|
14
|
+
from .lineage import children_of, descendants, lineage
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"TrajectoryEntry",
|
|
18
|
+
"Operation",
|
|
19
|
+
"TrajectoryPool",
|
|
20
|
+
"ParentSelector",
|
|
21
|
+
"SelectionStrategy",
|
|
22
|
+
"children_of",
|
|
23
|
+
"descendants",
|
|
24
|
+
"lineage",
|
|
25
|
+
]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""TrajectoryEntry — 单条演化轨迹。"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import uuid
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from ..constants import METRIC_KEYS as _METRIC_KEYS
|
|
13
|
+
from ..feedback import FactorFeedback
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Operation(str, Enum):
|
|
17
|
+
"""M1: 演化操作类型 — 替代硬编码字符串 'original'/'mutation'/'crossover'。
|
|
18
|
+
|
|
19
|
+
str Enum 同时兼容 dataclass.field(default="original") 旧用法。
|
|
20
|
+
"""
|
|
21
|
+
ORIGINAL = "original"
|
|
22
|
+
MUTATION = "mutation"
|
|
23
|
+
CROSSOVER = "crossover"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class TrajectoryEntry:
|
|
28
|
+
"""单条演化轨迹 — QuantaAlpha `Trace.hist` 等价物。"""
|
|
29
|
+
|
|
30
|
+
entry_id: str = field(default_factory=lambda: str(uuid.uuid4()))
|
|
31
|
+
round_idx: int = 0
|
|
32
|
+
operation: str = Operation.ORIGINAL # M1: enum 默认值, 仍兼容 str
|
|
33
|
+
config_snapshot: dict = field(default_factory=dict)
|
|
34
|
+
context_subset: dict = field(default_factory=dict)
|
|
35
|
+
feedback: FactorFeedback | None = None
|
|
36
|
+
parent_ids: list[str] = field(default_factory=list)
|
|
37
|
+
metrics: dict = field(default_factory=dict)
|
|
38
|
+
timestamp: datetime = field(default_factory=datetime.now)
|
|
39
|
+
|
|
40
|
+
# ------------------------------------------------------------------
|
|
41
|
+
# Parquet 序列化 (元数据)
|
|
42
|
+
# ------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
def to_parquet_row(self) -> dict:
|
|
45
|
+
"""展平为单行 dict 供 Parquet 写入。"""
|
|
46
|
+
row = {
|
|
47
|
+
"entry_id": self.entry_id,
|
|
48
|
+
"round_idx": int(self.round_idx),
|
|
49
|
+
"operation": str(self.operation),
|
|
50
|
+
"parent_ids": ",".join(self.parent_ids),
|
|
51
|
+
"decision": bool(self.feedback.decision) if self.feedback else False,
|
|
52
|
+
"duration_ms": float(self.feedback.duration_ms) if self.feedback else 0.0,
|
|
53
|
+
"timestamp": self.timestamp.isoformat(),
|
|
54
|
+
"factor_name": str(self.feedback.factor_name) if self.feedback else "",
|
|
55
|
+
"summary": str(self.feedback.summary) if self.feedback else "",
|
|
56
|
+
}
|
|
57
|
+
for key in _METRIC_KEYS:
|
|
58
|
+
row[key] = self.metrics.get(key)
|
|
59
|
+
return row
|
|
60
|
+
|
|
61
|
+
# ------------------------------------------------------------------
|
|
62
|
+
# JSON 序列化 (完整记录)
|
|
63
|
+
# ------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def to_json_dict(self) -> dict:
|
|
66
|
+
"""转为 JSON-safe dict。"""
|
|
67
|
+
return {
|
|
68
|
+
"entry_id": self.entry_id,
|
|
69
|
+
"round_idx": self.round_idx,
|
|
70
|
+
"operation": self.operation,
|
|
71
|
+
"config_snapshot": _jsonify(self.config_snapshot),
|
|
72
|
+
"context_subset": _jsonify(self.context_subset),
|
|
73
|
+
"feedback": self.feedback.to_dict() if self.feedback else None,
|
|
74
|
+
"parent_ids": list(self.parent_ids),
|
|
75
|
+
"metrics": _jsonify(self.metrics),
|
|
76
|
+
"timestamp": self.timestamp.isoformat(),
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_json_dict(cls, d: dict) -> "TrajectoryEntry":
|
|
81
|
+
"""从 JSON dict 还原。"""
|
|
82
|
+
return cls(
|
|
83
|
+
entry_id=d["entry_id"],
|
|
84
|
+
round_idx=int(d.get("round_idx", 0)),
|
|
85
|
+
operation=str(d.get("operation", "original")),
|
|
86
|
+
config_snapshot=d.get("config_snapshot", {}),
|
|
87
|
+
context_subset=d.get("context_subset", {}),
|
|
88
|
+
feedback=(
|
|
89
|
+
FactorFeedback.from_dict(d["feedback"])
|
|
90
|
+
if d.get("feedback") is not None
|
|
91
|
+
else None
|
|
92
|
+
),
|
|
93
|
+
parent_ids=list(d.get("parent_ids", [])),
|
|
94
|
+
metrics=d.get("metrics", {}),
|
|
95
|
+
timestamp=datetime.fromisoformat(d["timestamp"]),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _jsonify(obj: Any) -> Any:
|
|
100
|
+
"""把 pd.Timestamp / np.ndarray / datetime 等转为 JSON-safe 类型。"""
|
|
101
|
+
if isinstance(obj, dict):
|
|
102
|
+
return {k: _jsonify(v) for k, v in obj.items()}
|
|
103
|
+
if isinstance(obj, (list, tuple)):
|
|
104
|
+
return [_jsonify(v) for v in obj]
|
|
105
|
+
if isinstance(obj, datetime):
|
|
106
|
+
return obj.isoformat()
|
|
107
|
+
if isinstance(obj, pd.Timestamp):
|
|
108
|
+
return obj.isoformat()
|
|
109
|
+
if hasattr(obj, "isoformat"):
|
|
110
|
+
try:
|
|
111
|
+
return obj.isoformat()
|
|
112
|
+
except Exception:
|
|
113
|
+
return str(obj)
|
|
114
|
+
if isinstance(obj, (str, int, float, bool)) or obj is None:
|
|
115
|
+
return obj
|
|
116
|
+
return str(obj)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""谱系追踪: children_of + lineage (从原始到当前)。
|
|
2
|
+
|
|
3
|
+
提供 stateless 工具函数, 接受 entries dict 或 list 操作。
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Iterable, Mapping
|
|
8
|
+
|
|
9
|
+
from .entry import TrajectoryEntry
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def children_of(
|
|
13
|
+
entries: Mapping[str, TrajectoryEntry] | Iterable[TrajectoryEntry],
|
|
14
|
+
parent_id: str,
|
|
15
|
+
) -> list[TrajectoryEntry]:
|
|
16
|
+
"""返回指定父辈的所有子代。"""
|
|
17
|
+
items = entries.values() if isinstance(entries, Mapping) else entries
|
|
18
|
+
return [e for e in items if parent_id in e.parent_ids]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def lineage(
|
|
22
|
+
entries: Mapping[str, TrajectoryEntry],
|
|
23
|
+
entry_id: str,
|
|
24
|
+
) -> list[TrajectoryEntry]:
|
|
25
|
+
"""返回完整谱系 (从原始到当前), 顺序: 最老 → 最新。
|
|
26
|
+
|
|
27
|
+
BFS 防环: 同一节点不重复访问, crossover 时只走第一个 parent。
|
|
28
|
+
"""
|
|
29
|
+
if entry_id not in entries:
|
|
30
|
+
return []
|
|
31
|
+
chain: list[TrajectoryEntry] = []
|
|
32
|
+
current = entries[entry_id]
|
|
33
|
+
chain.append(current)
|
|
34
|
+
visited = {current.entry_id}
|
|
35
|
+
while current.parent_ids:
|
|
36
|
+
next_id = current.parent_ids[0]
|
|
37
|
+
if next_id in visited or next_id not in entries:
|
|
38
|
+
break
|
|
39
|
+
current = entries[next_id]
|
|
40
|
+
chain.append(current)
|
|
41
|
+
visited.add(current.entry_id)
|
|
42
|
+
chain.reverse()
|
|
43
|
+
return chain
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def descendants(
|
|
47
|
+
entries: Mapping[str, TrajectoryEntry],
|
|
48
|
+
entry_id: str,
|
|
49
|
+
max_depth: int | None = None,
|
|
50
|
+
) -> list[TrajectoryEntry]:
|
|
51
|
+
"""返回所有后代 (子代、孙代...), BFS。"""
|
|
52
|
+
if entry_id not in entries:
|
|
53
|
+
return []
|
|
54
|
+
seen: set[str] = {entry_id}
|
|
55
|
+
queue: list[tuple[TrajectoryEntry, int]] = [(entries[entry_id], 0)]
|
|
56
|
+
result: list[TrajectoryEntry] = []
|
|
57
|
+
while queue:
|
|
58
|
+
node, depth = queue.pop(0)
|
|
59
|
+
if max_depth is not None and depth >= max_depth:
|
|
60
|
+
continue
|
|
61
|
+
for child in children_of(entries, node.entry_id):
|
|
62
|
+
if child.entry_id in seen:
|
|
63
|
+
continue
|
|
64
|
+
seen.add(child.entry_id)
|
|
65
|
+
result.append(child)
|
|
66
|
+
queue.append((child, depth + 1))
|
|
67
|
+
return result
|