primerJinn 1.0.0.dev2__tar.gz → 1.0.0.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of primerJinn might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: primerJinn
3
- Version: 1.0.0.dev2
3
+ Version: 1.0.0.dev3
4
4
  Summary: In silico PCR tool
5
5
  Home-page: https://github.com/SemiQuant/primerJinn
6
6
  Author: Jason D Limberis
@@ -0,0 +1,268 @@
1
+ #!/bin/python3
2
+ import os
3
+ import pandas as pd
4
+ from Bio.Seq import Seq
5
+ from Bio.SeqUtils import MeltingTemp
6
+ from Bio import SeqIO
7
+ import argparse
8
+ import itertools
9
+ import json
10
+ import requests
11
+ import primer3
12
+
13
+ # Define the arguments to be parsed
14
+ parser = argparse.ArgumentParser(description='PCR parameter inputs')
15
+ parser.add_argument('--target_tm', type=int, help='Annealing temperature (in Celsius)', default = 55.0)
16
+ parser.add_argument('--salt_concentration', type=float, help='Salt concentration (in nM)', default = 50)
17
+ parser.add_argument('--product_size_max', type=float, help='maximum length of PCR products in nucleotides', default = 2000)
18
+ parser.add_argument('--req_five', type=str, help="Require the 5' end of the primer to bind?", default = True)
19
+ parser.add_argument('--primer_seq', type=str, help="Primer sequences, one per line", required = True)
20
+ parser.add_argument('--input_file', type=str, help="Reference FASTA file", required = True)
21
+ parser.add_argument('--output', type=str, help="Output file name", default = "in_silico_PCR")
22
+ parser.add_argument('--Q5', action='store_true', help='Whether to use Q5 approximation settings for Tm calculations.', default=False)
23
+
24
+ # check if blastn is in the system path
25
+ try:
26
+ status = os.system('which blastn > /dev/null 2>&1')
27
+ if status != 0:
28
+ print('Error: BLAST is not installed.')
29
+ exit(1)
30
+ except OSError as e:
31
+ print('Error:', e)
32
+ exit(1)
33
+
34
+ # Check if required arguments are missing and print help message
35
+ args = parser.parse_args()
36
+ if not args.primer_seq or not args.input_file:
37
+ parser.print_help()
38
+ exit()
39
+
40
+ # Define the inputs
41
+ annealing_temp = args.target_tm - 4
42
+ salt_conc = args.salt_concentration
43
+ max_amplicon_len = args.product_size_max
44
+ req_five = args.req_five
45
+ primer_seq = args.primer_seq
46
+ ref_fasta_file = args.input_file
47
+ out_file = args.output
48
+
49
+
50
+ def q5_melting_temp(seq1, seq2, salt=0.5):
51
+ url = "https://tmapi.neb.com/tm/q5/%s/%s/%s?&fmt=short" % (salt, seq1, seq2)
52
+ response = requests.get(url)
53
+ json_string = response.json()
54
+ tm1 = json_string["data"]["tm1"]
55
+ tm2 = json_string["data"]["tm2"]
56
+ return [tm1, tm2]
57
+
58
+ def calc_tm(seq, seq2='', Q5=args.Q5):
59
+ if Q5:
60
+ # tm = MeltingTemp.Tm_NN(seq, c_seq = seq2, nn_table=MeltingTemp.DNA_NN4, dnac1=2500, dnac2=2500, Na=40, K=0, Tris=0, Mg=0.4, dNTPs=0, saltcorr=5.0)
61
+ # tm = q5_melting_temp(str(seq), str(seq2), salt_conc/1000)
62
+ if seq2 != '':
63
+ tm = primer3.bindings.calcTm(seq, dv_conc=2, mv_conc=70, dna_conc=3300)
64
+ else:
65
+ primer3.calcHeterodimer(seq, seq2, temp_c=100, dv_conc = 2, mv_conc = 70, dna_conc = 3300)
66
+ else:
67
+ tm = MeltingTemp.Tm_NN(seq, c_seq = seq2, Na=salt_conc, dnac1=250, dnac2=0, saltcorr=7, nn_table=MeltingTemp.DNA_NN4, selfcomp=False, check=True, shift=0.0)
68
+ return tm
69
+
70
+ def find_binding_positions(primer_seq, ref_fasta_file, annealing_temp, req_five, salt_conc):
71
+ # Run BLAST to search for primer sequence against reference FASTA
72
+ blast_cmd = f"blastn -query {primer_seq} -subject {ref_fasta_file} -task blastn-short -outfmt '6 qseqid sseqid qstart qend sstart send qseq sseq mismatch length' > blast_output.txt"
73
+ os.system(blast_cmd)
74
+
75
+ blast_df = pd.DataFrame(columns=['Query ID', 'Subject ID', 'Query Start', 'Query End', 'Subject Start', 'Subject End', 'Query Sequence Match', 'Direction', 'Binding Position', 'Mismatches', 'Binding Length'])
76
+
77
+ with open('blast_output.txt', 'r') as f:
78
+ for line in f:
79
+ fields = line.strip().split('\t')
80
+ qseqid, sseqid, qstart, qend, sstart, send, qseq, sseq, mismatch, length = fields
81
+ direction = '+' if int(sstart) < int(send) else '-'
82
+ binding_pos = sstart if direction == '+' else send
83
+ # Check if primer binds at the specified annealing temperature
84
+ if req_five and int(qstart) >= 2:
85
+ continue
86
+ # tm = MeltingTemp.Tm_NN(Seq(sseq), Na=salt_conc, dnac1=250, dnac2=0, saltcorr=7, nn_table=MeltingTemp.DNA_NN4, selfcomp=False, check=True, shift=0.0)
87
+ tm = calc_tm(Seq(sseq))
88
+ if annealing_temp <= tm:
89
+ blast_df.loc[len(blast_df)] = [qseqid, sseqid, qstart, qend, sstart, send, sseq, direction, binding_pos, mismatch, length]
90
+ return blast_df
91
+
92
+ def find_compatible_pairs(blast_df, max_len):
93
+ pairs = itertools.combinations(blast_df.index, 2)
94
+ compatible_pairs = []
95
+ for pair in pairs:
96
+ row1 = blast_df.loc[pair[0]]
97
+ row2 = blast_df.loc[pair[1]]
98
+ amp_size = int(row1['Binding Position']) - int(row2['Binding Position'])
99
+ if abs(amp_size) <= max_len and row1['Direction'] != row2['Direction'] and row1['Subject ID'] == row2['Subject ID']:
100
+ if row1['Direction'] == '+' and amp_size < 0:
101
+ compatible_pairs.append({'qseq1': row1['Query Seq'], 'qseq1_input': row1['Sequence'], 'qstart1': row1['Query Start'], 'qend1': row1['Query End'], 'direction1': row1['Direction'], 'mismatch1': row1['Mismatches'],
102
+ 'qseq2': row2['Query Seq'], 'qseq2_input': row2['Sequence'], 'qstart2': row2['Query Start'], 'qend2': row2['Query End'], 'direction2': row2['Direction'], 'mismatch2': row2['Mismatches'],
103
+ 'binding_pos_diff': abs(amp_size), 'reference': row1['Subject ID'], 'ref_region': str(row2['Binding Position']) + ", " + str(row1['Binding Position'])})
104
+ elif row1['Direction'] == '-' and amp_size > 0:
105
+ compatible_pairs.append({'qseq1': row2['Query Seq'], 'qseq2_input': row2['Sequence'], 'qstart1': row2['Query Start'], 'qend1': row2['Query End'], 'direction1': row2['Direction'], 'mismatch2': row2['Mismatches'],
106
+ 'qseq2': row1['Query Seq'], 'qseq1_input': row1['Sequence'], 'qstart2': row1['Query Start'], 'qend2': row1['Query End'], 'direction2': row1['Direction'], 'mismatch1': row1['Mismatches'],
107
+ 'binding_pos_diff': abs(amp_size), 'reference': row1['Subject ID'], 'ref_region': str(row1['Binding Position']) + ", " + str(row2['Binding Position'])})
108
+ else:
109
+ continue
110
+ return pd.DataFrame(compatible_pairs)
111
+
112
+ def find_oligo_dimers(fasta_file, temp, salt_conc):
113
+ # Read in the fasta sequences
114
+ seq_records = list(SeqIO.parse(fasta_file, "fasta"))
115
+
116
+ # Create a list to hold the dimer pairs and melting temperatures
117
+ dimers = []
118
+ melting_temps = []
119
+
120
+ # Loop through all possible pairs of sequences
121
+ for seq1, seq2 in itertools.combinations(seq_records, 2):
122
+ # Calculate the melting temperature of the dimer
123
+ # dimer_tm = MeltingTemp.Tm_NN(str(seq1.seq + seq2.seq), nn_table=MeltingTemp.DNA_NN4, Na=salt_conc, saltcorr=7)
124
+ dimer_tm = calc_tm(str(seq1.seq + seq2.seq))
125
+
126
+ # Check if the dimer's melting temperature is above the given temperature
127
+ if dimer_tm > temp:
128
+ # Add the dimer's names and melting temperature to the lists
129
+ dimers.append((seq1.id, seq2.id))
130
+ melting_temps.append(round(dimer_tm))
131
+
132
+ # Create a pandas dataframe from the dimer pairs and melting temperatures
133
+ df = pd.DataFrame({'Sequence1': [d[0] for d in dimers],
134
+ 'Sequence2': [d[1] for d in dimers],
135
+ 'MeltingTemp': melting_temps})
136
+
137
+ return df
138
+
139
+ def is_valid_dna_sequence(sequence):
140
+ """Checks if a DNA sequence only contains valid characters."""
141
+ valid_chars = set('ACGTN')
142
+ return all(char in valid_chars for char in sequence.upper())
143
+
144
+ def main():
145
+ i=0
146
+ with open(primer_seq, 'r') as infile, open(primer_seq+'.fasta', 'w') as outfile:
147
+ # Initialize a dictionary to keep track of sequence names
148
+ seen_names = {}
149
+ i+=1
150
+ for line in infile:
151
+ columns = line.strip().split('\t')
152
+ if len(columns) == 1:
153
+ # Remove any leading/trailing whitespace from the sequence
154
+ sequence = line.strip()
155
+ if not (is_valid_dna_sequence(sequence)):
156
+ print("error in sequence on: " + line)
157
+ break
158
+ # Generate a unique sequence name
159
+ name = f'sequence{i}'
160
+ else:
161
+ sequence, name = columns
162
+ if not (is_valid_dna_sequence(sequence)):
163
+ print("error in sequence on: " + name)
164
+ break
165
+ # Check if the name has already been used
166
+ if name in seen_names:
167
+ # Increment the count for this name
168
+ count = seen_names[name] + 1
169
+ # Generate a new name by appending the count to the original name
170
+ new_name = f'{name}_{count}'
171
+ # Update the dictionary with the new count
172
+ seen_names[name] = count
173
+ # Use the new name for the sequence
174
+ name = new_name
175
+ else:
176
+ # Add the name to the dictionary with a count of 1
177
+ seen_names[name] = 1
178
+ # Write the sequence to the output file in FASTA format
179
+ outfile.write(f'>{name}\n{sequence}\n')
180
+
181
+
182
+ # primer dimers
183
+ dimers = find_oligo_dimers(primer_seq+'.fasta', annealing_temp, salt_conc)
184
+ # print("Writing output to " + out_file + '_primer_dimears.tsv')
185
+ # dimers.to_csv(out_file + '_primer_dimers.tsv', index=False, sep="\t")
186
+
187
+
188
+ blast_df = find_binding_positions(primer_seq+'.fasta', ref_fasta_file, annealing_temp, req_five, salt_conc)
189
+
190
+ # Read in the FASTA file as a dictionary of SeqRecord objects
191
+ fasta_dict = SeqIO.to_dict(SeqIO.parse(primer_seq+'.fasta', "fasta"))
192
+
193
+ # Iterate through the rows of the DataFrame and replace the add primer with sequences
194
+ for i, row in blast_df.iterrows():
195
+ query_id = row["Query ID"]
196
+ if query_id in fasta_dict:
197
+ sequence = str(fasta_dict[query_id].seq)
198
+ blast_df.at[i, "Sequence"] = sequence
199
+ else:
200
+ blast_df.at[i, "Sequence"] = ""
201
+
202
+ blast_df = blast_df.rename(columns={'Query ID': 'Query Seq'})
203
+
204
+ amp_df = find_compatible_pairs(blast_df, max_len=max_amplicon_len)
205
+ # print("Writing output to " + out_file + '.tsv')
206
+ # amp_df.to_csv(out_file + '.tsv', index=False, sep="\t")
207
+
208
+
209
+
210
+ # get interactions
211
+ amplicons = []
212
+ ref_seq = SeqIO.read(ref_fasta_file, "fasta").seq
213
+ for index, row in amp_df.iterrows():
214
+ ref_region = row['ref_region']
215
+ #add in the primer sequences
216
+ if row['direction1'] == '-':
217
+ pf_seq = Seq(row['qseq1_input'])
218
+ pf_seq = str(pf_seq.reverse_complement())
219
+ else:
220
+ pf_seq = Seq(row['qseq1_input'])
221
+ if row['direction2'] == '-':
222
+ pr_seq = Seq(row['qseq2_input'])
223
+ pr_seq = str(pf_seq.reverse_complement())
224
+ else:
225
+ pr_seq = Seq(row['qseq2_input'])
226
+ ref_start, ref_end = ref_region.split(",")
227
+ ref_end = int(ref_end)
228
+ ref_start = int(ref_start)
229
+ if ref_start > ref_end:
230
+ amplicon_seq = ref_seq[ref_end-1:ref_start]
231
+ else:
232
+ amplicon_seq = ref_seq[ref_start-1:ref_end]
233
+ amplicon_seq = str(pf_seq) + str(amplicon_seq) + str(pr_seq)
234
+ amplicons.append({'Forward_primer': row['qseq1'], 'Reverse_primer': row['qseq2'], 'amplicon_seq': amplicon_seq})
235
+
236
+
237
+ tm_data = []
238
+ for pair in itertools.combinations(amplicons, 2):
239
+ # tm = MeltingTemp.Tm_NN(pair[0]['amplicon_seq'], pair[1]['amplicon_seq'], Na=salt_conc, saltcorr=7)
240
+ try:
241
+ tm = calc_tm(seq=pair[0]['amplicon_seq'], seq2=pair[1]['amplicon_seq'])
242
+ tm_data.append({"amplicon1_PF": pair[0]['Forward_primer'],
243
+ "amplicon1_PR": pair[0]['Reverse_primer'],
244
+ "amplicon2_PF": pair[1]['Forward_primer'],
245
+ "amplicon2_PR": pair[1]['Reverse_primer'],
246
+ 'tm': str(tm)})
247
+ except:
248
+ continue
249
+
250
+ tm_df = pd.DataFrame(tm_data)
251
+ # print("Writing output to " + out_file + '_amplicon_interactions.tsv')
252
+ # tm_df.to_csv(out_file + '_amplicon_interactions.tsv', index=False, sep="\t")
253
+
254
+
255
+ with pd.ExcelWriter(out_file + '.xlsx', engine='xlsxwriter') as writer:
256
+ amp_df.to_excel(writer, sheet_name='amplicons', index=False)
257
+ dimers.to_excel(writer, sheet_name='dimers', index=False)
258
+ tm_df.to_excel(writer, sheet_name='interactions', index=False)
259
+
260
+ # cleanup
261
+ os.remove(primer_seq+'.fasta')
262
+ os.remove("blast_output.txt")
263
+
264
+
265
+ if __name__ == '__main__':
266
+ main()
267
+
268
+
File without changes
@@ -0,0 +1,520 @@
1
+ #!/bin/python
2
+ from Bio import SeqIO
3
+ from Bio.SeqUtils import MeltingTemp as mt
4
+ from Bio.Seq import Seq
5
+ from Bio.SeqRecord import SeqRecord
6
+ import primer3
7
+ import pandas as pd
8
+ import itertools
9
+ import argparse
10
+ import numpy as np
11
+ import concurrent.futures
12
+ import sys
13
+ import random
14
+ import requests
15
+ from sklearn.cluster import AgglomerativeClustering
16
+ import tempfile
17
+ import subprocess
18
+ import shutil
19
+ import os
20
+ # import matplotlib.pyplot as plt
21
+
22
+ parser = argparse.ArgumentParser(description='PCR primer design')
23
+ # Define input arguments
24
+ # parser.add_argument('--cpus', type=int, help='number of threads (even though it says cpus)', default=1000)
25
+ parser.add_argument('--region_file', type=str, help='The path to the primer design region file. Two columns, start position and end position (1-based). tsv or xlxs', required=True)
26
+ parser.add_argument('--input_file', type=str, help="Reference FASTA file", required = True)
27
+ parser.add_argument('--target_tm', type=float, help='The desired melting temperature (Tm) for the primers.', default=65)
28
+ parser.add_argument('--primer_len', type=int, help='The desired length of the primers.', default=20)
29
+ parser.add_argument('--product_size_min', type=int, help='The desired min size for the PCR product. Default is 400.', default=400)
30
+ parser.add_argument('--product_size_max', type=int, help='The desired max size for the PCR product. Default is 800.', default=800)
31
+ parser.add_argument('--ret', type=int, help='The maximum number of primer pairs to return.', default=100)
32
+ parser.add_argument('--Q5', action='store_true', help='Whether to use Q5 approximation settings for Tm calculations.', default=True)
33
+ parser.add_argument('--background', type=str, help='The path to the mispriming library FASTA file.', default='')
34
+ parser.add_argument('--output', type=str, help='Output name.', default='MultiPlexPrimerSet')
35
+ parser.add_argument('--eval', type=int, help='The maximum number of primer sets to evaluate.', default=10000)
36
+ parser.add_argument('--wiggle', type=int, help='Half the region around the optimal Tm', default=3)
37
+ parser.add_argument('--ill_adapt', action='store_true', help='Add Illumina partial adapters', default=False)
38
+ parser.add_argument('--clamp', type=int, help='Require GC clamp', default=0)
39
+ parser.add_argument('--poly', type=int, help='Maximum allowable length of a mononucleotide repeat (poly-X) in the primer sequence', default=3)
40
+ args = parser.parse_args()
41
+
42
+ product_size_range = (args.product_size_min, args.product_size_max)
43
+
44
+ def design_primers(input_file, region_start, region_end, target_tm=args.target_tm, primer_len=20, product_size_range=(400, 800), name='', ret=100, Q5=True, background='', wiggle=args.wiggle, clamp=args.clamp, poly=args.poly):
45
+ """
46
+ This function takes a FASTA file, start and end positions of a target region, and desired melting temperature
47
+ and primer length, and returns the best primer set for that region using Biopython and primer3.
48
+
49
+ Args:
50
+ input_file (str): The path to the input FASTA file.
51
+ region_start (int): The start position of the target region (1-based).
52
+ region_end (int): The end position of the target region (1-based).
53
+ target_tm (float): The desired melting temperature (Tm) for the primers.
54
+ primer_len (int): The desired length of the primers.
55
+ product_size_range (tuple): The desired size range for the PCR product.
56
+ name (str): The name of the primer set.
57
+ ret (int): The maximum number of primer pairs to return.
58
+ Q5 (bool): Whether to use Q5 settings for primer3.
59
+ background (str): The name of a mispriming library to use for primer3.
60
+
61
+ Returns:
62
+ list: A list of dicts containing information about the primer pairs.
63
+ """
64
+
65
+ # Parse the input FASTA file and extract the target region sequence.
66
+ # it seems that primer3 doesnt look for non-specificity in the input file, so need to append the target non-regions to the background fasta.
67
+ print("Picking initial primers for " + name)
68
+ # giving issues on some systems because of the -i flag
69
+ # command = "sed -i '$d;$d' " + background
70
+ # subprocess.run(command, shell=True)
71
+ # Create a temporary file to hold the modified output
72
+ with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
73
+ # Use sed to remove the last two lines from the input file and write the result to the temporary file
74
+ subprocess.run(f"sed '$d;$d' '{background}'", stdout=tmp_file, shell=True)
75
+
76
+ # Move the temporary file over the original file
77
+ shutil.move(tmp_file.name, background)
78
+
79
+ if region_start - 10000 > 0:
80
+ target_seq = input_file.seq[region_start-10000:region_end+10000]
81
+ seq_target = (10000-1, region_end-region_start)
82
+ add_to = 10000
83
+ with open(background, "a") as fasta_file:
84
+ fasta_file.write(">appended_sequence\n")
85
+ fasta_file.write(str(input_file.seq[0:region_start-10000]) + "\n")
86
+ fasta_file.write(">appended_sequence2\n")
87
+ fasta_file.write(str(input_file.seq[region_end+10000:]) + "\n")
88
+ else:
89
+ target_seq = input_file.seq[0:region_end+10000]
90
+ seq_target = (region_start-1, region_end-region_start)
91
+ add_to = 0
92
+ with open(background, "a") as fasta_file:
93
+ fasta_file.write(">appended_sequence\n")
94
+ fasta_file.write(str(input_file.seq[region_end+10000:]) + "\n")
95
+ fasta_file.write(">appended_sequence2\n")
96
+ fasta_file.write("gagagagaga" + "\n")
97
+
98
+
99
+ # target_seq = input_file.seq
100
+ # seq_target = (region_start-1, region_end-region_start+2)
101
+
102
+ # Set up the primer3 input parameters.
103
+ input_params = {
104
+ 'SEQUENCE_ID': record.id,
105
+ 'SEQUENCE_TEMPLATE': str(target_seq),
106
+ 'SEQUENCE_TARGET': seq_target,
107
+ 'PRIMER_OPT_SIZE': primer_len,
108
+ 'PRIMER_MIN_SIZE' : primer_len - 10,
109
+ 'PRIMER_MAX_SIZE' : primer_len + 20,
110
+ 'PRIMER_PICK_INTERNAL_OLIGO': 0,
111
+ 'PRIMER_MISPRIMING_LIBRARY': background,
112
+ }
113
+
114
+ global_args = {
115
+ 'PRIMER_MIN_GC': 40,
116
+ 'PRIMER_MAX_GC': 80,
117
+ 'PRIMER_NUM_RETURN': ret,
118
+ 'PRIMER_EXPLAIN_FLAG': 1,
119
+ 'PRIMER_MIN_TM': target_tm-wiggle,
120
+ 'PRIMER_OPT_TM': target_tm,
121
+ 'PRIMER_MAX_TM': target_tm+wiggle,
122
+ 'PRIMER_PRODUCT_SIZE_RANGE': product_size_range,
123
+ 'PRIMER_INTERNAL_MAX_POLY_X':poly,
124
+ }
125
+
126
+ if Q5:
127
+ global_args.update({
128
+ 'PRIMER_SALT_DIVALENT': 2,
129
+ 'PRIMER_SALT_MONOVALENT': 70,
130
+ 'PRIMER_DNA_CONC': 3300,
131
+ 'PRIMER_TM_FORMULA': 1,
132
+ 'PRIMER_SALT_CORRECTIONS': 2,
133
+ })
134
+
135
+ if clamp > 0:
136
+ global_args.update({'PRIMER_GC_CLAMP': clamp,})
137
+
138
+ # Run primer3 to design the primers.
139
+ primers = primer3.bindings.designPrimers(input_params, global_args)
140
+ no_miss = False
141
+ if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
142
+ print("No primers found for: " + name + "; trying with relaxed restraints.")
143
+ del global_args['PRIMER_INTERNAL_MAX_POLY_X']
144
+ global_args.update({'PRIMER_PICK_ANYWAY': 1,})
145
+ primers = primer3.bindings.designPrimers(input_params, global_args)
146
+ if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
147
+ del input_params['PRIMER_MISPRIMING_LIBRARY']
148
+ global_args.update({'PRIMER_MIN_TM': target_tm - wiggle * 1.5,})
149
+ global_args.update({'PRIMER_MAX_TM': target_tm + wiggle * 1.5,})
150
+ primers = primer3.bindings.designPrimers(input_params, global_args)
151
+ no_miss = True
152
+ if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
153
+ global_args.update({'PRIMER_MIN_TM': target_tm - wiggle * 5,})
154
+ global_args.update({'PRIMER_MAX_TM': target_tm + wiggle * 5,})
155
+ product_size_range_tmp = (50, round(product_size_range[1] * 1.5))
156
+ global_args.update({'PRIMER_PRODUCT_SIZE_RANGE': product_size_range_tmp,})
157
+ global_args.update({'PRIMER_MIN_SIZE': 5,})
158
+ global_args.update({'PRIMER_MAX_SIZE': 36,})
159
+ primers = primer3.bindings.designPrimers(input_params, global_args)
160
+ try:
161
+ # Check if any primer pairs were returned.
162
+ if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
163
+ return []
164
+ else:
165
+ if no_miss:
166
+ print("No mispriming library used for " + name)
167
+ # Extract information about the primer pairs.
168
+ primer_pairs = []
169
+ for i in range(primers['PRIMER_PAIR_NUM_RETURNED']):
170
+ forward_seq = primers[f'PRIMER_LEFT_{i}_SEQUENCE']
171
+ reverse_seq = primers[f'PRIMER_RIGHT_{i}_SEQUENCE']
172
+ forward_tm = primers[f'PRIMER_RIGHT_{i}_TM']
173
+ reverse_tm = primers[f'PRIMER_LEFT_{i}_TM']
174
+ product_size = primers[f'PRIMER_PAIR_{i}_PRODUCT_SIZE']
175
+ start = primers['PRIMER_LEFT_{}'.format(i)][0] + region_start - add_to
176
+ end = primers['PRIMER_RIGHT_{}'.format(i)][0] + region_start - add_to
177
+
178
+ # Check that the product size is within the specified range.
179
+ # if product_size < int(product_size_range[0]) or product_size > int(product_size_range[1]):
180
+ if args.ill_adapt:
181
+ # add illumina partial adapter, dont adjust Tm as these are tails
182
+ forward_seq = "ACACTCTTTCCCTACACGACGCTCTTCCGATCT" + forward_seq
183
+ reverse_seq = "GACTGGAGTTCAGACGTGTGCTCTTCCGATCT" + reverse_seq
184
+ primer_pairs.append({
185
+ 'Forward Primer': forward_seq,
186
+ 'Reverse Primer': reverse_seq,
187
+ 'Forward tm': forward_tm,
188
+ 'Reverse tm': reverse_tm,
189
+ 'Product Size': product_size,
190
+ 'Binding Start': str(start),
191
+ 'Binding End': str(end),
192
+ 'name': name
193
+ })
194
+ except Exception as e:
195
+ print("An error occurred:", e)
196
+
197
+ return primer_pairs
198
+
199
+ def q5_melting_temp(seq1, seq2="", salt=0.5):
200
+ url = "https://tmapi.neb.com/tm/q5/%s/%s/%s?&fmt=short" % (salt, seq1, seq2)
201
+ response = requests.get(url)
202
+ json_string = response.json()
203
+ tm1 = json_string["data"]["tm1"]
204
+ # tm2 = json_string["data"]["tm2"]
205
+ return tm1 #[tm1, tm2]
206
+
207
+ def is_valid_combination(combination, names):
208
+ if set(entry['name'] for entry in combination) == names:
209
+ return combination
210
+ return []
211
+
212
+ def evaluate_combination(comb, Q5=args.Q5):
213
+ # Create a list of primer pairs
214
+ primer_pairs = [(p1, p2) for p1, p2 in itertools.combinations(comb, 2)]
215
+ # Extract the primer sequences from the primer pairs
216
+ primer_pairs_sequences = [(p1['Forward Primer'], p2['Reverse Primer']) for p1, p2 in primer_pairs]
217
+ # Calculate heterodimer formation energy
218
+ heterodimer_scores = []
219
+ for p in primer_pairs_sequences:
220
+ if Q5:
221
+ heterodimer_scores.append(primer3.calcHeterodimer(p[0], p[1], temp_c=args.target_tm, dv_conc = 2, mv_conc = 70, dna_conc = 3300).dg) #gibbs free energy
222
+ else:
223
+ heterodimer_scores.append(primer3.calcHeterodimer(p[0], p[1], temp_c=args.target_tm).dg) #gibbs free energy
224
+ product_size_weight=0.2
225
+ heterodimer_score_weight =0.8
226
+ score = {'size': product_size_range,
227
+ 'tmp': tm_range,
228
+ 'mean': np.mean(heterodimer_scores),
229
+ 'range': abs(np.min(heterodimer_scores)) - abs(np.max(heterodimer_scores))
230
+ # 'weighted_score': product_size_weight * (1 - product_size_range) + heterodimer_score_weight * (1 - abs(np.mean(heterodimer_scores)) / 100)
231
+ }
232
+ return score, comb
233
+
234
+
235
+ # Define the features to consider for clustering
236
+ def get_features(primer, target_tm=args.target_tm):
237
+ fwd_tm = primer['Forward tm']
238
+ rev_tm = primer['Reverse tm']
239
+ avg_tm = (fwd_tm + rev_tm) / 2
240
+ product_size = primer['Product Size']
241
+ tm_difference = abs(fwd_tm - rev_tm)
242
+ dimer_prob = primer3.calcHeterodimer(primer['Forward Primer'], primer['Reverse Primer'], temp_c=target_tm, dv_conc = 2, mv_conc = 70, dna_conc = 3300).dg
243
+ return (avg_tm, product_size, tm_difference, dimer_prob)
244
+
245
+
246
+ def cluster_primers(primers, target_tm=args.target_tm, distance_threshold=10):
247
+ # Cluster the primers based on their features
248
+ X = [get_features(primer) for primer in primers]
249
+ clusterer = AgglomerativeClustering(n_clusters=None, affinity='euclidean', linkage='ward', distance_threshold=distance_threshold)
250
+ clusters = clusterer.fit_predict(X)
251
+
252
+ # Select the largest cluster
253
+ name_counts = {}
254
+ for i, cluster in enumerate(clusters):
255
+ name = primers[i]['name']
256
+ if cluster in name_counts:
257
+ name_counts[cluster].add(name)
258
+ else:
259
+ name_counts[cluster] = {name}
260
+
261
+ most_unique_cluster = max(name_counts, key=lambda k: len(name_counts[k]))
262
+ largest_cluster = [primers[i] for i, cluster in enumerate(clusters) if cluster == most_unique_cluster]
263
+
264
+ # Add missing names from the next closest cluster until all names are included
265
+ all_names = set(primer['name'] for primer in primers)
266
+ selected_names = set(primer['name'] for primer in largest_cluster)
267
+ missing_names = all_names - selected_names
268
+
269
+ while missing_names:
270
+ # Find the closest cluster that contains missing names
271
+ closest_cluster_idx = None
272
+ closest_distance = float('inf')
273
+ for i, cluster in enumerate(clusters):
274
+ if cluster == most_unique_cluster:
275
+ continue
276
+ cluster_names = set(primers[j]['name'] for j in range(len(primers)) if clusters[j] == cluster)
277
+ common_names = cluster_names & missing_names
278
+ if common_names:
279
+ distance = np.linalg.norm(np.array(X[i]) - np.array(X[0]))
280
+ if distance < closest_distance:
281
+ closest_cluster_idx = cluster
282
+ closest_distance = distance
283
+
284
+ # Add the missing names to the largest cluster
285
+ closest_cluster = [primers[i] for i, cluster in enumerate(clusters) if cluster == closest_cluster_idx]
286
+ for primer in closest_cluster:
287
+ if primer['name'] in missing_names:
288
+ largest_cluster.append(primer)
289
+ missing_names.remove(primer['name'])
290
+
291
+ # Remove duplicates by name
292
+ selected_primers = []
293
+ selected_names = set()
294
+ for primer in largest_cluster:
295
+ name = primer['name']
296
+ if name not in selected_names:
297
+ selected_primers.append(primer)
298
+ selected_names.add(name)
299
+ return selected_primers
300
+
301
+
302
+ def plot_cluster(clusterer, primers):
303
+ # Obtain the cluster labels
304
+ labels = clusterer.labels_
305
+
306
+ # Plot the clusters
307
+ fig, ax = plt.subplots()
308
+ ax.scatter([x[0] for x in X], [x[1] for x in X], c=labels, cmap='viridis')
309
+
310
+ # Add labels for each point
311
+ for i, primer in enumerate(primers):
312
+ ax.annotate(primer['name'], (X[i][0], X[i][1]))
313
+
314
+ # Customize the plot
315
+ ax.set_xlabel('Average TM')
316
+ ax.set_ylabel('Product Size')
317
+ ax.set_title('Primer Clustering')
318
+
319
+ # Obtain the cluster labels
320
+ labels = clusterer.labels_
321
+
322
+ # Create a dictionary of primer names and their cluster assignments
323
+ cluster_dict = defaultdict(list)
324
+ for i, primer in enumerate(primers):
325
+ cluster_dict[primer['name']].append(labels[i])
326
+
327
+ # Print the primer names and their cluster assignments as a table
328
+ rows = []
329
+ for name, clusters in cluster_dict.items():
330
+ rows.append([name, ', '.join(str(c) for c in clusters)])
331
+
332
+ return (fig, tabulate(rows, headers=['Primer Name', 'Clusters']))
333
+
334
+
335
+ def main():
336
+ #########################################
337
+ # Read the file into a pandas DataFrame #
338
+ file_path = args.region_file # or 'file.xlsx'
339
+ if file_path.endswith('.tsv'):
340
+ df = pd.read_csv(file_path, sep='\t')
341
+ else:
342
+ df = pd.read_excel(file_path)
343
+
344
+ seen_names = set()
345
+ modified_names = {}
346
+
347
+ primers_all = []
348
+
349
+ record = SeqIO.read(args.input_file, "fasta")
350
+
351
+
352
+ # check if regions overlap
353
+ # Sort the DataFrame by 'start' column
354
+ df = df.sort_values(by='start')
355
+ overlap = df.loc[(df['start'] < df['end'].shift()) & (df['end'] > df['start'].shift())]
356
+ if not overlap.empty:
357
+ print("Overlaps found, please edit input")
358
+ print(overlap)
359
+ exit(1)
360
+
361
+
362
+ # Iterate over each row
363
+ for index, row in df.iterrows():
364
+ # Access the "start" and "end" values using the column names
365
+ # name=str(row['name'])
366
+ start = int(row['start'])
367
+ end = int(row['end'])
368
+ name = 'Target ' + str(start) + "-" + str(end)
369
+
370
+ if end - start > int(product_size_range[1]):
371
+ print("Region " + str(start) + ", ", str(end) + " larger than product_size_range!")
372
+ pass
373
+
374
+ # Check if name is already in seen_names
375
+ if name in seen_names:
376
+ # If so, modify the name to make it unique
377
+ if name in modified_names:
378
+ modified_name = modified_names[name]
379
+ else:
380
+ modified_name = name + '_' + str(random.randint(1, 100))
381
+ modified_names[name] = modified_name
382
+ # Update name in row
383
+ df.at[index, 'name'] = modified_name
384
+ seen_names.add(modified_name)
385
+ name = modified_name
386
+ else:
387
+ seen_names.add(name)
388
+
389
+ # copy background fasta
390
+ tmp_dir = tempfile.TemporaryDirectory()
391
+ tmp_back_n = tmp_dir.name
392
+ if args.background != '':
393
+ shutil.copy(args.background, tmp_back_n)
394
+ tmp_back = os.path.join(tmp_back_n, os.path.basename(args.background))
395
+ else:
396
+ tmp_back = os.path.join(tmp_back_n, "tmp.fasta")
397
+ open(tmp_back_n, 'w').close()
398
+ tmp_back.write(b'')
399
+
400
+ # print(tmp_back)
401
+ # if args.background != '':
402
+ # with tempfile.TemporaryDirectory() as tmp_back:
403
+ # # copy the file to the temporary directory
404
+ # shutil.copy(args.background, tmp_back)
405
+ # # construct the destination path in the temporary directory
406
+ # tmp_back = os.path.join(tmp_back, os.path.basename(args.background))
407
+ # else:
408
+ # # create a temporary file with a .fasta extension
409
+ # with tempfile.NamedTemporaryFile(suffix='.fasta', delete=False) as tmp_back:
410
+ # # write an empty string to the file
411
+ # tmp_back.write(b'')
412
+
413
+ # add two random lines for initilization
414
+ with open(tmp_back, "a") as fasta_file:
415
+ fasta_file.write(">appended_sequence1\n")
416
+ fasta_file.write("gcagcagtcgctcgatccgat" + "\n")
417
+ fasta_file.write(">appended_sequence2\n")
418
+ fasta_file.write("gcagcagtcggagatagacctcgatccgat" + "\n")
419
+
420
+ # Call the design_primers function to design primers for the target region.
421
+ primer_tmp = []
422
+ primer_tmp = design_primers(
423
+ input_file=record,
424
+ region_start=start,
425
+ region_end=end,
426
+ target_tm=args.target_tm,
427
+ primer_len=args.primer_len,
428
+ product_size_range=product_size_range,
429
+ name=name,
430
+ ret=args.ret,
431
+ Q5=args.Q5,
432
+ background=tmp_back
433
+ )
434
+
435
+ if primer_tmp is not None and len(primer_tmp) > 0:
436
+ primers_all.append(primer_tmp)
437
+ else:
438
+ print("No primer found for: " + name)
439
+
440
+
441
+
442
+ #Typically, a ΔG value below -9 kcal/mol is considered to indicate a high likelihood of dimer formation, while values between -6 and -9 kcal/mol indicate a moderate likelihood. Values above -6 kcal/mol are considered unlikely to result in dimer formation.
443
+ # Define initial placeholder score
444
+ best_score = {'size': float('inf'), 'tmp': float('inf'), 'range': float('inf'), 'mean': float('inf')}
445
+ best_comb = []
446
+ # get a set of unique names
447
+ flat_list = []
448
+ for sublist in primers_all:
449
+ for item in sublist:
450
+ flat_list.append(item)
451
+
452
+ primers_all = flat_list
453
+ cluster_method = True
454
+
455
+ names = set([primer['name'] for primer in primers_all]) # get unique names
456
+ if len(names) <= 1:
457
+ print("not enough targets! " + ' '.join(map(str, names)))
458
+ exit(1)
459
+ else:
460
+ print("Finding best primer set for the following targets: " + ', '.join(map(str, names)))
461
+ if cluster_method:
462
+ best_comb = cluster_primers(primers_all)
463
+ else:
464
+ best_score = {'mean': float('inf'), 'range': float('inf'), 'tmp': float('inf'), 'size': float('inf')}
465
+ best_comb = None
466
+ valid_combinations = []
467
+ pos = 0
468
+ name_primers_dict = {}
469
+ for name in names:
470
+ name_primers_dict[name] = [primer for primer in primers_all if primer['name'] == name] # group primers by name
471
+
472
+ combinations = []
473
+ for i in range(args.eval):
474
+ combination = []
475
+ for name in names:
476
+ name_primers = name_primers_dict[name] # get primers for the current name
477
+ combination.append(random.choice(name_primers))
478
+ combinations.append(combination)
479
+
480
+ print("Picking best set from: ", len(combinations), " combinations")
481
+ # tm and size
482
+ product_sizes = [d['Product Size'] for d in primers_all]
483
+ tm_values = [d['Forward tm'] for d in primers_all] + [d['Reverse tm'] for d in primers_all]
484
+ # product_size_range = max(product_sizes) - min(product_sizes)
485
+ tm_range = max(tm_values) - min(tm_values)
486
+ best_score = {'mean': float('inf'), 'range': float('inf'), 'tmp': float('inf')}
487
+ best_comb = None
488
+
489
+ with concurrent.futures.ThreadPoolExecutor() as executor:
490
+ futures = [executor.submit(evaluate_combination, comb) for comb in combinations]
491
+
492
+ for future in concurrent.futures.as_completed(futures):
493
+ score, comb = future.result()
494
+ if best_score['mean'] > score['mean']:
495
+ if best_score['range'] * 0.9 > score['range']:
496
+ best_score = score
497
+ best_comb = comb
498
+ elif best_score['tmp'] > 4 or score['tmp'] > 4 and best_score['tmp'] > score['tmp']:
499
+ best_score = score
500
+ best_comb = comb
501
+
502
+ ######
503
+ print("")
504
+ print("writing file: " + args.output + '.xlsx')
505
+ # convert best_comb tuple to DataFrame object
506
+ best_comb = pd.DataFrame(list(best_comb))
507
+ # add in NEB calc.
508
+ best_comb['Forward Primer TM NEB'] = best_comb['Forward Primer'].apply(q5_melting_temp)
509
+ best_comb['Reverse Primer TM NEB'] = best_comb['Reverse Primer'].apply(q5_melting_temp)
510
+
511
+ best_comb.to_excel(args.output + '.xlsx', sheet_name='PrimerSet', index=False)
512
+
513
+
514
+ tmp_dir.cleanup()
515
+
516
+ # (plt, tab) = plot_cluster(clusterer, primers)
517
+ # print(tab)
518
+
519
+ if __name__ == '__main__':
520
+ main()
@@ -0,0 +1,12 @@
1
+ #!/bin/python
2
+ import os
3
+
4
+ def main():
5
+ print("Welcome to primerJinn")
6
+ print("")
7
+ os.system('getMultiPrimerSet')
8
+ print("")
9
+ os.system('PCRinSilico')
10
+
11
+ if __name__ == '__main__':
12
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: primerJinn
3
- Version: 1.0.0.dev2
3
+ Version: 1.0.0.dev3
4
4
  Summary: In silico PCR tool
5
5
  Home-page: https://github.com/SemiQuant/primerJinn
6
6
  Author: Jason D Limberis
@@ -1,5 +1,9 @@
1
1
  README.md
2
2
  setup.py
3
+ primerJinn/PCRinSilico.py
4
+ primerJinn/__init__.py
5
+ primerJinn/getMultiPrimerSet.py
6
+ primerJinn/primerJinn.py
3
7
  primerJinn.egg-info/PKG-INFO
4
8
  primerJinn.egg-info/SOURCES.txt
5
9
  primerJinn.egg-info/dependency_links.txt
@@ -0,0 +1 @@
1
+ primerJinn
@@ -28,7 +28,7 @@ class CustomInstallCommand(install):
28
28
 
29
29
  setup(
30
30
  name='primerJinn',
31
- version='1.0.0.dev2',
31
+ version='1.0.0.dev3',
32
32
  url='https://github.com/SemiQuant/primerJinn',
33
33
  install_requires=dependencies,
34
34
  description='In silico PCR tool',