This file is indexed.

/usr/lib/python3/dist-packages/csb/statistics/samplers/mc/neqsteppropagator.py is in python3-csb 1.2.3+dfsg-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
"""
Propagator class employing stepwise trajectories as used in the NCMC
algorithm (Nilmeier et al., "Nonequilibrium candidate Monte Carlo is 
an efficient tool for equilibrium simulation", PNAS 2011)
"""

import csb

import numpy

from abc import ABCMeta, abstractmethod
from csb.statistics.samplers.mc import TrajectoryBuilder, Trajectory, augment_state, PropagationResult
from csb.statistics.samplers.mc.propagators import AbstractPropagator, MDPropagator, HMCPropagator
from csb.numeric import InvertibleMatrix
from csb.numeric.integrators import FastLeapFrog

class NonequilibriumTrajectory(Trajectory):
    """
    Trajectory holding additional information about energy difference
    the Jacobian.

    @param items: sequence of trajectory states
    @type items: list of L{State}s

    @param heat: heat produced during the trajectory
    @type heat: float

    @param work: work expended during the trajectory
    @type work: float

    @param deltaH: energy difference between initial and final states
    @type deltaH: float

    @param jacobian: product of Jacobians of perturbations applied  in the
                     calculation of the trajectory
    @type jacobian: float
    """

    def __init__(self, items, heat=0.0, work=0.0, deltaH=0.0, jacobian=1.0, stats=None):
        
        super(NonequilibriumTrajectory, self).__init__(items, heat=heat, work=work)

        self._deltaH = None
        self.deltaH = deltaH
        self._jacobian = None
        self.jacobian = jacobian
        self._stats = None
        self.stats = stats

    @property
    def jacobian(self):
        return self._jacobian
    @jacobian.setter
    def jacobian(self, value):
        self._jacobian = value

    @property
    def deltaH(self):
        return self._deltaH
    @deltaH.setter
    def deltaH(self, value):
        self._deltaH = value

    @property
    def stats(self):
        return self._stats
    @stats.setter
    def stats(self, value):
        self._stats = value

        
class AbstractSystemInfo(object):
    """
    Subclasses hold all information describing a current system setup
    (Hamiltonian, boundaries, ...)
    """
    
    pass
        
class PerturbationResult(Trajectory):
    """
    Instances hold the result of a perturbation.

    @param items: list of states defining a phase-space trajectory
    @type items: list of L{AbstractState}s
    
    @param work: work performed on the system during perturbation
    @type work: float
    
    @param jacobian: jacobian of the perturbation
    @type jacobian: float
    
    @param perturbed_sys: L{AbstractSystemInfo} instance 
                          describing the perturbed system
    @type perturbed_sys: L{AbstractSystemInfo}
    """
    
    def __init__(self, items, perturbed_sys, work, heat=0.0, jacobian=1.0):

        super(PerturbationResult, self).__init__(items, heat, work)

        self._jacobian = None
        self.jacobian = jacobian
        self._perturbed_sys = None
        self.perturbed_sys = perturbed_sys

    @property
    def jacobian(self):
        return self._jacobian
    @jacobian.setter
    def jacobian(self, value):
        self._jacobian = value

    @property
    def perturbed_sys(self):
        return self._perturbed_sys
    @perturbed_sys.setter
    def perturbed_sys(self, value):
        self._perturbed_sys = value

        
class Protocol(object):
    """
    Describes a stepwise protocol as in Nilmeier et al. (2011).

    @param steps: the steps making up the protocol
    @type steps: list of L{Step}s
    """

    def __init__(self, steps):

        self._steps = None
        self.steps = steps

    @property
    def steps(self):
        """
        The steps making up the protocol
        """
        return self._steps
    @steps.setter
    def steps(self, value):
        self._steps = value
    
class Step(object):
    """
    Defines a step in an NCMC-like stepwise protocol.

    @param perturbation: The perturbation of the system
    @type perturbation: L{AbstractPerturbation}

    @param propagation: The propagation of the perturbed system
    @type propagation: L{AbstractPropagation}
    """
        
    def __init__(self, perturbation, propagation):

        self._perturbation = None
        self.perturbation = perturbation
        self._propagation = None
        self.propagation = propagation
        self._perform = None
        self.perform = self._perform_pert_prop

    def _perform_pert_prop(self, state, extra_info=None):
        '''
        First, perform the perturbation, and then the propagation.
        Override this in a subclass if you want to pass on extra
        information to the next step in the protocol or if you want
        to gather some statistics on what happens in the intermediate steps.
        
        @param state: state to be evolved
        @type state: L{State}
        @param extra_info: possible extra information resulting 
                           from previous steps
        @type extra_info: any type

        @rtype: L{list} containing a short trajectory consisting of
                the initial and the evolved state, possible extra information
                which will be passed on to the next step in the protocol and
                possible subclasses of L{AbstractStepStatistics} containing 
                information on what happend in the step.
        '''
        
        perturbation_result = self.perturbation(state)
        propagation_result = self.propagation(perturbation_result.final)
        result_state = propagation_result.final

        shorttraj = NonequilibriumTrajectory([state, result_state],
                                             heat=propagation_result.heat,
                                             work=perturbation_result.work,
                                             jacobian=perturbation_result.jacobian)
        
        return shorttraj, None, None
    
    def _perform_prop_pert(self, state, extra_info=None):
        '''
        First, perform the propagation, and then the perturbation.
        Override this in a subclass if you want to pass on extra
        information to the next step in the protocol or if you want
        to gather some statistics on what happens in the intermediate steps.

        @param state: state to be evolved
        @type state: L{State}
        @param extra_info: possible extra information resulting 
                           from previous steps
        @type extra_info: any type

        @rtype: L{list} containing a short trajectory consisting of
                the initial and the evolved state, possible extra information
                which will be passed on to the next step in the protocol and
                possible subclasses of L{AbstractStepStatistics} containing 
                information on what happend in the step.
        '''
        
        propagation_result = self.propagation(state)
        perturbation_result = self.perturbation(propagation_result.final)
        result_state = perturbation_result.final

        shorttraj = NonequilibriumTrajectory([state, result_state],
                                             heat=propagation_result.heat,
                                             work=perturbation_result.work,
                                             jacobian=perturbation_result.jacobian)
        
        return shorttraj, None, None
    
    def set_perturbation_first(self):
        """
        Perform first perturbation, then propagation
        """
        
        self.perform = self._perform_pert_prop

    def set_propagation_first(self):
        """
        Perform first propagation, then perturbation
        """
        
        self.perform = self._perform_prop_pert
        
    @property
    def perturbation(self):
        return self._perturbation
    @perturbation.setter
    def perturbation(self, value):
        self._perturbation = value

    @property
    def propagation(self):
        return self._propagation
    @propagation.setter
    def propagation(self, value):
        self._propagation = value
        

class ReducedHamiltonian(object):
    """
    Describes a reduced Hamiltonian (Hamiltonian, its position gradient
    and the system temperature)

    @param log_prob: log probability of the PDF under consideration, that is,
                     the negative potential energy of the system
    @type log_prob: callable

    @param gradient: gradient of the negative log probability of the PDF under
                     consideration, that is, the gradient of the potential energy;
                     function of position array and time
    @type gradient: callable

    @param temperature: system temperature
    @type temperature: float
    
    @param mass_matrix: system mass matrix
    @type mass_matrix: L{InvertibleMatrix}
    """                 

    def __init__(self, log_prob, gradient=None, temperature=1.0, mass_matrix=None):
        self._log_prob = None
        self.log_prob = log_prob
        self._gradient = None
        self.gradient = gradient
        self._temperature = None
        self.temperature = temperature
        self._mass_matrix = None
        self.mass_matrix = mass_matrix

    def E(self, x):
        """
        Potential energy of the system, aka negative log probability

        @param x: position vector
        @type x: 1D numpy array
        """
        
        return -self.log_prob(x)

    def kinetic_energy(self, p):
        """
        Kinetic energy of the system

        @param p: system momentum vector
        @type p: 1D numpy array
        """
        
        if p is not None:
            if self.mass_matrix is None:
                return 0.5 * sum(p ** 2)
            else:
                if self.mass_matrix.is_unity_multiple:
                    return 0.5 * sum(p ** 2) / self.mass_matrix[0][0]
                else:
                    return 0.5 * numpy.dot(p, numpy.dot(self.mass_matrix.inverse, p))
        else:
            return 0.0

    def rlog_prob(self, x):
        """
        Reduced log probability

        @param x: position vector
        @type x: 1D numpy array
        """
        
        return self.log_prob(x) / self.temperature

    def rkinetic_energy(self, p):
        """
        Reduced kinetic energy

        @param p: system momentum vector
        @type p: 1D numpy array
        """
        
        return self.kinetic_energy(p) / self.temperature

    def __call__(self, x):
        """
        Evaluates the reduced Hamiltionian at the state x

        @param x: system state
        @type x: L{State}
        """
        
        return -self.rlog_prob(x.position) + self.rkinetic_energy(x.momentum)

    @property
    def log_prob(self):
        return self._log_prob
    @log_prob.setter
    def log_prob(self, value):
        self._log_prob = value
    
    @property
    def gradient(self):
        return self._gradient
    @gradient.setter
    def gradient(self, value):
        self._gradient = value

    @property
    def temperature(self):
        return self._temperature
    @temperature.setter
    def temperature(self, value):
        self._temperature = value

    @property
    def mass_matrix(self):
        return self._mass_matrix
    @mass_matrix.setter
    def mass_matrix(self, value):
        self._mass_matrix = value

        
class AbstractPerturbation(object):
    """
    Describes an abstract system perturbation

    @param sys_before: information about the system before the perturbation
    @type sys_before: L{AbstractSystemInfo}

    @param sys_after: information about the system after the perturbation
    @type sys_after: L{AbstractSystemInfo}

    @param param: parameters neccessary for system perturbation
    @type param: L{AbstractPerturbationParam}

    @param evaluate_work: Allows to switch off the work evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_work: boolean
    """

    __metaclass__ = ABCMeta

    def __init__(self, sys_before, sys_after, param=None, evaluate_work=True):
        self._sys_before = None
        self.sys_before = sys_before
        self._sys_after = None
        self.sys_after = sys_after
        self.param = param
        self._evaluate_work = None
        self.evaluate_work = evaluate_work

    @abstractmethod
    def _run_perturbator(self, state):
        """
        Calculates the trajectory of the system while it is being perturbed.

        @param state: The initial system state
        @type state: L{State}

        @return: The trajectory of the system while it is being perturbed
        @rtype: L{Trajectory}
        """

        pass

    @abstractmethod
    def _calculate_work(self, traj):
        """
        Calculates the work expended during perturbation of the system.

        @param traj: The trajectory of the system while being perturbed
        @type traj: L{Trajectory}

        @return: The work expended during perturbation
        @rtype: float
        """

        pass

    @abstractmethod
    def _calculate_jacobian(self, traj):
        """
        Calculates the Jacobian determinant which reflects phase
        space compression during perturbation.

        @param traj: The trajectory of the system while being perturbed
        @type traj: L{Trajectory}

        @return: The Jacobian determinant
        @rtype: float
        """

        pass

    def _evaluate(self, state):
        """
        Performs the perturbation of the system and / or the state

        @param state: system state
        @type state: L{State}
        """

        traj = self._run_perturbator(state)
        work = self._calculate_work(traj)
        jacobian = self._calculate_jacobian(traj)

        return PerturbationResult([traj.initial, traj.final], self.sys_after, 
                                  work, jacobian=jacobian)
        
    def __call__(self, state):
        """
        Performs the perturbation of the system and / or the state

        @param state: system state
        @type state: L{State}
        """
        
        return self._evaluate(state)

    @property
    def sys_before(self):
        return self._sys_before
    @sys_before.setter
    def sys_before(self, value):
        self._sys_before = value

    @property
    def sys_after(self):
        return self._sys_after
    @sys_after.setter
    def sys_after(self, value):
        self._sys_after = value
        
    @property
    def param(self):
        return self._param
    @param.setter
    def param(self, value):
        self._param = value

    @property
    def evaluate_work(self):
        return self._evaluate_work
    @evaluate_work.setter
    def evaluate_work(self, value):
        self._evaluate_work = value
        
        
class AbstractPropagation(object):
    """
    Describes an abstract system propagation

    @param sys: information about the current system setup
    @type sys: L{AbstractSystemInfo}

    @param param: parameters neccessary for propagating the system
    @type param: L{AbstractPropagationParam}

    @param evaluate_heat: Allows to switch off the heat evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_heat: boolean
    """

    __metaclass__ = ABCMeta

    def __init__(self, sys, param, evaluate_heat=True):

        self._sys = None
        self.sys = sys
        self._param = None
        self.param = param
        self._evaluate_heat = None
        self.evaluate_heat = evaluate_heat

    @abstractmethod
    def _propagator_factory(self):
        """
        Factory method which returns the propagator to be used for
        propagating the system.

        @return: Some propagator object
        @rtype: L{AbstractPropagator}
        """

    @abstractmethod
    def _run_propagator(self, state):
        """
        Propagates the system using the propagator instance returned
        by _propagator_factory().

        @param state: Initial state
        @type state: L{State}

        @return: The result of the propagation
        @rtype: L{PropagationResult}
        """
        
        pass

    @abstractmethod
    def _calculate_heat(self, traj):
        """
        Calculates the heat resulting from system propagation.

        @param traj: The trajectory of the system during propagation
        @type traj: L{Trajectory}

        @return: The heat resulting from system propagation.
        @rtype: float
        """
        
        pass

    def _evaluate(self, state):
        """
        Performs the propagation of a state in the specified system

        @param state: system state
        @type state: L{State}
        """
        
        traj = self._run_propagator(state)
        heat = self._calculate_heat(traj)
        
        return PropagationResult(traj.initial, traj.final, heat=heat)

    def __call__(self, state):
        """
        Performs the propagation of a state in the specified system

        @param state: system state
        @type state: L{State}
        """
        
        return self._evaluate(state)

    @property
    def sys(self):
        return self._sys
    @sys.setter
    def sys(self, value):
        self._sys = value
    
    @property
    def param(self):
        return self._param
    @param.setter
    def param(self, value):
        self._param = value
    
    @property
    def evaluate_heat(self):
        return self._evaluate_heat
    @evaluate_heat.setter
    def evaluate_heat(self, value):
        self._evaluate_heat = value

    
class ReducedHamiltonianPerturbation(AbstractPerturbation):
    """
    System perturbation by changing the reduced Hamiltonian

    @param sys_before: information about the system before the perturbation
    @type sys_before: L{AbstractSystemInfo}

    @param sys_after: information about the system after the perturbation
    @type sys_after: L{AbstractSystemInfo}

    @param evaluate_work: Allows to switch off the work evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_work: boolean
    """

    def __init__(self, sys_before, sys_after, evaluate_work=True):

        super(ReducedHamiltonianPerturbation, self).__init__(sys_before, sys_after,
                                                             evaluate_work=evaluate_work)

    def _calculate_work(self, traj):

        work = 0.0
        if self.evaluate_work == True:
            work = self.sys_after.hamiltonian(traj.final) - \
                   self.sys_before.hamiltonian(traj.initial)

        return work

    def _calculate_jacobian(self, traj):

        return 1.0

    def _run_perturbator(self, state):

        return Trajectory([state, state])


class AbstractMCPropagation(AbstractPropagation):
    """
    System propagation by some MC algorithm.

    @param sys: information about the current system setup
    @type sys: L{AbstractSystemInfo}

    @param param: parameters neccessary for propagating the system
    @type param: L{AbstractPropagationParam}

    @param evaluate_heat: Allows to switch off the heat evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_heat: boolean
    """

    ## Not neccessary, but otherwise epydoc complains
    def __init__(self, sys, param, evaluate_heat=True):

        super(AbstractMCPropagation, self).__init__(sys, param, evaluate_heat=True)

    def _calculate_heat(self, traj):
        
        heat = 0.0
        if self.evaluate_heat == True:
            heat = self.sys.hamiltonian.E(traj.final.position) - \
                   self.sys.hamiltonian.E(traj.initial.position)

        return heat

    def _run_propagator(self, state):

        gen = self._propagator_factory()

        return gen.generate(state, self.param.iterations, False)

    
class HMCPropagation(AbstractMCPropagation):
    """
    System propagation by HMC

    @param sys: information about the current system setup
    @type sys: L{AbstractSystemInfo}

    @param param: parameters neccessary for propagating the system
    @type param: L{HMCPropagationParam}

    @param evaluate_heat: Allows to switch off the heat evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_heat: boolean
    """
    
    def __init__(self, sys, param, evaluate_heat=True):

        super(HMCPropagation, self).__init__(sys, param, evaluate_heat)
        
        if self.param.gradient is None:
            self.param.gradient = self.sys.hamiltonian.gradient

    def _set_mass_matrix(self, state):
        """
        Sets the mass matrix in the param object.

        @param state: The initial state which is used to determine the dimension
                      of the mass matrix
        @type state: L{State}
        """

        if self.param.mass_matrix is None:
            d = len(state.position)
            self.param.mass_matrix = InvertibleMatrix(numpy.eye(d))

    def _propagator_factory(self):

        gen = HMCPropagator(self.sys.hamiltonian, self.param.gradient,
                            self.param.timestep, self.param.traj_length,
                            temperature=self.sys.hamiltonian.temperature,
                            integrator=self.param.integrator,
                            mass_matrix=self.param.mass_matrix)
        
        return gen
    
    def _evaluate(self, state):
        
        self._set_mass_matrix(state)

        return super(HMCPropagation, self)._evaluate(state)

    @property
    def param(self):
        return self._param
    @param.setter
    def param(self, value):
        self._param = value


class AbstractMDPropagation(AbstractPropagation):
    """
    System propagation by some MD algorithm

    @param sys: information about the current system setup
    @type sys: L{AbstractSystemInfo}

    @param param: parameters neccessary for propagating the system
    @type param: L{MDPropagationParam}

    @param evaluate_heat: Allows to switch off the heat evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_heat: boolean
    """

    __metaclass__ = ABCMeta

    ## Not neccessary, but otherwise epydoc complains
    def __init__(self, sys, param, evaluate_heat=True):

        super(AbstractMDPropagation, self).__init__(sys, param, evaluate_heat=True)
    
    def _set_mass_matrix(self, state):
        """
        Sets the mass matrix in the param object.

        @param state: The initial state which is used to determine the dimension
                      of the mass matrix
        @type state: L{State}
        """

        if self.param.mass_matrix is None:
            d = len(state.position)
            self.param.mass_matrix = InvertibleMatrix(numpy.eye(d))

    def _augment_state(self, state):
        """
        Augments the initial state by a momentum if none is defined.

        @param state: Initial state
        @type state: L{State}
        """

        if state.momentum == None:
            state = augment_state(state, self.sys.hamiltonian.temperature,
                                  self.param.mass_matrix)

        return state

    def _run_propagator(self, state):
        
        gen = self._propagator_factory()
        state = self._augment_state(state)
        traj = gen.generate(state, self.param.traj_length)

        return traj

        
class PlainMDPropagation(AbstractMDPropagation):
    """
    System propagation by plain, microcanonical MD

    @param sys: information about the current system setup
    @type sys: L{AbstractSystemInfo}

    @param param: parameters neccessary for propagating the system
    @type param: L{PlainMDPropagationParam}

    @param evaluate_heat: Allows to switch off the heat evaluation,
                          which might not always be needed, in order to
                          save computation time.
    @type evaluate_heat: boolean
    """

    ## Not neccessary, but otherwise epydoc is complaining
    def __init__(self, sys, param, evaluate_heat=True):

        super(PlainMDPropagation, self).__init__(sys, param, evaluate_heat=evaluate_heat)

    def _propagator_factory(self):

        return MDPropagator(self.param.gradient, self.param.timestep,
                            mass_matrix=self.param.mass_matrix,
                            integrator=self.param.integrator)

    def _calculate_heat(self, traj):
        
        heat = 0.0
        if self.evaluate_heat == True:
            heat = self.sys.hamiltonian(traj.final) - self.sys.hamiltonian(traj.initial)

        return heat

    def _evaluate(self, state):

        self._set_mass_matrix(state)

        return super(PlainMDPropagation, self)._evaluate(state)
        
        
class AbstractPerturbationParam(object):
    """
    Subclasses hold informations required for different kinds
    of system perturbation
    """

    pass


class AbstractPropagationParam(object):
    """
    Subclasses hold informations required for different kinds
    of system propagation
    """

    pass


class MDParam(object):
    """
    Holds all required information for calculating a MD trajectory.

    @param timestep: integration timestep
    @type timestep: float

    @param traj_length: MD trajectory length
    @type traj_length: int

    @param gradient: gradient governing the equations of motion, function of
                     position array and time
    @type gradient: callable

    @param temperature: System temperature for drawing momenta from the
                        Maxwell distribution
    @type temperature: float
    
    @param integrator: Integration scheme to be utilized
    @type integrator: L{AbstractIntegrator}

    @param mass_matrix: mass matrix for kinetic energy definition
    @type mass_matrix: L{InvertibleMatrix}
    """
    
    def __init__(self, timestep, traj_length, gradient, temperature=1.0,
                 integrator=FastLeapFrog, mass_matrix=None):

        self._timestep = None
        self.timestep = timestep
        self._traj_length = None
        self.traj_length = traj_length
        self._gradient = None
        self.gradient = gradient
        self._temperature = None
        self.temperature = temperature
        self._integrator = None
        self.integrator = integrator
        self._mass_matrix = None
        self.mass_matrix = mass_matrix

    @property
    def timestep(self):
        return self._timestep
    @timestep.setter
    def timestep(self, value):
        self._timestep = value

    @property
    def traj_length(self):
        return self._traj_length
    @traj_length.setter
    def traj_length(self, value):
        self._traj_length = value

    @property
    def gradient(self):
        return self._gradient
    @gradient.setter
    def gradient(self, value):
        self._gradient = value

    @property
    def temperature(self):
        return self._temperature
    @temperature.setter
    def temperature(self, value):
        self._temperature = value
 
    @property
    def integrator(self):
        return self._integrator
    @integrator.setter
    def integrator(self, value):
        self._integrator = value
    
    @property
    def mass_matrix(self):
        return self._mass_matrix
    @mass_matrix.setter
    def mass_matrix(self, value):
        self._mass_matrix = value
        

class HMCPropagationParam(MDParam, AbstractPropagationParam):
    """
    Holds all required information for propagating a system by HMC.
    The system temperature is taken from the 
    HMCPropagation.sys.hamiltonian.temperature property.
    
    @param timestep: integration timestep
    @type timestep: float

    @param traj_length: MD trajectory length
    @type traj_length: int

    @param gradient: gradient governing the equations of motion, function of
                     position array and time
    @type gradient: callable
    
    @param iterations: number of HMC iterations to be performed
    @type iterations: int

    @param integrator: Integration scheme to be utilized
    @type integrator: l{AbstractIntegrator}

    @param mass_matrix: mass matrix for kinetic energy definition
    @type mass_matrix: L{InvertibleMatrix}
    """
    
    def __init__(self, timestep, traj_length, gradient, iterations=1,
                 integrator=FastLeapFrog, mass_matrix=None):

        super(HMCPropagationParam, self).__init__(timestep, traj_length, gradient,
                                                  integrator=integrator, mass_matrix=mass_matrix)

        self._iterations = None
        self.iterations = iterations

    @property
    def iterations(self):
        return self._iterations
    @iterations.setter
    def iterations(self, value):
        self._iterations = value


class MDPropagationParam(MDParam, AbstractPropagationParam):

    pass


class PlainMDPropagationParam(MDParam, AbstractPropagationParam):
    """
    Holds all required information for propagating a system by MD.
    The system temperature is taken from the 
    MDPropagation.sys.hamiltonian.temperature property.
    
    @param timestep: integration timestep
    @type timestep: float

    @param traj_length: MD trajectory length
    @type traj_length: int

    @param gradient: gradient governing the equations of motion, function of
                     position array and time
    @type gradient: callable

    @param integrator: Integration scheme to be utilized
    @type integrator: l{AbstractIntegrator}

    @param mass_matrix: mass matrix for kinetic energy definition
    @type mass_matrix: L{InvertibleMatrix}
    """
    
    def __init__(self, timestep, traj_length, gradient,
                 integrator=FastLeapFrog, mass_matrix=None):

        super(PlainMDPropagationParam, self).__init__(timestep, traj_length, gradient,
                                                 integrator=integrator, mass_matrix=mass_matrix)


class HamiltonianSysInfo(AbstractSystemInfo):
    """
    Holds information describing a system by its Hamiltonian only.
    
    @param hamiltonian: the Hamiltonian of the system to be described
    @type hamiltonian: L{ReducedHamiltonian}
    """
    
    def __init__(self, hamiltonian):
        
        self._hamiltonian = None
        self.hamiltonian = hamiltonian
    
    @property
    def hamiltonian(self):
        return self._hamiltonian
    @hamiltonian.setter
    def hamiltonian(self, value):
        self._hamiltonian = value


class AbstractStepStatistics(object):
    '''
    Abstract class defining a minimal interface for objects allowing to store statistics
    of what happens in L{Step} instances.
    '''

    @abstractmethod
    def update(self, step_index, shorttraj, stats_data):
        pass

    
class DummyStepStatistics(AbstractStepStatistics):

    def update(self, step_index, shorttraj, stats_data):
        pass


class AbstractHeatWorkJacobianLogger(object):
    '''
    Abstract class defining the interface for objects keeping track of and accumulating
    heat, work and the Jacobian during a nonequilibrium trajectory.
    '''

    def __init__(self):

        self._heat = 0.0
        self._work = 0.0
        self._jacobian = 1.0

    @abstractmethod
    def accumulate(self, heat=0.0, work=0.0, jacobian=1.0):
        '''
        Adds heat and work contribution to the so far accumulated values and
        "multiply-accumulates" the Jacobian to the so far "multiply-accumulated" values.
        '''
        pass

    @property
    def heat(self):
        return self._heat
    
    @property
    def work(self):
        return self._work

    @property
    def jacobian(self):
        return self._jacobian


class TrivialHeatWorkJacobianLogger(AbstractHeatWorkJacobianLogger):

    def accumulate(self, heat=0.0, work=0.0, jacobian=1.0):

        self._heat += heat
        self._work += work
        self._jacobian *= jacobian

    
class NonequilibriumStepPropagator(AbstractPropagator):
    """
    Propagator class which propagates a system using NCMC-like
    stepwise trajectories
    
    @param protocol: stepwise protocol to be followed
    @type protocol: L{Protocol}
    """
    
    def __init__(self, protocol):

        self._protocol = None
        self.protocol = protocol

    def _calculate_deltaH(self, traj):
        """
        Calculate the difference of the Hamiltonian between the initial and
        the final state of a NCMC trajectory.

        @param traj: The NCMC trajectory between whose initial and final states
                     the Hamiltonian difference should be calculated
        @type traj: L{NonequilibriumTrajectory}
        """

        return self.protocol.steps[-1].perturbation.sys_after.hamiltonian(traj.final) - \
               self.protocol.steps[0].perturbation.sys_before.hamiltonian(traj.initial)

    def _create_heat_work_jacobian_logger(self):
        '''
        Factory method for the L{AbstractHeatWorkJacobianLogger} subclass instance
        which keeps track of work, heat and Jacobian contributions during the nonequilibrium
        trajectory.

        @rtype: instance of an L{AbstractHeatWorkJacobianLogger}-derived class
        '''

        return TrivialHeatWorkJacobianLogger()

    def _create_step_stats(self):
        '''
        Factory method for the L{AbstractStepStatistics} subclass instance
        which can be used to collect statistics of what happens during steps.

        @rtype: instance of an L{AbstractStepStatistics}-derived class
        '''
        
        return DummyStepStatistics()

    def _set_initial_extra_info(self, init_state):
        '''
        Provides additional information for the first step in the protocol.

        @rtype: any type
        '''

        return None

    def _perform_step_iteration(self, estate, hwj_logger, step_stats, builder, extra_info):
        '''
        Performs the iteration over all steps in the nonequilibrium protocol.

        @param estate: the state which will be evolved
        @type estate: L{State}
        @param hwj_logger: an instance of an L{AbstractHeatWorkJacobianLogger}-derived class,
                           which keeps track of work, heat and Jacobian contributions
        @type hwj_logger: subclass of L{AbstractHeatWorkJacobianLogger}
        @param step_stats: an instance of an L{AbstractStepStatistics}-derived class,
                           which may collect some statistics of what happens during steps
        @type step_stats: subclass of L{AbstractStepStatistics}
        @param builder: L{TrajectoryBuilder} instance in charge of building the L{Trajectory} object
        @type builder: L{TrajectoryBuilder}
        @param extra_info: Dictionary containing eventual additional information, which needs to
                           be passed on from one step to the following
        @type extra_info: any type

        @rtype: L{Trajectory}
        '''

        for i in range(len(self.protocol.steps)):

            shorttraj, extra_info, stats_data = self.protocol.steps[i].perform(estate, extra_info)

            step_stats.update(i, shorttraj, stats_data)
            hwj_logger.accumulate(shorttraj.heat, shorttraj.work, shorttraj.jacobian)

            estate = shorttraj.final
                        
            if i == 0:
                builder.add_initial_state(shorttraj.initial)
            elif i != len(self.protocol.steps) - 1:
                builder.add_intermediate_state(estate)
            else:
                builder.add_final_state(estate)
        
        return builder.product


    def generate(self, init_state, return_trajectory=False):

        estate = init_state.clone()

        hwj_logger = self._create_heat_work_jacobian_logger()
        step_stats = self._create_step_stats()
        builder = TrajectoryBuilder.create(full=return_trajectory)
        extra_info = self._set_initial_extra_info(estate)

        traj = self._perform_step_iteration(estate, hwj_logger, step_stats, 
                                            builder, extra_info)

        reduced_deltaH = self._calculate_deltaH(traj)
        
        if init_state.momentum is None:
            for s in traj:
                s.momentum = None
        
        result = NonequilibriumTrajectory([x for x in traj],
                                          heat=hwj_logger.heat,
                                          work=hwj_logger.work,
                                          deltaH=reduced_deltaH,
                                          jacobian=hwj_logger.jacobian, 
                                          stats=step_stats)
        
        return result

    @property
    def protocol(self):
        return self._protocol
    @protocol.setter
    def protocol(self, value):
        self._protocol = value