File: classesAndMethods.R

package info (click to toggle)
r-cran-markovchain 0.8.5-4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,060 kB
  • sloc: cpp: 2,854; sh: 13; makefile: 2
file content (1368 lines) | stat: -rw-r--r-- 42,664 bytes parent folder | download | duplicates (2)
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
#' @title Markov Chain class
#' @name markovchain-class
#' @aliases markovchain-class *,markovchain,markovchain-method
#'   *,markovchain,matrix-method *,markovchain,numeric-method
#'   *,matrix,markovchain-method *,numeric,markovchain-method
#'   ==,markovchain,markovchain-method !=,markovchain,markovchain-method
#'   absorbingStates,markovchain-method transientStates,markovchain-method
#'   recurrentStates,markovchain-method transientClasses,markovchain-method
#'   recurrentClasses,markovchain-method communicatingClasses,markovchain-method
#'   steadyStates,markovchain-method meanNumVisits,markovchain-method
#'   is.regular,markovchain-method is.irreducible,markovchain-method
#'   is.accessible,markovchain,character,character-method
#'   is.accessible,markovchain,missing,missing-method
#'   absorptionProbabilities,markovchain-method
#'   meanFirstPassageTime,markovchain,character-method 
#'   meanFirstPassageTime,markovchain,missing-method
#'   meanAbsorptionTime,markovchain-method
#'   meanRecurrenceTime,markovchain-method
#'   conditionalDistribution,markovchain-method hittingProbabilities,markovchain-method
#'   canonicForm,markovchain-method coerce,data.frame,markovchain-method
#'   coerce,markovchain,data.frame-method coerce,table,markovchain-method
#'   coerce,markovchain,igraph-method coerce,markovchain,matrix-method
#'   coerce,markovchain,sparseMatrix-method coerce,sparseMatrix,markovchain-method
#'   coerce,matrix,markovchain-method coerce,msm,markovchain-method
#'   coerce,msm.est,markovchain-method coerce,etm,markovchain-method
#'   dim,markovchain-method initialize,markovchain-method
#'   names<-,markovchain-method plot,markovchain,missing-method
#'   predict,markovchain-method print,markovchain-method
#'   show,markovchain-method summary,markovchain-method
#'   sort,markovchain-method t,markovchain-method
#'   [,markovchain,ANY,ANY,ANY-method ^,markovchain,numeric-method
#' @description The S4 class that describes \code{markovchain} objects.
#' 
#' @param states Name of the states. Must be the same of \code{colnames} and \code{rownames} of the transition matrix
#' @param byrow TRUE or FALSE indicating whether the supplied matrix 
#'   is either stochastic by rows or by columns
#' @param transitionMatrix Square transition matrix
#' @param name Optional character name of the Markov chain
#' 
#' @section Creation of objects:
#' 
#' Objects can be created by calls of the form \code{new("markovchain", states, byrow, transitionMatrix, ...)}.
#' 
#' @section Methods:
#' 
#' \describe{
#'    \item{*}{\code{signature(e1 = "markovchain", e2 = "markovchain")}: multiply two \code{markovchain} objects}
#'    \item{*}{\code{signature(e1 = "markovchain", e2 = "matrix")}: markovchain by matrix multiplication}
#'    \item{*}{\code{signature(e1 = "markovchain", e2 = "numeric")}: markovchain by numeric vector multiplication }
#'    \item{*}{\code{signature(e1 = "matrix", e2 = "markovchain")}: matrix by markov chain}
#'    \item{*}{\code{signature(e1 = "numeric", e2 = "markovchain")}: numeric vector by \code{markovchain} multiplication   }
#'    \item{[}{\code{signature(x = "markovchain", i = "ANY", j = "ANY", drop = "ANY")}: ... }
#'    \item{^}{\code{signature(e1 = "markovchain", e2 = "numeric")}: power of a \code{markovchain} object}
#'    \item{==}{\code{signature(e1 = "markovchain", e2 = "markovchain")}: equality of two \code{markovchain} object}
#'    \item{!=}{\code{signature(e1 = "markovchain", e2 = "markovchain")}: non-equality of two \code{markovchain} object}
#'    \item{absorbingStates}{\code{signature(object = "markovchain")}: method to get absorbing states }
#'    \item{canonicForm}{\code{signature(object = "markovchain")}: return a \code{markovchain} object into canonic form }
#'    \item{coerce}{\code{signature(from = "markovchain", to = "data.frame")}: coerce method from markovchain to \code{data.frame}}
#'    \item{conditionalDistribution}{\code{signature(object = "markovchain")}: returns the conditional probability of subsequent states given a state}
#'    \item{coerce}{\code{signature(from = "data.frame", to = "markovchain")}: coerce method from \code{data.frame} to \code{markovchain}}
#'    \item{coerce}{\code{signature(from = "table", to = "markovchain")}: coerce method from \code{table} to \code{markovchain} }
#'    \item{coerce}{\code{signature(from = "msm", to = "markovchain")}: coerce method from \code{msm} to \code{markovchain} }
#'    \item{coerce}{\code{signature(from = "msm.est", to = "markovchain")}: coerce method from \code{msm.est} (but only from a Probability Matrix) to \code{markovchain} }
#'    \item{coerce}{\code{signature(from = "etm", to = "markovchain")}: coerce method from \code{etm} to \code{markovchain} }
#'    \item{coerce}{\code{signature(from = "sparseMatrix", to = "markovchain")}: coerce method from \code{sparseMatrix} to \code{markovchain} }
#'    \item{coerce}{\code{signature(from = "markovchain", to = "igraph")}: coercing to \code{igraph} objects }
#'    \item{coerce}{\code{signature(from = "markovchain", to = "matrix")}: coercing to \code{matrix} objects }
#'    \item{coerce}{\code{signature(from = "markovchain", to = "sparseMatrix")}: coercing to \code{sparseMatrix} objects }
#'    \item{coerce}{\code{signature(from = "matrix", to = "markovchain")}: coercing to \code{markovchain} objects from \code{matrix} one }
#'    \item{dim}{\code{signature(x = "markovchain")}: method to get the size}
#'    \item{names}{\code{signature(x = "markovchain")}: method to get the names of states}
#'    \item{names<-}{\code{signature(x = "markovchain", value = "character")}: method to set the names of states}
#'    \item{initialize}{\code{signature(.Object = "markovchain")}: initialize method }
#'    \item{plot}{\code{signature(x = "markovchain", y = "missing")}: plot method for \code{markovchain} objects }
#'    \item{predict}{\code{signature(object = "markovchain")}: predict method }
#'    \item{print}{\code{signature(x = "markovchain")}: print method. }
#'    \item{show}{\code{signature(object = "markovchain")}: show method. }
#'    \item{sort}{\code{signature(x = "markovchain", decreasing=FALSE)}: sorting the transition matrix. }
#'    \item{states}{\code{signature(object = "markovchain")}: returns the names of states (as \code{names}. }
#'    \item{steadyStates}{\code{signature(object = "markovchain")}: method to get the steady vector. }
#'    \item{summary}{\code{signature(object = "markovchain")}: method to summarize structure of the markov chain }
#'    \item{transientStates}{\code{signature(object = "markovchain")}: method to get the transient states. }
#'    \item{t}{\code{signature(x = "markovchain")}: transpose matrix }
#'    \item{transitionProbability}{\code{signature(object = "markovchain")}: transition probability }
#' }
#' 
#' @references 
#' A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#' 
#' @author Giorgio Spedicato
#' @note  
#' \enumerate{
#' \item \code{markovchain} object are backed by S4 Classes.
#' \item Validation method is used to assess whether either columns or rows totals to one. 
#' Rounding is used up to \code{.Machine$double.eps * 100}. If state names are not properly
#' defined for a probability  \code{matrix}, coercing to \code{markovhcain} object leads 
#' to overriding states name with artificial "s1", "s2", ... sequence. In addition, operator
#' overloading has been applied for \eqn{+,*,^,==,!=} operators.
#' }
#' 
#' @seealso \code{\link{markovchainSequence}},\code{\link{markovchainFit}}
#' 
#' @examples
#' #show markovchain definition
#' showClass("markovchain")
#' #create a simple Markov chain
#' transMatr<-matrix(c(0.4,0.6,.3,.7),nrow=2,byrow=TRUE)
#' simpleMc<-new("markovchain", states=c("a","b"),
#'               transitionMatrix=transMatr, 
#'               name="simpleMc")
#' #power
#' simpleMc^4
#' #some methods
#' steadyStates(simpleMc)
#' absorbingStates(simpleMc)
#' simpleMc[2,1]
#' t(simpleMc)
#' is.irreducible(simpleMc)
#' #conditional distributions
#' conditionalDistribution(simpleMc, "b")
#' #example for predict method
#' sequence<-c("a", "b", "a", "a", "a", "a", "b", "a", "b", "a", "b", "a", "a", "b", "b", "b", "a")
#' mcFit<-markovchainFit(data=sequence)
#' predict(mcFit$estimate, newdata="b",n.ahead=3)
#' #direct conversion
#' myMc<-as(transMatr, "markovchain")
#' 
#' #example of summary
#' summary(simpleMc)
#' \dontrun{plot(simpleMc)}
#' 
#' @keywords classes
#' 
#' @export
setClass(
  # Class name
  "markovchain",
  # Define the slots
  slots = list(states = "character", byrow = "logical",
  transitionMatrix = "matrix", name = "character"),
  # Set the default values for the slots
  prototype = list(
    states = c("a", "b"), 
    byrow = TRUE,
    transitionMatrix = matrix(
      data = c(0, 1, 1, 0), 
      nrow = 2, 
      byrow = TRUE, 
      dimnames = list(c("a", "b"), c("a", "b"))), 
    name = "Unnamed Markov chain")
)

# Initializing method for markovchain objects
setMethod(
  "initialize",
  signature(.Object = "markovchain"),
  function (.Object, states, byrow, transitionMatrix, name, ...) {
    # Put the standard markovchain
    if (missing(transitionMatrix)) {
      transitionMatrix <- matrix(
        data = c(0, 1, 1, 0),
        nrow = 2,
        byrow = TRUE,
        dimnames = list(c("a", "b"), c("a", "b")))
    }
    
    rowNames <- rownames(transitionMatrix)
    colNames <- colnames(transitionMatrix)
    
    # Check names of transition matrix
    # if all names are missing it initializes them to "1", "2", ....
    if (all(is.null(rowNames), is.null(colNames)) == TRUE) {
      if (missing(states)) {
        numRows <- nrow(transitionMatrix)
        stateNames <- as.character(seq(1:numRows))
      } else {
        stateNames <- states
      }
      
      rownames(transitionMatrix) <- stateNames
      colnames(transitionMatrix) <- stateNames
      
    # Fix when rownames null
    } else if (is.null(rowNames)) {
      rownames(transitionMatrix) <- colNames
    # Fix when colnames null
    } else if (is.null(colNames)) {
      colnames(transitionMatrix) <- rowNames
    # Fix when different
    } else if (! setequal(rowNames, colNames)) {
      colnames(transitionMatrix) <- rowNames
    }
    
    if (missing(states))
      states <- rownames(transitionMatrix)
    
    if (missing(byrow))
      byrow <- TRUE
    
    if (missing(name))
      name <- "Unnamed Markov chain"
    
    callNextMethod(
      .Object,
      states = states,
      byrow = byrow,
      transitionMatrix = transitionMatrix,
      name = name,
      ...
    )
  }
)

#' @title Non homogeneus discrete time Markov Chains class
#' @name markovchainList-class
#' @aliases [[,markovchainList-method dim,markovchainList-method
#'   predict,markovchainList-method print,markovchainList-method
#'   show,markovchainList-method
#' @description A class to handle non homogeneous discrete Markov chains
#' 
#' @param markovchains Object of class \code{"list"}: a list of markovchains
#' @param name Object of class \code{"character"}: optional name of the class
#' 
#' @section Objects from the Class:
#'
#'   A \code{markovchainlist} is a list of \code{markovchain} objects. They can
#'   be used to model non homogeneous discrete time Markov Chains, when
#'   transition probabilities (and possible states) change by time.
#' @section Methods:
#' \describe{
#' \item{[[}{\code{signature(x = "markovchainList")}: extract the
#' i-th \code{markovchain} }
#' \item{dim}{\code{signature(x = "markovchainList")}: number 
#' of \code{markovchain} underlying the matrix }
#' \item{predict}{\code{signature(object = "markovchainList")}: predict 
#' from a \code{markovchainList} }
#' \item{print}{\code{signature(x = "markovchainList")}: prints the list 
#'   of markovchains }
#' \item{show}{\code{signature(object = "markovchainList")}: same as \code{print} }
#' }
#' 
#' @references 
#' A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#' 
#' @author  Giorgio Spedicato
#' 
#' @note 
#' The class consists in a list of \code{markovchain} objects. 
#' It is aimed at working with non homogeneous Markov chains.
#' 
#' @seealso \code{\linkS4class{markovchain}}
#' @examples
#' showClass("markovchainList")
#' #define a markovchainList
#' statesNames=c("a","b")
#' 
#' mcA<-new("markovchain",name="MCA", 
#'          transitionMatrix=matrix(c(0.7,0.3,0.1,0.9),
#'                           byrow=TRUE, nrow=2, 
#'                           dimnames=list(statesNames,statesNames))
#'         )
#'                                                            
#' mcB<-new("markovchain", states=c("a","b","c"), name="MCB",
#'          transitionMatrix=matrix(c(0.2,0.5,0.3,0,1,0,0.1,0.8,0.1),
#'          nrow=3, byrow=TRUE))
#'  
#' mcC<-new("markovchain", states=c("a","b","c","d"), name="MCC",
#'          transitionMatrix=matrix(c(0.25,0.75,0,0,0.4,0.6,
#'                                    0,0,0,0,0.1,0.9,0,0,0.7,0.3), 
#'                                  nrow=4, byrow=TRUE)
#' )
#' mcList<-new("markovchainList",markovchains=list(mcA, mcB, mcC), 
#'            name="Non - homogeneous Markov Chain")
#' 
#' @keywords classes
#' 
#' @export
setClass(
  "markovchainList",
  slots = list(
    markovchains = "list",
    name = "character")
)

# Verifies whether a markovchainList object is valid or not
# A markovchainList is valid iff all the slots are markovchain objects
# Returns true if the markovchainList is valid, the indexes of the
# wrong slots otherwise
setValidity(
  "markovchainList",
  function(object) {
    check <- FALSE
    markovchains <- object@markovchains
    
    classes <- sapply(markovchains, class)
    nonMarkovchain <- which(classes != "markovchain")
    errors <- sapply(nonMarkovchain, function(i) {
      paste(i, "-th element class is not 'markovchain'")
    })
    
    if (length(errors) == 0) TRUE else errors
  }
)

# generic method to print out states

#' @name states
#' 
#' @title Defined states of a transition matrix
#' 
#' @description This method returns the states of a transition matrix.
#' 
#' @param object A discrete \code{markovchain} object
#' @return The character vector corresponding to states slot.
#' 
#' @references A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#' 
#' @author Giorgio Spedicato
#' 
#' @seealso \code{\linkS4class{markovchain}}
#' 
#' @examples 
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix =
#'                 matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
#'                 byrow = TRUE, dimnames=list(statesNames,statesNames)),
#'                 name = "A markovchain Object" 
#' )
#' states(markovB)
#' names(markovB)
#' 
#' @rdname states
#' 
#' @export
setGeneric("states", function(object) standardGeneric("states"))

#' @rdname states
#' @title states
setMethod(
  "states",
  "markovchain", 
  function(object) {
    object@states
  }
)

#' @title Returns the states for a Markov chain object
#'
#' @param x object we want to return states for
#' 
#' @rdname names
setMethod(
  "names",
  "markovchain", 
  function(x) {
    x@states
  }
)

#' @title Method to retrieve name of markovchain object  
#' 
#' @name name
#' 
#' @description This method returns the name of a markovchain object
#' 
#' @param object A markovchain object
#' @rdname getName
#' @author Giorgio Spedicato, Deepak Yadav
#' 
#' @examples 
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix =
#'                 matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
#'                 byrow = TRUE, dimnames=list(statesNames,statesNames)),
#'                 name = "A markovchain Object" 
#' )
#' name(markovB)
#' 
#' @export
setGeneric("name", function(object) standardGeneric("name"))


#' @rdname getName
setMethod(
  "name", 
  "markovchain", 
  function(object) {
    object@name
})

#' @title Method to set name of markovchain object
#' 
#' @name name<-
#' 
#' @description This method modifies the existing name of markovchain object
#' 
#' @param object A markovchain object
#' @param value New name of markovchain object
#' @rdname setName
#' @author Giorgio Spedicato, Deepak Yadav
#' 
#' @examples 
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix =
#'                 matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
#'                 byrow = TRUE, dimnames=list(statesNames,statesNames)),
#'                 name = "A markovchain Object" 
#' )
#' name(markovB) <- "dangerous mc"
#' 
#' @export
setGeneric("name<-", function(object, value) standardGeneric("name<-"))

#' @rdname setName
setMethod(
  "name<-", 
  "markovchain", 
  function(object, value) {
    object@name <- value
    object
  }
)

setMethod(
  "names<-", 
  "markovchain", 
  function(x, value) {
    rownames(x@transitionMatrix) <- value
    colnames(x@transitionMatrix) <- value
    x@states <- value
    x
  }
)


#' @exportMethod dim
setGeneric("dim")

# Generic methods to get the dim of a markovchain and markovchainList
setMethod(
  "dim",
  "markovchain", 
  function(x) {
    nrow(x@transitionMatrix)
  }
)

setMethod(
  "dim",
  "markovchainList", 
  function(x) {
    length(x@markovchains)
  }
)


# method  to set the validity of a markovchain object
setValidity(
  "markovchain",
  function(object) {
    errors <- character()
    transitionMatrix <- object@transitionMatrix
    states           <- object@states
    
    if (length(setdiff(states, unique(states))) > 0) {
      msg    <- "Error! States must be unique!"
      errors <- c(errors, msg)
    }
    # Performs a set of checks. If any error arises, it ends up concatenated to errors
    
    # Check all values of transition matrix belongs to [0, 1]
    maybeProbabilities <- sapply(as.numeric(transitionMatrix), .isProbability)
    
    if (any(maybeProbabilities) == FALSE) {
      msg    <- "Error! Some elements of transitionMatrix are not probabilities"
      errors <- c(errors, msg)
    }
    
    # Check whether matrix is square matrix or not
    if (nrow(transitionMatrix) != ncol(transitionMatrix)) {
      msg    <- "Error! transitionMatrix is not a square matrix"
      errors <- c(errors, msg)
    }
    
    if (!.checkMatrix(transitionMatrix, object@byrow)) {
      msg <- paste(
               paste("Error!", 
               ifelse(object@byrow, "Rows", "Cols")),
               "of transition matrix do not sum to one"
             )
      errors <- c(errors, msg)
    }
    
    # Check whether column names or rows names equal to state names or not
    if (! setequal(colnames(transitionMatrix), states)) {
      msg    <- "Error! Colnames of transitionMatrix do not match states"
      errors <- c(errors, msg)
    }
    if (! setequal(rownames(transitionMatrix), states)) {
      msg    <- "Error! Rownames of transitionMatrix do not match states"
      errors <- c(errors, msg)
    }
    
    if (length(errors) > 0) errors else TRUE
  }
)


# generic method to extract transition probability
# from state t0 to state t1

#' @name transitionProbability
#' @title Function to get the transition probabilities from initial 
#'        to subsequent states.
#' @description This is a convenience function to get transition probabilities.
#' 
#' @param object A \code{markovchain} object.
#' @param t0 Initial state.
#' @param t1 Subsequent state.
#' 
#' @references A First Course in Probability (8th Edition), 
#'             Sheldon Ross, Prentice Hall 2010
#' 
#' @return Numeric Vector  
#' 
#' @author Giorgio Spedicato
#' @seealso \code{\linkS4class{markovchain}}
#' 
#' @examples 
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix =
#'                 matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
#'                 byrow = TRUE, dimnames=list(statesNames,statesNames)),
#'                name = "A markovchain Object" 
#' )    
#' transitionProbability(markovB,"b", "c")
#' @rdname transitionProbability
#'      
#' @exportMethod transitionProbability
setGeneric("transitionProbability", function(object, t0, t1) standardGeneric("transitionProbability"))

#' @rdname transitionProbability
setMethod("transitionProbability", "markovchain", 
  function(object, t0, t1) {
    fromState <- which(object@states == t0)
    toState <- which(object@states == t1)
    out <- ifelse(object@byrow == TRUE, object@transitionMatrix[fromState, toState] , 
                  object@transitionMatrix[toState, fromState])
    return(out)
  }
)

#  print, plot and show methods

.showInt <- function(object, verbose = TRUE) {
	
  # find the direction
  if (object@byrow == TRUE) {
	  direction <- "(by rows)" 
	} else {
	  direction <- "(by cols)" 
	}
  
	if (verbose == TRUE) {
	  cat(object@name, "\n A ", dim(object), "- dimensional discrete Markov Chain defined by the following states: \n",
	      paste(states(object), collapse=", "), "\n The transition matrix ", 
	      direction, " is defined as follows: \n")
	}
  
	print(object@transitionMatrix)
	cat("\n")
}

#' @exportMethod show
setGeneric("show")

# show methods for markovchain and markovchain list objects 
setMethod("show", "markovchain",
  function(object){
    .showInt(object)
  }
)

setMethod("show", "markovchainList",
  function(object) {
    cat(object@name, " list of Markov chain(s)", "\n")
    for(i in 1:length(object@markovchains)) {
      cat("Markovchain ",i,"\n")
      show(object@markovchains[[i]])
    }
  }
)

#' @exportMethod print
setGeneric("print")

# print methods
setMethod("print", "markovchainList", function(x) show(x))
setMethod("print", "markovchain",
  function(x){
   object <- x
   .showInt(object, verbose = FALSE)
  }
)

.getNet <- function(object, round = FALSE) {
 	
  # function to get the absorbency matrix to plot and export to igraph
	#
 	# Args: 
	# object: a markovchain object
	# round: boolean to round
 	#
	# Returns:
	#
	# a graph adjacency
  
	if (object@byrow == FALSE) {
	  object <- t(object)
	}
  
	matr <- object@transitionMatrix*100
	if(round == TRUE) {
	  matr <- round(matr, 2)
	}
	
	net <- graph.adjacency(adjmatrix = matr, weighted = TRUE, mode = "directed")
	return(net)
}

getColorVector <- function(object){
  list <- .communicatingClassesRcpp(object)
  sections <- length(list)
  colorList <- grDevices::colors()
  colorList <- sample(colorList,sections)
  colorvector <- rep("white",length(object@states))
  for(i in 1:length(list)){
    part <- list[[i]]
    for(j in 1:length(part)){
      colorvector[match(part[j],object@states)] <- colorList[i]
    }
  }
  return(colorvector)
}


#' @exportMethod plot
setGeneric("plot")

# Plot methods for markovchain objects

# plot method from stat5
setMethod("plot", signature(x = "markovchain", y = "missing"),
  function(x, y, package = "igraph", ...) {
    switch(package,
     diagram = {
       if (requireNamespace("diagram", quietly = TRUE)) {
         .plotdiagram(object = x, ...)
       } else {
         netMc <- .getNet(object = x, round = TRUE)
         edgeLabel <- round(E(netMc)$weight / 100, 2)
         plot.igraph(x = netMc, edge.label = edgeLabel, ...)
       }
     },
     
     DiagrammeR = {
       if (requireNamespace("DiagrammeR", quietly = TRUE)) {
         .plotDiagrammeR(object = x, ...)
       } else {
         netMc <- .getNet(object = x, round = TRUE)
         edgeLabel <- round(E(netMc)$weight / 100, 2)
         plot.igraph(x = netMc, edge.label = edgeLabel, ...)
       }
     },
     {
       netMc <- .getNet(object = x,round = TRUE)
       edgeLabel <- round(E(netMc)$weight / 100, 2)
       plot.igraph(x = netMc, edge.label = edgeLabel, ...)
    })
  }
)


##################################################AS METHODS#########################

.checkMatrix <- function(matr, byrow = TRUE, verbose = FALSE) {
	
  # firstly, check size
	if (ncol(matr) != nrow(matr)) {
		if(verbose) stop("Error! Not a rectangular matrix")
		return(FALSE)
	}
  
  # secondly, check is stochastic
  isStochastic <- .isStochasticMatrix(matr, byrow)
  
  if (!isStochastic) {
    if (verbose)
	    stop("Error! Either rows or cols should sum to 1")
  
	  return(FALSE)
  }
  
	# if all test are passed
	return(TRUE)
}

# Internal function to return a markovchain object given a matrix
.matrix2Mc <- function(from) {
	
  # whether given matrix is a transition matrix or not
  # if it is then how probabilities are stored
  # row-wise or columnwise
  
	byrow <- TRUE
	checkByRows <- .checkMatrix(from, byrow = byrow)
	
	if(!checkByRows) {
	  byrow <- FALSE
		checkByCols <- .checkMatrix(from, byrow = byrow)
		
		if(!checkByCols) {
		  #error could be either in rows or in cols
		  if (any(colSums(from) != 1)) cat("columns sums not equal to one are:", which(colSums(from) != 1),"\n")
		  if (any(rowSums(from) != 1)) cat("row sums not equal to one are:", which(rowSums(from) != 1),"\n")
		  stop("Error! Not a transition matrix")	
		}
	}
	
	# extract states names
	if(byrow) {
	  namesCandidate <- rownames(from) 
	} else {
	  namesCandidate <- colnames(from)
	}
	
	# if states names is not there create it s1, s2, s3, ....
	if(is.null(namesCandidate)) {
		namesCandidate <- paste("s", 1:nrow(from), sep = "")
	}
	
	# create markovchain object
	out <- new("markovchain", transitionMatrix = from, states = namesCandidate, byrow = byrow)
	
	invisible(out)
}

#' @exportMethod coerce
NULL

# coerce matrix to markovchain object using internal method
# example: as("some matrix", "markovchain")
setAs(from = "matrix", to = "markovchain", def = .matrix2Mc)

# Function to transform a markovchain into a data.frame
# Args:
# from: a markovchain object
#
# returns:
# a data.frame
.mc2Df <- function(from) {
  
  # number of rows or columns
	nr <- nrow(from@transitionMatrix)
	for(i in 1:nr){
		for(j in 1:nr){
			t0 <- from@states[i]
			t1 <- from@states[j]
			prob <- transitionProbability(object = from, t0 = t0, t1 = t1)
			#cope with the new default of R 4.0 (5-3-2020)
			rowDf <- data.frame(t0 = t0, t1 = t1, prob = prob,stringsAsFactors = TRUE )
			
			# go to else part if first row of data frame is generated
			if(exists("outDf")) {
			  outDf <- rbind(outDf, rowDf)
			} else {
			  outDf <- rowDf
			}
		}
	}
	
	return(outDf)
}

# method to convert(coerce) from markovchain to data.frame
setAs(from = "markovchain", to = "data.frame", def = .mc2Df)

# method to find the column which stores transition probability
.whichColProb <- function(df) {
	
  # column number which stores transition probability
  out <- 0
  
  # check for validity of data frame
	if(ncol(df) > 3) {
	  warning("Warning! More than three columns. Only the first three will be used")
	}
  
	if(ncol(df) < 3) {
	  stop("Error! Three columns needed")
	}
	
	for(i in 1:ncol(df)) {
	    
	  # when found the first numeric and probability col
			if((class(df[, i]) == "numeric") & (all(sapply(df[, i], .isProbability) == TRUE))) {
					out <- i
					break
			}
	}
  
	return(out)
}

# Function to convert from a data.frame containing initial, ending 
#    and probability columns to a proper markovchain object
#
# Args:
# from: a data.frame
#
# Returns:
# A markovchain object 

.df2Mc <- function(from) {
	
	statesNames <- unique(from[, 1])
	colProb <- .whichColProb(from) # what is the use
	
	# transition matrix
	prMatr <- zeros(length(statesNames))
	rownames(prMatr) <- statesNames
	colnames(prMatr) <- statesNames
	
	
	for(i in 1:nrow(from)) {
		idRow <- which(statesNames == from[i, 1]) # assume first col from
		idCol <- which(statesNames == from[i, 2]) # assume second col to
		prMatr[idRow, idCol] <- from[i, 3]        # assume third col t-probability
	}
	
 	out <- new("markovchain", transitionMatrix = prMatr)
	return(out)
}

# method to convert(coerce) data frame to markovchain object 
setAs(from = "data.frame", to = "markovchain", def = .df2Mc)


# example
# data <- data.frame(from = c("a", "a", "b", "b", "b", "b"), 
#                      to = c("a", "b", "b", "b", "b", "a"))
# 
# from <- table(data)
# .table2Mc(from)

.table2Mc <- function(from) {
	
  # check whether table has square dimension or not
	if(dim(from)[1] != dim(from)[2]) {
	  stop("Error! Table is not squared")
	}
  
  # rows ond columns name should be same
	if(!setequal(rownames(from),colnames(from))) {
	  stop("Error! Rows not equal to coulumns")
	}
  
  temp <- unclass(as.matrix(from))
  
  # make same sequence of col / row
	fromMatr <- temp[, order(rownames(temp))]
	
	# obtain transition matrix
	outMatr <- fromMatr / rowSums(fromMatr)
	
	out <- new("markovchain", states = rownames(temp), 
	           transitionMatrix = outMatr, byrow=TRUE)
	
	return(out)
}

# coerce table to markovchain object
setAs(from = "table", to = "markovchain", def = .table2Mc)


# function from msm to markovchain
# msm is a package. Use this package to create msm object.
# see how to create msm object using ?msm

.msm2Mc <- function(from) {
  temp <- msm::pmatrix.msm(from)
  prMatr <- unclass(as.matrix(temp))
  out <- new("markovchain", transitionMatrix = prMatr)
  return(out)
}


# coerce msm object to markovchain object
setClass("msm")
setAs(from = "msm", to = "markovchain", def = .msm2Mc)


# function for msm.est to mc. Assume a probability matrix given
.msmest2Mc <- function(from) {
  
  if (is.matrix(from)) {
    # central estimate
    pMatr <- from 
  }
    
  if (is.list(from)) {
    # central estimate
    pMatr <- from[[1]] 
  }
    
  out <- new("markovchain", transitionMatrix = as(pMatr, "matrix"))
  
  return(out)
}

# coerce ms.est to markovchain object
setClass("msm.est")
setAs(from = "msm.est", to = "markovchain", def = .msmest2Mc)


# function from etm to markovchain
.etm2Mc<-function(from) {
  
  # data frame consists of  'from' and 'to' column
  df <- from$trans
  
  # name of states
  elements <- from$state.names
  # number of unique states
  nelements <- length(elements)
  
  # temporary t-matrix
  prMatr <- matlab::zeros(nelements)
  dimnames(prMatr) <- list(elements, elements)
  
  # populate t-matrix
  for(i in 1:dim(df)[1]) {
    r <- df[i, ] # each row one by one
    stateFrom <- r$from
    stateTo <- r$to
    prMatr[stateFrom, stateTo] <- prMatr[stateFrom, stateTo] + 1
  }
  
  # convert freq-matrix to trans-matrix
  rsums <- rowSums(prMatr)
  prMatr <- prMatr / rsums
  
  # take care of rows with all entries 0
  if(any(rsums == 0)) {
    indicesToBeSanitized <- which(rsums == 0)
    
    for(i in indicesToBeSanitized) {
      for(j in 1:nelements) {
        prMatr[i, j] <- 1 / nelements
      }
    }
  }
  
  # create markovchain object
  out <- new("markovchain", transitionMatrix = prMatr)
  return(out)
}

# coerce etm object to markovchain object
setClass("etm")
setAs(from = "etm", to = "markovchain", def = .etm2Mc)


#sparse matrix from Matrix package
.sparseMatrix2markovchain<-function(from){
  temp<-as(from,"matrix")
  out <- as(temp, "markovchain")
  return(out)
}

.markovchain2sparseMatrix<-function(from){
  temp<-as(from,"matrix")
  out <- as(temp, "sparseMatrix")
  return(out)
}


setAs(from = "sparseMatrix", to = "markovchain", def = .sparseMatrix2markovchain)
setAs(from = "markovchain", to = "sparseMatrix", def = .markovchain2sparseMatrix)



# functions and methods to return a matrix
.mc2matrix <- function(from) {
	out <- from@transitionMatrix
	return(out)
}

# coerce markovchain object to matrix(transition)
setAs(from = "markovchain", to = "matrix", def = .mc2matrix)


# functions and methods to return a matrix
.mc2igraph <- function(from) {
  
  # convert the markovchain to data.frame
	temp <- .mc2Df(from=from) 
	
	# convert the data frame to igraph graph
	# need to set only non zero weights
	out <- graph.data.frame(d=temp[temp$prob>0,]) 
	return(out)
}

# coerce markovchain object to igraph
setClass("igraph")
setAs(from = "markovchain", to = "igraph", def = .mc2igraph)


#' @exportMethod t
setGeneric("t")


# transposing method for markovchain objects
setMethod("t", "markovchain", 
  function(x) { 
    out <- new("markovchain", byrow = !x@byrow, 
               transitionMatrix = t(x@transitionMatrix))
    
    return(out)
  } 
)

#' @exportMethod *
setGeneric("*")

# function to multiplicate two markov chains
#
# Args:
# e1: first markovchain
# e2: second markov chain
#
# Returns:
# if feasible, a markovchain where the transition matrix is e1*e2

setMethod("*", c("markovchain", "markovchain"),
  function(e1, e2) {
    
    # compare states of markovchains
    if(!setequal(e1@states, e2@states)) {
      warning("Warning! Different states")
    }
    
    # dimension must be equal
    if(!setequal(dim(e1@transitionMatrix), dim(e2@transitionMatrix))) {
      stop("Error! Different size")
    }

    # both must be either row wise or col wise
    if(!(e1@byrow == e2@byrow)) {
      stop("Error! Both transition matrix should be defined either by row or by column")
    }

    newStates <- e1@states
    newTransMatr <- e1@transitionMatrix %*% e2@transitionMatrix
    byRow <- e1@byrow
    # multiplicated matrix takes the first matrix's name
    mcName <- e1@name 
    
    out<-new("markovchain", states = newStates, transitionMatrix = newTransMatr, 
             byrow = byRow, name = mcName)
    
    return(out)
  }
)

# methods implemented for multiplication of markovchain object with 
# matrix, 1-D vector, and vice-versa

setMethod("*", c("matrix", "markovchain"),
  function(e1, e2) {
    out <- e1 %*% e2@transitionMatrix
    return(out)
  }
)

setMethod("*", c("markovchain", "matrix"),
  function(e1, e2) {
    out <- e1@transitionMatrix %*% e2
    return(out)
  }
)

setMethod("*", c("numeric", "markovchain"), 
  function(e1, e2) {
    if(length(e1) != dim(e2)) {
      stop("Error! Uncompatible dimensions")
    } else {
      out <- e1 %*% e2@transitionMatrix
    }
    
    return(out)
  }
)

setMethod("*", c("markovchain", "numeric"), 
  function(e1, e2) {
    if(length(e2) != dim(e1)) {
      stop("Error! Uncompatible dimensions")
    } else {
      out <- e1@transitionMatrix %*% e2
    }
    
     return(out)
  }
)

#' @exportMethod ==
setGeneric("==")

# compare two markovchain object
setMethod("==", c("markovchain", "markovchain"), 
  function(e1, e2) {
    out <- .approxEqualMatricesRcpp(e1@transitionMatrix, e2@transitionMatrix)
    return(out)
  }
)

#' @exportMethod !=
setGeneric("!=")

setMethod("!=", c("markovchain", "markovchain"), 
  function(e1, e2) {
    out <- FALSE
    out <- !(e1 == e2)
    return(out)
  }
)

#'@exportMethod ^
setGeneric("^")

# markovchain raise to some power
# this method is O(n³ log(m)) where n = {num cols (= rows) of e1} and m = e2
setMethod("^", c("markovchain", "numeric"), 
  function(e1, e2) {
    out <- new("markovchain", states = e1@states, byrow = e1@byrow,
               transitionMatrix = e1@transitionMatrix %^% e2,
               name = paste(e1@name, "^", e2, sep = "")
              )
    
    return(out)
  }
)

#' @exportMethod [
setGeneric("[")

# methods to directly access transition matrix elements
setMethod("[", signature(x = "markovchain", i = "ANY", j = "ANY"), 
  function(x, i, j) {
    out <- x@transitionMatrix[i, j]
    return(out)
  }
)

#' @exportMethod [[
setGeneric("[[")

# methods to directly access markovchain objects composing a markovchainList object
setMethod("[[", signature(x = "markovchainList", i = "ANY"),
  function(x, i) {
    out <- x@markovchains[[i]]
    return(out)
  }
)

# transition probabilty vector from a given state

#' @title \code{conditionalDistribution} of a Markov Chain
#' 
#' @name conditionalDistribution
#' 
#' @description It extracts the conditional distribution of the subsequent state, 
#'              given current state.
#' 
#' @param object A \code{markovchain} object.
#' @param state Subsequent state.
#' 
#' @author Giorgio Spedicato, Deepak Yadav
#' 
#' @return A named probability vector
#' @references A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#' 
#' @seealso \code{\linkS4class{markovchain}}
#' 
#' @examples 
#' # define a markov chain
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix = 
#'                matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1),nrow = 3, 
#'                       byrow = TRUE, dimnames = list(statesNames, statesNames)))
#'                       
#' conditionalDistribution(markovB, "b")                       
#' 
#' @exportMethod conditionalDistribution
setGeneric("conditionalDistribution", function(object, state) standardGeneric("conditionalDistribution"))
setMethod("conditionalDistribution", "markovchain",
  function(object, state) {
    # get the states names
    stateNames <- states(object) 
    
    # number of unique states
    out <- numeric(length(stateNames))
    
    # states are assumed to be sorted
    index2Take <- which(stateNames == state) 
    
    if(object@byrow == TRUE) {
      out <- object@transitionMatrix[index2Take, ]
    } else {
      out <- object@transitionMatrix[, index2Take]
    }
    
    # names the output and returs it
    names(out) <- stateNames
    
    return(out) 
  }
)
		  
# Function to get the mode of a probability vector
# 
# Args:
# probVector: the probability vector
# ties: specifies if ties are to be sampled, otherwise more than one element is returned
#
# Returns:
# the name of the model element

.getMode <- function(probVector, ties = "random") {
	maxIndex <- which(probVector == max(probVector))
	temp <- probVector[maxIndex] # index of maximum probabilty
	
	if((ties == "random") & (length(temp) > 1)) {
	  out <- sample(temp, 1) 
	} else {
	  out <- temp
	}
	
	return(names(out))
}


#' @exportMethod predict
setGeneric("predict")

# predict method for markovchain objects
# given initial state return a vector of next n.ahead states

setMethod("predict", "markovchain", 
  function(object, newdata, n.ahead = 1) {
    # identify the last state
    lastState <- newdata[length(newdata)]
    out <- character()
    
    for(i in 1:n.ahead) {
      # cyclically determine the most probable subsequent state from the conditional distribution
      newState <- .getMode(probVector = conditionalDistribution(object, lastState), ties = "random") 
      out <- c(out, newState)
      lastState <- newState
    }
    
    return(out)
  }
)

# predict method for markovchainList objects
setMethod("predict", "markovchainList",
  function(object, newdata, n.ahead = 1, continue = FALSE) {
    # object a markovchainList
    # newdata = the actual data 
    # n.ahead = how much ahead 
    # continue = veryfy if that lasts
      
    # allocate output
    out <- character() 
    actualPos <- length(newdata) 
    lastState <- newdata[actualPos] # take last position
    for(i in 1:n.ahead) {
      newPos <- actualPos + i - 1
      if(newPos <= dim(object)) {
        newState <- predict(object = object[[newPos]], newdata = lastState, n.ahead = 1)
        out <- c(out, newState)
        lastState <- newState
      } else {
          if(continue == TRUE) {
            newState <- predict(object = object[[dim(object)]], newdata = lastState, n.ahead = 1)
            out <- c(out, newState)
            lastState <- newState
          } else break;
        }
    }

    return(out)
  }
)

#sort method for markovchain objects

setGeneric("sort", function(x, decreasing=FALSE, ...) standardGeneric("sort"))

setMethod("sort", signature(x="markovchain"), function(x, decreasing = FALSE) {
    #get matrix and state names 2 be sorted
   
    matr2besorted<-x@transitionMatrix 
    if (x@byrow) 
      states2besorted <- rownames(matr2besorted) 
    else 
      states2besorted <- colnames(matr2besorted)
    
    #sorting
    sort_index<-order(states2besorted,decreasing = decreasing)
    
    #reallocating
    matr_sorted<-matr2besorted[sort_index,sort_index]
    states_sorted<-states2besorted[sort_index]
    
    out<-x
    
    out@transitionMatrix<-matr_sorted
    out@states<-states_sorted
    
    return(out)
  }
)


# method to get stationary states

#' @name steadyStates
#' @title Stationary states of a \code{markovchain} object
#' 
#' @description This method returns the stationary vector in matricial form of a markovchain object.
#' @param object A discrete \code{markovchain} object
#' 
#' @return A matrix corresponding to the stationary states
#' 
#' @references A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#' @author Giorgio Spedicato
#' @seealso \code{\linkS4class{markovchain}}
#' 
#' @note The steady states are identified starting from which eigenvectors correspond 
#'       to identity eigenvalues and then normalizing them to sum up to unity. When negative values are found 
#'       in the matrix, the eigenvalues extraction is performed on the recurrent classes submatrix.
#'       
#' @examples 
#' statesNames <- c("a", "b", "c")
#' markovB <- new("markovchain", states = statesNames, transitionMatrix =
#'                 matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
#'                 byrow = TRUE, dimnames=list(statesNames,statesNames)),
#'                name = "A markovchain Object" 
#' )       
#' steadyStates(markovB)
#' 
#' @rdname steadyStates
#' @exportMethod steadyStates
setGeneric("steadyStates", function(object) standardGeneric("steadyStates"))