/* 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.spin.heisenberg;

import etomica.api.IAtom;
import etomica.api.IAtomList;
import etomica.api.IBox;
import etomica.api.IMoleculeList;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.atom.IAtomOriented;
import etomica.atom.iterator.AtomIteratorLeafAtoms;
import etomica.data.DataSourceScalar;
import etomica.data.IEtomicaDataSource;
import etomica.space.ISpace;
import etomica.space3d.Vector3D;
import etomica.units.Undefined;


/**
 * returns dipole square
 *
 * @author  Weisong Lin
 *
 */
public class MeterSpinMSquare extends DataSourceScalar implements IEtomicaDataSource {

    /**
     * 
     */
	
    public MeterSpinMSquare(ISpace space,IBox box,double dipoleMagnitude) {
        super("Spin",Undefined.DIMENSION);
        sum = space.makeVector();
        this.box = box;
        this.dipoleMagnitude = dipoleMagnitude;
    }

    public double getDataAsScalar() {
        sum.E(0.0);
        int count = 0;
        iterator.setBox(box);
        iterator.reset();
        for (IAtomOriented atom = (IAtomOriented) iterator.nextAtom(); atom != null;
             atom = (IAtomOriented) iterator.nextAtom()) {
            sum.PE(atom.getOrientation().getDirection());
            count++;
        }
        
        return sum.squared()*dipoleMagnitude*dipoleMagnitude;
    }
    
    
    

    /**
     * @return Returns the box.
     */
    public IBox getBox() {
        return box;
    }
    /**
     * @param box The box to set.
     */
    public void setBox(IBox box) {
        this.box = box;
    }

    private static final long serialVersionUID = 1L;
    private IBox box;
    private final AtomIteratorLeafAtoms iterator = new AtomIteratorLeafAtoms();
    private final IVectorMutable sum;
    private final double dipoleMagnitude;
}

@@ -1139,16 +1139,19 @@
 E(0.0);%0A
+%0A//
         
@@ -1165,16 +1165,18 @@
 nt = 0;%0A
+//
         
@@ -1197,16 +1197,18 @@
 x(box);%0A
+//
         
@@ -1221,24 +1221,26 @@
 or.reset();%0A
+//
         for 
@@ -1312,16 +1312,18 @@
 = null;%0A
+//
         
@@ -1369,24 +1369,428 @@
 xtAtom()) %7B%0A
+//            sum.PE(atom.getOrientation().getDirection());%0A//            count++;%0A//        %7D%0A%0A        // test for new way to get MSquare%0A        if (box == null) throw new IllegalStateException(%22no box%22);%0A        IAtomList leafList = box.getLeafList();%0A        int nM = leafList.getAtomCount();%0A        for (int i = 0;i %3C nM; i++)%7B%0A            IAtomOriented atom = (IAtomOriented) leafList.getAtom(i);%0A
             
@@ -1847,39 +1847,18 @@
     
-    count++;%0A        %7D%0A        
+%7D//i loop%0A
 %0A   

add a test calculation for the total dipolemoment