-
Notifications
You must be signed in to change notification settings - Fork 67
/
DTMCModelChecker.java
2530 lines (2184 loc) · 84.8 KB
/
DTMCModelChecker.java
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
//==============================================================================
//
// Copyright (c) 2002-
// Authors:
// * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford)
//
//------------------------------------------------------------------------------
//
// This file is part of PRISM.
//
// PRISM is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// PRISM is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with PRISM; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//==============================================================================
package explicit;
import java.io.File;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PrimitiveIterator;
import java.util.Vector;
import parser.VarList;
import parser.ast.Declaration;
import parser.ast.DeclarationIntUnbounded;
import parser.ast.Expression;
import prism.OptionsIntervalIteration;
import prism.Prism;
import prism.PrismComponent;
import prism.PrismException;
import prism.PrismFileLog;
import prism.PrismNotSupportedException;
import prism.PrismSettings;
import prism.PrismUtils;
import acceptance.AcceptanceReach;
import acceptance.AcceptanceType;
import automata.DA;
import common.IntSet;
import common.StopWatch;
import common.IterableBitSet;
import explicit.LTLModelChecker.LTLProduct;
import explicit.modelviews.DTMCAlteredDistributions;
import explicit.modelviews.MDPFromDTMC;
import explicit.rewards.MCRewards;
import explicit.rewards.MDPRewards;
import explicit.rewards.Rewards;
/**
* Explicit-state model checker for discrete-time Markov chains (DTMCs).
*/
public class DTMCModelChecker extends ProbModelChecker
{
/**
* Create a new DTMCModelChecker, inherit basic state from parent (unless null).
*/
public DTMCModelChecker(PrismComponent parent) throws PrismException
{
super(parent);
}
// Model checking functions
@Override
protected StateValues checkProbPathFormulaLTL(Model model, Expression expr, boolean qual, MinMax minMax, BitSet statesOfInterest) throws PrismException
{
LTLModelChecker mcLtl;
StateValues probsProduct, probs;
LTLModelChecker.LTLProduct<DTMC> product;
DTMCModelChecker mcProduct;
// For LTL model checking routines
mcLtl = new LTLModelChecker(this);
// Build product of Markov chain and automaton
AcceptanceType[] allowedAcceptance = {
AcceptanceType.RABIN,
AcceptanceType.REACH,
AcceptanceType.BUCHI,
AcceptanceType.STREETT,
AcceptanceType.GENERIC
};
product = mcLtl.constructProductMC(this, (DTMC)model, expr, statesOfInterest, allowedAcceptance);
// Output product, if required
if (getExportProductTrans()) {
mainLog.println("\nExporting product transition matrix to file \"" + getExportProductTransFilename() + "\"...");
product.getProductModel().exportToPrismExplicitTra(getExportProductTransFilename());
}
if (getExportProductStates()) {
mainLog.println("\nExporting product state space to file \"" + getExportProductStatesFilename() + "\"...");
PrismFileLog out = new PrismFileLog(getExportProductStatesFilename());
VarList newVarList = (VarList) modulesFile.createVarList().clone();
String daVar = "_da";
while (newVarList.getIndex(daVar) != -1) {
daVar = "_" + daVar;
}
newVarList.addVar(0, new Declaration(daVar, new DeclarationIntUnbounded()), 1, null);
product.getProductModel().exportStates(Prism.EXPORT_PLAIN, newVarList, out);
out.close();
}
// Find accepting states + compute reachability probabilities
BitSet acc;
if (product.getAcceptance() instanceof AcceptanceReach) {
mainLog.println("\nSkipping BSCC computation since acceptance is defined via goal states...");
acc = ((AcceptanceReach)product.getAcceptance()).getGoalStates();
} else {
mainLog.println("\nFinding accepting BSCCs...");
acc = mcLtl.findAcceptingBSCCs(product.getProductModel(), product.getAcceptance());
}
mainLog.println("\nComputing reachability probabilities...");
mcProduct = new DTMCModelChecker(this);
mcProduct.inheritSettings(this);
ModelCheckerResult res = mcProduct.computeReachProbs(product.getProductModel(), acc);
probsProduct = StateValues.createFromDoubleArray(res.soln, product.getProductModel());
// Output vector over product, if required
if (getExportProductVector()) {
mainLog.println("\nExporting product solution vector matrix to file \"" + getExportProductVectorFilename() + "\"...");
PrismFileLog out = new PrismFileLog(getExportProductVectorFilename());
probsProduct.print(out, false, false, false, false);
out.close();
}
// Mapping probabilities in the original model
probs = product.projectToOriginalModel(probsProduct);
probsProduct.clear();
return probs;
}
/**
* Compute rewards for a co-safe LTL reward operator.
*/
protected StateValues checkRewardCoSafeLTL(Model model, Rewards modelRewards, Expression expr, MinMax minMax, BitSet statesOfInterest) throws PrismException
{
LTLModelChecker mcLtl;
MCRewards productRewards;
StateValues rewardsProduct, rewards;
DTMCModelChecker mcProduct;
LTLProduct<DTMC> product;
// For LTL model checking routines
mcLtl = new LTLModelChecker(this);
// Model check maximal state formulas and construct DFA, with the special
// handling needed for cosafety reward translation
Vector<BitSet> labelBS = new Vector<BitSet>();
DA<BitSet, AcceptanceReach> da = mcLtl.constructDFAForCosafetyRewardLTL(this, model, expr, labelBS);
StopWatch timer = new StopWatch(mainLog);
mainLog.println("\nConstructing " + model.getModelType() + "-" + da.getAutomataType() + " product...");
timer.start(model.getModelType() + "-" + da.getAutomataType() + " product");
product = mcLtl.constructProductModel(da, (DTMC)model, labelBS, statesOfInterest);
timer.stop("product has " + product.getProductModel().infoString());
// Adapt reward info to product model
productRewards = ((MCRewards) modelRewards).liftFromModel(product);
// Output product, if required
if (getExportProductTrans()) {
mainLog.println("\nExporting product transition matrix to file \"" + getExportProductTransFilename() + "\"...");
product.getProductModel().exportToPrismExplicitTra(getExportProductTransFilename());
}
if (getExportProductStates()) {
mainLog.println("\nExporting product state space to file \"" + getExportProductStatesFilename() + "\"...");
PrismFileLog out = new PrismFileLog(getExportProductStatesFilename());
VarList newVarList = (VarList) modulesFile.createVarList().clone();
String daVar = "_da";
while (newVarList.getIndex(daVar) != -1) {
daVar = "_" + daVar;
}
newVarList.addVar(0, new Declaration(daVar, new DeclarationIntUnbounded()), 1, null);
product.getProductModel().exportStates(Prism.EXPORT_PLAIN, newVarList, out);
out.close();
}
// Find accepting states + compute reachability rewards
BitSet acc = ((AcceptanceReach)product.getAcceptance()).getGoalStates();
mainLog.println("\nComputing reachability rewards...");
mcProduct = new DTMCModelChecker(this);
mcProduct.inheritSettings(this);
ModelCheckerResult res = mcProduct.computeReachRewards((DTMC)product.getProductModel(), productRewards, acc);
rewardsProduct = StateValues.createFromDoubleArray(res.soln, product.getProductModel());
// Output vector over product, if required
if (getExportProductVector()) {
mainLog.println("\nExporting product solution vector matrix to file \"" + getExportProductVectorFilename() + "\"...");
PrismFileLog out = new PrismFileLog(getExportProductVectorFilename());
rewardsProduct.print(out, false, false, false, false);
out.close();
}
// Mapping rewards in the original model
rewards = product.projectToOriginalModel(rewardsProduct);
rewardsProduct.clear();
return rewards;
}
public ModelCheckerResult computeInstantaneousRewards(DTMC dtmc, MCRewards mcRewards, int k, BitSet statesOfInterest) throws PrismException
{
if (statesOfInterest.cardinality() == 1) {
return computeInstantaneousRewardsForwards(dtmc, mcRewards, k, statesOfInterest.nextSetBit(0));
} else {
return computeInstantaneousRewardsBackwards(dtmc, mcRewards, k);
}
}
public ModelCheckerResult computeInstantaneousRewardsBackwards(DTMC dtmc, MCRewards mcRewards, int k) throws PrismException
{
ModelCheckerResult res = null;
int i, n, iters;
double soln[], soln2[], tmpsoln[];
long timer;
// Store num states
n = dtmc.getNumStates();
// Start backwards transient computation
timer = System.currentTimeMillis();
mainLog.println("\nStarting backwards instantaneous rewards computation...");
// Create solution vector(s)
soln = new double[n];
soln2 = new double[n];
// Initialise solution vectors.
for (i = 0; i < n; i++)
soln[i] = mcRewards.getStateReward(i);
// Start iterations
for (iters = 0; iters < k; iters++) {
// Matrix-vector multiply
dtmc.mvMult(soln, soln2, null, false);
// Swap vectors for next iter
tmpsoln = soln;
soln = soln2;
soln2 = tmpsoln;
}
// Finished backwards transient computation
timer = System.currentTimeMillis() - timer;
mainLog.print("Backwards transient instantaneous rewards computation");
mainLog.println(" took " + iters + " iters and " + timer / 1000.0 + " seconds.");
// Return results
res = new ModelCheckerResult();
res.soln = soln;
res.lastSoln = soln2;
res.numIters = iters;
res.timeTaken = timer / 1000.0;
res.timePre = 0.0;
return res;
}
public ModelCheckerResult computeInstantaneousRewardsForwards(DTMC dtmc, MCRewards mcRewards, int k, int stateOfInterest) throws PrismException
{
// Build a point probability distribution for the required state
double[] initDist = new double[dtmc.getNumStates()];
initDist[stateOfInterest] = 1.0;
// Compute (forward) transient probabilities
ModelCheckerResult res = computeTransientProbs(dtmc, k, initDist);
// Compute expected value (from initial state)
int n = dtmc.getNumStates();
double avg = 0.0;
for (int i = 0; i < n; i++) {
avg += res.soln[i] *= mcRewards.getStateReward(i);
}
// Reuse vector/result storage
for (int i = 0; i < n; i++) {
res.soln[i] = 0.0;
}
res.soln[stateOfInterest] = avg;
return res;
}
public ModelCheckerResult computeCumulativeRewards(DTMC dtmc, MCRewards mcRewards, double t) throws PrismException
{
ModelCheckerResult res = null;
int i, n, iters;
double soln[], soln2[], tmpsoln[];
long timer;
int right = (int) t;
// Store num states
n = dtmc.getNumStates();
// Start backwards transient computation
timer = System.currentTimeMillis();
mainLog.println("\nStarting backwards cumulative rewards computation...");
// Create solution vector(s)
soln = new double[n];
soln2 = new double[n];
// Start iterations
for (iters = 0; iters < right; iters++) {
// Matrix-vector multiply plus adding rewards
dtmc.mvMult(soln, soln2, null, false);
for (i = 0; i < n; i++) {
soln2[i] += mcRewards.getStateReward(i);
}
// Swap vectors for next iter
tmpsoln = soln;
soln = soln2;
soln2 = tmpsoln;
}
// Finished backwards transient computation
timer = System.currentTimeMillis() - timer;
mainLog.print("Backwards cumulative rewards computation");
mainLog.println(" took " + iters + " iters and " + timer / 1000.0 + " seconds.");
// Return results
res = new ModelCheckerResult();
res.soln = soln;
res.lastSoln = soln2;
res.numIters = iters;
res.timeTaken = timer / 1000.0;
res.timePre = 0.0;
return res;
}
public ModelCheckerResult computeTotalRewards(DTMC dtmc, MCRewards mcRewards) throws PrismException
{
ModelCheckerResult res = null;
int n, numBSCCs = 0;
long timer;
if (getDoIntervalIteration()) {
throw new PrismNotSupportedException("Interval iteration for total rewards is currently not supported");
}
// Switch to a supported method, if necessary
if (!(linEqMethod == LinEqMethod.POWER)) {
linEqMethod = LinEqMethod.POWER;
mainLog.printWarning("Switching to linear equation solution method \"" + linEqMethod.fullName() + "\"");
}
// Store num states
n = dtmc.getNumStates();
// Start total rewards computation
timer = System.currentTimeMillis();
mainLog.println("\nStarting total reward computation...");
// Compute bottom strongly connected components (BSCCs)
SCCConsumerStore sccStore = new SCCConsumerStore();
SCCComputer sccComputer = SCCComputer.createSCCComputer(this, dtmc, sccStore);
sccComputer.computeSCCs();
List<BitSet> bsccs = sccStore.getBSCCs();
numBSCCs = bsccs.size();
// Find BSCCs with non-zero reward
BitSet bsccsNonZero = new BitSet();
for (int b = 0; b < numBSCCs; b++) {
BitSet bscc = bsccs.get(b);
for (int i = bscc.nextSetBit(0); i >= 0; i = bscc.nextSetBit(i + 1)) {
if (mcRewards.getStateReward(i) > 0) {
bsccsNonZero.or(bscc);
break;
}
}
}
mainLog.print("States in non-zero reward BSCCs: " + bsccsNonZero.cardinality() + "\n");
// Find states with infinite reward (those reach a non-zero reward BSCC with prob > 0)
BitSet inf;
if (preRel) {
// prob0 using predecessor relation
PredecessorRelation pre = dtmc.getPredecessorRelation(this, true);
inf = prob0(dtmc, null, bsccsNonZero, pre);
} else {
// prob0 using fixed point algorithm
inf = prob0(dtmc, null, bsccsNonZero);
}
inf.flip(0, n);
int numInf = inf.cardinality();
mainLog.println("inf=" + numInf + ", maybe=" + (n - numInf));
// Compute rewards
// (do this using the functions for "reward reachability" properties but with no targets)
switch (linEqMethod) {
case POWER:
res = computeReachRewardsValIter(dtmc, mcRewards, new BitSet(), inf, null, null);
break;
default:
throw new PrismException("Unknown linear equation solution method " + linEqMethod.fullName());
}
// Finished total reward computation
timer = System.currentTimeMillis() - timer;
mainLog.print("Total reward computation");
mainLog.println(" took " + timer / 1000.0 + " seconds.");
// Return results
return res;
}
// Steady-state/transient probability computation
/**
* Compute steady-state probability distribution (forwards).
* Start from initial state (or uniform distribution over multiple initial states).
*/
public StateValues doSteadyState(DTMC dtmc) throws PrismException
{
return doSteadyState(dtmc, (StateValues) null);
}
/**
* Compute steady-state probability distribution (forwards).
* Optionally, use the passed in file initDistFile to give the initial probability distribution (time 0).
* If null, start from initial state (or uniform distribution over multiple initial states).
*/
public StateValues doSteadyState(DTMC dtmc, File initDistFile) throws PrismException
{
StateValues initDist = readDistributionFromFile(initDistFile, dtmc);
return doSteadyState(dtmc, initDist);
}
/**
* Compute steady-state probability distribution (forwards).
* Optionally, use the passed in vector initDist as the initial probability distribution (time 0).
* If null, start from initial state (or uniform distribution over multiple initial states).
* For reasons of efficiency, when a vector is passed in, it will be trampled over,
* so if you wanted it, take a copy.
* @param dtmc The DTMC
* @param initDist Initial distribution (will be overwritten)
*/
public StateValues doSteadyState(DTMC dtmc, StateValues initDist) throws PrismException
{
StateValues initDistNew = (initDist == null) ? buildInitialDistribution(dtmc) : initDist;
ModelCheckerResult res = computeSteadyStateProbs(dtmc, initDistNew.getDoubleArray());
return StateValues.createFromDoubleArray(res.soln, dtmc);
}
/**
* Compute transient probability distribution (forwards).
* Start from initial state (or uniform distribution over multiple initial states).
*/
public StateValues doTransient(DTMC dtmc, int k) throws PrismException
{
return doTransient(dtmc, k, (StateValues) null);
}
/**
* Compute transient probability distribution (forwards).
* Optionally, use the passed in file initDistFile to give the initial probability distribution (time 0).
* If null, start from initial state (or uniform distribution over multiple initial states).
* @param dtmc The DTMC
* @param k Time step
* @param initDistFile File containing initial distribution
*/
public StateValues doTransient(DTMC dtmc, int k, File initDistFile) throws PrismException
{
StateValues initDist = readDistributionFromFile(initDistFile, dtmc);
return doTransient(dtmc, k, initDist);
}
/**
* Compute transient probability distribution (forwards).
* Optionally, use the passed in vector initDist as the initial probability distribution (time step 0).
* If null, start from initial state (or uniform distribution over multiple initial states).
* For reasons of efficiency, when a vector is passed in, it will be trampled over,
* so if you wanted it, take a copy.
* @param dtmc The DTMC
* @param k Time step
* @param initDist Initial distribution (will be overwritten)
*/
public StateValues doTransient(DTMC dtmc, int k, StateValues initDist) throws PrismException
{
StateValues initDistNew = (initDist == null) ? buildInitialDistribution(dtmc) : initDist;
ModelCheckerResult res = computeTransientProbs(dtmc, k, initDistNew.getDoubleArray());
return StateValues.createFromDoubleArray(res.soln, dtmc);
}
// Numerical computation functions
/**
* Compute next=state probabilities.
* i.e. compute the probability of being in a state in {@code target} in the next step.
* @param dtmc The DTMC
* @param target Target states
*/
public ModelCheckerResult computeNextProbs(DTMC dtmc, BitSet target) throws PrismException
{
ModelCheckerResult res = null;
int n;
double soln[], soln2[];
long timer;
timer = System.currentTimeMillis();
// Store num states
n = dtmc.getNumStates();
// Create/initialise solution vector(s)
soln = Utils.bitsetToDoubleArray(target, n);
soln2 = new double[n];
// Next-step probabilities
dtmc.mvMult(soln, soln2, null, false);
// Return results
res = new ModelCheckerResult();
res.soln = soln2;
res.numIters = 1;
res.timeTaken = timer / 1000.0;
return res;
}
/**
* Given a value vector x, compute the probability:
* v(s) = Sum_s' P(s,s')*x(s') for s labeled with a,
* v(s) = 0 for s not labeled with a.
*
* @param dtmc the DTMC model
* @param a the set of states labeled with a
* @param x the value vector
*/
protected double[] computeRestrictedNext(DTMC dtmc, BitSet a, double[] x)
{
double[] soln;
int n;
// Store num states
n = dtmc.getNumStates();
// initialized to 0.0
soln = new double[n];
// Next-step probabilities multiplication
// restricted to a states
dtmc.mvMult(x, soln, a, false);
return soln;
}
/**
* Compute reachability probabilities.
* i.e. compute the probability of reaching a state in {@code target}.
* @param dtmc The DTMC
* @param target Target states
*/
public ModelCheckerResult computeReachProbs(DTMC dtmc, BitSet target) throws PrismException
{
return computeReachProbs(dtmc, null, target, null, null);
}
/**
* Compute until probabilities.
* i.e. compute the probability of reaching a state in {@code target},
* while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
*/
public ModelCheckerResult computeUntilProbs(DTMC dtmc, BitSet remain, BitSet target) throws PrismException
{
return computeReachProbs(dtmc, remain, target, null, null);
}
/**
* Compute reachability/until probabilities.
* i.e. compute the min/max probability of reaching a state in {@code target},
* while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
* @param init Optionally, an initial solution vector (may be overwritten)
* @param known Optionally, a set of states for which the exact answer is known
* Note: if 'known' is specified (i.e. is non-null, 'init' must also be given and is used for the exact values.
*/
public ModelCheckerResult computeReachProbs(DTMC dtmc, BitSet remain, BitSet target, double init[], BitSet known) throws PrismException
{
ModelCheckerResult res = null;
BitSet no, yes;
int n, numYes, numNo;
long timer, timerProb0, timerProb1;
PredecessorRelation pre = null;
// Local copy of setting
LinEqMethod linEqMethod = this.linEqMethod;
// Switch to a supported method, if necessary
switch (linEqMethod)
{
case POWER:
case GAUSS_SEIDEL:
case BACKWARDS_GAUSS_SEIDEL:
case JACOBI:
break; // supported
default:
linEqMethod = LinEqMethod.GAUSS_SEIDEL;
mainLog.printWarning("Switching to linear equation solution method \"" + linEqMethod.fullName() + "\"");
}
if (doIntervalIteration && (!precomp || !prob0 || !prob1)) {
throw new PrismNotSupportedException("Interval iteration requires precomputations to be active");
}
// Start probabilistic reachability
timer = System.currentTimeMillis();
mainLog.println("\nStarting probabilistic reachability...");
// Check for deadlocks in non-target state (because breaks e.g. prob1)
dtmc.checkForDeadlocks(target);
// Store num states
n = dtmc.getNumStates();
// Optimise by enlarging target set (if more info is available)
if (init != null && known != null && !known.isEmpty()) {
BitSet targetNew = (BitSet) target.clone();
for (int i : new IterableBitSet(known)) {
if (init[i] == 1.0) {
targetNew.set(i);
}
}
target = targetNew;
}
// If required, export info about target states
if (getExportTarget()) {
BitSet bsInit = new BitSet(n);
for (int i = 0; i < n; i++) {
bsInit.set(i, dtmc.isInitialState(i));
}
List<BitSet> labels = Arrays.asList(bsInit, target);
List<String> labelNames = Arrays.asList("init", "target");
mainLog.println("\nExporting target states info to file \"" + getExportTargetFilename() + "\"...");
exportLabels(dtmc, labels, labelNames, Prism.EXPORT_PLAIN, new PrismFileLog(getExportTargetFilename()));
}
if (precomp && (prob0 || prob1) && preRel) {
pre = dtmc.getPredecessorRelation(this, true);
}
// Precomputation
timerProb0 = System.currentTimeMillis();
if (precomp && prob0) {
if (preRel) {
no = prob0(dtmc, remain, target, pre);
} else {
no = prob0(dtmc, remain, target);
}
} else {
no = new BitSet();
}
timerProb0 = System.currentTimeMillis() - timerProb0;
timerProb1 = System.currentTimeMillis();
if (precomp && prob1) {
if (preRel) {
yes = prob1(dtmc, remain, target, pre);
} else {
yes = prob1(dtmc, remain, target);
}
} else {
yes = (BitSet) target.clone();
}
timerProb1 = System.currentTimeMillis() - timerProb1;
// Print results of precomputation
numYes = yes.cardinality();
numNo = no.cardinality();
mainLog.println("target=" + target.cardinality() + ", yes=" + numYes + ", no=" + numNo + ", maybe=" + (n - (numYes + numNo)));
boolean termCritAbsolute = termCrit == TermCrit.ABSOLUTE;
// Compute probabilities
IterationMethod iterationMethod = null;
switch (linEqMethod) {
case POWER:
iterationMethod = new IterationMethodPower(termCritAbsolute, termCritParam);
break;
case JACOBI:
iterationMethod = new IterationMethodJacobi(termCritAbsolute, termCritParam);
break;
case GAUSS_SEIDEL:
case BACKWARDS_GAUSS_SEIDEL: {
boolean backwards = linEqMethod == LinEqMethod.BACKWARDS_GAUSS_SEIDEL;
iterationMethod = new IterationMethodGS(termCritAbsolute, termCritParam, backwards);
break;
}
default:
throw new PrismException("Unknown linear equation solution method " + linEqMethod.fullName());
}
if (doIntervalIteration) {
res = doIntervalIterationReachProbs(dtmc, no, yes, init, known, iterationMethod, getDoTopologicalValueIteration());
} else {
res = doValueIterationReachProbs(dtmc, no, yes, init, known, iterationMethod, getDoTopologicalValueIteration());
}
// Finished probabilistic reachability
timer = System.currentTimeMillis() - timer;
mainLog.println("Probabilistic reachability took " + timer / 1000.0 + " seconds.");
// Update time taken
res.timeTaken = timer / 1000.0;
res.timeProb0 = timerProb0 / 1000.0;
res.timePre = (timerProb0 + timerProb1) / 1000.0;
return res;
}
/**
* Prob0 precomputation algorithm (using predecessor relation),
* i.e. determine the states of a DTMC which, with probability 0,
* reach a state in {@code target}, while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: {@code null} means "all states")
* @param target Target states
* @param pre The predecessor relation
*/
public BitSet prob0(DTMC dtmc, BitSet remain, BitSet target, PredecessorRelation pre)
{
BitSet canReachTarget, result;
long timer;
// Start precomputation
timer = System.currentTimeMillis();
if (!silentPrecomputations)
mainLog.println("Starting Prob0...");
// Special case: no target states
if (target.isEmpty()) {
BitSet soln = new BitSet(dtmc.getNumStates());
soln.set(0, dtmc.getNumStates());
return soln;
}
// calculate all states that can reach 'target'
// while remaining in 'remain' in the underlying graph,
// where all the 'target' states are made absorbing
canReachTarget = pre.calculatePreStar(remain, target, target);
// prob0 = complement of 'canReachTarget'
result = new BitSet();
result.set(0, dtmc.getNumStates(), true);
result.andNot(canReachTarget);
// Finished precomputation
timer = System.currentTimeMillis() - timer;
if (!silentPrecomputations) {
mainLog.print("Prob0");
mainLog.println(" took " + timer / 1000.0 + " seconds.");
}
return result;
}
/**
* Prob0 precomputation algorithm (using a fixed-point computation),
* i.e. determine the states of a DTMC which, with probability 0,
* reach a state in {@code target}, while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: {@code null} means "all")
* @param target Target states
*/
public BitSet prob0(DTMC dtmc, BitSet remain, BitSet target)
{
int n, iters;
BitSet u, soln, unknown;
boolean u_done;
long timer;
// Start precomputation
timer = System.currentTimeMillis();
if (!silentPrecomputations)
mainLog.println("Starting Prob0...");
// Special case: no target states
if (target.cardinality() == 0) {
soln = new BitSet(dtmc.getNumStates());
soln.set(0, dtmc.getNumStates());
return soln;
}
// Initialise vectors
n = dtmc.getNumStates();
u = new BitSet(n);
soln = new BitSet(n);
// Determine set of states actually need to perform computation for
unknown = new BitSet();
unknown.set(0, n);
unknown.andNot(target);
if (remain != null)
unknown.and(remain);
// Fixed point loop
iters = 0;
u_done = false;
// Least fixed point - should start from 0 but we optimise by
// starting from 'target', thus bypassing first iteration
u.or(target);
soln.or(target);
while (!u_done) {
iters++;
// Single step of Prob0
dtmc.prob0step(unknown, u, soln);
// Check termination
u_done = soln.equals(u);
// u = soln
u.clear();
u.or(soln);
}
// Negate
u.flip(0, n);
// Finished precomputation
timer = System.currentTimeMillis() - timer;
if (!silentPrecomputations) {
mainLog.print("Prob0");
mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
}
return u;
}
/**
* Prob1 precomputation algorithm (using predecessor relation),
* i.e. determine the states of a DTMC which, with probability 1,
* reach a state in {@code target}, while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
* @param pre The predecessor relation of the DTMC
*/
public BitSet prob1(DTMC dtmc, BitSet remain, BitSet target, PredecessorRelation pre) {
// Implements the constrained reachability algorithm from
// Baier, Katoen: Principles of Model Checking (Corollary 10.31 Qualitative Constrained Reachability)
long timer;
// Start precomputation
timer = System.currentTimeMillis();
if (!silentPrecomputations)
mainLog.println("Starting Prob1...");
// Special case: no 'target' states
if (target.isEmpty()) {
// empty set
return new BitSet();
}
// mark all states in 'target' and all states not in 'remain' as absorbing
BitSet absorbing = new BitSet();
if (remain != null) {
// complement remain
absorbing.set(0, dtmc.getNumStates(), true);
absorbing.andNot(remain);
} else {
// for remain == null, remain consists of all states
// thus, absorbing = the empty set is already the complementation of remain
}
// union with 'target'
absorbing.or(target);
// M' = DTMC where all 'absorbing' states are considered to be absorbing
// the set of states that satisfy E [ F target ] in M'
// Pre*(target)
BitSet canReachTarget = pre.calculatePreStar(null, target, absorbing);
// complement canReachTarget
// S\Pre*(target)
BitSet canNotReachTarget = new BitSet();
canNotReachTarget.set(0, dtmc.getNumStates(), true);
canNotReachTarget.andNot(canReachTarget);
// the set of states that can reach a canNotReachTarget state in M'
// Pre*(S\Pre*(target))
BitSet probTargetNot1 = pre.calculatePreStar(null, canNotReachTarget, absorbing);
// complement probTargetNot1
// S\Pre*(S\Pre*(target))
BitSet result = new BitSet();
result.set(0, dtmc.getNumStates(), true);
result.andNot(probTargetNot1);
// Finished precomputation
timer = System.currentTimeMillis() - timer;
if (!silentPrecomputations) {
mainLog.print("Prob1");
mainLog.println(" took " + timer / 1000.0 + " seconds.");
}
return result;
}
/**
* Prob1 precomputation algorithm (using a fixed-point computation)
* i.e. determine the states of a DTMC which, with probability 1,
* reach a state in {@code target}, while remaining in those in {@code remain}.
* @param dtmc The DTMC
* @param remain Remain in these states (optional: {@code null} means "all")
* @param target Target states
*/
public BitSet prob1(DTMC dtmc, BitSet remain, BitSet target)
{
int n, iters;
BitSet u, v, soln, unknown;
boolean u_done, v_done;
long timer;
// Start precomputation
timer = System.currentTimeMillis();
if (!silentPrecomputations)
mainLog.println("Starting Prob1...");
// Special case: no target states
if (target.cardinality() == 0) {
return new BitSet(dtmc.getNumStates());
}
// Initialise vectors
n = dtmc.getNumStates();
u = new BitSet(n);
v = new BitSet(n);
soln = new BitSet(n);
// Determine set of states actually need to perform computation for
unknown = new BitSet();
unknown.set(0, n);
unknown.andNot(target);
if (remain != null)
unknown.and(remain);
// Nested fixed point loop
iters = 0;
u_done = false;
// Greatest fixed point
u.set(0, n);
while (!u_done) {
v_done = false;
// Least fixed point - should start from 0 but we optimise by
// starting from 'target', thus bypassing first iteration
v.clear();
v.or(target);
soln.clear();
soln.or(target);
while (!v_done) {
iters++;
// Single step of Prob1
dtmc.prob1step(unknown, u, v, soln);
// Check termination (inner)
v_done = soln.equals(v);
// v = soln
v.clear();
v.or(soln);
}
// Check termination (outer)
u_done = v.equals(u);
// u = v
u.clear();
u.or(v);
}
// Finished precomputation
timer = System.currentTimeMillis() - timer;
if (!silentPrecomputations) {
mainLog.print("Prob1");
mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds.");
}
return u;
}
/**
* Compute reachability probabilities using value iteration.
* @param dtmc The DTMC
* @param no Probability 0 states
* @param yes Probability 1 states
* @param init Optionally, an initial solution vector (will be overwritten)