Debian Codegraph @

examples/newick-fasta-unrooted/newick-fasta-unrooted.c

raw symbols SCIP
1 /*
2 Copyright (C) 2015 Tomas Flouri, Diego Darriba
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Affero General Public License as
6 published by the Free Software Foundation, either version 3 of the
7 License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Affero General Public License for more details.
13
14 You should have received a copy of the GNU Affero General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 Contact: Tomas Flouri <[email protected]>,
18 Exelixis Lab, Heidelberg Instutute for Theoretical Studies
19 Schloss-Wolfsbrunnenweg 35, D-69118 Heidelberg, Germany
20 */
21
22 #include "pll.h"
23 #include <stdarg.h>
24 #include <search.h>
25 #include <time.h>
26
27 #define STATES 4
28 #define RATE_CATS 4
29
30 static void fatal(const char * format, ...) __attribute__ ((noreturn));
31
32 static void * xmalloc(size_t size)
33 {
34 void * t;
35 t = malloc(size);
36 if (!t)
37 fatal("Unable to allocate enough memory.");
38
39 return t;
40 }
41
42 static char * xstrdup(const char * s)
43 {
44 size_t len = strlen(s);
45 char * p = (char *)xmalloc(len+1);
46 return strcpy(p,s);
47 }
48
49 /* a callback function for performing a full traversal */
50 static int cb_full_traversal(pll_unode_t * node)
51 {
52 return 1;
53 }
54
55 /* branch lengths not present in the newick file get a value of 0.000001 */
56 static void set_missing_branch_length(pll_utree_t * tree, double length)
57 {
58 unsigned int i;
59
60 for (i = 0; i < tree->tip_count; ++i)
61 if (!tree->nodes[i]->length)
62 tree->nodes[i]->length = length;
63
64 for (i = tree->tip_count; i < tree->tip_count + tree->inner_count; ++i)
65 {
66 if (!tree->nodes[i]->length)
67 tree->nodes[i]->length = length;
68 if (!tree->nodes[i]->next->length)
69 tree->nodes[i]->next->length = length;
70 if (!tree->nodes[i]->next->next->length)
71 tree->nodes[i]->next->next->length = length;
72 }
73 }
74
75 static void fatal(const char * format, ...)
76 {
77 va_list argptr;
78 va_start(argptr, format);
79 vfprintf(stderr, format, argptr);
80 va_end(argptr);
81 fprintf(stderr, "\n");
82 exit(EXIT_FAILURE);
83 }
84
85 int main(int argc, char * argv[])
86 {
87 unsigned int i;
88 unsigned int tip_nodes_count, inner_nodes_count, nodes_count, branch_count;
89 unsigned int matrix_count, ops_count;
90 unsigned int * matrix_indices;
91 double * branch_lengths;
92 pll_partition_t * partition;
93 pll_operation_t * operations;
94 pll_unode_t ** travbuffer;
95 unsigned int params_indices[RATE_CATS] = {0,0,0,0};
96
97 /* we accept only two arguments - the newick tree (unrooted binary) and the
98 alignment in the form of FASTA reads */
99 if (argc != 3)
100 fatal(" syntax: %s [newick] [fasta]", argv[0]);
101
102 /* parse the unrooted binary tree in newick format, and store the number
103 of tip nodes in tip_nodes_count */
104 pll_utree_t * tree = pll_utree_parse_newick(argv[1]);
105 if (!tree)
106 fatal("Tree must be an unrooted binary tree");
107
108 tip_nodes_count = tree->tip_count;
109
110 /* fix all missing branch lengths (i.e. those that did not appear in the
111 newick) to 0.000001 */
112 set_missing_branch_length(tree, 0.000001);
113
114 /* compute and show node count information */
115 inner_nodes_count = tip_nodes_count - 2;
116 nodes_count = inner_nodes_count + tip_nodes_count;
117 branch_count = nodes_count - 1;
118
119 printf("Number of tip/leaf nodes in tree: %d\n", tip_nodes_count);
120 printf("Number of inner nodes in tree: %d\n", inner_nodes_count);
121 printf("Total number of nodes in tree: %d\n", nodes_count);
122 printf("Number of branches in tree: %d\n", branch_count);
123
124 /* Uncomment to display the parsed tree ASCII tree together with information
125 as to which CLV index, branch length and label is associated with each
126 node. The code will also write (and print on screen) the newick format
127 of the tree.
128
129 pll_utree_show_ascii(tree, PLL_UTREE_SHOW_LABEL |
130 PLL_UTREE_SHOW_BRANCH_LENGTH |
131 PLL_UTREE_SHOW_CLV_INDEX);
132 char * newick = pll_utree_export_newick(tree,NULL);
133 printf("%s\n", newick);
134 free(newick);
135
136 */
137
138 /* create a libc hash table of size tip_nodes_count */
139 hcreate(tip_nodes_count);
140
141 /* populate a libc hash table with tree tip labels */
142 unsigned int * data = (unsigned int *)xmalloc(tip_nodes_count *
143 sizeof(unsigned int));
144 for (i = 0; i < tip_nodes_count; ++i)
145 {
146 data[i] = tree->nodes[i]->clv_index;
147 ENTRY entry;
148 #ifdef __APPLE__
149 entry.key = xstrdup(tree->nodes[i]->label);
150 #else
151 entry.key = tree->nodes[i]->label;
152 #endif
153 entry.data = (void *)(data+i);
154 hsearch(entry, ENTER);
155 }
156
157 /* open FASTA file */
158 pll_fasta_t * fp = pll_fasta_open(argv[2], pll_map_fasta);
159 if (!fp)
160 fatal("Error opening file %s", argv[2]);
161
162 char * seq = NULL;
163 char * hdr = NULL;
164 long seqlen;
165 long hdrlen;
166 long seqno;
167
168 /* allocate arrays to store FASTA headers and sequences */
169 char ** headers = (char **)calloc(tip_nodes_count, sizeof(char *));
170 char ** seqdata = (char **)calloc(tip_nodes_count, sizeof(char *));
171
172 /* read FASTA sequences and make sure they are all of the same length */
173 int sites = -1;
174 for (i = 0; pll_fasta_getnext(fp,&hdr,&hdrlen,&seq,&seqlen,&seqno); ++i)
175 {
176 if (i >= tip_nodes_count)
177 fatal("FASTA file contains more sequences than expected");
178
179 if (sites != -1 && sites != seqlen)
180 fatal("FASTA file does not contain equal size sequences\n");
181
182 if (sites == -1) sites = seqlen;
183
184 headers[i] = hdr;
185 seqdata[i] = seq;
186 }
187
188 /* did we stop reading the file because we reached EOF? */
189 if (pll_errno != PLL_ERROR_FILE_EOF)
190 fatal("Error while reading file %s", argv[2]);
191
192 /* close FASTA file */
193 pll_fasta_close(fp);
194
195 if (sites == -1)
196 fatal("Unable to read alignment");
197
198 if (i != tip_nodes_count)
199 fatal("Some taxa are missing from FASTA file");
200
201 /* create the PLL partition instance
202
203 tip_nodes_count : the number of tip sequences we want to have
204 inner_nodes_count : the number of CLV buffers to be allocated for inner nodes
205 STATES : the number of states that our data have
206 1 : number of different substitution models (or eigen decomposition)
207 to use concurrently (i.e. 4 for LG4)
208 branch_count: number of probability matrices to be allocated
209 RATE_CATS : number of rate categories we will use
210 inner_nodes_count : how many scale buffers to use
211 PLL_ATTRIB_ARCH_SSE : list of flags for hardware acceleration (not yet implemented)
212
213 */
214
215 partition = pll_partition_create(tip_nodes_count,
216 inner_nodes_count,
217 STATES,
218 (unsigned int)sites,
219 1,
220 branch_count,
221 RATE_CATS,
222 inner_nodes_count,
223 PLL_ATTRIB_PATTERN_TIP | PLL_ATTRIB_ARCH_AVX);
224
225 /* initialize the array of base frequencies */
226 double frequencies[4] = { 0.17, 0.19, 0.25, 0.39 };
227
228 /* substitution rates for the 4x4 GTR model. This means we need exactly
229 (4*4-4)/2 = 6 values, i.e. the number of elements above the diagonal */
230 double subst_params[6] = {1,1,1,1,1,1};
231
232 /* we'll use 4 rate categories, and currently initialize them to 0 */
233 double rate_cats[4] = {0};
234
235 /* compute the discretized category rates from a gamma distribution
236 with alpha shape 1 and store them in rate_cats */
237 pll_compute_gamma_cats(1, 4, rate_cats, PLL_GAMMA_RATES_MEAN);
238
239 /* set frequencies at model with index 0 (we currently have only one model) */
240 pll_set_frequencies(partition, 0, frequencies);
241
242 /* set 6 substitution parameters at model with index 0 */
243 pll_set_subst_params(partition, 0, subst_params);
244
245 /* set rate categories */
246 pll_set_category_rates(partition, rate_cats);
247
248 /* find sequences in hash table and link them with the corresponding taxa */
249 for (i = 0; i < tip_nodes_count; ++i)
250 {
251 ENTRY query;
252 query.key = headers[i];
253 ENTRY * found = NULL;
254
255 found = hsearch(query,FIND);
256
257 if (!found)
258 fatal("Sequence with header %s does not appear in the tree", headers[i]);
259
260 unsigned int tip_clv_index = *((unsigned int *)(found->data));
261
262 pll_set_tip_states(partition, tip_clv_index, pll_map_nt, seqdata[i]);
263 }
264
265 /* destroy hash table */
266 hdestroy();
267
268 /* we no longer need these two arrays (keys and values of hash table... */
269 free(data);
270
271 /* ...neither the sequences and the headers as they are already
272 present in the form of probabilities in the tip CLVs */
273 for(i = 0; i < tip_nodes_count; ++i)
274 {
275 free(seqdata[i]);
276 free(headers[i]);
277 }
278 free(seqdata);
279 free(headers);
280
281
282 /* allocate a buffer for storing pointers to nodes of the tree in postorder
283 traversal */
284 travbuffer = (pll_unode_t **)xmalloc(nodes_count * sizeof(pll_unode_t *));
285
286 branch_lengths = (double *)xmalloc(branch_count * sizeof(double));
287 matrix_indices = (unsigned int *)xmalloc(branch_count * sizeof(unsigned int));
288 operations = (pll_operation_t *)xmalloc(inner_nodes_count *
289 sizeof(pll_operation_t));
290
291 /* perform a postorder traversal of the unrooted tree */
292 /* perform a postorder traversal starting from the inner node that
293 was the the root of the parsed 'unrooted' binary tree */
294
295 pll_unode_t * root = tree->nodes[tip_nodes_count+inner_nodes_count-1];
296 unsigned int traversal_size;
297
298 if (!pll_utree_traverse(root,
299 PLL_TREE_TRAVERSE_POSTORDER,
300 cb_full_traversal,
301 travbuffer,
302 &traversal_size))
303 fatal("Function pll_utree_traverse() requires inner nodes as parameters");
304
305 /* given the computed traversal descriptor, generate the operations
306 structure, and the corresponding probability matrix indices that
307 may need recomputing */
308 pll_utree_create_operations(travbuffer,
309 traversal_size,
310 branch_lengths,
311 matrix_indices,
312 operations,
313 &matrix_count,
314 &ops_count);
315
316
317 printf ("Traversal size: %d\n", traversal_size);
318 printf ("Operations: %d\n", ops_count);
319 printf ("Probability Matrices: %d\n", matrix_count);
320
321 /* update matrix_count probability matrices for model with index 0. The i-th
322 matrix (i ranges from 0 to matrix_count - 1) is generated using branch
323 length branch_lengths[i] and can be refered to with index
324 matrix_indices[i] */
325 pll_update_prob_matrices(partition,
326 params_indices,
327 matrix_indices,
328 branch_lengths,
329 matrix_count);
330
331 /* Uncomment to output the probability matrices (for each branch and each rate
332 category) on screen
333 for (i = 0; i < branch_count; ++i)
334 {
335 printf ("P-matrix (%d) for branch length %f\n", i, branch_lengths[i]);
336 pll_show_pmatrix(partition, i,17);
337 printf ("\n");
338 }
339
340 */
341
342 /* use the operations array to compute all ops_count inner CLVs. Operations
343 will be carried out sequentially starting from operation 0 towrds ops_count-1 */
344 pll_update_partials(partition, operations, ops_count);
345
346 /* Uncomment to print on screen the CLVs at tip and inner nodes. From 0 to
347 tip_nodes_count-1 are tip CLVs, the rest are inner node CLVs.
348
349 for (i = 0; i < nodes_count; ++i)
350 {
351 printf ("CLV %d: ", i);
352 pll_show_clv(partition,i,17);
353 }
354
355 */
356
357 /* compute the likelihood on an edge of the unrooted tree by specifying
358 the CLV indices at the two end-point of the branch, the probability matrix
359 index for the concrete branch length, and the index of the model of whose
360 frequency vector is to be used */
361
362 double logl = pll_compute_edge_loglikelihood(partition,
363 root->clv_index,
364 root->scaler_index,
365 root->back->clv_index,
366 root->back->scaler_index,
367 root->pmatrix_index,
368 params_indices,
369 NULL);
370 printf("Log-L: %f\n", logl);
371
372 /* destroy all structures allocated for the concrete PLL partition instance */
373 pll_partition_destroy(partition);
374
375 /* deallocate traversal buffer, branch lengths array, matrix indices
376 array and operations */
377 free(travbuffer);
378 free(branch_lengths);
379 free(matrix_indices);
380 free(operations);
381
382 /* we will no longer need the tree structure */
383 pll_utree_destroy(tree,NULL);
384
385 return (EXIT_SUCCESS);
386 }