primerJinn 1.0.41.dev0__tar.gz → 2.0.0__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.
@@ -1,25 +1,35 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: primerJinn
3
- Version: 1.0.41.dev0
3
+ Version: 2.0.0
4
4
  Summary: In silico PCR tool
5
5
  Home-page: https://github.com/SemiQuant/primerJinn
6
6
  Author: Jason D Limberis
7
7
  Author-email: Jason.Limberis@ucsf.edu
8
- License: MIT
8
+ License: GPL
9
9
  Keywords: PCR,in silico PCR
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
12
12
  Classifier: Operating System :: OS Independent
13
13
  Description-Content-Type: text/markdown
14
14
  Requires-Dist: scipy
15
15
  Requires-Dist: pandas
16
16
  Requires-Dist: biopython
17
17
  Requires-Dist: numpy
18
- Requires-Dist: primer3-py
18
+ Requires-Dist: primer3-py==2.0.3
19
19
  Requires-Dist: networkx
20
20
  Requires-Dist: scikit-learn
21
21
  Requires-Dist: requests
22
22
  Requires-Dist: openpyxl
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: requires-dist
32
+ Dynamic: summary
23
33
 
24
34
  <div>
25
35
  <img src="https://user-images.githubusercontent.com/8179171/236663567-94d1f5dc-2ac6-49de-9fc1-a99c7a13945d.png" width="20%" height="20%">
File without changes
@@ -18,7 +18,9 @@ import subprocess
18
18
  import shutil
19
19
  import os
20
20
  import openpyxl
21
- # import matplotlib.pyplot as plt
21
+ import matplotlib.pyplot as plt
22
+ from collections import defaultdict
23
+ from tabulate import tabulate
22
24
 
23
25
  parser = argparse.ArgumentParser(description='PCR primer design')
24
26
  # Define input arguments
@@ -32,7 +34,7 @@ parser.add_argument('--product_size_max', type=int, help='The desired max size f
32
34
  parser.add_argument('--ret', type=int, help='The maximum number of primer pairs to return.', default=100)
33
35
  parser.add_argument('--Q5', action='store_true', help='Whether to use Q5 approximation settings for Tm calculations.', default=True)
34
36
  parser.add_argument('--background', type=str, help='The path to the mispriming library FASTA file.', default='')
35
- parser.add_argument('--no_self_background', action='store_true', help='If specified, primers are NOT checked for mispriming against the input genome as for large genomes this is very slow', default=False)
37
+ parser.add_argument('--no_self_background', action='store_true', help='If specified, primers are NOT checked for mispriming against the input genome as for large genomes this is very slow')
36
38
  parser.add_argument('--output', type=str, help='Output name.', default='MultiPlexPrimerSet')
37
39
  parser.add_argument('--eval', type=int, help='The maximum number of primer sets to evaluate.', default=10000)
38
40
  parser.add_argument('--wiggle', type=int, help='Half the region around the optimal Tm', default=3)
@@ -43,7 +45,7 @@ args = parser.parse_args()
43
45
 
44
46
  product_size_range = (args.product_size_min, args.product_size_max)
45
47
 
46
- 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, no_self_background=args.no_self_background, Q5=args.Q5):
48
+ 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, no_self_background=False):
47
49
  """
48
50
  This function takes a FASTA file, start and end positions of a target region, and desired melting temperature
49
51
  and primer length, and returns the best primer set for that region using Biopython and primer3.
@@ -64,150 +66,128 @@ def design_primers(input_file, region_start, region_end, target_tm=args.target_t
64
66
  list: A list of dicts containing information about the primer pairs.
65
67
  """
66
68
 
67
- # Parse the input FASTA file and extract the target region sequence.
68
- # 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.
69
69
  print("Picking initial primers for " + name)
70
- # giving issues on some systems because of the -i flag
71
- # command = "sed -i '$d;$d' " + background
72
- # subprocess.run(command, shell=True)
73
- # Create a temporary file to hold the modified output
74
- # with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
75
- # # Use sed to remove the last four lines from the input file and write the result to the temporary file
76
- # subprocess.run(f"sed '$d;$d;$d;$d' '{background}'", stdout=tmp_file, shell=True) #doesnt seem to work on linux
77
70
 
78
- # # Move the temporary file over the original file
79
- # shutil.move(tmp_file.name, background)
71
+ # Initialize mispriming library with minimal content if empty
72
+ if os.path.exists(background) and os.path.getsize(background) == 0:
73
+ with open(background, "w") as fasta_file:
74
+ fasta_file.write(">dummy_sequence\n")
75
+ fasta_file.write("GCTAGCTAGCTAGCTAGCTAG\n")
80
76
 
81
- # Read the file and store its content
82
- with open(background, 'r') as file:
83
- lines = file.readlines()
84
-
85
- # Remove the last four lines
86
- new_lines = lines[:-4]
87
-
88
- # Write the updated content back to the file
89
- with open(background, 'w') as file:
90
- file.writelines(new_lines)
91
-
92
- if not no_self_background:
93
- if region_start - 10000 > 0:
94
- target_seq = input_file.seq[region_start-10000:region_end+10000]
95
- seq_target = (10000-1, region_end-region_start)
96
- add_to = 10000
97
- with open(background, "a") as fasta_file:
98
- fasta_file.write(">appended_sequence\n")
99
- fasta_file.write(str(input_file.seq[0:region_start-10000]) + "\n")
100
- fasta_file.write(">appended_sequence2\n")
101
- fasta_file.write(str(input_file.seq[region_end+10000:]))
102
- else:
103
- target_seq = input_file.seq[0:region_end+10000]
104
- seq_target = (region_start-1, region_end-region_start)
105
- add_to = 0
106
- with open(background, "a") as fasta_file:
107
- fasta_file.write(">appended_sequence\n")
108
- fasta_file.write(str(input_file.seq[region_end+10000:]) + "\n")
109
- fasta_file.write(">appended_sequence2\n")
110
- fasta_file.write("gagagagaga")
111
-
112
- # target_seq = input_file.seq
113
- # seq_target = (region_start-1, region_end-region_start+2)
114
-
115
- # shutil.copy(background, "/home/semiquant/Desktop/tmp/tmp.fasta")
116
-
117
- # Set up the primer3 input parameters.
77
+ # Calculate flanking region size based on max product size
78
+ flank_size = min(500, product_size_range[1])
79
+
80
+ # Extract sequence with flanking regions, ensuring we don't go out of bounds
81
+ seq_start = max(0, region_start - flank_size)
82
+ seq_end = min(len(input_file.seq), region_end + flank_size)
83
+ target_seq = input_file.seq[seq_start:seq_end]
84
+
85
+ # Adjust target coordinates relative to extracted sequence
86
+ target_start = region_start - seq_start
87
+ target_length = region_end - region_start
88
+ seq_target = (target_start, target_length)
89
+
90
+ # Add non-target regions to mispriming library if requested
91
+ if not no_self_background and len(input_file.seq) > len(target_seq):
92
+ with open(background, "a") as fasta_file:
93
+ if seq_start > 0:
94
+ fasta_file.write(">upstream_sequence\n")
95
+ fasta_file.write(str(input_file.seq[0:seq_start]) + "\n")
96
+ if seq_end < len(input_file.seq):
97
+ fasta_file.write(">downstream_sequence\n")
98
+ fasta_file.write(str(input_file.seq[seq_end:]) + "\n")
99
+
100
+ # Set up primer3 parameters
118
101
  input_params = {
119
- 'SEQUENCE_ID': input_file.id,
120
- 'SEQUENCE_TEMPLATE': str(target_seq),
121
- 'SEQUENCE_TARGET': seq_target,
122
- 'PRIMER_OPT_SIZE': primer_len,
123
- 'PRIMER_MIN_SIZE' : 10,
124
- 'PRIMER_MAX_SIZE' : 36,
125
- 'PRIMER_PICK_INTERNAL_OLIGO': 0,
126
- 'PRIMER_MISPRIMING_LIBRARY': background,
102
+ 'SEQUENCE_ID': input_file.id,
103
+ 'SEQUENCE_TEMPLATE': str(target_seq),
104
+ 'SEQUENCE_TARGET': seq_target,
105
+ 'PRIMER_OPT_SIZE': primer_len,
106
+ 'PRIMER_MIN_SIZE': 10,
107
+ 'PRIMER_MAX_SIZE': 36,
108
+ 'PRIMER_PICK_INTERNAL_OLIGO': 0,
127
109
  }
128
110
 
111
+ if not no_self_background:
112
+ input_params['PRIMER_MISPRIMING_LIBRARY'] = background
113
+
129
114
  global_args = {
130
- 'PRIMER_MIN_GC': 40,
131
- 'PRIMER_MAX_GC': 80,
132
- 'PRIMER_NUM_RETURN': ret,
133
- 'PRIMER_EXPLAIN_FLAG': 1,
134
- 'PRIMER_MIN_TM': target_tm-wiggle,
135
- 'PRIMER_OPT_TM': target_tm,
136
- 'PRIMER_MAX_TM': target_tm+wiggle,
137
- 'PRIMER_PRODUCT_SIZE_RANGE': product_size_range,
138
- 'PRIMER_INTERNAL_MAX_POLY_X':poly,
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,
139
124
  }
140
-
125
+
141
126
  if Q5:
142
127
  global_args.update({
143
- 'PRIMER_SALT_DIVALENT': 2,
144
- 'PRIMER_SALT_MONOVALENT': 70,
145
- 'PRIMER_DNA_CONC': 3300,
146
- 'PRIMER_TM_FORMULA': 1,
147
- 'PRIMER_SALT_CORRECTIONS': 2,
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,
148
133
  })
149
134
 
150
135
  if clamp > 0:
151
- global_args.update({'PRIMER_GC_CLAMP': clamp,})
136
+ global_args.update({'PRIMER_GC_CLAMP': clamp})
152
137
 
153
- # Run primer3 to design the primers.
154
- primers = primer3.bindings.designPrimers(input_params, global_args)
155
- no_miss = False
138
+ # Run primer3 with increasingly relaxed constraints if needed
139
+ primers = primer3.bindings.design_primers(input_params, global_args)
140
+
156
141
  if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
157
- print("No primers found for: " + name + "; trying with relaxed restraints.")
142
+ print(f"No primers found for: {name}; trying with relaxed constraints.")
158
143
  del global_args['PRIMER_INTERNAL_MAX_POLY_X']
159
- global_args.update({'PRIMER_PICK_ANYWAY': 1,})
160
- primers = primer3.bindings.designPrimers(input_params, global_args)
144
+ global_args.update({'PRIMER_PICK_ANYWAY': 1})
145
+ primers = primer3.bindings.design_primers(input_params, global_args)
146
+
161
147
  if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
162
- del input_params['PRIMER_MISPRIMING_LIBRARY']
163
- global_args.update({'PRIMER_MIN_TM': target_tm - wiggle * 1.5,})
164
- global_args.update({'PRIMER_MAX_TM': target_tm + wiggle * 1.5,})
165
- primers = primer3.bindings.designPrimers(input_params, global_args)
166
- no_miss = True
167
- if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
168
- global_args.update({'PRIMER_MIN_TM': target_tm - wiggle * 5,})
169
- global_args.update({'PRIMER_MAX_TM': target_tm + wiggle * 5,})
170
- product_size_range_tmp = (50, round(product_size_range[1] * 1.5))
171
- global_args.update({'PRIMER_PRODUCT_SIZE_RANGE': product_size_range_tmp,})
172
- global_args.update({'PRIMER_MIN_SIZE': 5,})
173
- global_args.update({'PRIMER_MAX_SIZE': 36,})
174
- primers = primer3.bindings.designPrimers(input_params, global_args)
148
+ if not no_self_background and 'PRIMER_MISPRIMING_LIBRARY' in input_params:
149
+ del input_params['PRIMER_MISPRIMING_LIBRARY']
150
+ global_args.update({
151
+ 'PRIMER_MIN_TM': target_tm - wiggle * 1.5,
152
+ 'PRIMER_MAX_TM': target_tm + wiggle * 1.5
153
+ })
154
+ primers = primer3.bindings.design_primers(input_params, global_args)
155
+
175
156
  try:
176
- # Check if any primer pairs were returned.
177
157
  if 'PRIMER_PAIR_NUM_RETURNED' not in primers or primers['PRIMER_PAIR_NUM_RETURNED'] == 0:
178
158
  return []
179
- else:
180
- if no_miss:
181
- print("No mispriming library used for " + name)
182
- # Extract information about the primer pairs.
183
- primer_pairs = []
184
- for i in range(primers['PRIMER_PAIR_NUM_RETURNED']):
185
- forward_seq = primers[f'PRIMER_LEFT_{i}_SEQUENCE']
186
- reverse_seq = primers[f'PRIMER_RIGHT_{i}_SEQUENCE']
187
- forward_tm = primers[f'PRIMER_RIGHT_{i}_TM']
188
- reverse_tm = primers[f'PRIMER_LEFT_{i}_TM']
189
- product_size = primers[f'PRIMER_PAIR_{i}_PRODUCT_SIZE']
190
- start = primers['PRIMER_LEFT_{}'.format(i)][0] + region_start - add_to
191
- end = primers['PRIMER_RIGHT_{}'.format(i)][0] + region_start - add_to
192
-
193
- # Check that the product size is within the specified range.
194
- # if product_size < int(product_size_range[0]) or product_size > int(product_size_range[1]):
195
- if args.ill_adapt:
196
- # add illumina partial adapter, dont adjust Tm as these are tails
197
- forward_seq = "ACACTCTTTCCCTACACGACGCTCTTCCGATCT" + forward_seq
198
- reverse_seq = "GACTGGAGTTCAGACGTGTGCTCTTCCGATCT" + reverse_seq
199
- primer_pairs.append({
200
- 'Forward Primer': forward_seq,
201
- 'Reverse Primer': reverse_seq,
202
- 'Forward tm': forward_tm,
203
- 'Reverse tm': reverse_tm,
204
- 'Product Size': product_size,
205
- 'Binding Start': str(start),
206
- 'Binding End': str(end),
207
- 'name': name
208
- })
159
+
160
+ # Extract and process primer pairs
161
+ primer_pairs = []
162
+ for i in range(primers['PRIMER_PAIR_NUM_RETURNED']):
163
+ forward_seq = primers[f'PRIMER_LEFT_{i}_SEQUENCE']
164
+ reverse_seq = primers[f'PRIMER_RIGHT_{i}_SEQUENCE']
165
+ forward_tm = primers[f'PRIMER_LEFT_{i}_TM']
166
+ reverse_tm = primers[f'PRIMER_RIGHT_{i}_TM']
167
+ product_size = primers[f'PRIMER_PAIR_{i}_PRODUCT_SIZE']
168
+
169
+ # Adjust binding sites to global coordinates
170
+ start = primers[f'PRIMER_LEFT_{i}'][0] + seq_start
171
+ end = primers[f'PRIMER_RIGHT_{i}'][0] + seq_start
172
+
173
+ if args.ill_adapt:
174
+ forward_seq = "ACACTCTTTCCCTACACGACGCTCTTCCGATCT" + forward_seq
175
+ reverse_seq = "GACTGGAGTTCAGACGTGTGCTCTTCCGATCT" + reverse_seq
176
+
177
+ primer_pairs.append({
178
+ 'Forward Primer': forward_seq,
179
+ 'Reverse Primer': reverse_seq,
180
+ 'Forward tm': forward_tm,
181
+ 'Reverse tm': reverse_tm,
182
+ 'Product Size': product_size,
183
+ 'Binding Start': str(start),
184
+ 'Binding End': str(end),
185
+ 'name': name
186
+ })
187
+
209
188
  except Exception as e:
210
- print("An error occurred:", e)
189
+ print(f"An error occurred while processing primers for {name}:", e)
190
+ return []
211
191
 
212
192
  return primer_pairs
213
193
 
@@ -233,11 +213,19 @@ def evaluate_combination(comb, Q5=args.Q5):
233
213
  heterodimer_scores = []
234
214
  for p in primer_pairs_sequences:
235
215
  if Q5:
236
- 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
216
+ heterodimer_scores.append(primer3.calc_heterodimer(p[0], p[1], temp_c=args.target_tm, dv_conc = 2, mv_conc = 70, dna_conc = 3300).dg) #gibbs free energy
237
217
  else:
238
- heterodimer_scores.append(primer3.calcHeterodimer(p[0], p[1], temp_c=args.target_tm).dg) #gibbs free energy
218
+ heterodimer_scores.append(primer3.calc_heterodimer(p[0], p[1], temp_c=args.target_tm).dg) #gibbs free energy
239
219
  product_size_weight=0.2
240
220
  heterodimer_score_weight =0.8
221
+
222
+ # Calculate tm_range
223
+ tm_values = []
224
+ for primer in comb:
225
+ tm_values.append(primer['Forward tm'])
226
+ tm_values.append(primer['Reverse tm'])
227
+ tm_range = max(tm_values) - min(tm_values)
228
+
241
229
  score = {'size': product_size_range,
242
230
  'tmp': tm_range,
243
231
  'mean': np.mean(heterodimer_scores),
@@ -254,14 +242,14 @@ def get_features(primer, target_tm=args.target_tm):
254
242
  avg_tm = (fwd_tm + rev_tm) / 2
255
243
  product_size = primer['Product Size']
256
244
  tm_difference = abs(fwd_tm - rev_tm)
257
- dimer_prob = primer3.calcHeterodimer(primer['Forward Primer'], primer['Reverse Primer'], temp_c=target_tm, dv_conc = 2, mv_conc = 70, dna_conc = 3300).dg
245
+ dimer_prob = primer3.calc_heterodimer(primer['Forward Primer'], primer['Reverse Primer'], temp_c=target_tm, dv_conc = 2, mv_conc = 70, dna_conc = 3300).dg
258
246
  return (avg_tm, product_size, tm_difference, dimer_prob)
259
247
 
260
248
 
261
249
  def cluster_primers(primers, target_tm=args.target_tm, distance_threshold=10):
262
250
  # Cluster the primers based on their features
263
251
  X = [get_features(primer) for primer in primers]
264
- clusterer = AgglomerativeClustering(n_clusters=None, affinity='euclidean', linkage='ward', distance_threshold=distance_threshold)
252
+ clusterer = AgglomerativeClustering(n_clusters=None, metric='euclidean', linkage='ward', distance_threshold=distance_threshold)
265
253
  clusters = clusterer.fit_predict(X)
266
254
 
267
255
  # Select the largest cluster
@@ -315,34 +303,32 @@ def cluster_primers(primers, target_tm=args.target_tm, distance_threshold=10):
315
303
 
316
304
 
317
305
  def plot_cluster(clusterer, primers):
318
- # Obtain the cluster labels
306
+ # Get features for each primer
307
+ X = [get_features(primer) for primer in primers]
308
+ # Convert to 2D for visualization using first two features
309
+ X_2d = [[x[0], x[1]] for x in X]
319
310
  labels = clusterer.labels_
320
-
321
- # Plot the clusters
311
+
312
+ # Create the plot
322
313
  fig, ax = plt.subplots()
323
- ax.scatter([x[0] for x in X], [x[1] for x in X], c=labels, cmap='viridis')
324
-
314
+ ax.scatter([x[0] for x in X_2d], [x[1] for x in X_2d], c=labels, cmap='viridis')
315
+ ax.set_xlabel('Average Tm')
316
+ ax.set_ylabel('Product Size')
317
+
325
318
  # Add labels for each point
326
319
  for i, primer in enumerate(primers):
327
- ax.annotate(primer['name'], (X[i][0], X[i][1]))
328
-
329
- # Customize the plot
330
- ax.set_xlabel('Average TM')
331
- ax.set_ylabel('Product Size')
332
- ax.set_title('Primer Clustering')
333
-
334
- # Obtain the cluster labels
335
- labels = clusterer.labels_
336
-
337
- # Create a dictionary of primer names and their cluster assignments
320
+ ax.annotate(primer['name'], (X_2d[i][0], X_2d[i][1]))
321
+
322
+ plt.title('Primer Clusters')
323
+
324
+ # Create a table of cluster assignments
325
+ rows = []
338
326
  cluster_dict = defaultdict(list)
339
327
  for i, primer in enumerate(primers):
340
- cluster_dict[primer['name']].append(labels[i])
341
-
342
- # Print the primer names and their cluster assignments as a table
343
- rows = []
344
- for name, clusters in cluster_dict.items():
345
- rows.append([name, ', '.join(str(c) for c in clusters)])
328
+ cluster_dict[labels[i]].append(primer['name'])
329
+
330
+ for cluster_id, primer_names in cluster_dict.items():
331
+ rows.append([', '.join(primer_names), cluster_id])
346
332
 
347
333
  return (fig, tabulate(rows, headers=['Primer Name', 'Clusters']))
348
334
 
@@ -416,72 +402,73 @@ def main():
416
402
  # fasta_file.write("gcaggcaggcaggcag" + "\n")
417
403
  # fasta_file.write(">random_testing2\n")
418
404
  # fasta_file.write("gcaggcaggcaggccag" + "\n")
419
- # # Create a temporary file for writing
420
- # with tempfile.NamedTemporaryFile(delete=False) as tmp_back:
421
- # # You can write to the temporary file as needed
422
- # tmp_back.write(b'')
423
-
424
- # # Use the 'tmp_back.name' as the path to the temporary file
425
-
426
- # # copy background fasta
427
- # tmp_dir = tempfile.TemporaryDirectory()
428
- # tmp_back_n = tmp_dir.name
429
- # if args.background != '':
430
- # shutil.copy(args.background, tmp_back_n)
431
- # tmp_back = os.path.join(tmp_back_n, os.path.basename(args.background))
432
- # else:
433
- # tmp_back = os.path.join(tmp_back_n, "tmp.fasta")
434
- # open(tmp_back_n, 'w').close()
435
- # tmp_back.write(b'')
436
-
437
- # print(tmp_back)
438
- # if args.background != '':
439
- # with tempfile.TemporaryDirectory() as tmp_back:
440
- # # copy the file to the temporary directory
441
- # shutil.copy(args.background, tmp_back)
442
- # # construct the destination path in the temporary directory
443
- # tmp_back = os.path.join(tmp_back, os.path.basename(args.background))
444
- # else:
445
- # # create a temporary file with a .fasta extension
446
- # with tempfile.NamedTemporaryFile(suffix='.fasta', delete=False) as tmp_back:
447
- # # write an empty string to the file
448
- # tmp_back.write(b'')
449
-
450
- # add two random lines for initialization
451
- with open(tmp_back, "a") as fasta_file:
452
- fasta_file.write(">appended_rdm_sequence1\n")
453
- fasta_file.write("gcagcagtcgctcgatccgat" + "\n")
454
- fasta_file.write(">appended_rdm_sequence2\n")
455
- fasta_file.write("gcagcagtcggagatagacctcgatccgat")
456
-
457
- # # Read the content of tmp_back and filter out blank lines, in case there were in the input file
458
- # with open(tmp_back, "r") as fasta_file:
459
- # lines = fasta_file.readlines()
460
- # filtered_lines = [line.strip() for line in lines if line.strip()]
461
-
462
- # # Write the filtered content back to tmp_back
463
- # with open(tmp_back, "w") as fasta_file:
464
- # fasta_file.write("\n".join(filtered_lines))
465
-
466
- # Call the design_primers function to design primers for the target region.
467
- primer_tmp = []
468
- primer_tmp = design_primers(
469
- input_file=record,
470
- region_start=start,
471
- region_end=end,
472
- target_tm=args.target_tm,
473
- primer_len=args.primer_len,
474
- product_size_range=product_size_range,
475
- name=name,
476
- ret=args.ret,
477
- Q5=args.Q5,
478
- background=tmp_back
479
- )
480
-
481
- if primer_tmp is not None and len(primer_tmp) > 0:
482
- primers_all.append(primer_tmp)
483
- else:
484
- print("No primer found for: " + name)
405
+ # # Create a temporary file for writing
406
+ # with tempfile.NamedTemporaryFile(delete=False) as tmp_back:
407
+ # # You can write to the temporary file as needed
408
+ # tmp_back.write(b'')
409
+
410
+ # # Use the 'tmp_back.name' as the path to the temporary file
411
+
412
+ # # copy background fasta
413
+ # tmp_dir = tempfile.TemporaryDirectory()
414
+ # tmp_back_n = tmp_dir.name
415
+ # if args.background != '':
416
+ # shutil.copy(args.background, tmp_back_n)
417
+ # tmp_back = os.path.join(tmp_back_n, os.path.basename(args.background))
418
+ # else:
419
+ # tmp_back = os.path.join(tmp_back_n, "tmp.fasta")
420
+ # open(tmp_back_n, 'w').close()
421
+ # tmp_back.write(b'')
422
+
423
+ # print(tmp_back)
424
+ # if args.background != '':
425
+ # with tempfile.TemporaryDirectory() as tmp_back:
426
+ # # copy the file to the temporary directory
427
+ # shutil.copy(args.background, tmp_back)
428
+ # # construct the destination path in the temporary directory
429
+ # tmp_back = os.path.join(tmp_back, os.path.basename(args.background))
430
+ # else:
431
+ # # create a temporary file with a .fasta extension
432
+ # with tempfile.NamedTemporaryFile(suffix='.fasta', delete=False) as tmp_back:
433
+ # # write an empty string to the file
434
+ # tmp_back.write(b'')
435
+
436
+ # add two random lines for initialization
437
+ with open(tmp_back, "a") as fasta_file:
438
+ fasta_file.write(">appended_rdm_sequence1\n")
439
+ fasta_file.write("gcagcagtcgctcgatccgat" + "\n")
440
+ fasta_file.write(">appended_rdm_sequence2\n")
441
+ fasta_file.write("gcagcagtcggagatagacctcgatccgat")
442
+
443
+ # # Read the content of tmp_back and filter out blank lines, in case there were in the input file
444
+ # with open(tmp_back, "r") as fasta_file:
445
+ # lines = fasta_file.readlines()
446
+ # filtered_lines = [line.strip() for line in lines if line.strip()]
447
+
448
+ # # Write the filtered content back to tmp_back
449
+ # with open(tmp_back, "w") as fasta_file:
450
+ # fasta_file.write("\n".join(filtered_lines))
451
+
452
+ # Call the design_primers function to design primers for the target region.
453
+ primer_tmp = []
454
+ primer_tmp = design_primers(
455
+ input_file=record,
456
+ region_start=start,
457
+ region_end=end,
458
+ target_tm=args.target_tm,
459
+ primer_len=args.primer_len,
460
+ product_size_range=product_size_range,
461
+ name=name,
462
+ ret=args.ret,
463
+ Q5=args.Q5,
464
+ background=tmp_back,
465
+ no_self_background=args.no_self_background
466
+ )
467
+
468
+ if primer_tmp is not None and len(primer_tmp) > 0:
469
+ primers_all.append(primer_tmp)
470
+ else:
471
+ print("No primer found for: " + name)
485
472
 
486
473
 
487
474
 
@@ -509,32 +496,12 @@ def main():
509
496
  else:
510
497
  best_score = {'mean': float('inf'), 'range': float('inf'), 'tmp': float('inf'), 'size': float('inf')}
511
498
  best_comb = None
512
- valid_combinations = []
513
- pos = 0
514
- name_primers_dict = {}
515
- for name in names:
516
- name_primers_dict[name] = [primer for primer in primers_all if primer['name'] == name] # group primers by name
517
-
518
- combinations = []
519
- for i in range(args.eval):
520
- combination = []
521
- for name in names:
522
- name_primers = name_primers_dict[name] # get primers for the current name
523
- combination.append(random.choice(name_primers))
524
- combinations.append(combination)
525
-
526
- print("Picking best set from: ", len(combinations), " combinations")
527
- # tm and size
528
- product_sizes = [d['Product Size'] for d in primers_all]
529
- tm_values = [d['Forward tm'] for d in primers_all] + [d['Reverse tm'] for d in primers_all]
530
- # product_size_range = max(product_sizes) - min(product_sizes)
531
- tm_range = max(tm_values) - min(tm_values)
532
- best_score = {'mean': float('inf'), 'range': float('inf'), 'tmp': float('inf')}
533
- best_comb = None
534
-
499
+
535
500
  with concurrent.futures.ThreadPoolExecutor() as executor:
536
- futures = [executor.submit(evaluate_combination, comb) for comb in combinations]
537
-
501
+ # Pass primers_all to evaluate_combination
502
+ futures = [executor.submit(evaluate_combination, comb, primers_all)
503
+ for comb in combinations]
504
+
538
505
  for future in concurrent.futures.as_completed(futures):
539
506
  score, comb = future.result()
540
507
  if best_score['mean'] > score['mean']:
@@ -1,25 +1,35 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: primerJinn
3
- Version: 1.0.41.dev0
3
+ Version: 2.0.0
4
4
  Summary: In silico PCR tool
5
5
  Home-page: https://github.com/SemiQuant/primerJinn
6
6
  Author: Jason D Limberis
7
7
  Author-email: Jason.Limberis@ucsf.edu
8
- License: MIT
8
+ License: GPL
9
9
  Keywords: PCR,in silico PCR
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
12
12
  Classifier: Operating System :: OS Independent
13
13
  Description-Content-Type: text/markdown
14
14
  Requires-Dist: scipy
15
15
  Requires-Dist: pandas
16
16
  Requires-Dist: biopython
17
17
  Requires-Dist: numpy
18
- Requires-Dist: primer3-py
18
+ Requires-Dist: primer3-py==2.0.3
19
19
  Requires-Dist: networkx
20
20
  Requires-Dist: scikit-learn
21
21
  Requires-Dist: requests
22
22
  Requires-Dist: openpyxl
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: requires-dist
32
+ Dynamic: summary
23
33
 
24
34
  <div>
25
35
  <img src="https://user-images.githubusercontent.com/8179171/236663567-94d1f5dc-2ac6-49de-9fc1-a99c7a13945d.png" width="20%" height="20%">
@@ -2,7 +2,7 @@ scipy
2
2
  pandas
3
3
  biopython
4
4
  numpy
5
- primer3-py
5
+ primer3-py==2.0.3
6
6
  networkx
7
7
  scikit-learn
8
8
  requests
@@ -0,0 +1,104 @@
1
+ from setuptools import setup, find_packages
2
+ from setuptools.command.install import install
3
+ from pathlib import Path
4
+ import os
5
+
6
+ # read the contents of your README file
7
+ this_directory = Path(__file__).parent
8
+ long_description = (this_directory / "README.md").read_text()
9
+
10
+ dependencies = [
11
+ 'scipy',
12
+ 'pandas',
13
+ 'biopython',
14
+ 'numpy',
15
+ 'primer3-py==2.0.3',
16
+ 'networkx',
17
+ 'scikit-learn',
18
+ 'requests',
19
+ 'openpyxl'
20
+ ]
21
+
22
+ class CustomInstallCommand(install):
23
+ def run(self):
24
+ install.run(self)
25
+
26
+ # First check if BLAST is already functional
27
+ print("\nChecking for existing BLAST+ installation...")
28
+ try:
29
+ # Try to run blastn -version
30
+ if os.system("blastn -version > /dev/null 2>&1") == 0:
31
+ print("Found working BLAST+ installation. Skipping download.")
32
+ return
33
+ except:
34
+ pass
35
+
36
+ # If we get here, we need to install BLAST
37
+ print("No working BLAST+ installation found.")
38
+
39
+ # Determine platform-specific download URL
40
+ platform = os.uname().sysname.lower()
41
+ if platform == 'darwin':
42
+ blast_url = "https://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/2.14.0/ncbi-blast-2.14.0+-x64-macosx.tar.gz"
43
+ dirname = "ncbi-blast-2.14.0+"
44
+ elif platform == 'linux':
45
+ blast_url = "https://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/2.14.0/ncbi-blast-2.14.0+-x64-linux.tar.gz"
46
+ dirname = "ncbi-blast-2.14.0+"
47
+ else:
48
+ raise Exception(f"Unsupported platform: {platform}")
49
+
50
+ # Get the installation directory
51
+ install_dir = os.path.join(self.install_lib, 'primerJinn', 'blast')
52
+ os.makedirs(install_dir, exist_ok=True)
53
+
54
+ print(f"Downloading BLAST+ for {platform}...")
55
+ tarfile = os.path.join(install_dir, "blast.tar.gz")
56
+ r = os.system(f"wget {blast_url} -O {tarfile}")
57
+ if r: raise Exception("wget failed")
58
+
59
+ # Extract to the correct location
60
+ current_dir = os.getcwd()
61
+ os.chdir(install_dir)
62
+ r = os.system(f"tar -xzf {tarfile}")
63
+ if r: raise Exception("tar failed")
64
+ os.remove(tarfile)
65
+ os.chdir(current_dir)
66
+
67
+ # Add BLAST to PATH for this session
68
+ blast_bin = os.path.join(install_dir, dirname, "bin")
69
+ os.environ["PATH"] = blast_bin + os.pathsep + os.environ["PATH"]
70
+
71
+ # Verify installation
72
+ if os.system("blastn -version > /dev/null 2>&1") != 0:
73
+ raise Exception("BLAST+ installation failed verification")
74
+ print("BLAST+ installation successful!")
75
+
76
+ setup(
77
+ name='primerJinn',
78
+ version='2.0.0',
79
+ url='https://github.com/SemiQuant/primerJinn',
80
+ install_requires=dependencies,
81
+ description='In silico PCR tool',
82
+ long_description=long_description,
83
+ long_description_content_type='text/markdown',
84
+ author='Jason D Limberis',
85
+ author_email='Jason.Limberis@ucsf.edu',
86
+ keywords=['PCR', 'in silico PCR'],
87
+ license='GPL',
88
+ classifiers=[
89
+ 'Programming Language :: Python :: 3',
90
+ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
91
+ 'Operating System :: OS Independent',
92
+ ],
93
+ packages=find_packages(),
94
+ entry_points={
95
+ 'console_scripts': [
96
+ 'getMultiPrimerSet=primerJinn.getMultiPrimerSet:main',
97
+ 'PCRinSilico=primerJinn.PCRinSilico:main',
98
+ 'primerJinn=primerJinn.primerJinn:main'
99
+ ],
100
+ },
101
+ cmdclass={
102
+ 'install': CustomInstallCommand,
103
+ }
104
+ )
@@ -1,65 +0,0 @@
1
- from setuptools import setup, find_packages
2
- from setuptools.command.install import install
3
- from pathlib import Path
4
- import os
5
-
6
- # read the contents of your README file
7
- this_directory = Path(__file__).parent
8
- long_description = (this_directory / "README.md").read_text()
9
-
10
- dependencies = [
11
- 'scipy',
12
- 'pandas',
13
- 'biopython',
14
- 'numpy',
15
- 'primer3-py',
16
- 'networkx',
17
- 'scikit-learn',
18
- 'requests',
19
- 'openpyxl'
20
- ]
21
-
22
- class CustomInstallCommand(install):
23
- def run(self):
24
- install.run(self)
25
- r=os.system("wget https://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/2.14.0/ncbi-blast-2.14.0+-x64-linux.tar.gz")
26
- if r: raise Exception("wget failed")
27
- r=os.system("tar -xzvf ncbi-blast-2.14.0+-x64-linux.tar.gz")
28
- if r: raise Exception("tar failed")
29
- # os.system("export PATH=$PATH:%s" % os.path.abspath("$(pwd)/ncbi-blast-2.14.0+/bin"))
30
- # - this command has no effect
31
- # (the 'export' lasts only until system() returned)
32
- # os.environ["PATH"] += ":"+os.path.abspath("$(pwd)/ncbi-blast-2.14.0+/bin")
33
- # ^^ this is what you meant if you
34
- # wanted the new PATH to take effect
35
- # in any future programs we call here
36
-
37
- setup(
38
- name='primerJinn',
39
- version='1.0.41dev',
40
- url='https://github.com/SemiQuant/primerJinn',
41
- install_requires=dependencies,
42
- description='In silico PCR tool',
43
- long_description=long_description,
44
- long_description_content_type='text/markdown',
45
- author='Jason D Limberis',
46
- author_email='Jason.Limberis@ucsf.edu',
47
- keywords=['PCR', 'in silico PCR'],
48
- license='MIT',
49
- classifiers=[
50
- 'Programming Language :: Python :: 3',
51
- 'License :: OSI Approved :: MIT License',
52
- 'Operating System :: OS Independent',
53
- ],
54
- packages=find_packages(),
55
- entry_points={
56
- 'console_scripts': [
57
- 'getMultiPrimerSet=primerJinn.getMultiPrimerSet:main',
58
- 'PCRinSilico=primerJinn.PCRinSilico:main',
59
- 'primerJinn=primerJinn.primerJinn:main'
60
- ],
61
- },
62
- cmdclass={
63
- 'install': CustomInstallCommand,
64
- }
65
- )
File without changes