forked from sbotond/phylosim
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AminoAcidSubst.R
654 lines (571 loc) · 13.7 KB
/
AminoAcidSubst.R
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
##
## Copyright 2009 Botond Sipos
## See the package description for licensing information.
##
##########################################################################/**
#
# @RdocClass AminoAcidSubst
#
# @title "The AminoAcidSubst class"
#
# \description{
# This is a class implementing a continuous-time Markov process acting on
# the state-space defined by the \code{AminoAcidAlphabet} class. The rate
# matrix of this model is completely unrestricted.
#
# The rate matrix can be built from PAML files specified by the \code{paml.file} argument.
# Alternatively the rates can be specified as a list through the \code{rate.list} parameter.
#
# @classhierarchy
# }
#
# @synopsis
#
# \arguments{
# \item{name}{The name of the object.}
# \item{paml.file}{The name of the PAML file used to construct the rate matrix.}
# \item{rate.list}{A list of unscaled substitution rates (see \code{setRateList.GeneralSubstitution}).}
# \item{equ.dist}{Equilibrium distribution.}
# \item{...}{Additional arguments.}
# }
#
# \section{Fields and Methods}{
# @allmethods
# }
#
# \examples{
# # create an object
# p<-AminoAcidSubst()
# # build rate matrix from paml file
# # buildFromPAML(p,"path_to_paml_file") # do not run this
# # set a rate
# setRate(p,"A->D",2)
# # get object summary
# summary(p)
# }
#
# @author
#
# \seealso{
# @seeclass
# }
#
#*/###########################################################################
setConstructorS3(
"AminoAcidSubst",
function(
name="Anonymous",
paml.file=NA,
rate.list=NA,
equ.dist=NA,
...
) {
got.rate.list<-!missing(rate.list);
got.equ.dist<-!missing(equ.dist);
extend.with.s<-function(this){
this<-extend(this, "AminoAcidSubst",
.s.matrix=data.matrix(matrix(ncol=this$.alphabet$size,nrow=this$.alphabet$size)),
.paml.file=NA
);
rownames(this$.s.matrix)<-this$.alphabet$.symbols;
colnames(this$.s.matrix)<-this$.alphabet$.symbols;
# Setting diagonal elements to zero:
diag(this$.s.matrix)<-0;
return(this);
}
this<-NA;
if(missing(paml.file)){
# No PAML file given
# Got rate list and equlibrium distribution:
if(got.rate.list & got.equ.dist){
this<-GeneralSubstitution(
name=name,
alphabet=AminoAcidAlphabet(),
rate.list=rate.list,
equ.dist=equ.dist
);
this<-extend(this, "AminoAcidSubst");
}
# Got rate list
else if(got.rate.list & !got.equ.dist){
this<-GeneralSubstitution(
name=name,
alphabet=AminoAcidAlphabet(),
rate.list=rate.list
);
this<-extend.with.s(this);
}
# Got equlibrium distribution,
else if(!got.rate.list & got.equ.dist){
this<-GeneralSubstitution(
name=name,
alphabet=AminoAcidAlphabet(),
equ.dist=equ.dist
);
this<-extend(this, "AminoAcidSubst");
this<-extend.with.s(this);
}
# Got nothing:
else if(!got.rate.list & !got.equ.dist){
this<-GeneralSubstitution(
name=name,
alphabet=AminoAcidAlphabet()
);
this<-extend.with.s(this);
}
}
else {
# PAML file given:
if( got.rate.list){
warning("Building process from PAML file, the \"rate.list\" parameter is ignored!\n");
}
this<-GeneralSubstitution(
name=name,
alphabet=AminoAcidAlphabet()
);
this<-extend.with.s(this);
if(got.equ.dist){
setEquDist(this,equ.dist,force=TRUE);
}
buildFromPAML(this, paml.file);
}
# Force clearing id cache:
this$name<-this$name;
return(this);
},
enforceRCC=TRUE
);
##
## Method: checkConsistency
##
###########################################################################/**
#
# @RdocMethod checkConsistency
#
# @title "Check object consistency"
#
# \description{
# @get "title".
# }
#
# @synopsis
#
# \arguments{
# \item{this}{An object.}
# \item{...}{Not used.}
# }
#
#
# \value{
# Returns an invisible TRUE if no inconsistencies found in the object, throws
# an error otherwise.
# }
#
# @author
#
# \seealso{
# @seeclass
# }
#
#*/###########################################################################
setMethodS3(
"checkConsistency",
class="AminoAcidSubst",
function(
this,
...
){
wp<-this$writeProtected;
if (wp) {
this$writeProtected<-FALSE;
}
may.fail<-function(this) {
if(!inherits(this$alphabet, "AminoAcidAlphabet")){
throw("This process must have as alphabet an AminoAcidAlphabet object!\n");
}
if(!any(is.na(this$.s.matrix))){
for(i in this$.alphabet$.symbols){
for(j in this$.alphabet$.symbols){
if(i != j){
expected<-this$.s.matrix[i, j] * this$.equ.dist[1,j];
actual<-this$.q.matrix$.orig.matrix[i,j];
if(!PSRoot$my.all.equal(expected, actual)){
throw("The rate matrix is not compatible with the exchangeability matrix and the equilibrium distribution!\n");
}
}
}
}
}
}
tryCatch(may.fail(this),finally=this$writeProtected<-wp);
NextMethod();
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);
##
## Method: buildFromPAML
##
###########################################################################/**
#
# @RdocMethod buildFromPAML
#
# @title "Build rate matrix from PAML file"
#
# \description{
# @get "title".
# }
#
# @synopsis
#
# \arguments{
# \item{this}{An AminoAcidSubst object.}
# \item{paml.file}{Path to the PAML file.}
# \item{...}{Not used.}
# }
#
# \value{
# The AminoAcidSubst object (invisible).
# }
#
# \examples{
# # create an object
# p<-AminoAcidSubst()
# # build rate matrix from paml file
# # buildFromPAML(p,"path_to_paml_file") # do not run this
# # get object summary
# summary(p)
# }
#
# @author
#
# \seealso{
# @seeclass
# }
#
#*/###########################################################################
setMethodS3(
"buildFromPAML",
class="AminoAcidSubst",
function(
this,
paml.file,
...
){
if(!missing(paml.file)){
data<-.readFromPAML(this, paml.file=paml.file);
this$.paml.file<-paml.file;
if(all(is.na(this$equDist))){
setEquDist(this, value=data[["pi"]], force=TRUE, silent=TRUE)
}
S<-data$S;
this$.s.matrix<-S;
for(i in this$.alphabet$.symbols){
for(j in this$.alphabet$.symbols){
if(i != j){
setRate(this$.q.matrix,from=i,to=j,value=(S[i,j] * this$.equ.dist[1, j]),scale=FALSE);
}
}
}
.callRateRescaling(this$.q.matrix,guess.equ=FALSE);
}
else{
throw("PAML data file not specified");
}
return(invisible(this));
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);
##
## Method: .readFromPAML
##
setMethodS3(
".readFromPAML",
class="AminoAcidSubst",
function(
this,
paml.file,
...
){
if(missing(paml.file)){
throw("No PAML data file specified!\n");
}
else if(file.access(c(paml.file), mode=0) != c(0)){
throw("The specified PAML data file \"",paml.file,"\" does not exist!\n",sep="");
}
else if(file.access(c(paml.file), mode=4) != c(0)){
throw("The specified PAML data file \"",paml.file,"\" cannot be opened for reading because of insufficient permissions!\n",sep="");
}
else {
size<-this$alphabet$size;
symbols<-this$alphabet$symbols;
lines<-scan(file=paml.file,what="character",sep="\n",blank.lines.skip=FALSE,quiet=TRUE);
is.blank<-function(line){
if(length(grep(pattern="^\\s*$",x=line,perl=TRUE,value=FALSE)) > 0 ){
return(TRUE);
}
else if(length(grep(pattern="\\d",x=line,perl=TRUE,value=FALSE)) < 1){
# If the line has no decimal number than is considered blank!
return(TRUE);
}
return(FALSE);
}
# Skip blank lines:
count<-1;
while(is.blank(lines[[count]])){
count<-count+1;
}
skip<-count-1;
# Find the beggining of the equilibrium distribution:
count<-skip+size+1;
while(is.blank(lines[[count]])){
count<-count+1;
}
equ.skip<-count-1;
# How many lines has the equilibrium distribution?
count<-equ.skip;
while(!is.blank(lines[[count<-count+1]])){ }
equ.nlines<-count-equ.skip-1;
# We don't need the lines any more.
rm(lines);
# Reading the exchangeability matrix:
# Assuming here that the order of the
# amino acids is the same as in the AminoAcidAlphabet
# object.
numbers<-scan(file=paml.file,what=0.0,skip=skip,nlines=(size-1),quiet=TRUE);
if(length(numbers) != ((size^2-size)/2)){
throw("Error reading exchangeability matrix from PAML data file!\n");
}
s.matrix<-matrix(nrow=size,ncol=size);
diag(s.matrix)<-0;
colnames(s.matrix)<-symbols;
rownames(s.matrix)<-symbols;
counter<-1;
for(i in 1:size) {
for(j in 1:i){
if( i!= j){
s.matrix[i, j]<-numbers[counter];
s.matrix[j, i]<-numbers[counter];
counter<-counter + 1;
}
}
}
# Reading the equilibrium distribution:
equ.dist<-(scan(file=paml.file,what=0.0,skip=equ.skip, nlines=equ.nlines, quiet=TRUE));
if(length(equ.dist) != size){
throw("Error reading equlibrium distribution from PAML data file!\n");
}
equ.dist<-rbind(equ.dist);
colnames(equ.dist)<-symbols;
return(list(
"S"=s.matrix,
"pi"=equ.dist
));
}
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);
##
## Method: setEquDist
##
setMethodS3(
"setEquDist",
class="AminoAcidSubst",
function(
this,
value,
force=FALSE,
silent=FALSE,
...
){
# Behave like GeneralSubstitution if the S matrix is empty.
if(any(is.na(this$.s.matrix))){
return(NextMethod());
}
.checkWriteProtection(this);
if(!is.Alphabet(this$alphabet)){
throw("Cannot set equilibrium distribution because the alphabet is undefined!");
}
if(missing(value)) {
throw("No new value provided!\n");}
else if(!is.numeric(value)) {
throw("The new value must be numeric!\n");
}
else if(length(value) != this$alphabet$size){
throw("The new value must be a vector of length ",this$alphabet$size,"!\n");
}
else if(!PSRoot$my.all.equal(sum(value), 1.0)) {
value<-(value/sum(value));
if (silent == FALSE){
warning("The provided probabilities were rescaled in order to sum to one!\n");
}
}
value<-rbind(value);
colnames(value)<-this$.alphabet$symbols;
this$.equ.dist<-value;
for(i in this$.alphabet$.symbols){
for(j in this$.alphabet$.symbols){
if(i != j){
setRate(this$.q.matrix,from=i,to=j,value=(this$.s.matrix[i,j] * value[1, j]),scale=FALSE);
}
}
}
.callRateRescaling(this$QMatrix,guess.equ=FALSE);
return(invisible(this));
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);
##
## Method: summary
##
###########################################################################/**
#
# @RdocMethod summary
#
# @title "Summarize the properties of an object"
#
# \description{
# @get "title".
# }
#
# @synopsis
#
# \arguments{
# \item{object}{An object}
# \item{...}{Not used.}
# }
#
# \value{
# Returns a PSRootSummary object.
# }
#
# \examples{
#
# # create an object
# a<-AminoAcidSubst()
# # get a summary
# summary(a)
# }
#
# @author
#
# \seealso{
# @seeclass
# }
#
#*/###########################################################################
setMethodS3(
"summary",
class="AminoAcidSubst",
function(
object,
...
){
this<-object;
.addSummaryNameId(this);
.addSummaryAlphabet(this);
if(is.na(this$.paml.file)){
this$.summary$"Unscaled rate matrix"<-paste( "\n\t",paste(capture.output(print(this$.q.matrix$matrix,digits=5)
),collapse="\n\t"),"\n",sep="");
}
else {
this$.summary$"PAML data file:"<-this$.paml.file;
this$.summary$"Unscaled rate matrix"<-"not shown";
}
this$.summary$"Equilibrium distribution"<-paste( "\n\t",paste(capture.output(print(this$.equ.dist)),collapse="\n\t"
),"\n",sep="");
NextMethod();
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);
##
## Method: newAAMatrix
##
###########################################################################/**
#
# @RdocMethod newAAMatrix
#
# @title "Undocumented method"
#
# \description{
# @get "title".
# }
#
# @synopsis
#
# \arguments{
# \item{name}{Object name}
# \item{paml.file}{PAML file.}
# \item{equ.dist}{Equilibrium distribution.}
# \item{...}{Not used.}
# }
#
# \value{
# A process object inheriting from AminoAcidSubst.
# }
#
#
# @author
#
# \seealso{
# @seeclass
# }
#
#*/###########################################################################
setMethodS3(
"newAAMatrix",
class="AminoAcidSubst",
function(
name=NA,
paml.file=NA,
equ.dist=NA,
...
){
PAMLDIR<-"./PAMLdat";
RDATDIR<-"./RData";
# Use the package data directory if loaded:
if(length(intersect(search(),c("package:phylosim"))) == 1){
RDATDIR<-paste(path.package("phylosim"),"/data/",sep="");
PAMLDIR<-paste(path.package("phylosim"),"/extdata/",sep="");
}
rdname<-paste(RDATDIR,"/",name,".RData",sep="");
if( ( file.access(c(rdname), mode=0) == c(0) ) & (file.access(c(rdname), mode=4) == c(0))){
this<-clone(Object$load(rdname));
}
else {
file<-paste(PAMLDIR,"/",paml.file,sep="");
this<-AminoAcidSubst(paml.file=file);
this<-extend(this,name);
this$name<-this$name;
save(this, file=rdname);
}
if(!any(is.na(equ.dist))){
setEquDist(this,value=equ.dist,force=TRUE);
}
return(this);
},
private=FALSE,
protected=FALSE,
overwrite=FALSE,
conflict="warning",
validators=getOption("R.methodsS3:validators:setMethodS3")
);