Timefold SolverFactory.create()报错:预期2个参数但仅传1个
问题排查与解决方案
直接错误原因
报错ValueError: Invalid function: expected 2 arguments but got 1的核心原因是约束提供者函数define_constraints的签名不符合Timefold Python绑定的要求,底层Java接口期望该函数接收2个参数,但你只定义了1个。
分步修复
1. 修正约束提供者函数签名
修改constraints.py中的define_constraints函数,添加第二个参数(即使暂时不需要使用它):
from timefold.solver.core.api.domain.solution import ProblemFactCollection from timefold.solver.score import constraint_provider, HardSoftScore, ConstraintFactory @constraint_provider def define_constraints(constraint_factory: ConstraintFactory, problem_fact_collection: ProblemFactCollection): return [ technician_capacity_hard(constraint_factory), technician_skill_conflict(constraint_factory), ]
2. 为规划实体添加@planning_entity注解
你的Device类缺少@planning_entity注解,Timefold无法识别它为规划实体,必须补上:
@dataclass @planning_entity # 添加该注解 class Device: index: Annotated[int, PlanningId] ium: str nazwa: str typ: str nr_fabryczny: str rbh_norma: float dni_w_om: int uzytkownik: str technician: Annotated[Technician | None, PlanningVariable(allows_unassigned=True)] = field(default=None)
3. 关联规划变量与值范围提供者
在DeviceSchedule的technician_list字段为ValueRangeProvider指定id,然后在Device的PlanningVariable中引用该id:
# 修改DeviceSchedule的technician_list注解 @dataclass @planning_solution class DeviceSchedule: id: str technician_list: Annotated[List[Technician], ProblemFactCollectionProperty, ValueRangeProvider(id="technicianRange")] device_list: Annotated[List[Device], PlanningEntityCollectionProperty] score: Annotated[HardSoftScore, PlanningScore] = field(default=None) # 修改Device的technician字段的PlanningVariable technician: Annotated[Technician | None, PlanningVariable(allows_unassigned=True, value_range_provider_refs=["technicianRange"])] = field(default=None)
4. 修复约束中的空指针风险
在technician_capacity_hard约束中,分组后可能得到technician=None(因为设备允许未分配),需要先判断非空再访问属性:
def technician_capacity_hard(constraint_factory: ConstraintFactory): return ( constraint_factory.for_each(Device) .group_by(lambda device: device.technician, sum(lambda device: device.rbh_norma)) .filter(lambda technician, total_rbh_norma: technician is not None and total_rbh_norma > technician.rbh_do_zaplanowania) .penalize(HardSoftScore.ONE_HARD, lambda technician, total_rbh_norma: total_rbh_norma - technician.rbh_do_zaplanowania) .as_constraint("Technician capacity") )
完成以上修改后,重新运行代码,即可解决当前SolverFactory.create()的报错,同时避免后续运行时的潜在问题。
内容的提问来源于stack exchange,提问作者Peter Pirog
相关产品推荐
相关产品推荐

