Контекст: я пытаюсь решить проблему планирования турниров.
Я хочу проанализировать решение, сгенерированное алгоритмом Timefold, но столкнулся с проблемой. проблема с сериализацией:
ScoreSerializer = PlainSerializer(lambda score: str(score) if score is not None else None,
return_type=str | None)
def validate_score(v: Any, info: ValidationInfo) -> Any:
logger.info(f"Validating score: type={type(v)}, value={v}")
if isinstance(v, HardMediumSoftDecimalScore) or v is None:
return v
if isinstance(v, str):
return HardMediumSoftDecimalScore.parse(v)
raise ValueError('"score" should be a string')
ScoreValidator = BeforeValidator(validate_score)
class JsonDomainBase(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True,
from_attributes=True,
)
[b]Контекст[/b]: я пытаюсь решить проблему планирования турниров. Я хочу проанализировать решение, сгенерированное алгоритмом Timefold, но столкнулся с проблемой. проблема с сериализацией: [code]INFO: @ timefold_solver : Validating score: type=, value=0hard/-1.195230medium/-2.563480soft INFO: @ timefold_solver : Analysis result: Explanation of score (0hard/-1.19523medium/-2.56348soft): Constraint matches: -1.19523medium: constraint (fairAssignmentCountPerTeam) has 1 matches: -1.19523medium: justified with ([ai.timefold.solver.core.impl.score.stream.collector.LoadBalanceImpl@34afdb84]) -2.56348soft: constraint (evenlyConfrontationCount) has 1 matches: -2.56348soft: justified with ([ai.timefold.solver.core.impl.score.stream.collector.LoadBalanceImpl@3192c24f]) 0: constraint (oneAssignmentPerDatePerTeam) has no matches. 0: constraint (unavailabilityPenalty) has no matches.
[/code] Ниже приведен мой код (фрагмент кода, относящийся к этой проблеме): rest_api.py [code]async def setup_context(request: Request) -> TournamentSchedule: json = await request.json() return TournamentSchedule.model_validate(json, context={ 'teams': { team['id']: Team.model_validate(team) for team in json.get('teams', []) }, 'days': { day['dateIndex']: Day.model_validate(day) for day in json.get('days', []) } })
@app.put("/schedules/analyze") async def analyze_timetable(tournament_schedule: Annotated[TournamentSchedule, Depends(setup_context)]) -> dict: # Call the analyze method and log its raw output analysis_result = solution_manager.analyze(tournament_schedule) logger.info(f"Analysis result: {analysis_result}")
# Log detailed constraint analyses for constraint in analysis_result.constraint_analyses: logger.info( f"Constraint Analysis: {constraint.constraint_name}, Weight: {constraint.weight}, Score: {constraint.score}") for match in constraint.matches: logger.info( f" Match Analysis: {match.constraint_ref.constraint_name}, Score: {match.score}, Justification: {match.justification}")
return {'constraints': [ConstraintAnalysisDTO( name=constraint.constraint_name, weight=constraint.weight, score=constraint.score, matches=[ MatchAnalysisDTO( name=match.constraint_ref.constraint_name, score=match.score, justification=match.justification ) for match in constraint.matches ] ) for constraint in solution_manager.analyze(tournament_schedule).constraint_analyses]} [/code] json_serialization.py [code]ScoreSerializer = PlainSerializer(lambda score: str(score) if score is not None else None, return_type=str | None)
def validate_score(v: Any, info: ValidationInfo) -> Any: logger.info(f"Validating score: type={type(v)}, value={v}") if isinstance(v, HardMediumSoftDecimalScore) or v is None: return v if isinstance(v, str): return HardMediumSoftDecimalScore.parse(v) raise ValueError('"score" should be a string')
ScoreValidator = BeforeValidator(validate_score)
class JsonDomainBase(BaseModel): model_config = ConfigDict( alias_generator=to_camel, populate_by_name=True, from_attributes=True, ) [/code] domain.py [code]class Day(JsonDomainBase): date_index: int
class Team(JsonDomainBase): id: Annotated[int, PlanningId] name: Annotated[str, Field(default=None)]
Контекст : я пытаюсь решить проблему планирования турниров.
Я хочу проанализировать решение, сгенерированное алгоритмом Timefold, но столкнулся с проблемой. проблема с сериализацией:
INFO: @ timefold_solver : Validating score: type=,...
Контекст : я пытаюсь решить проблему планирования турниров.
Я хочу проанализировать решение, сгенерированное алгоритмом Timefold, но столкнулся с проблемой. проблема с сериализацией:
INFO: @ timefold_solver : Validating score: type=,...
Поскольку он не указан в качестве опции по адресу я предполагаю, что это не поддерживается. Некоторый код тестов заставил меня задуматься, поддерживается ли он?
Я работаю со сложными структурами данных с участием пользовательских классов, которые ссылаются друг на друга. В деструкторах или используйте SleedRef , чтобы избежать утечек памяти?
Для моего последнего магистерского проекта я пытаюсь выполнить дополнение данных в наборе данных тепловых изображений ( черно-белые ) для обнаружения рака молочной железы. Этот набор данных содержит только 280 изображений, которые можно...