/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package etomica.normalmode;

import etomica.data.DataSourceScalar;
import etomica.integrator.mcmove.MCMoveOverlapListener;
import etomica.units.Pressure;

/**
 * Computes pressure from the grand canonical route based on measured free
 * energy differences and simulation parameters.
 * 
 * @author Andrew Schultz
 */
public class DataSourceAvgPressure2 extends DataSourceScalar {
    protected final MCMoveOverlapListener mcMoveOverlapMeter;
    protected double bmu;
    protected double bALattice;
    protected double latticeDensity;
    protected double volume;

    public DataSourceAvgPressure2(MCMoveOverlapListener mcMoveOverlapMeter, double betaMu, double betaALattice, double latticeDensity, double volume) {
        super("pressure", Pressure.DIMENSION);
        this.mcMoveOverlapMeter = mcMoveOverlapMeter;
        this.bmu = betaMu;
        this.bALattice = betaALattice;
        this.latticeDensity = latticeDensity;
        this.volume = volume;
    }

    public void setBetaMu(double newBetaMu) {
        bmu = newBetaMu;
    }

    public double getDataAsScalar() {
        double[] ratios = mcMoveOverlapMeter.getRatios();
        if (ratios == null) return Double.NaN;
        double q = 1;
        double sum = 1;
        double l = Math.exp(bmu);
        for (int i=ratios.length-1; i>=0; i--) {
            q *= ratios[i]/l;
            sum += q;
        }
        return (bmu-bALattice)*latticeDensity+Math.log(sum)/volume;
    }
}
@@ -228,16 +228,102 @@
 lmode;%0A%0A
+import etomica.data.AccumulatorAverageBlockless;%0Aimport etomica.data.DataDistributer;%0A
 import e
@@ -745,18 +745,39 @@
 ted 
-double bmu
+final DataDistributer pSplitter
 ;%0A  
@@ -796,24 +796,18 @@
 double b
-ALattice
+mu
 ;%0A    pr
@@ -865,16 +865,53 @@
  volume;
+%0A    protected DataSourceMuRoot dsmr;
 %0A%0A    pu
@@ -938,16 +938,43 @@
 essure2(
+DataDistributer pSplitter, 
 MCMoveOv
@@ -1010,44 +1010,8 @@
 ter,
- double betaMu, double betaALattice,
  dou
@@ -1094,16 +1094,52 @@
 NSION);%0A
+        this.pSplitter = pSplitter;%0A
         
@@ -1188,74 +1188,8 @@
 er;%0A
-        this.bmu = betaMu;%0A        this.bALattice = betaALattice;%0A
     
@@ -1290,58 +1290,71 @@
  set
-BetaMu(double newBetaMu) %7B%0A        bmu = newBetaMu
+DataSourceMuRoot(DataSourceMuRoot dsmr) %7B%0A    %09this.dsmr = dsmr
 ;%0A  
@@ -1704,30 +1704,332 @@
     
-return (bmu-bALattice)
+double lastDMu = dsmr.getLastDMu();%0A        AccumulatorAverageBlockless acc = (AccumulatorAverageBlockless)pSplitter.getDataSink(0);%0A        if (acc == null %7C%7C acc.getSampleCount() == 0) %7B%0A            return Double.NaN;%0A        %7D%0A        double pLat = acc.getData().getValue(acc.AVERAGE.index);%0A        return pLat + lastDMu
 *lat

Work even without betaA for lattice