1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
|
""" Augustus Results Visualization and ROC Analysis This script creates various visualizations for Augustus evaluation results """
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.patches import Rectangle import matplotlib.patches as mpatches
plt.style.use('default') sns.set_palette("husl")
class AugustusVisualizer: """Visualizer for Augustus evaluation results""" def __init__(self, evaluation_data, species_name='Augustus_Model'): self.data = evaluation_data self.species_name = species_name plt.rcParams['font.sans-serif'] = ['DejaVu Sans', 'SimHei', 'Arial Unicode MS'] plt.rcParams['axes.unicode_minus'] = False def explain_roc_limitations(self): """Explain why ROC curve cannot be drawn from current data""" print("🔍 ROC曲线分析说明") print("=" * 50) print("\n❌ 无法绘制ROC曲线的原因:") print("1. ROC曲线需要多个阈值点的数据(sensitivity vs 1-specificity)") print("2. Augustus输出的是固定阈值下的二元分类结果,不是概率分数") print("3. 当前数据只有3个评估级别的单点结果,不是连续的阈值变化数据") print("\n📊 当前可用数据点:") if 'nucleotide_sensitivity' in self.data: fpr_nuc = 1 - self.data['nucleotide_specificity'] print(f" 核苷酸水平: TPR={self.data['nucleotide_sensitivity']:.3f}, FPR={fpr_nuc:.3f}") if 'exon_sensitivity' in self.data: fpr_exon = 1 - self.data['exon_specificity'] print(f" 外显子水平: TPR={self.data['exon_sensitivity']:.3f}, FPR={fpr_exon:.3f}") if 'gene_sensitivity' in self.data: fpr_gene = 1 - self.data['gene_specificity'] print(f" 基因水平: TPR={self.data['gene_sensitivity']:.3f}, FPR={fpr_gene:.3f}") print("\n💡 要绘制真正的ROC曲线,需要:") print(" - Augustus预测的概率分数或置信度分数") print(" - 在不同阈值下重新计算敏感性和特异性") print(" - 通常需要修改Augustus参数或使用后处理工具") def create_performance_dashboard(self): """Create a comprehensive performance dashboard""" fig = plt.figure(figsize=(16, 12)) ax1 = plt.subplot(2, 3, 1) self.plot_sensitivity_specificity_scatter(ax1) ax2 = plt.subplot(2, 3, 2) self.plot_performance_bars(ax2) ax3 = plt.subplot(2, 3, 3) self.plot_pseudo_roc(ax3) ax4 = plt.subplot(2, 3, 4) self.plot_confusion_metrics(ax4) ax5 = plt.subplot(2, 3, 5) self.plot_precision_recall(ax5) ax6 = plt.subplot(2, 3, 6) self.plot_summary_text(ax6) plt.tight_layout() plt.suptitle(f'Augustus Performance Dashboard - {self.species_name}', fontsize=16, fontweight='bold', y=0.98) return fig def plot_sensitivity_specificity_scatter(self, ax): """Plot sensitivity vs specificity scatter""" levels = [] sensitivity = [] specificity = [] colors = ['red', 'blue', 'green'] if 'nucleotide_sensitivity' in self.data: levels.append('Nucleotide') sensitivity.append(self.data['nucleotide_sensitivity']) specificity.append(self.data['nucleotide_specificity']) if 'exon_sensitivity' in self.data: levels.append('Exon') sensitivity.append(self.data['exon_sensitivity']) specificity.append(self.data['exon_specificity']) if 'gene_sensitivity' in self.data: levels.append('Gene') sensitivity.append(self.data['gene_sensitivity']) specificity.append(self.data['gene_specificity']) for i, (level, sens, spec) in enumerate(zip(levels, sensitivity, specificity)): ax.scatter(spec, sens, s=200, c=colors[i], alpha=0.7, label=level, edgecolors='black', linewidth=2) ax.annotate(f'{level}\n({spec:.3f}, {sens:.3f})', (spec, sens), xytext=(10, 10), textcoords='offset points', fontsize=10, bbox=dict(boxstyle='round,pad=0.3', facecolor=colors[i], alpha=0.3)) ax.set_xlabel('Specificity', fontsize=12) ax.set_ylabel('Sensitivity', fontsize=12) ax.set_title('Sensitivity vs Specificity', fontsize=14, fontweight='bold') ax.grid(True, alpha=0.3) ax.legend() ax.set_xlim(0, 1.05) ax.set_ylim(0, 1.05) ax.scatter(1, 1, s=100, c='gold', marker='*', label='Ideal (1,1)', edgecolors='black', linewidth=1) def plot_performance_bars(self, ax): """Plot performance metrics as bar chart""" metrics = [] values = [] levels = [] if 'nucleotide_sensitivity' in self.data: metrics.extend(['Sensitivity', 'Specificity']) values.extend([self.data['nucleotide_sensitivity'], self.data['nucleotide_specificity']]) levels.extend(['Nucleotide', 'Nucleotide']) if 'exon_sensitivity' in self.data: metrics.extend(['Sensitivity', 'Specificity']) values.extend([self.data['exon_sensitivity'], self.data['exon_specificity']]) levels.extend(['Exon', 'Exon']) if 'gene_sensitivity' in self.data: metrics.extend(['Sensitivity', 'Specificity']) values.extend([self.data['gene_sensitivity'], self.data['gene_specificity']]) levels.extend(['Gene', 'Gene']) df = pd.DataFrame({'Metric': metrics, 'Value': values, 'Level': levels}) x = np.arange(len(df['Level'].unique())) width = 0.35 sens_data = df[df['Metric'] == 'Sensitivity'] spec_data = df[df['Metric'] == 'Specificity'] bars1 = ax.bar(x - width/2, sens_data['Value'], width, label='Sensitivity', alpha=0.8) bars2 = ax.bar(x + width/2, spec_data['Value'], width, label='Specificity', alpha=0.8) for bar in bars1: height = bar.get_height() ax.annotate(f'{height:.3f}', xy=(bar.get_x() + bar.get_width()/2, height), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom') for bar in bars2: height = bar.get_height() ax.annotate(f'{height:.3f}', xy=(bar.get_x() + bar.get_width()/2, height), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom') ax.set_xlabel('Evaluation Level', fontsize=12) ax.set_ylabel('Performance Score', fontsize=12) ax.set_title('Performance Metrics by Level', fontsize=14, fontweight='bold') ax.set_xticks(x) ax.set_xticklabels(sens_data['Level'].unique()) ax.legend() ax.set_ylim(0, 1.1) ax.grid(True, alpha=0.3, axis='y') def plot_pseudo_roc(self, ax): """Plot pseudo-ROC curve with available points""" tpr_values = [] fpr_values = [] labels = [] if 'nucleotide_sensitivity' in self.data: tpr_values.append(self.data['nucleotide_sensitivity']) fpr_values.append(1 - self.data['nucleotide_specificity']) labels.append('Nucleotide') if 'exon_sensitivity' in self.data: tpr_values.append(self.data['exon_sensitivity']) fpr_values.append(1 - self.data['exon_specificity']) labels.append('Exon') if 'gene_sensitivity' in self.data: tpr_values.append(self.data['gene_sensitivity']) fpr_values.append(1 - self.data['gene_specificity']) labels.append('Gene') ax.plot([0, 1], [0, 1], 'k--', alpha=0.5, label='Random Classifier') colors = ['red', 'blue', 'green'] for i, (fpr, tpr, label) in enumerate(zip(fpr_values, tpr_values, labels)): ax.scatter(fpr, tpr, s=200, c=colors[i], alpha=0.7, label=f'{label} Level', edgecolors='black', linewidth=2) ax.annotate(f'{label}\n(FPR:{fpr:.3f}, TPR:{tpr:.3f})', (fpr, tpr), xytext=(10, 10), textcoords='offset points', fontsize=10, bbox=dict(boxstyle='round,pad=0.3', facecolor=colors[i], alpha=0.3)) if len(fpr_values) > 1: sorted_points = sorted(zip(fpr_values, tpr_values), key=lambda x: x[0]) fpr_sorted, tpr_sorted = zip(*sorted_points) ax.plot(fpr_sorted, tpr_sorted, 'o-', alpha=0.5, linewidth=2) ax.set_xlabel('False Positive Rate (1 - Specificity)', fontsize=12) ax.set_ylabel('True Positive Rate (Sensitivity)', fontsize=12) ax.set_title('Pseudo-ROC Curve\n(Limited Points Available)', fontsize=14, fontweight='bold') ax.grid(True, alpha=0.3) ax.legend() ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.text(0.6, 0.2, 'Note: This is not a true ROC curve.\nOnly fixed threshold points available.', bbox=dict(boxstyle='round,pad=0.5', facecolor='yellow', alpha=0.7), fontsize=10) def plot_confusion_metrics(self, ax): """Plot confusion matrix style metrics""" if 'gene_tp' in self.data: tp = self.data['gene_tp'] fp = self.data['gene_fp'] fn = self.data['gene_fn'] tn = 0 categories = ['True\nPositives', 'False\nPositives', 'False\nNegatives'] values = [tp, fp, fn] colors = ['green', 'red', 'orange'] bars = ax.bar(categories, values, color=colors, alpha=0.7, edgecolor='black') for bar, value in zip(bars, values): height = bar.get_height() ax.annotate(f'{value}', xy=(bar.get_x() + bar.get_width()/2, height), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom', fontsize=12, fontweight='bold') ax.set_ylabel('Number of Genes', fontsize=12) ax.set_title('Gene Level Classification Results', fontsize=14, fontweight='bold') ax.grid(True, alpha=0.3, axis='y') total_pred = tp + fp total_true = tp + fn ax.text(0.5, 0.95, f'Total Predicted: {total_pred}\nTotal True: {total_true}', transform=ax.transAxes, ha='center', va='top', bbox=dict(boxstyle='round,pad=0.3', facecolor='lightblue', alpha=0.7)) else: ax.text(0.5, 0.5, 'Gene level data\nnot available', transform=ax.transAxes, ha='center', va='center', fontsize=14, bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray')) def plot_precision_recall(self, ax): """Plot precision and recall comparison""" if 'gene_tp' in self.data: tp = self.data['gene_tp'] fp = self.data['gene_fp'] fn = self.data['gene_fn'] precision = tp / (tp + fp) if (tp + fp) > 0 else 0 recall = tp / (tp + fn) if (tp + fn) > 0 else 0 f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0 metrics = ['Precision', 'Recall', 'F1-Score'] values = [precision, recall, f1_score] colors = ['skyblue', 'lightcoral', 'lightgreen'] bars = ax.bar(metrics, values, color=colors, alpha=0.8, edgecolor='black') for bar, value in zip(bars, values): height = bar.get_height() ax.annotate(f'{value:.3f}', xy=(bar.get_x() + bar.get_width()/2, height), xytext=(0, 3), textcoords='offset points', ha='center', va='bottom', fontsize=12, fontweight='bold') ax.set_ylabel('Score', fontsize=12) ax.set_title('Precision, Recall & F1-Score\n(Gene Level)', fontsize=14, fontweight='bold') ax.set_ylim(0, 1.1) ax.grid(True, alpha=0.3, axis='y') if f1_score > 0.7: interpretation = "Good Balance" color = 'green' elif f1_score > 0.5: interpretation = "Moderate Performance" color = 'orange' else: interpretation = "Needs Improvement" color = 'red' ax.text(0.5, 0.05, f'Overall: {interpretation}', transform=ax.transAxes, ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.3', facecolor=color, alpha=0.3), fontsize=11, fontweight='bold') else: ax.text(0.5, 0.5, 'Gene level data\nnot available', transform=ax.transAxes, ha='center', va='center', fontsize=14, bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray')) def plot_summary_text(self, ax): """Plot summary statistics as text""" ax.axis('off') summary_text = f"Augustus Evaluation Summary\n" summary_text += f"Species: {self.species_name}\n\n" if 'nucleotide_sensitivity' in self.data: summary_text += f"🧬 Nucleotide Level:\n" summary_text += f" Sensitivity: {self.data['nucleotide_sensitivity']:.3f}\n" summary_text += f" Specificity: {self.data['nucleotide_specificity']:.3f}\n\n" if 'exon_sensitivity' in self.data: summary_text += f"📝 Exon Level:\n" summary_text += f" Sensitivity: {self.data['exon_sensitivity']:.3f}\n" summary_text += f" Specificity: {self.data['exon_specificity']:.3f}\n" summary_text += f" Predicted: {self.data['exon_pred_total']}\n" summary_text += f" Annotated: {self.data['exon_anno_total']}\n\n" if 'gene_sensitivity' in self.data: summary_text += f"🧲 Gene Level:\n" summary_text += f" Sensitivity: {self.data['gene_sensitivity']:.3f}\n" summary_text += f" Specificity: {self.data['gene_specificity']:.3f}\n" summary_text += f" Predicted: {self.data['gene_pred']}\n" summary_text += f" Annotated: {self.data['gene_anno']}\n" summary_text += f" True Positives: {self.data['gene_tp']}\n" summary_text += f" False Positives: {self.data['gene_fp']}\n" summary_text += f" False Negatives: {self.data['gene_fn']}\n\n" summary_text += "💡 Recommendations:\n" if 'gene_specificity' in self.data and self.data['gene_specificity'] < 0.7: summary_text += "• Reduce false positives\n" if 'gene_sensitivity' in self.data and self.data['gene_sensitivity'] < 0.7: summary_text += "• Improve gene detection\n" summary_text += "• Consider parameter tuning\n" summary_text += "• Use more training data\n" ax.text(0.05, 0.95, summary_text, transform=ax.transAxes, fontsize=11, verticalalignment='top', bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', alpha=0.3)) def save_dashboard(self, filename='augustus_dashboard.png', dpi=300): """Save the dashboard to file""" fig = self.create_performance_dashboard() fig.savefig(filename, dpi=dpi, bbox_inches='tight') plt.close(fig) print(f"Dashboard saved as: {filename}") return filename def show_dashboard(self): """Display the dashboard""" fig = self.create_performance_dashboard() plt.show() return fig
def main(): """Main function with example data""" evaluation_data = { 'nucleotide_sensitivity': 0.988, 'nucleotide_specificity': 0.911, 'exon_pred_total': 2893, 'exon_anno_total': 2742, 'exon_tp': 2027, 'exon_sensitivity': 0.739, 'exon_specificity': 0.701, 'gene_pred': 1139, 'gene_anno': 1008, 'gene_tp': 556, 'gene_fp': 583, 'gene_fn': 452, 'gene_sensitivity': 0.552, 'gene_specificity': 0.488, 'tss_pred': 40, 'tts_pred': 66, 'identical_paths': 1008 } visualizer = AugustusVisualizer(evaluation_data, 'Rice_35minicore_NLR') visualizer.explain_roc_limitations() print("\n" + "="*50) print("📊 生成可视化仪表板...") filename = visualizer.save_dashboard('augustus_performance_dashboard.png') print(f"\n✅ 可视化完成!") print(f"📁 文件保存为: {filename}") print("\n💡 虽然无法绘制标准ROC曲线,但我们提供了:") print(" 1. 敏感性vs特异性散点图") print(" 2. 性能指标对比图") print(" 3. 伪ROC曲线(显示可用点)") print(" 4. 混淆矩阵风格的分类结果") print(" 5. 精确度-召回率分析") print(" 6. 详细统计摘要")
if __name__ == '__main__': main()
|