You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

667 lines
21 KiB

<?php
declare(strict_types=1);
/**
* AbstractScoreStrategy.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app\service\score;
/**
* 评分骨架
* 设计说明:
* - 定义所有策略共享的步骤,子类只覆写差异点
* 1 作答完整性校验 2 逐题聚合 3 归一化 4 对偶轴判定 5 置信度/综合评分/雷达/认知功能
* - 把 2/3/4 拆成三个钩子:四个策略的差别恰好落在这三处
* 差异之外的一切(阈值、置信度映射、图表映射)必须共用
* 否则「同一次测评换个策略」连阈值口径都变了,A/B 对比失去意义
* - 无硬编码:轴数、极点数、题目数、功能数全部来自 ScoreContext
* 换成 5 轴量表或 30 题短版都不需要改本文件
*/
abstract class AbstractScoreStrategy implements ScoreStrategyInterface
{
// 算法可调参数,来自 config/score.php 的 options
protected $options = [];
public function __construct($options = [])
{
$this->options = (array) $options;
}
final public function score(ScoreContext $context)
{
$context->assertAnswerComplete();
$agg_data = $this->aggregate($context);
$pct_list = $this->normalize($agg_data, $context);
$axis_result = $this->deriveAxes($pct_list, $context);
$type_code = $this->resolveTypeCode($axis_result, $context);
$axis_result = $this->alignAxesToType($axis_result, $type_code, $context);
$result = [];
$result['type_code'] = $type_code;
$result['type_name'] = $context->getTypeName($type_code);
$result['dimension_scores'] = $this->formatDimensions($agg_data, $pct_list, $context);
$result['axes'] = $axis_result;
$result['radar'] = $this->buildRadar($pct_list, $context);
$result['functions'] = $this->buildFunctions($pct_list, $context);
$result['confidence'] = $this->confidence($axis_result);
$result['match_score'] = $this->matchScore($axis_result);
$result['keywords'] = $context->getTypeKeywords($type_code);
$result['strategy'] = $this->getName();
$result['strategy_version'] = $this->getVersion();
$result['debug'] = $this->debugPayload($agg_data, $pct_list, $type_code);
return new ScoreResult($result);
}
/* ------------------------------------------------------------------ *
* 差异点A:逐题聚合
* ------------------------------------------------------------------ */
/**
* 逐题聚合计分
* aggregate
* @param ScoreContext $context 评分输入
* @return array 含 raw_list / max_list / part_list
*
* 强迫选择式:每题各选项分别计分到本轴的两个极点
* 反向题 polarity = -1 时,选项指向的极点翻到对偶极,得分在该题该极点内取反
* 取反用题目内该极点的最大分而非全局满分,避免题与题分值不同时算穿
*/
protected function aggregate(ScoreContext $context)
{
$raw_list = $this->createEmptyPoleData($context);
$max_list = $this->createEmptyPoleData($context);
$part_list = [];
foreach ($raw_list as $pole_code => $value) {
$part_list[$pole_code] = [];
}
foreach ($context->question_list as $q_no => $question) {
// 每题在各极点上的最大可能分,用于算 max 与反向题取反
$q_max_list = [];
foreach ($question['options'] as $option) {
$pole_code = $this->getTargetPole($context, $question, $option['dimension_code']);
$score = (float) $option['score'];
$old_score = 0.0;
if (!empty($q_max_list[$pole_code])) {
$old_score = $q_max_list[$pole_code];
}
if ($score > $old_score) {
$q_max_list[$pole_code] = $score;
}
}
foreach ($q_max_list as $pole_code => $score) {
$max_list[$pole_code] += $score;
}
$answer_key = $context->answer_list[$q_no];
$option = $question['options'][$answer_key];
$pole_code = $this->getTargetPole($context, $question, $option['dimension_code']);
$score = (float) $option['score'];
if ($question['polarity'] === -1) {
$score = $q_max_list[$pole_code] - $score;
}
$raw_list[$pole_code] += $score;
$part_list[$pole_code][] = [$score, $q_max_list[$pole_code]];
}
$data = [];
$data['raw_list'] = $raw_list;
$data['max_list'] = $max_list;
$data['part_list'] = $part_list;
return $data;
}
/**
* 取选项应计入的极点
* getTargetPole
* @param ScoreContext $context 评分输入
* @param array $question 题目
* @param string $pole_code 选项声明的极点
* @return string 反向题返回对偶极
*/
protected function getTargetPole(ScoreContext $context, $question, $pole_code)
{
if ($question['polarity'] === -1) {
return $context->getPairPole($pole_code);
}
return $pole_code;
}
/**
* 生成全零极点数据
* createEmptyPoleData
* @param ScoreContext $context 评分输入
* @return array
*/
protected function createEmptyPoleData(ScoreContext $context)
{
$data = [];
foreach ($context->pole_list as $pole_code => $pole_info) {
$data[$pole_code] = 0.0;
}
return $data;
}
/* ------------------------------------------------------------------ *
* 差异点B:归一化
* ------------------------------------------------------------------ */
/**
* 归一化为百分比
* normalize
* @param array $agg_data 聚合结果
* @param ScoreContext $context 评分输入
* @return array 键为极点码,值 0..100
*/
protected function normalize($agg_data, ScoreContext $context)
{
$pct_list = [];
foreach ($context->pole_list as $pole_code => $pole_info) {
$max_score = 0.0;
if (!empty($agg_data['max_list'][$pole_code])) {
$max_score = $agg_data['max_list'][$pole_code];
}
$pct = 0.0;
// 该极点无题时给 0 而不是 100,避免除零后出现「满分」的假象
if ($max_score > 0) {
$pct = $agg_data['raw_list'][$pole_code] / $max_score * 100;
}
$pct_list[$pole_code] = $pct;
}
return $pct_list;
}
/* ------------------------------------------------------------------ *
* 差异点C:类型码
* ------------------------------------------------------------------ */
/**
* 判定各轴主导极
* deriveAxes
* @param array $pct_list 各极点百分比
* @param ScoreContext $context 评分输入
* @return array 键为轴码
*/
protected function deriveAxes($pct_list, ScoreContext $context)
{
$per_axis = $this->countQuestionPerAxis($context);
$axis_result = [];
foreach ($context->axis_list as $axis) {
$a_pole = $axis['a'];
$b_pole = $axis['b'];
$a_pct = 0.0;
if (!empty($pct_list[$a_pole])) {
$a_pct = $pct_list[$a_pole];
}
$b_pct = 0.0;
if (!empty($pct_list[$b_pole])) {
$b_pct = $pct_list[$b_pole];
}
$diff = abs($a_pct - $b_pct);
// 平局归 a 极:保证确定性,避免同分时结果随浮点误差漂移
$winner = $a_pole;
if ($b_pct > $a_pct) {
$winner = $b_pole;
}
$threshold = $this->getMiddleThreshold($axis['code'], $per_axis);
// 用 <= :阈值本身就是「一题之差」的等价值,恰好等于阈值时即应判为中间型
// 用 < 会让奇数题量的量表在「全选同一位置」时正好落在边界外
$is_middle = false;
if ($diff <= $threshold + 0.000000001) {
$is_middle = true;
}
$item = [];
$item['axis'] = $axis['code'];
$item['name'] = $axis['name'];
$item['a'] = $a_pole;
$item['b'] = $b_pole;
$item['a_name'] = $axis['a_name'];
$item['b_name'] = $axis['b_name'];
$item['a_pct'] = round($a_pct, 1);
$item['b_pct'] = round($b_pct, 1);
$item['winner'] = $winner;
$item['winner_name'] = $context->getPoleName($winner);
$item['diff'] = round($diff, 1);
$item['is_middle'] = $is_middle;
$item['middle_threshold'] = round($threshold, 2);
$axis_result[$axis['code']] = $item;
}
return $axis_result;
}
/**
* 拼装类型码
* resolveTypeCode
* @param array $axis_result 各轴判定结果
* @param ScoreContext $context 评分输入
* @return string 轴数 N 对应 N 个字母,不假定 4
*/
protected function resolveTypeCode($axis_result, ScoreContext $context)
{
$type_code = '';
foreach ($context->axis_list as $axis) {
$type_code .= $axis_result[$axis['code']]['winner'];
}
return $type_code;
}
/**
* 让各轴主导极与类型码对齐
* alignAxesToType
* @param array $axis_result 各轴判定结果
* @param string $type_code 类型码
* @param ScoreContext $context 评分输入
* @return array
*
* 默认不动。原型距离策略需覆写,否则会出现类型码与各轴自相矛盾的结果
*/
protected function alignAxesToType($axis_result, $type_code, ScoreContext $context)
{
return $axis_result;
}
/* ------------------------------------------------------------------ *
* 公共部分
* ------------------------------------------------------------------ */
/**
* 取「倾向不显著」的判定阈值
* getMiddleThreshold
* @param string $axis_code 轴码
* @param array $per_axis 各轴题目数
* @return float 百分比阈值
*
* 单位为题库等价而不是百分比:同一道题的权重随题量变化
* 每轴 15 题时一题之差 6.7 个百分点,每轴 9 题时 11.1 个百分点
* 写死百分点会让同一个阈值在两张量表上含义不同
*/
protected function getMiddleThreshold($axis_code, $per_axis)
{
$eq = 1.0;
if (!empty($this->options['middle_threshold_questions'])) {
$eq = (float) $this->options['middle_threshold_questions'];
}
$num = 0;
if (!empty($per_axis[$axis_code])) {
$num = (int) $per_axis[$axis_code];
}
if ($num < 1) {
return 0.0;
}
return 100.0 * $eq / $num;
}
/**
* 统计各轴题目数
* countQuestionPerAxis
* @param ScoreContext $context 评分输入
* @return array 键为轴码
*/
protected function countQuestionPerAxis(ScoreContext $context)
{
$data = [];
foreach ($context->question_list as $question) {
$pole_code = $question['dimension_code'];
$axis_code = '';
if (!empty($context->pole_list[$pole_code]['axis'])) {
$axis_code = (string) $context->pole_list[$pole_code]['axis'];
}
if ($axis_code === '') {
continue;
}
$old_num = 0;
if (!empty($data[$axis_code])) {
$old_num = $data[$axis_code];
}
$data[$axis_code] = $old_num + 1;
}
return $data;
}
/**
* 计算置信度
* confidence
* @param array $axis_result 各轴判定结果
* @return int 0..100
*/
protected function confidence($axis_result)
{
$conf = [];
if (!empty($this->options['confidence'])) {
$conf = (array) $this->options['confidence'];
}
return intval(round($this->getWeightedDiffRatio($axis_result, $conf) * 100));
}
/**
* 计算综合评分
* matchScore
* @param array $axis_result 各轴判定结果
* @return int 0..100
*
* 语义红线:它衡量「这次作答把倾向表达得多清晰」,不是能力高低也不是测评准确性
* 前端文案不得写成「优秀程度」
*/
protected function matchScore($axis_result)
{
$conf = [];
if (!empty($this->options['match_score'])) {
$conf = (array) $this->options['match_score'];
}
$base = 50.0;
if (!empty($conf['base'])) {
$base = (float) $conf['base'];
}
$span = 45.0;
if (!empty($conf['span'])) {
$span = (float) $conf['span'];
}
$ratio = $this->getWeightedDiffRatio($axis_result, $conf);
$value = $base + $span * $ratio;
if ($value < 0) {
$value = 0;
}
if ($value > 100) {
$value = 100;
}
return intval(round($value));
}
/**
* 各轴差值归一化后加权平均
* getWeightedDiffRatio
* @param array $axis_result 各轴判定结果
* @param array $conf 配置,含 weights / full_at
* @return float 0..1
*
* 置信度与综合评分共用同一套映射,避免两者口径不一致
* 一个说很确定、一个说很模糊这种自相矛盾的结果,用户一眼就能看出问题
*/
private function getWeightedDiffRatio($axis_result, $conf)
{
$full_at = 40.0;
if (!empty($this->options['confidence']['full_at'])) {
$full_at = (float) $this->options['confidence']['full_at'];
}
$weight_list = [];
if (!empty($conf['weights'])) {
$weight_list = (array) $conf['weights'];
}
$num = 0.0;
$den = 0.0;
foreach ($axis_result as $axis_code => $axis_info) {
$weight = 1.0;
if (!empty($weight_list[$axis_code])) {
$weight = (float) $weight_list[$axis_code];
}
$ratio = 1.0;
if ($full_at > 0) {
$ratio = min($axis_info['diff'] / $full_at, 1.0);
}
$num += $weight * $ratio;
$den += $weight;
}
if ($den <= 0) {
return 0.0;
}
return $num / $den;
}
/**
* 构建雷达数据
* buildRadar
* @param array $pct_list 各极点百分比
* @param ScoreContext $context 评分输入
* @return array 含 codes / axes / values / norm / colors
*
* 极点顺序取自题库数据的 paper.radar.order(生成规则:各轴首极 + 各轴次极)
* 保证同轴两极在圆周上相对,点数 = 轴数 × 2,不写死 8
*/
protected function buildRadar($pct_list, ScoreContext $context)
{
$order_list = [];
if (!empty($context->radar['order'])) {
$order_list = (array) $context->radar['order'];
}
$norm = 50;
if (!empty($context->radar['norm'])) {
$norm = intval($context->radar['norm']);
}
$color_list = [];
if (!empty($context->radar['colors'])) {
$color_list = (array) $context->radar['colors'];
}
$code_list = [];
$label_list = [];
$value_list = [];
$out_colors = [];
foreach ($order_list as $index => $pole_code) {
$code_list[] = $pole_code;
$label_list[] = $context->getPoleName($pole_code);
$pct = 0.0;
if (!empty($pct_list[$pole_code])) {
$pct = $pct_list[$pole_code];
}
$value_list[] = intval(round($pct));
// 调色板为空时给中性色名,保证前端拿不到 null
$color = 'amber';
if (!empty($color_list)) {
$count = count($color_list);
$color = (string) $color_list[$index % $count];
}
$out_colors[] = $color;
}
$count = count($value_list);
$data = [];
$data['codes'] = $code_list;
$data['axes'] = $label_list;
$data['values'] = $value_list;
$data['norm'] = array_fill(0, $count, $norm);
$data['colors'] = $out_colors;
return $data;
}
/**
* 构建认知功能数据
* buildFunctions
* @param array $pct_list 各极点百分比
* @param ScoreContext $context 评分输入
* @return array 未配置功能定义时返回空数组
*
* 功能强度默认用乘法模型:一个功能要强,必须两极都强
* Ne 要强,既要偏 N 也要偏 E;只用加法或取最大值会让「高 N 但极度内向」算出高 Ne
* 公式可选 product / average / min,由题库数据的 function_formula 决定
*/
protected function buildFunctions($pct_list, ScoreContext $context)
{
if (empty($context->function_list)) {
return [];
}
$data = [];
foreach ($context->function_list as $function) {
$pole_code = $function['pole'];
$attitude = $function['attitude'];
$pole_pct = 0.0;
if (!empty($pct_list[$pole_code])) {
$pole_pct = $pct_list[$pole_code];
}
$attitude_pct = 0.0;
if (!empty($pct_list[$attitude])) {
$attitude_pct = $pct_list[$attitude];
}
$value = $pole_pct * $attitude_pct / 100;
if ($context->function_formula === 'average') {
$value = ($pole_pct + $attitude_pct) / 2;
}
if ($context->function_formula === 'min') {
$value = min($pole_pct, $attitude_pct);
}
if ($value < 0) {
$value = 0;
}
if ($value > 100) {
$value = 100;
}
$item = [];
$item['code'] = $function['code'];
$item['name'] = $function['name'];
$item['role'] = $function['role'];
$item['value'] = intval(round($value));
$data[] = $item;
}
return $data;
}
/**
* 格式化各极点得分
* formatDimensions
* @param array $agg_data 聚合结果
* @param array $pct_list 各极点百分比
* @param ScoreContext $context 评分输入
* @return array
*
* 按轴顺序输出两极,前端拿到的顺序稳定,不随 json 键序变化
*/
protected function formatDimensions($agg_data, $pct_list, ScoreContext $context)
{
$data = [];
foreach ($context->axis_list as $axis) {
$pole_list = [$axis['a'], $axis['b']];
foreach ($pole_list as $pole_code) {
$raw = 0.0;
if (!empty($agg_data['raw_list'][$pole_code])) {
$raw = $agg_data['raw_list'][$pole_code];
}
$max = 0.0;
if (!empty($agg_data['max_list'][$pole_code])) {
$max = $agg_data['max_list'][$pole_code];
}
$pct = 0.0;
if (!empty($pct_list[$pole_code])) {
$pct = $pct_list[$pole_code];
}
$item = [];
$item['name'] = $context->getPoleName($pole_code);
$item['axis_code'] = $axis['code'];
$item['raw'] = round($raw, 1);
$item['max'] = round($max, 1);
$item['pct'] = round($pct, 1);
$data[$pole_code] = $item;
}
}
return $data;
}
/**
* 构建调试中间量
* debugPayload
* @param array $agg_data 聚合结果
* @param array $pct_list 各极点百分比
* @param string $type_code 类型码
* @return array 非调试模式返回空数组
*/
protected function debugPayload($agg_data, $pct_list, $type_code)
{
if (empty($this->options['debug'])) {
return [];
}
$raw_list = [];
foreach ($agg_data['raw_list'] as $pole_code => $value) {
$raw_list[$pole_code] = round($value, 2);
}
$max_list = [];
foreach ($agg_data['max_list'] as $pole_code => $value) {
$max_list[$pole_code] = round($value, 2);
}
$pct_data = [];
foreach ($pct_list as $pole_code => $value) {
$pct_data[$pole_code] = round($value, 2);
}
$data = [];
$data['raw'] = $raw_list;
$data['max'] = $max_list;
$data['pct'] = $pct_data;
$data['picked'] = $type_code;
return $data;
}
}