Files
dpb/backend/app/api/v1/module_bre/cross_combination/service.py
T
34047007@qq.com b95053c52c init: 初始化 dpb 桃育种系统代码库
前后端 + 后端 FastAPI 全量源码、部署脚本与文档。
2026-08-06 00:17:49 +08:00

534 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from typing import Any
from datetime import datetime
from fastapi import UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.base_schema import AuthSchema, PageResultSchema, ImportResultSchema
from app.core.exceptions import CustomException
from app.core.logger import logger
from app.utils.common_util import search_to_dict
from app.utils.excel_util import ExcelUtil
from app.utils.dict_util import DictLabelResolver, dict_value_to_label
from app.utils.number_gen import NumberGenService
from .crud import BreedingCrossCombinationCRUD
from .model import CrossCombinationModel
from .schema import (
CrossCombinationCreateSchema,
CrossCombinationOutSchema,
CrossCombinationQueryParam,
CrossCombinationUpdateSchema,
)
from app.api.v1.module_bre.target.crud import BreedingTargetCRUD
from app.api.v1.module_bre.germplasm.crud import BreedingGermplasmCRUD
from app.core.base_crud import assert_dict_values, assert_no_children, assert_parents_exist
from app.api.v1.module_bre.germplasm.model import BreedingGermplasmModel
from app.api.v1.module_bre.pedigree.model import PedigreeModel
from app.api.v1.module_bre.planting.model import PlantingModel
from app.api.v1.module_bre.pollination.model import PollinationModel
from app.api.v1.module_bre.seed_treatment.model import SeedTreatmentModel
from app.api.v1.module_bre.seedling.model import SeedlingModel
from app.api.v1.module_bre.selection_result.model import SelectionResultModel
from app.api.v1.module_bre.target.model import TargetModel
from app.api.v1.module_bre.trait_observation.model import TraitObservationModel
from app.api.v1.module_bre.tree_evaluation.model import TreeEvaluationModel
from app.api.v1.module_bre.tree.model import TreeModel
from app.api.v1.module_bre.tree_photo.model import TreePhotoModel
# 交配设计取值(与统计引擎 combining.solve 分支一致;不入 sys_dict,同 selection_index.method 模式)
_COMBINING_DESIGNS = {"full_diallel", "partial_diallel", "line_tester", "nciii"}
_DESIGN_LABELS = {
"full_diallel": "完全双列",
"partial_diallel": "部分双列",
"line_tester": "line×tester (NCII)",
"nciii": "NCIII 测交",
}
_DESIGN_FROM_LABEL = {v: k for k, v in _DESIGN_LABELS.items()}
_SF_ALLELES = {"sf"}
def _parse_s_alleles(raw: str | None) -> set[str] | None:
"""解析 S-等位基因串(如 "S1/S3"、"S1,S2 S3")→ 归一化等位集合;空白/无数据返回 None。
大小写归一(S1/s1);"Sf"/"sf" 为自交亲和功能缺失等位,单独标记含 sf。
"""
if raw is None or not str(raw).strip():
return None
parts = [p.strip() for p in str(raw).replace("/", ",").replace(";", ",").replace(" ", ",").split(",")]
codes = {p.lower() for p in parts if p}
return codes or None
def _s_compat_check(female_s: str | None, male_s: str | None) -> tuple[str, str | None]:
"""桃配子体型自交不亲和(S-RNase) 交配兼容性判定。
规则:任一亲本携带 Sf(自交亲和等位,SI 功能缺失)→ 完全兼容;
否则按共享 S 等位数:0=完全兼容,1=半兼容(花粉半数不亲和,坐果率降),
2=完全不相容(配了不结)。缺 S 数据 → 不校验(None)。
返回 (状态, 文案):状态 full/half/none/unknown。
"""
f_set, m_set = _parse_s_alleles(female_s), _parse_s_alleles(male_s)
if f_set is None or m_set is None:
return "unknown", None
if f_set & _SF_ALLELES or m_set & _SF_ALLELES:
return "full", None
shared = sorted(f_set & m_set)
if len(shared) >= 2:
return "none", f"S-等位基因完全不相容(共享 {'/'.join(shared)}),该组合无法坐果"
if len(shared) == 1:
return "half", f"S-等位基因半兼容(共享 {shared[0]}),约半数花粉不亲和,坐果率下降"
return "full", None
def _validate_design_type(design_type: str | None) -> str | None:
if _is_blank(design_type):
return None
code = _DESIGN_FROM_LABEL.get(str(design_type).strip()) or str(design_type).strip()
if code not in _COMBINING_DESIGNS:
raise CustomException(
msg=f"交配设计取值不合法: {design_type}(可用: {'、'.join(_DESIGN_LABELS.values())}"
)
return code
def _is_blank(v: Any) -> bool:
return v is None or (isinstance(v, str) and v.strip() == "")
def _none_if_blank(v: Any) -> Any:
if _is_blank(v):
return None
return str(v).strip() if isinstance(v, str) else v
def _to_float(v: Any) -> float | None:
if _is_blank(v):
return None
try:
return float(v)
except (TypeError, ValueError):
return None
def _to_int(v: Any) -> int | None:
if _is_blank(v):
return None
try:
return int(float(v))
except (TypeError, ValueError):
return None
class CrossCombinationService:
"""杂交组合 模块服务层"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def _attach_fk_labels(self, items: list[CrossCombinationOutSchema]) -> None:
if not items:
return
crud = BreedingCrossCombinationCRUD(self.auth, self.db)
bre_target_id_ids = {getattr(it, "bre_target_id") for it in items if getattr(it, "bre_target_id")}
if bre_target_id_ids:
refs = await BreedingTargetCRUD(self.auth, self.db).get_list(search={"id": ("in", list(bre_target_id_ids))})
ref_map = {r.id: getattr(r, "target_name") for r in refs}
for it in items:
it.bre_target_name = ref_map.get(getattr(it, "bre_target_id"))
female_parent_id_ids = {getattr(it, "female_parent_id") for it in items if getattr(it, "female_parent_id")}
if female_parent_id_ids:
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(search={"id": ("in", list(female_parent_id_ids))})
ref_map = {r.id: getattr(r, "cultivar_name") for r in refs}
for it in items:
it.female_parent_name = ref_map.get(getattr(it, "female_parent_id"))
male_parent_id_ids = {getattr(it, "male_parent_id") for it in items if getattr(it, "male_parent_id")}
if male_parent_id_ids:
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(search={"id": ("in", list(male_parent_id_ids))})
ref_map = {r.id: getattr(r, "cultivar_name") for r in refs}
for it in items:
it.male_parent_name = ref_map.get(getattr(it, "male_parent_id"))
parent_combination_id_ids = {getattr(it, "parent_combination_id") for it in items if getattr(it, "parent_combination_id")}
if parent_combination_id_ids:
refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", list(parent_combination_id_ids))})
ref_map = {r.id: getattr(r, "combination_code") for r in refs}
for it in items:
it.parent_combination_code = ref_map.get(getattr(it, "parent_combination_id"))
async def detail(self, id: int) -> CrossCombinationOutSchema:
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="该杂交组合不存在")
out = CrossCombinationOutSchema.model_validate(obj)
await self._attach_fk_labels([out])
return out
async def get_list(
self,
search: CrossCombinationQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> list[CrossCombinationOutSchema]:
obj_list = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(
search=search_to_dict(search), order_by=order_by
)
outs = [CrossCombinationOutSchema.model_validate(obj) for obj in obj_list]
await self._attach_fk_labels(outs)
return outs
async def page(
self,
page_no: int,
page_size: int,
search: CrossCombinationQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[CrossCombinationOutSchema]:
offset = (page_no - 1) * page_size
result = await BreedingCrossCombinationCRUD(self.auth, self.db).page(
offset=offset,
limit=page_size,
order_by=order_by or [{"id": "asc"}],
search=search_to_dict(search, {}),
out_schema=CrossCombinationOutSchema,
)
await self._attach_fk_labels(result.items)
return result
async def _check_s_compat(self, female_parent_id: int | None, male_parent_id: int | None) -> str | None:
"""读亲本 S-等位基因做交配兼容性校验;完全不相容 → 409;半兼容返回警示文案。"""
if not female_parent_id or not male_parent_id:
return None
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(
search={"id": ("in", [female_parent_id, male_parent_id])}
)
by_id = {g.id: g for g in refs}
female_s = getattr(by_id.get(female_parent_id), "s_alleles", None)
male_s = getattr(by_id.get(male_parent_id), "s_alleles", None)
status, msg = _s_compat_check(female_s, male_s)
if status == "none":
raise CustomException(msg=msg)
return msg if status == "half" else None
async def _check_parent_roles(self, female_parent_id: int | None, male_parent_id: int | None) -> None:
"""亲本校验:母本父本同质自交 → 409;已显式配置为单角色的种质不得用于另一角色。
桃为两性花,绝大多数种质可双作;can_be_female/can_be_male 两列
default=False 表示未配置,视为均可(不拦)。仅当某侧被显式标记为
不可作(该侧 False、另一侧 True)时按数据错误拦截。
"""
if not female_parent_id or not male_parent_id:
return
refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(
search={"id": ("in", [female_parent_id, male_parent_id])}
)
by_id = {g.id: g for g in refs}
female = by_id.get(female_parent_id)
male = by_id.get(male_parent_id)
if female is None or male is None:
return
f_name = getattr(female, "cultivar_name", "母本") or "母本"
m_name = getattr(male, "cultivar_name", "父本") or "父本"
if female_parent_id == male_parent_id:
raise CustomException(msg=f"母本与父本同为「{f_name}」,自交组合请确认")
if female.can_be_male and not female.can_be_female:
raise CustomException(msg=f"母本「{f_name}」已标记为仅可作父本,不能作母本")
if male.can_be_female and not male.can_be_male:
raise CustomException(msg=f"父本「{m_name}」已标记为仅可作母本,不能作父本")
async def _gen_combination_code(self, cross_year: int | None) -> str:
"""自动生成组合编号:YY + 3 位序号(如 26001、26002…),原子取号。"""
year = cross_year or datetime.now().year
prefix = f"{year % 100:02d}"
async def _seed() -> int | None:
crud = BreedingCrossCombinationCRUD(self.auth, self.db)
objs = await crud.get_list(search={"combination_code": ("like", prefix)})
max_seq = 0
for o in objs:
code = o.combination_code or ""
if code.startswith(prefix) and code[len(prefix):].isdigit():
max_seq = max(max_seq, int(code[len(prefix):]))
return max_seq + 1
seq = await NumberGenService(self.db).next_seq(f"combination:{year}", seed_fn=_seed)
return f"{prefix}{seq:03d}"
async def create(self, data: CrossCombinationCreateSchema) -> CrossCombinationOutSchema:
fields = data.model_dump(exclude_none=True)
if _is_blank(fields.get("combination_code")):
fields["combination_code"] = await self._gen_combination_code(fields.get("cross_year"))
code = _validate_design_type(fields.get("design_type") or "full_diallel")
fields["design_type"] = code or "full_diallel"
data = CrossCombinationCreateSchema(**fields)
exist_obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(combination_code=data.combination_code)
if exist_obj:
raise CustomException(msg="创建失败,组合编号已存在")
await assert_parents_exist(
self.db,
[
(TargetModel, data.bre_target_id, '育种目标'),
(BreedingGermplasmModel, data.female_parent_id, '母本种质'),
(BreedingGermplasmModel, data.male_parent_id, '父本种质'),
(CrossCombinationModel, data.parent_combination_id, '母本组合'),
],
)
await assert_dict_values(
self.db,
[
('cross_method', data.cross_method, '杂交方式'),
('cross_type', data.cross_type, '杂交类型'),
('breeding_stage', data.stage, '育种阶段'),
],
)
await self._check_parent_roles(data.female_parent_id, data.male_parent_id)
s_compat = await self._check_s_compat(data.female_parent_id, data.male_parent_id)
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).create(data=data)
out = CrossCombinationOutSchema.model_validate(obj)
out.s_compat = s_compat
await self._attach_fk_labels([out])
return out
async def update(self, id: int, data: CrossCombinationUpdateSchema) -> CrossCombinationOutSchema:
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(id=id)
if not obj:
raise CustomException(msg="更新失败,该杂交组合不存在")
if data.combination_code is not None:
exist_obj = await BreedingCrossCombinationCRUD(self.auth, self.db).get(combination_code=data.combination_code)
if exist_obj and exist_obj.id != id:
raise CustomException(msg="更新失败,组合编号重复")
await assert_parents_exist(
self.db,
[
(TargetModel, data.bre_target_id, '育种目标'),
(BreedingGermplasmModel, data.female_parent_id, '母本种质'),
(BreedingGermplasmModel, data.male_parent_id, '父本种质'),
(CrossCombinationModel, data.parent_combination_id, '母本组合'),
],
)
await assert_dict_values(
self.db,
[
('cross_method', data.cross_method, '杂交方式'),
('cross_type', data.cross_type, '杂交类型'),
('breeding_stage', data.stage, '育种阶段'),
],
)
if data.design_type is not None:
data.design_type = _validate_design_type(data.design_type) or data.design_type
eff_female = data.female_parent_id if data.female_parent_id is not None else obj.female_parent_id
eff_male = data.male_parent_id if data.male_parent_id is not None else obj.male_parent_id
await self._check_parent_roles(eff_female, eff_male)
s_compat = await self._check_s_compat(eff_female, eff_male)
obj = await BreedingCrossCombinationCRUD(self.auth, self.db).update(id=id, data=data)
out = CrossCombinationOutSchema.model_validate(obj)
out.s_compat = s_compat
await self._attach_fk_labels([out])
return out
async def delete(self, ids: list[int]) -> None:
if not ids:
raise CustomException(msg="删除失败,删除对象不能为空")
objs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)})
obj_map = {o.id: o for o in objs}
for id_ in ids:
if id_ not in obj_map:
raise CustomException(msg="删除失败,该杂交组合不存在")
await assert_no_children(
self.db,
ids,
[
(PollinationModel, 'combination_id', '授粉'),
(SeedTreatmentModel, 'combination_id', '种子处理'),
(SeedlingModel, 'combination_id', '实生苗'),
(PlantingModel, 'combination_id', '定植'),
(TreeModel, 'combination_id', '单株'),
(TreeEvaluationModel, 'combination_id', '单株评价'),
(TreePhotoModel, 'combination_id', '单株照片'),
(SelectionResultModel, 'combination_id', '选择结果'),
(TraitObservationModel, 'combination_id', '性状观测'),
(PedigreeModel, 'combination_id', '系谱'),
],
)
await BreedingCrossCombinationCRUD(self.auth, self.db).delete(ids=ids)
async def list_options(self) -> list[dict[str, Any]]:
"""供前端下拉选择使用:返回 [{value, label, female_parent_id, male_parent_id}]。
female/male 亲本 id 供单株表单选中组合后自动回填母本/父本。
"""
obj_list = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
return [
{
"value": o.id,
"label": o.combination_code,
"female_parent_id": o.female_parent_id,
"male_parent_id": o.male_parent_id,
}
for o in obj_list
]
@staticmethod
def batch_export(obj_list: list[dict[str, Any]]) -> bytes:
mapping_dict = {
"combination_code": "组合编号",
"cross_year": "杂交年份",
"bre_target_name": "育种目标",
"female_parent_name": "母本",
"male_parent_name": "父本",
"parent_combination_code": "母本组合",
"cross_method": "杂交方式",
"cross_type": "杂交类型",
"design_type": "交配设计",
"reason": "组配理由",
"stage": "育种阶段",
"cross_date": "杂交日期",
"seed_count": "获种数",
"remark": "备注",
"created_time": "创建时间",
"created_by": "创建者",
}
data = [dict(item) for item in obj_list]
for item in data:
creator = item.get("created_by")
item["created_by"] = creator.get("name", "未知") if isinstance(creator, dict) else "未知"
item["cross_method"] = dict_value_to_label("cross_method", item.get("cross_method"))
item["cross_type"] = dict_value_to_label("cross_type", item.get("cross_type"))
item["design_type"] = _DESIGN_LABELS.get(item.get("design_type"), item.get("design_type"))
item["stage"] = dict_value_to_label("breeding_stage", item.get("stage"))
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
async def batch_import(self, file: UploadFile, update_support: bool = False) -> ImportResultSchema:
header_dict = {
"组合编号": "combination_code",
"杂交年份": "cross_year",
"育种目标": "bre_target_id",
"母本": "female_parent_id",
"父本": "male_parent_id",
"母本组合": "parent_combination_id",
"杂交方式": "cross_method",
"杂交类型": "cross_type",
"交配设计": "design_type",
"组配理由": "reason",
"育种阶段": "stage",
"杂交日期": "cross_date",
"获种数": "seed_count",
"备注": "remark",
}
try:
contents = await file.read()
rows = ExcelUtil.read_excel_to_dicts(contents)
await file.close()
if not rows:
raise CustomException(msg="导入文件为空")
missing_headers = [h for h in header_dict if h not in rows[0]]
if missing_headers:
raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
bre_target_id_refs = await BreedingTargetCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
bre_target_id_map = {getattr(r, "target_name"): r.id for r in bre_target_id_refs}
female_parent_id_refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
female_parent_id_map = {getattr(r, "cultivar_name"): r.id for r in female_parent_id_refs}
male_parent_id_refs = await BreedingGermplasmCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
male_parent_id_map = {getattr(r, "cultivar_name"): r.id for r in male_parent_id_refs}
parent_combination_id_refs = await BreedingCrossCombinationCRUD(self.auth, self.db).get_list(order_by=[{"id": "asc"}])
parent_combination_id_map = {getattr(r, "combination_code"): r.id for r in parent_combination_id_refs}
mapped_rows = []
for row in rows:
mapped_rows.append({en: row.get(ch) for ch, en in header_dict.items()})
required_fields = ["combination_code", "bre_target_id"]
errors = []
for field in required_fields:
missing_indices = [i + 1 for i, r in enumerate(mapped_rows) if _is_blank(r.get(field))]
if missing_indices:
field_name = next(k for k, v in header_dict.items() if v == field)
rows_str = "、".join(str(i) for i in missing_indices)
errors.append(f"{field_name}不能为空,第{rows_str}行")
if errors:
raise CustomException(msg=f"导入失败,以下行缺少必要字段:\n{'; '.join(errors)}")
error_msgs: list[str] = []
success_count = 0
crud = BreedingCrossCombinationCRUD(self.auth, self.db)
resolver = DictLabelResolver(self.auth, self.db, ["cross_method", "cross_type", "breeding_stage"])
for i, row in enumerate(mapped_rows, start=1):
try:
bre_target_id_val = bre_target_id_map.get(str(row.get("bre_target_id")).strip()) if not _is_blank(row.get("bre_target_id")) else None
female_parent_id_val = female_parent_id_map.get(str(row.get("female_parent_id")).strip()) if not _is_blank(row.get("female_parent_id")) else None
male_parent_id_val = male_parent_id_map.get(str(row.get("male_parent_id")).strip()) if not _is_blank(row.get("male_parent_id")) else None
parent_combination_id_val = parent_combination_id_map.get(str(row.get("parent_combination_id")).strip()) if not _is_blank(row.get("parent_combination_id")) else None
fields = {
"combination_code": _none_if_blank(row.get("combination_code")),
"cross_year": _to_int(row.get("cross_year")),
"bre_target_id": bre_target_id_val,
"female_parent_id": female_parent_id_val,
"male_parent_id": male_parent_id_val,
"parent_combination_id": parent_combination_id_val,
"cross_method": await resolver.resolve("cross_method", row.get("cross_method")),
"cross_type": await resolver.resolve("cross_type", row.get("cross_type")),
"design_type": _validate_design_type(row.get("design_type")) or "full_diallel",
"reason": _none_if_blank(row.get("reason")),
"stage": await resolver.resolve("breeding_stage", row.get("stage")),
"cross_date": _none_if_blank(row.get("cross_date")),
"seed_count": _to_int(row.get("seed_count")),
"remark": _none_if_blank(row.get("remark")),
}
await self._check_parent_roles(female_parent_id_val, male_parent_id_val)
unique_kwargs = {"combination_code": fields["combination_code"]}
create_data = CrossCombinationCreateSchema(**fields)
exist_obj = await crud.get(**unique_kwargs)
if exist_obj:
if update_support:
await crud.update(id=exist_obj.id, data=CrossCombinationUpdateSchema(**fields))
success_count += 1
else:
error_msgs.append(f"第{i}行: 组合编号 {fields['combination_code']} 已存在")
else:
await crud.create(data=create_data)
success_count += 1
except Exception as e:
error_msgs.append(f"第{i}行: {e!s}")
continue
return ImportResultSchema(
valid_count=success_count,
invalid_count=len(error_msgs),
message_list=error_msgs,
)
except Exception as e:
logger.error(f"批量导入杂交组合失败: {e!s}")
raise CustomException(msg=f"导入失败: {e!s}")
@staticmethod
def import_template_download() -> bytes:
header_list = [
"组合编号",
"杂交年份",
"育种目标",
"母本",
"父本",
"母本组合",
"杂交方式",
"杂交类型",
"交配设计",
"组配理由",
"育种阶段",
"杂交日期",
"获种数",
"备注",
]
selector_header_list = ["杂交方式", "杂交类型", "交配设计", "育种阶段"]
option_list = [
{"杂交方式": ["人工杂交", "自然授粉", "回交"]},
{"杂交类型": ["杂交", "自交", "开放"]},
{"交配设计": ["完全双列", "部分双列", "line×tester (NCII)", "NCIII 测交"]},
{"育种阶段": ["germplasm", "parent", "seedling", "sp", "ap", "line", "regional_trial", "released"]},
]
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list,
)