File size: 20,539 Bytes
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
 
289289c
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289289c
330773d
 
 
 
 
 
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
289289c
330773d
 
289289c
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
330773d
289289c
 
330773d
 
 
 
 
 
 
289289c
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
 
 
 
 
 
 
289289c
 
 
 
330773d
 
 
289289c
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
330773d
 
 
289289c
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
b44284c
289289c
 
 
b44284c
 
289289c
 
330773d
289289c
330773d
289289c
 
 
 
b44284c
289289c
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
b44284c
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b44284c
289289c
b44284c
 
 
 
 
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b44284c
289289c
 
 
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330773d
289289c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b44284c
 
 
 
 
 
 
 
 
 
 
289289c
 
 
b44284c
289289c
 
b44284c
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class PrimerAnalyzer:
    def __init__(self):
        self.thermo_params = {
            'mv_conc': 50,
            'dv_conc': 0,
            'dntp_conc': 0.2,
            'dna_conc': 50,
            'temp_c': 37
        }
    
    def calculate_gc_content(self, sequence):
        """Calculate GC content percentage"""
        if not sequence:
            return 0
        gc_count = sequence.upper().count('G') + sequence.upper().count('C')
        return (gc_count / len(sequence)) * 100
    
    def calculate_tm(self, sequence):
        """Calculate melting temperature using basic Wallace rule"""
        if not sequence:
            return 0
        return 2 * sequence.upper().count('A') + 2 * sequence.upper().count('T') + \
               4 * sequence.upper().count('G') + 4 * sequence.upper().count('C')
    
    def check_self_complementarity(self, sequence):
        """Check for self-complementarity"""
        if not sequence:
            return 0
            
        rev_comp = self.reverse_complement(sequence)
        max_complementarity = 0
        
        for i in range(len(sequence) - 4):
            for j in range(4, min(8, len(sequence) - i)):
                if sequence[i:i+j] in rev_comp:
                    max_complementarity = max(max_complementarity, j)
        
        return max_complementarity
    
    def reverse_complement(self, sequence):
        """Generate reverse complement"""
        comp_map = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'N': 'N'}
        return ''.join(comp_map.get(base, base) for base in sequence.upper()[::-1])
    
    def predict_secondary_structure(self, sequence):
        """Predict likelihood of secondary structure formation"""
        if not sequence:
            return 0
        hairpin_potential = sum(1 for i in range(len(sequence)-4) 
                              if sequence[i:i+2] == sequence[i+2:i+4][::-1])
        return hairpin_potential / len(sequence)
    
    def calculate_quality_score(self, analysis):
        """Calculate overall primer quality score"""
        score = 0
        
        # Length check (18-25 bp ideal)
        if 18 <= analysis['length'] <= 25:
            score += 25
        else:
            score -= 10
        
        # GC content (40-60% ideal)
        if 40 <= analysis['gc_content'] <= 60:
            score += 25
        else:
            score -= 10
        
        # TM check (55-65°C ideal)
        if 55 <= analysis['tm'] <= 65:
            score += 25
        else:
            score -= 10
        
        # Self-complementarity (max 4bp acceptable)
        if analysis['self_complementarity'] <= 4:
            score += 15
        else:
            score -= 10
        
        # Secondary structure risk
        if analysis['secondary_structure_risk'] < 0.1:
            score += 10
        
        return max(0, min(100, score))
    
    def analyze_primer(self, sequence):
        """Comprehensive primer analysis"""
        if not sequence or len(sequence) < 10:
            return {
                'sequence': sequence,
                'length': len(sequence) if sequence else 0,
                'gc_content': 0,
                'tm': 0,
                'self_complementarity': 0,
                'secondary_structure_risk': 0,
                'quality_score': 0
            }
        
        # Validate sequence contains only DNA bases
        valid_bases = {'A', 'T', 'G', 'C', 'N'}
        sequence_clean = ''.join(base for base in sequence.upper() if base in valid_bases)
        
        if len(sequence_clean) < 10:
            return {
                'sequence': sequence,
                'length': len(sequence),
                'gc_content': 0,
                'tm': 0,
                'self_complementarity': 0,
                'secondary_structure_risk': 0,
                'quality_score': 0
            }
        
        analysis = {
            'sequence': sequence_clean,
            'length': len(sequence_clean),
            'gc_content': self.calculate_gc_content(sequence_clean),
            'tm': self.calculate_tm(sequence_clean),
            'self_complementarity': self.check_self_complementarity(sequence_clean),
            'secondary_structure_risk': self.predict_secondary_structure(sequence_clean)
        }
        
        # Quality assessment
        analysis['quality_score'] = self.calculate_quality_score(analysis)
        
        return analysis

class PrimerDesignUI:
    def __init__(self):
        self.analyzer = PrimerAnalyzer()
        self.model = None
        self.tokenizer = None
        self.load_default_model()
    
    def load_default_model(self):
        """Try to load a compatible default model"""
        try:
            # Use a more compatible model - distilbert is widely supported
            model_name = "distilbert-base-uncased"
            self.tokenizer = AutoTokenizer.from_pretrained(model_name)
            self.model = AutoModelForSequenceClassification.from_pretrained(
                model_name, 
                num_labels=3
            )
            logger.info("Loaded DistilBERT model successfully")
        except Exception as e:
            logger.warning(f"Could not load model: {e}. Using analytical mode only.")
            self.model = None
            self.tokenizer = None
    
    def predict_primer_quality(self, sequence):
        """Predict primer quality using model"""
        if self.model is None or self.tokenizer is None or not sequence:
            return "Analytical Mode", 0.0
        
        try:
            # Validate sequence first
            valid_bases = {'A', 'T', 'G', 'C', 'N'}
            sequence_clean = ''.join(base for base in sequence.upper() if base in valid_bases)
            
            if len(sequence_clean) < 10:
                return "Invalid Sequence", 0.0
            
            inputs = self.tokenizer(
                sequence_clean, 
                return_tensors="pt", 
                padding=True, 
                truncation=True, 
                max_length=128
            )
            
            with torch.no_grad():
                outputs = self.model(**inputs)
                predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
                predicted_class = torch.argmax(predictions, dim=1).item()
                confidence = predictions[0][predicted_class].item()
            
            quality_labels = {0: "Poor", 1: "Average", 2: "Good"}
            return quality_labels[predicted_class], confidence
        except Exception as e:
            logger.error(f"Prediction error: {e}")
            return "Error in prediction", 0.0
    
    def create_analysis_plots(self, analysis):
        """Create visualization plots for primer analysis"""
        try:
            # Create subplots
            fig = make_subplots(
                rows=2, cols=2,
                subplot_titles=('GC Content Analysis', 'Length Distribution', 
                              'Melting Temperature', 'Quality Metrics'),
                specs=[[{"type": "indicator"}, {"type": "bar"}],
                       [{"type": "indicator"}, {"type": "pie"}]]
            )
            
            # GC Content gauge
            fig.add_trace(go.Indicator(
                mode = "gauge+number+delta",
                value = analysis['gc_content'],
                domain = {'x': [0, 1], 'y': [0, 1]},
                title = {'text': "GC Content (%)"},
                gauge = {
                    'axis': {'range': [0, 100]},
                    'bar': {'color': "darkblue"},
                    'steps': [
                        {'range': [0, 40], 'color': "lightgray"},
                        {'range': [40, 60], 'color': "lightgreen"},
                        {'range': [60, 100], 'color': "lightcoral"}
                    ],
                    'threshold': {
                        'line': {'color': "red", 'width': 4},
                        'thickness': 0.75,
                        'value': 50
                    }
                }
            ), row=1, col=1)
            
            # Length comparison
            ideal_lengths = [18, 20, 22, 24, 25]
            length_quality = [abs(analysis['length'] - l) for l in ideal_lengths]
            
            fig.add_trace(go.Bar(
                x=ideal_lengths,
                y=length_quality,
                name="Length Deviation",
                marker_color='coral'
            ), row=1, col=2)
            
            # Melting Temperature gauge
            fig.add_trace(go.Indicator(
                mode = "gauge+number+delta",
                value = analysis['tm'],
                domain = {'x': [0, 1], 'y': [0, 1]},
                title = {'text': "Melting Temp (°C)"},
                gauge = {
                    'axis': {'range': [0, 100]},
                    'bar': {'color': "darkblue"},
                    'steps': [
                        {'range': [0, 55], 'color': "lightgray"},
                        {'range': [55, 65], 'color': "lightgreen"},
                        {'range': [65, 100], 'color': "lightcoral"}
                    ]
                }
            ), row=2, col=1)
            
            # Quality score pie chart
            quality_components = {
                'Length': min(25, max(0, 25 - abs(analysis['length'] - 21.5) * 2)),
                'GC Content': min(25, max(0, 25 - abs(analysis['gc_content'] - 50) / 2)),
                'TM': min(25, max(0, 25 - abs(analysis['tm'] - 60) / 2)),
                'Specificity': min(15, max(0, 15 - analysis['self_complementarity'] * 3)),
                'Structure': min(10, max(0, 10 - analysis['secondary_structure_risk'] * 100))
            }
            
            fig.add_trace(go.Pie(
                labels=list(quality_components.keys()),
                values=list(quality_components.values()),
                name="Quality Components"
            ), row=2, col=2)
            
            fig.update_layout(
                height=600, 
                showlegend=False, 
                template="plotly_white",
                title_text="Primer Analysis Dashboard",
                title_x=0.5
            )
            return fig
        except Exception as e:
            logger.error(f"Plot creation error: {e}")
            # Return empty figure on error
            return go.Figure().update_layout(
                title={"text": "Error creating visualization", "x": 0.5}
            )
    
    def generate_recommendations(self, analysis):
        """Generate recommendations for primer improvement"""
        if analysis['length'] < 10:
            return "Please enter a valid primer sequence (minimum 10 bases containing only A, T, G, C)."
            
        recommendations = []
        
        # Length recommendations
        if analysis['length'] < 18:
            recommendations.append("❌ Primer too short. Increase length to 18-25 bp.")
        elif analysis['length'] > 25:
            recommendations.append("❌ Primer too long. Decrease length to 18-25 bp.")
        else:
            recommendations.append("✅ Primer length is optimal.")
        
        # GC content recommendations
        if analysis['gc_content'] < 40:
            recommendations.append("❌ GC content too low. Aim for 40-60%.")
        elif analysis['gc_content'] > 60:
            recommendations.append("❌ GC content too high. Aim for 40-60%.")
        else:
            recommendations.append("✅ GC content is optimal.")
        
        # TM recommendations
        if analysis['tm'] < 55:
            recommendations.append("❌ Melting temperature too low. Aim for 55-65°C.")
        elif analysis['tm'] > 65:
            recommendations.append("❌ Melting temperature too high. Aim for 55-65°C.")
        else:
            recommendations.append("✅ Melting temperature is optimal.")
        
        # Self-complementarity recommendations
        if analysis['self_complementarity'] > 4:
            recommendations.append(f"⚠️ High self-complementarity ({analysis['self_complementarity']}bp). Consider redesign.")
        else:
            recommendations.append("✅ Self-complementarity is acceptable.")
        
        # Secondary structure recommendations
        if analysis['secondary_structure_risk'] > 0.1:
            recommendations.append("⚠️ Potential secondary structure issues detected.")
        else:
            recommendations.append("✅ Secondary structure risk is low.")
        
        return "\n".join(recommendations)
    
    def batch_analyze_sequences(self, sequences_text):
        """Analyze multiple sequences at once"""
        if not sequences_text:
            return pd.DataFrame()
            
        sequences = [seq.strip() for seq in sequences_text.split('\n') if seq.strip()]
        results = []
        
        for seq in sequences:
            if len(seq) < 10:  # Basic validation
                continue
                
            analysis = self.analyzer.analyze_primer(seq)
            quality_pred, confidence = self.predict_primer_quality(seq)
            
            results.append({
                'Sequence': seq[:30] + "..." if len(seq) > 30 else seq,
                'Length': analysis['length'],
                'GC%': round(analysis['gc_content'], 2),
                'TM': round(analysis['tm'], 2),
                'SelfComp': analysis['self_complementarity'],
                'QualityScore': round(analysis['quality_score'], 2),
                'AIPrediction': quality_pred,
                'Confidence': round(confidence, 3)
            })
        
        if not results:
            return pd.DataFrame({"Message": ["No valid sequences found"]})
        
        return pd.DataFrame(results)
    
    def create_primer_analysis_dashboard(self, sequence):
        """Create comprehensive analysis dashboard"""
        if not sequence or len(sequence) < 10:
            return 0, go.Figure(), "Please enter a valid primer sequence (minimum 10 bases containing only A, T, G, C).", "N/A", 0.0
            
        analysis = self.analyzer.analyze_primer(sequence)
        fig = self.create_analysis_plots(analysis)
        recommendations = self.generate_recommendations(analysis)
        quality_pred, confidence = self.predict_primer_quality(sequence)
        
        return analysis['quality_score'], fig, recommendations, quality_pred, confidence

# Create the Gradio interface with minimal configuration
def create_demo():
    analyzer_ui = PrimerDesignUI()
    
    # Use simplest Blocks initialization
    with gr.Blocks() as demo:
        gr.Markdown("""
        # 🧬 Advanced Primer Design & Analysis
        **AI-Powered Primer Quality Assessment**
        
        *Analyze single primers or batch process multiple sequences with comprehensive quality metrics*
        """)
        
        with gr.Tab("🧪 Single Primer Analysis"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Primer Input")
                    sequence_input = gr.Textbox(
                        label="Primer Sequence",
                        placeholder="Enter DNA sequence (e.g., ATGCATGCATGCATGCATGC)",
                        value="ATCGATCGATCGATCGATCGATCG"
                    )
                    
                    analyze_btn = gr.Button("Analyze Primer", variant="primary")
                    
                    with gr.Accordion("💡 Example Sequences", open=False):
                        gr.Markdown("""
                        **Good Primer:** `ATCGATCGATCGATCGATCGATCG`  
                        **Short Primer:** `ATCGATCGATCG`  
                        **High GC:** `GGCCGGCCGGCCGGCCGGCCGGCC`  
                        **Low GC:** `ATATATATATATATATATATATAT`
                        """)
                
                with gr.Column():
                    gr.Markdown("### AI Assessment")
                    with gr.Row():
                        quality_output = gr.Textbox(
                            label="AI Quality Prediction",
                            interactive=False
                        )
                        confidence_output = gr.Number(
                            label="Confidence Score",
                            interactive=False
                        )
                    score_output = gr.Number(
                        label="Overall Quality Score",
                        interactive=False
                    )
            
            gr.Markdown("### 📊 Comprehensive Analysis Dashboard")
            analysis_plot = gr.Plot()
            
            recommendations_output = gr.Textbox(
                label="🔍 Recommendations & Improvements",
                lines=4,
                interactive=False
            )
        
        with gr.Tab("📊 Batch Analysis"):
            gr.Markdown("### Analyze Multiple Primers")
            with gr.Row():
                with gr.Column():
                    batch_input = gr.Textbox(
                        label="Primer Sequences (one per line)",
                        placeholder="ATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTA\nTTTTTTTTTTTTTTTTTTTTTTTT\n...",
                        lines=10,
                        value="ATCGATCGATCGATCGATCGATCG\nGCTAGCTAGCTAGCTAGCTAGCTA\nCCCCCCCCCCCCCCCCCCCCCCCC\nATATATATATATATATATATATAT"
                    )
                    batch_btn = gr.Button("Analyze All Primers", variant="primary")
                
                with gr.Column():
                    batch_output = gr.Dataframe(
                        label="Batch Analysis Results",
                        wrap=True
                    )
        
        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
            ## About This Tool
            
            This AI-powered primer analysis system provides:
            
            ### 🔬 Key Features
            - **AI Quality Prediction**: Transformer model for primer quality assessment
            - **Comprehensive Analysis**: GC content, melting temperature, self-complementarity, secondary structure
            - **Batch Processing**: Analyze multiple primers simultaneously
            - **Visual Analytics**: Interactive dashboards with detailed metrics
            
            ### 🧪 Analysis Parameters
            - **GC Content**: Optimal range 40-60%
            - **Length**: Optimal range 18-25 bp
            - **Melting Temperature**: Optimal range 55-65°C
            - **Self-complementarity**: Maximum 4 bp allowed
            - **Secondary Structure**: Minimal hairpin formation
            
            ### 🚀 How to Use
            1. Enter a DNA sequence in the Single Primer Analysis tab
            2. Click "Analyze Primer" for comprehensive assessment
            3. View AI predictions and quality scores
            4. Use recommendations to optimize your primers
            5. For multiple primers, use the Batch Analysis tab
            
            *Note: Sequences should contain only A, T, G, C bases (N is also accepted)*
            """)
        
        # Event handlers
        analyze_btn.click(
            fn=analyzer_ui.create_primer_analysis_dashboard,
            inputs=[sequence_input],
            outputs=[score_output, analysis_plot, recommendations_output, quality_output, confidence_output]
        )
        
        batch_btn.click(
            fn=analyzer_ui.batch_analyze_sequences,
            inputs=[batch_input],
            outputs=[batch_output]
        )
        
        # Examples
        gr.Examples(
            examples=[
                ["ATCGATCGATCGATCGATCGATCG"],  # Good primer
                ["ATCGATCGATCG"],              # Too short
                ["GGCCGGCCGGCCGGCCGGCCGGCC"],  # High GC
                ["ATATATATATATATATATATATAT"],  # Low GC
            ],
            inputs=sequence_input,
            outputs=[score_output, analysis_plot, recommendations_output, quality_output, confidence_output],
            fn=analyzer_ui.create_primer_analysis_dashboard
        )
    
    return demo

# Launch the application
if __name__ == "__main__":
    demo = create_demo()
    demo.launch()