Package com.mockturtlesolutions.snifflib.datatypes

Examples of com.mockturtlesolutions.snifflib.datatypes.DblMatrix


    if (anexperimenthastitration)
    {
      pname = this.mkParameterName(new String[]{"sigmaCb",buffername});
      if (!this.hasParameter(pname))//We do it like this to allow sigmaCb to always be present even with inverted declares.
      {
        this.declareParameter(pname,new DblMatrix(0.01));
      }
   
      if (((Boolean)this.adjustForMap.get("adjustForBufferConc")).booleanValue())
      {
        pname = this.mkParameterName(new String[]{"C",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(0.03)); //Represents the average concentration
       
        ////////////////////////////////////////////////////////////////////////////////
        //Prior parameters for this...
       
        this.establishedPriors.add(pname);
       
        pname = this.mkParameterName(new String[]{"prior","mean","C",buffername});
        this.setPriorParam(pname,new DblMatrix(0.03));
        pname = this.mkParameterName(new String[]{"prior","sigma","C",buffername});
        this.setPriorParam(pname,new DblMatrix(0.01));
       
       
       
        //System.out.println("Declaring parameter:"+pname);
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkIntercept")).booleanValue())
      {
        pname = this.mkParameterName(new String[]{"interceptpH",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(0.0));
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkLinear")).booleanValue())
      {
        pname = this.mkParameterName(new String[]{"linearpH",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(1.0));
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkQuadratic")).booleanValue())
      {
        pname = this.mkParameterName(new String[]{"quadraticpH",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(-0.001));
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkCubic")).booleanValue())
      {
        pname = this.mkParameterName(new String[]{"cubicpH",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(0.0001));
      }
     
     
      if (this.adjustForLatentpHLink()) // Regardless
      {
        //The standard deviation of error for the latent pH. 
        pname = this.mkParameterName(new String[]{"sigmaCalib",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(0.02));
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForPipettingErrors")).booleanValue())
      {
        //We assume the actual volume is the reported volume +/- normal error having
        //mean zero and a standard deviation equal to sigmaFactorVolume times the reported
        //volume.  Assumes relative error in pipetting...
        pname = this.mkParameterName(new String[]{"sigmaFactorVolume",buffername});
        this.declareIfNotParameter(pname,new DblMatrix(0.05));
      }
     
      if (this.adjustForSmoothingComponent())
      {
        this.smoothingCbResidualMap = new HashMap();
        this.smoothingpHMap = new HashMap();
      }
     
     
      if (((Boolean)this.adjustForMap.get("adjustForSmoothing")).booleanValue())
      {
       
        if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
        {
          //We assume the actual volume is the reported volume +/- normal error having
          //mean zero and a standard deviation equal to sigmaFactorVolume times the reported
          //volume.  Assumes relative error in pipetting...
         
          //System.out.println("Going with LOWESS fitting!!!");
          pname = this.mkParameterName(new String[]{"smoothingParameter",buffername});
          this.declareIfNotParameter(pname,new DblMatrix(0.1)); // Make close to 1 for really smooth initially.
        }
        else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
        {
          //System.out.println("Going with Polynomial fitting!!!");
          if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.LINEAR_SMOOTHER)
          {
            pname = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
            pname = this.mkParameterName(new String[]{"smoothingSlope",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
          }
          else if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.QUADRATIC_SMOOTHER)
          {
            pname = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
            pname = this.mkParameterName(new String[]{"smoothingSlope",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
            pname = this.mkParameterName(new String[]{"smoothingQuadratic",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
          }
          else if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.CUBIC_SMOOTHER)
          {
            pname = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
            pname = this.mkParameterName(new String[]{"smoothingSlope",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
           
            pname = this.mkParameterName(new String[]{"smoothingQuadratic",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
       
            pname = this.mkParameterName(new String[]{"smoothingCubic",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.0)); // Make close to 1 for really smooth initially.
          }
        }
      }
   
   
   
      if (morethanoneexperimenthastitration)
      {
        if (thisexperimenthastitration)
        {
          if (((Boolean)this.adjustForMap.get("adjustForSmoothingExp")).booleanValue())
          {
            //We assume the actual volume is the reported volume +/- normal error having
            //mean zero and a standard deviation equal to sigmaFactorVolume times the reported
            //volume.  Assumes relative error in pipetting...
            pname = this.mkParameterName(new String[]{"smoothingParameterExp",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.1)); // Make close to 1 for really smooth initially.
          }
   
          if (((Boolean)this.adjustForMap.get("adjustForBufferExpConc")).booleanValue())
          {
            //Declare the standard deviation of the CExpdevs if not already defined!
            //Note this will not be defined if there is only one experiment (no
            //variance component needed).
            DblMatrix cdevsig = new DblMatrix(0.0001);
            pname = this.mkParameterName(new String[]{"CExpsigma",buffername});
            this.declareIfNotParameter(pname,cdevsig);

            pname = this.mkParameterName(new String[]{"CExpdev",buffername,exp});
            this.normal.setMean(new DblMatrix(0.0));
            this.normal.setStd(cdevsig);

            this.declareIfNotParameter(pname,this.normal.random(1)); //Represents deviations of concentrations
            //from the mean which is given by the "C" parameter for this buffer.
          }
       
          if (((Boolean)this.adjustForMap.get("interceptExp")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"initialpHExp",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"initialpHExpsigma",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("linearExp")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"linearpHExp",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"linearpHExpsigma",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("quadraticExp")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"quadraticpHExp",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"quadraticpHExpsigma",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("cubicExp")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"cubicpHExp",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.001));

            pname = this.mkParameterName(new String[]{"cubicpHExpsigma",buffername});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }
         
        }
      }
     
     
      if (thisexperimenthastitration)
      {
        for (int j=0;j<tssids.size();j++)
        {
          ssid = (String)tssids.get(j);
          obs = this.transientStorage.getTitrationObservationNumbers(exp,ssid);
          for (int k=0;k<obs.size();k++)
          {
            this.totalNumberOfTitrationPoints++;

            obsnum = (String)obs.get(k);
            //These are the latent observed pH
            //InitialpHParameterListener initpHlisten = new InitialpHParameterListener(buffername,exp,ssid,obsnum);

            val = this.transientStorage.getpH(exp,ssid,obsnum);
            if (this.adjustForLatentpHLink())
            {
              //These are the latent pH for each observation...
              pname = this.mkParameterName(new String[]{"pH",buffername,exp,ssid,obsnum});
              this.declareIfNotDistributedParameter(pname,new DblMatrix(val));
            }

            val = this.transientStorage.getVolumeAdded(exp,ssid,obsnum);
            Double VAL = new Double(val);

            if (VAL.doubleValue() != 0.0) //If no volume added we can accept that as fact (typically when initial pH is recorded at outset of a titration).
            {
              //System.out.println("val="+val);
              if (((Boolean)this.adjustForMap.get("adjustForPipettingErrors")).booleanValue())
              {
                //These are the latent aliquot volumes added for each observation...
                //System.out.println("Hitting the v line.");
                pname = this.mkParameterName(new String[]{"v",buffername,exp,ssid,obsnum});
                this.declareIfNotDistributedParameter(pname,new DblMatrix(VAL));
              }
            }

            val = this.transientStorage.getTitrant(exp,ssid,obsnum);

            if (!this.titrantMap.containsKey(val))
            {
              BufferSolution titrSol = new BufferSolution();
              titrSol.setConnection(this.connection);
             
              System.out.println("this.repository is:"+this.repository);
              titrSol.setRepository(this.repository);
              titrSol.initialize();
              titrSol.add(val,new DblMatrix(1.0));
              this.titrantMap.put(val,titrSol);
            }

            //These are the latent titrant stock concentrations
            //actually used then are figured based on dilution of this amount.
            pname = this.mkParameterName(new String[]{"T",val,buffername});

            if (((Boolean)this.adjustForMap.get("adjustForTitrantConc")).booleanValue())
             {
               this.declareParameter(pname,new DblMatrix(1.0));
             
             
              this.establishedPriors.add(pname);
             
              //Put in prior parameters...
              pname = this.mkParameterName(new String[]{"prior","mean","T",val,buffername});
              this.setPriorParam(pname,new DblMatrix(1.0));
              pname = this.mkParameterName(new String[]{"prior","sigma","T",val,buffername});
              this.setPriorParam(pname,new DblMatrix(0.1));
             
             
             
             
             
            }


            if (((Boolean)this.adjustForMap.get("adjustForTitrantExpConc")).booleanValue())
            {
              if (Exps.size()>1) //This is a bit of a hunch here.  We're assuming same titrants used in all experiments...
              {
                pname = this.mkParameterName(new String[]{"TExpdev",val,buffername,exp});

                DblMatrix tsdev = new DblMatrix(0.0001);
                this.normal.setMean(DblMatrix.ZERO);
                this.normal.setStd(tsdev);
                this.declareIfNotParameter(pname,this.normal.random(1));

                pname = this.mkParameterName(new String[]{"TExpsigma",val,buffername});
                this.declareIfNotParameter(pname,tsdev);
              }
            }

            // if (((Boolean)this.adjustForMap.get("adjustForTitrantExpSSConc")).booleanValue())
//             {
//               if (tssids.size() >1)//This is a bit of a hunch here.  We're assuming same titrants used in all experiments and subsamples...
//               {
//                 pname = this.mkParameterName(new String[]{"TExpSSdev",val,buffername,exp,ssid});
//
//                 DblMatrix tsdev = new DblMatrix(0.0001);
//                 this.normal.setMean(DblMatrix.ZERO);
//                 this.normal.setStd(tsdev);
//                 this.declareIfNotParameter(pname,this.normal.random(1));
//
//                 //***
//                 //*** Let's assume that the standard deviation for subsamples within
//                 //    experiment is the same for all experiments!!!
//                 //The standard deviation of TExpSSdev's across subsamples within this experiment.
//                 pname = this.mkParameterName(new String[]{"TExpSSsigma",val,buffername});
//                 this.declareIfNotParameter(pname,tsdev);
//               }
//             }

          }
        }
      }
     
       
      if (thisexperimenthasmultipletitrationSS)
      {
        for (int j=0;j<tssids.size();j++)
        {
          ssid = (String)tssids.get(j);
         
          if (((Boolean)this.adjustForMap.get("adjustForSmoothingExpSS")).booleanValue())
          {
            //We assume the actual volume is the reported volume +/- normal error having
            //mean zero and a standard deviation equal to sigmaFactorVolume times the reported
            //volume.  Assumes relative error in pipetting...
            pname = this.mkParameterName(new String[]{"smoothingParameterExpSS",buffername,exp,ssid});
            this.declareIfNotParameter(pname,new DblMatrix(0.1)); // Make close to 1 for really smooth initially.
          }
         
          if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkInterceptExpSS")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"initialpHExpSS",buffername,exp,ssid});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"initialpHExpSSsigma",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkLinearExpSS")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"linearpHExpSS",buffername,exp,ssid});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"linearpHExpSSsigma",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkQuadraticExpSS")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"quadraticpHExpSS",buffername,exp,ssid});
            this.declareIfNotParameter(pname,new DblMatrix(0.0001));

            pname = this.mkParameterName(new String[]{"quadraticpHExpSSsigma",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }

          if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkCubicExpSS")).booleanValue())
          {
            pname = this.mkParameterName(new String[]{"cubicpHExpSS",buffername,exp,ssid});
            this.declareIfNotParameter(pname,new DblMatrix(0.001));

            pname = this.mkParameterName(new String[]{"cubicpHExpSSsigma",buffername,exp});
            this.declareIfNotParameter(pname,new DblMatrix(0.01));
          }
         
          if (((Boolean)this.adjustForMap.get("adjustForBufferExpSSConc")).booleanValue())
          {
            //Declare the standard deviation of the CExpdevs if not already defined!
            //Note this will not be defined if there is only one experiment (no
            //variance component needed).
            DblMatrix cdevsig = new DblMatrix(0.0001);
            pname = this.mkParameterName(new String[]{"CExpSSsigma",buffername});
            this.declareIfNotParameter(pname,cdevsig);

            pname = this.mkParameterName(new String[]{"CExpSSdev",buffername,exp,ssid});
            this.normal.setMean(new DblMatrix(0.0));
            this.normal.setStd(cdevsig);

            this.declareIfNotParameter(pname,this.normal.random(1)); //Represents deviations of concentrations
            //from the mean which is given by the "C" parameter for this buffer.
          }
         
          if (((Boolean)this.adjustForMap.get("adjustForTitrantExpSSConc")).booleanValue())
          {
            if (tssids.size() >1)//This is a bit of a hunch here.  We're assuming same titrants used in all experiments and subsamples...
            {
              pname = this.mkParameterName(new String[]{"TExpSSdev",val,buffername,exp,ssid});

              DblMatrix tsdev = new DblMatrix(0.0001);
              this.normal.setMean(DblMatrix.ZERO);
              this.normal.setStd(tsdev);
              this.declareIfNotParameter(pname,this.normal.random(1));

              //***
              //*** Let's assume that the standard deviation for subsamples within
              //    experiment is the same for all experiments!!!
              //The standard deviation of TExpSSdev's across subsamples within this experiment.
              pname = this.mkParameterName(new String[]{"TExpSSsigma",val,buffername});
              this.declareIfNotParameter(pname,tsdev);
            }
          }
        }
      }
    }
   
    bcssids = this.referenceStorage.getBufferCoefficientsSubsampleIDs(exp);
    //The number of buffer coefficients subsamples in the transient storage should equal
    //and correspond to the number of titration subsamples.
    //System.out.println("bcssids.size()"+bcssids.size());
    //System.out.println("In configureParametersFor "+(((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue()));
    if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
    {
      if (bcssids.size() > 0) //We have pKa/pKb's given for the top-level buffer!! Whoopie, maybe we are rewriting history...
      {
        for (int j=0;j<bcssids.size();j++)
        {
          ssid = (String)bcssids.get(j);

          DblMatrix[] pKa = this.parseKa(this.referenceStorage.getpKa(exp,ssid));
          DblMatrix[] pKb = this.parseKa(this.referenceStorage.getpKb(exp,ssid));
          DblMatrix[] SaltType = this.parseKa(this.referenceStorage.getSaltType(exp,ssid));

          for (int ion=0;ion<SaltType.length;ion++)
          {
            Integer ION = new Integer(ion);
            String ionstr = ION.toString();

            if (!pKa[ion].isEmpty())
            {
              for (int group=0;group<pKa[ion].getN();group++)
              {
                Integer GROUP = new Integer(group);
                String groupstr = GROUP.toString();
               
                if (group == 0)
                {
                  pname = this.mkParameterName(new String[]{"pKa",buffername,ionstr,groupstr});
                  this.declareIfNotParameter(pname,pKa[ion].getDblAt(group));
                  //System.out.println("Just declared "+pname);
                  //Decare deviations in the pKa and pKb for each titration experiment and subsample within experiment.
                             
                  if (Exps.size()>1)
                  {
                    if (((Boolean)this.adjustForMap.get("adjustForpKaExp")).booleanValue())
                    { 
                      pname = this.mkParameterName(new String[]{"pKaExpdev",buffername,exp,ionstr,groupstr});

                      DblMatrix pKadev = new DblMatrix(0.01);
                      this.normal.setMean(DblMatrix.ZERO);
                      this.normal.setStd(pKadev);

                      this.declareIfNotParameter(pname,this.normal.random(1));

                      pname = this.mkParameterName(new String[]{"pKaExpsigma",buffername,ionstr,groupstr});
                      this.declareIfNotParameter(pname,pKadev);
                    }
                   
                    if (((Boolean)this.adjustForMap.get("adjustForpKaExpSS")).booleanValue())
                    {
                      if (tssids.size()>1)
                      {
                        for (int k=0;k<tssids.size();k++)
                        {
                          String tssid = (String)tssids.get(k);
                          DblMatrix pKaSSdev = new DblMatrix(0.001);
                          this.normal.setMean(DblMatrix.ZERO);
                          this.normal.setStd(pKaSSdev);

                          pname = this.mkParameterName(new String[]{"pKaExpSSdev",buffername,exp,tssid,ionstr,groupstr});
                          this.declareIfNotParameter(pname,this.normal.random(1));

                          pname = this.mkParameterName(new String[]{"pKaExpSSsigma",buffername,ionstr,groupstr});
                          this.declareIfNotParameter(pname,pKaSSdev);
                        }
                      }
                      else
                      {
                        throw new RuntimeException("Just make me take the average or something...");

                      }
                    }
                  }
                }
                else
                {
               
                  if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
                  {
                    DblMatrix pKadiff = pKa[ion].getDblAt(group).minus(pKa[ion].getDblAt(group-1));

                    pname = this.mkParameterName(new String[]{"pKadiff",buffername,ionstr,groupstr});


                    this.declareIfNotParameter(pname,pKadiff);

                    //Decare deviations in the pKa and pKb for each titration experiment and subsample within experiment.
                    if (Exps.size()>1)
                    {
                   
                      if (((Boolean)this.adjustForMap.get("adjustForpKaExp")).booleanValue())
                      {
                        pname = this.mkParameterName(new String[]{"pKadiffExpdev",buffername,exp,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.001));

                        pname = this.mkParameterName(new String[]{"pKadiffExpsigma",buffername,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.0001));
                      }
                     
                      if (((Boolean)this.adjustForMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        if (tssids.size()>1)
                        {
                          for (int k=0;k<tssids.size();k++)
                          {
                            String tssid = (String)tssids.get(k);
                            pname = this.mkParameterName(new String[]{"pKadiffExpSSdev",buffername,exp,tssid,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.001));

                            pname = this.mkParameterName(new String[]{"pKadiffExpSSsigma",buffername,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.0001));
                          }
                        }
                        else
                        {
                          throw new RuntimeException("Just make me take the average or something...");

                        }
                      }
                    }
                  }
                }
              }
            }

            if (!pKb[ion].isEmpty())
            {
              for (int group=0;group<pKb[ion].getN();group++)
              {
                Integer GROUP = new Integer(group);
                String groupstr = GROUP.toString();

                if (group == 0)
                {
                  if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
                  {
                    pname = this.mkParameterName(new String[]{"pKb",buffername,ionstr,groupstr});
                    this.declareIfNotParameter(pname,pKb[ion].getDblAt(group));
                    //Decare deviations in the pKa and pKb for each titration experiment and subsample within experiment.
                    if (Exps.size()>1)
                    { 
                   
                      if (((Boolean)this.adjustForMap.get("adjustForpKaExp")).booleanValue())
                      {
                        pname = this.mkParameterName(new String[]{"pKbExpdev",buffername,exp,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.0));

                        pname = this.mkParameterName(new String[]{"pKbExpsigma",buffername,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.1));
                      }
                     
                      if (((Boolean)this.adjustForMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        if (tssids.size()>1)
                        {
                          for (int k=0;k<tssids.size();k++)
                          {
                            String tssid = (String)tssids.get(k);
                            pname = this.mkParameterName(new String[]{"pKbExpSSdev",buffername,exp,tssid,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.0));

                            pname = this.mkParameterName(new String[]{"pKbExpSSsigma",buffername,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.1));
                          }
                        }
                        else
                        {
                          throw new RuntimeException("Just make me take the average or something...");
                        }
                      }
                    }
                  }
                }
                else
                {
               
                  if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
                  {
                    DblMatrix pKbdiff = pKb[ion].getDblAt(group).minus(pKb[ion].getDblAt(group-1));

                    pname = this.mkParameterName(new String[]{"pKbdiff",buffername,ionstr,groupstr});
                    this.declareIfNotParameter(pname,pKbdiff);

                    //Decare deviations in the pKb and pKb for each titration experiment and subsample within experiment.
                    if (Exps.size()>1)
                    {
                   
                      if (((Boolean)this.adjustForMap.get("adjustForpKaExp")).booleanValue())
                      {
                        pname = this.mkParameterName(new String[]{"pKbdiffExpdev",buffername,exp,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.0001));

                        pname = this.mkParameterName(new String[]{"pKbdiffExpsigma",buffername,ionstr,groupstr});
                        this.declareIfNotParameter(pname,new DblMatrix(0.1));
                      }

                      if (((Boolean)this.adjustForMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        if (tssids.size()>1)
                        {
                          for (int k=0;k<tssids.size();k++)
                          {
                            String tssid = (String)tssids.get(k);
                            pname = this.mkParameterName(new String[]{"pKbdiffExpSSdev",buffername,exp,tssid,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.00001));

                            pname = this.mkParameterName(new String[]{"pKbdiffExpSSsigma",buffername,ionstr,groupstr});
                            this.declareIfNotParameter(pname,new DblMatrix(0.1));
                          }
                        }
                        else
                        {
                          throw new RuntimeException("Just make me take the average or something...");
View Full Code Here


    for (int j=0;j<names.length;j++)
    {
      //String newName= names[j].replaceFirst("#"+oldNickname,"#"+newNickname);
      String oldname = names[j];
      String newName= names[j].replaceFirst(match,replaceStr);
      DblMatrix value = this.getDistributedParam(oldname);
     
      this.declareDistributedParameter(newName,value);
      this.revokeDistributedParameter(oldname);
      //oldMap.put(newName,oldMap.get(oldname));
      //oldMap.remove(oldname);
View Full Code Here

    Vector pKaSet = new Vector();
    int ionStart=0;
    int ionStop=0;
    String ion;
    boolean readingIon=false;
    DblMatrix val;
    int k=0;
    while (k<pKa.length())
    {
      if (pKa.charAt(k)=='[')
      {
        if (readingIon)
        {
          throw new RuntimeException("Encountered extra '[' in buffer coefficients.")
        }
        readingIon = true;
        ionStart = k;
       
      }
      else
      {
        if (pKa.charAt(k)==']')
        {
          if (!readingIon)
          {
            throw new RuntimeException("Encountered extra ']' in buffer coefficients.")
          }
          ionStop = k+1;
          ion = pKa.substring(ionStart,ionStop);
          pKaSet.add(new DblMatrix(ion));
         
          readingIon = false;
        }
      }
      k++;
View Full Code Here

        getter = "getParamSuper";
        setter = "setParamSuper";

        String paramName = p;
        DblMatrix value = new DblMatrix(0);

        getArg = new Object[]{paramName};
        getArgClasses = new Class[]{String.class};

        setArg = new Object[]{paramName,value};
View Full Code Here

 
  public DblMatrix getPredictionAt(DblMatrix[] X)
        {
    //Note: probably the X should be the hidden (i.e. randomly drawn pH value rather than the observed pH values).
 
    DblMatrix pH = X[0];
    DblMatrix OUT = new DblMatrix(pH.Size); // the predicted cummulant...
   
                return(OUT);
        }
View Full Code Here

    String exp;
    String ssid;
    String obsnum;
    String param;
    String buffername = this.transientStorage.getNickname();
    DblMatrix val1,val2;
   
    DblMatrix interceptpH = null;
    DblMatrix interceptpHExp = null;
    DblMatrix interceptpHExpSigma = null;
    DblMatrix interceptpHExpSS = null;
    DblMatrix interceptpHExpSSSigma = null;
   
    DblMatrix linearpH = null;
    DblMatrix linearpHExp = null;
    DblMatrix linearpHExpSigma = null;
    DblMatrix linearpHExpSS = null;
    DblMatrix linearpHExpSSSigma = null;
   
    DblMatrix quadraticpH = null;
    DblMatrix quadraticpHExp = null;
    DblMatrix quadraticpHExpSigma = null;
    DblMatrix quadraticpHExpSS = null;
    DblMatrix quadraticpHExpSSSigma = null;
   
    DblMatrix cubicpH = null;
    DblMatrix cubicpHExp = null;
    DblMatrix cubicpHExpSigma = null;
    DblMatrix cubicpHExpSS = null;
    DblMatrix cubicpHExpSSSigma = null;
   
    DblMatrix sigmaCalib = null;
   
    DblMatrix sigmaCb = null;
   
    //DblMatrix initialpH_mean = null;
    DblMatrix latentpHi = null;
   
   
    if (this.numParams()==0)
    {
      throw new RuntimeException("No parameters have been established.");
    }
   
    BufferSolution MarginalSol = null;
   
    param = this.mkParameterName(new String[]{"sigmaCb",buffername});
   
    sigmaCb = this.getParam(param);
   
    sigmaCb.show("sigmaCb","0.00000E0");
   
    //System.out.println("adjustForLatentpHLinkIntercept is "+(((Boolean)this.adjustForMap.get("adjustForLatentpHLinkIntercept")).booleanValue()));
    if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkIntercept")).booleanValue())
    {
      param = this.mkParameterName(new String[]{"interceptpH",buffername});
      if (this.hasParameter(param))
      {
     
        //System.out.println("Has intercept!");
        interceptpH = this.getParam(param);
      }
      else
      {
       
        interceptpH = new DblMatrix(0.0);
      }
    }
    else
    {
      interceptpH = new DblMatrix(0.0);
    }
   
   
     
    if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkLinear")).booleanValue())
    {
      param = this.mkParameterName(new String[]{"linearpH",buffername});
      if (this.hasParameter(param))
      {
        //System.out.println("Has linear!");
        linearpH = this.getParam(param);
      }
      else
      {
        linearpH = new DblMatrix(0.0);
      }
    }
    else
    {
      linearpH = new DblMatrix(0.0);
    }
     
    if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkQuadratic")).booleanValue())
    {
      param = this.mkParameterName(new String[]{"quadraticpH",buffername});
      if (this.hasParameter(param))
      {
        //System.out.println("Has quadratic!");
        quadraticpH = this.getParam(param);
      }
      else
      {
        quadraticpH = new DblMatrix(0.0);
      }
    }
    else
    {
      quadraticpH = new DblMatrix(0.0);
    }
   
    if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkCubic")).booleanValue())
    {
      param = this.mkParameterName(new String[]{"cubicpH",buffername});
      if (this.hasParameter(param))
      {
        //System.out.println("Has cubic!");
        cubicpH = this.getParam(param);
      }
      else
      {
        cubicpH = new DblMatrix(0.0);
      }
    }
    else
    {
      cubicpH = new DblMatrix(0.0);
    }
   
    this.normal.setMean(new DblMatrix(0.0));
   
    DblMatrix LIKE = DblMatrix.J(2*this.totalNumberOfTitrationPoints);
   
    DblMatrix pHresids = new DblMatrix(2*this.totalNumberOfTitrationPoints);
    Vector CbThatShouldBeZero = new Vector();
    Vector pH4CbThatShouldBeZero = new Vector();
    Vector legendStrings = new Vector();
    BufferSolution RhsSol = null;
   
    ////
    int smoothingDataIndex = 0;
   
   
    int like_index = 0;
    //int cb_index = 0;
   
   
    if (((Boolean)this.adjustForMap.get("adjustForSmoothing")).booleanValue())
    {
      smoothingDataIndex = 0;
    }
   
    DblMatrix SmoothingpH = null;
    DblMatrix SmoothingCbResidual = null;
    Lpreg SmoothingSmoother = null;
   
    for (int i=0;i<Exps.size();i++)
    {
      exp = (String)Exps.get(i);
     
      //RhsSol.add(this.transientStorage,thisConc);
     
      SSIDS = this.transientStorage.getTitrationSubsampleIDs(exp);
     
   
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkInterceptExp")).booleanValue())
      {
        param = this.mkParameterName(new String[]{"interceptpHExp",buffername,exp});
        if (this.hasParameter(param))
        {
          interceptpHExp = this.getParam(param);
        }
        else
        {
          interceptpHExp = new DblMatrix(0.0);
        }
      }
      else
      {
        interceptpHExp = new DblMatrix(0.0);
      }
     
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkLinearExp")).booleanValue())
      {
        param = this.mkParameterName(new String[]{"linearpHExp",buffername,exp});
        if (this.hasParameter(param))
        {
          linearpHExp = this.getParam(param);
        }
        else
        {
          linearpHExp = new DblMatrix(0.0);
        }
      }
      else
      {
        linearpHExp = new DblMatrix(0.0);
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkQuadraticExp")).booleanValue())
      {
        param = this.mkParameterName(new String[]{"quadraticpHExp",buffername,exp});
        if (this.hasParameter(param))
        {
          quadraticpHExp = this.getParam(param);
        }
        else
        {
          quadraticpHExp = new DblMatrix(0.0);
        }
      }
      else
      {
        quadraticpHExp = new DblMatrix(0.0);
      }
     
      if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkCubicExp")).booleanValue())
      {
        param = this.mkParameterName(new String[]{"cubicpHExp",buffername,exp});
        if (this.hasParameter(param))
        {
          cubicpHExp = this.getParam(param);
        }
        else
        {
          cubicpHExp = new DblMatrix(0.0);
        }
      }
      else
      {
        cubicpHExp = new DblMatrix(0.0);
      }
     
     
      if (((Boolean)this.adjustForMap.get("adjustForSmoothingExp")).booleanValue())
      {
        smoothingDataIndex = 0;
      }
         
     
      for (int j=0;j<SSIDS.size();j++)
      { 
       
        ssid = (String)SSIDS.get(j);
       
       
        if (this.adjustForLatentpHLink())//Regardless -- now we know we have at least one titration.
        {
          param = this.mkParameterName(new String[]{"sigmaCalib",buffername});
          sigmaCalib = this.getParam(param);
         
          //sigmaCalib.show(param);
          this.normal.setStd(sigmaCalib);
        }
       
       
        if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkInterceptExpSS")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"interceptpHExpSS",buffername,exp,ssid});
          if (this.hasParameter(param))
          {
            interceptpHExpSS = this.getParam(param);
          }
          else
          {
            interceptpHExpSS = new DblMatrix(0.0);
          }
        }
        else
        {
          interceptpHExpSS = new DblMatrix(0.0);
        }


        if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkLinearExpSS")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"linearpHExpSS",buffername,exp,ssid});
          if (this.hasParameter(param))
          {
            linearpHExpSS = this.getParam(param);
          }
          else
          {
            linearpHExpSS= new DblMatrix(0.0);
          }
        }
        else
        {
          linearpHExpSS = new DblMatrix(0.0);
        }

        if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkQuadraticExpSS")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"quadraticpH",buffername,exp,ssid});
          if (this.hasParameter(param))
          {
            quadraticpHExpSS = this.getParam(param);
          }
          else
          {
            quadraticpHExpSS = new DblMatrix(0.0);
          }
        }
        else
        {
          quadraticpHExpSS = new DblMatrix(0.0);
        }

        if (((Boolean)this.adjustForMap.get("adjustForLatentpHLinkCubicExpSS")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"cubicpH",buffername,exp,ssid});
          if (this.hasParameter(param))
          {
            cubicpHExpSS = this.getParam(param);
          }
          else
          {
            cubicpHExpSS = new DblMatrix(0.0);
          }
        }
        else
        {
          cubicpHExpSS = new DblMatrix(0.0);
        }
       
       
        //This is probably a big time drag...
       
       
        //stop = System.currentTimeMillis();
        //System.out.println("Time it took1="+(stop-start));
        //start = stop;
       
       
        RhsSol = new BufferSolution();
        RhsSol.setConnection(this.connection);
        RhsSol.setRepository(this.repository);
        RhsSol.initialize();
       
        if (this.isSamplingObject("RandomBufferSolution"))
        {
          MarginalSol = new BufferSolution();
          MarginalSol.setConnection(this.connection);
          MarginalSol.setRepository(this.repository);
          MarginalSol.initialize();
        }
       
        //stop = System.currentTimeMillis();
        //System.out.println("Time it took2="+(stop-start));
        //start = stop;
       
        DblMatrix thisConc = new DblMatrix(1.0);
        DblMatrix marginalConc = thisConc.copy();
       
        if (((Boolean)this.adjustForMap.get("adjustForBufferConc")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"C",buffername});
          thisConc = this.getParam(param);
          if (this.isSamplingObject("RandomBufferSolution"))
          {
            if (!((Boolean)this.marginalizeMap.get("adjustForBufferConc")).booleanValue())
            {
              marginalConc = thisConc.copy();
            }
         
          }
        }
       
       
        //thisConc.show("This conc");
       
        //Even though thisConc would not be updated unless the parameters were defined we
        //check the boolean flags for self-documentation purposes and clarity.
       
        if (((Boolean)this.adjustForMap.get("adjustForBufferExpConc")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"CExpdev",buffername,exp});
          if (this.hasParameter(param))
          {
            thisConc = thisConc.plus(this.getParam(param));
           
            if (this.isSamplingObject("RandomBufferSolution"))
            {
              if (!((Boolean)this.marginalizeMap.get("adjustForBufferExpConc")).booleanValue())
              {
                marginalConc = thisConc.copy();
              }

            }
          }
        }
       
        if (((Boolean)this.adjustForMap.get("adjustForBufferExpSSConc")).booleanValue())
        {
          param = this.mkParameterName(new String[]{"CExpSSdev",buffername,exp,ssid});
          if (this.hasParameter(param))
          {
            thisConc = thisConc.plus(this.getParam(param));
           
            if (this.isSamplingObject("RandomBufferSolution"))
            {
              if (!((Boolean)this.marginalizeMap.get("adjustForBufferExpSSConc")).booleanValue())
              {
                marginalConc = thisConc.copy();
              }

            }
          }
        }
       
        //thisConc.show("This concentration");
        RhsSol.add(this.transientStorage,thisConc);
       
        if (this.isSamplingObject("RandomBufferSolution"))
        {
          MarginalSol.add(this.transientStorage,marginalConc);
        }
       
       
       
        DblMatrix smoothingParameter = null;
       
        if (this.adjustForSmoothingComponent())
        {
          String mapkey1 = null;
          String mapkey2 = null;
          String mapkey3 = null;
          //These initializations of the maps should only need to be run once under any new parameter configuration.
          if (((Boolean)this.adjustForMap.get("adjustForSmoothing")).booleanValue())
          {
            if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH"});
              mapkey2 = this.mkParameterName(new String[]{"CbResidual"});
              mapkey3 = this.mkParameterName(new String[]{"Lpreg"});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,totalNumberOfTitrationPoints));
                this.smoothingCbResidualMap.put(mapkey2,new DblMatrix(totalNumberOfTitrationPoints));
                this.smoothingSmootherMap.put(mapkey3,null);
              }

              param = this.mkParameterName(new String[]{"smoothingParameter",buffername});
              smoothingParameter = this.getParam(param);
            }
            else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH"});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,totalNumberOfTitrationPoints));
              }
             
            } 
          }
          else if (((Boolean)this.adjustForMap.get("adjustForSmoothingExp")).booleanValue())
          {
         
            if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH",exp});
              mapkey2 = this.mkParameterName(new String[]{"CbResidual",exp});
              mapkey3 = this.mkParameterName(new String[]{"Lpreg",exp});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                int numOfPoints = 0;

                for (int ii=0;ii<SSIDS.size();ii++)
                {
                  String ss = (String)SSIDS.get(ii);
                  OBSNUM = this.transientStorage.getTitrationObservationNumbers(exp,ss);
                  numOfPoints = numOfPoints + OBSNUM.size();
                }
                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,numOfPoints));
                this.smoothingCbResidualMap.put(mapkey2,new DblMatrix(numOfPoints));
                this.smoothingSmootherMap.put(mapkey3,null);
              }

              param = this.mkParameterName(new String[]{"smoothingParameterExp",buffername,exp});
              smoothingParameter = this.getParam(param);
            }
            else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH"});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,totalNumberOfTitrationPoints));
              }
             
            } 
           
          }
          else if (((Boolean)this.adjustForMap.get("adjustForSmoothingExpSS")).booleanValue())
          {
            if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH",exp,ssid});
              mapkey2 = this.mkParameterName(new String[]{"CbResidual",exp,ssid});
              mapkey3 = this.mkParameterName(new String[]{"Lpreg",exp,ssid});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                int numOfPoints = 0;
                OBSNUM = this.transientStorage.getTitrationObservationNumbers(exp,ssid);
                numOfPoints = numOfPoints + OBSNUM.size();

                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,numOfPoints));
                this.smoothingCbResidualMap.put(mapkey2,new DblMatrix(numOfPoints));
                this.smoothingSmootherMap.put(mapkey3,null);
              }

              param = this.mkParameterName(new String[]{"smoothingParameterExpSS",buffername,exp,ssid});
              smoothingParameter = this.getParam(param);
            }
            else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
            {
              mapkey1 = this.mkParameterName(new String[]{"pH"});
              if (!this.smoothingpHMap.containsKey(mapkey1))
              {
                this.smoothingpHMap.put(mapkey1,DblMatrix.span(0.0,14.0,totalNumberOfTitrationPoints));
              }
             
            }
          }
         
          if (smoothingDataIndex == 0) //We are starting anew...
          {
         
            if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
            {
                    SmoothingpH = (DblMatrix)this.smoothingpHMap.get(mapkey1);
                    SmoothingCbResidual = (DblMatrix)this.smoothingCbResidualMap.get(mapkey2);
              SmoothingSmoother = (Lpreg)this.smoothingSmootherMap.get(mapkey3);
              if (SmoothingSmoother == null)
              {
                SmoothingSmoother = new Lpreg();
                this.smoothingSmootherMap.put(mapkey3,SmoothingSmoother);
              }

              DblMatrix[] XDATA = new DblMatrix[]{SmoothingpH};
               DblMatrix YDATA = SmoothingCbResidual;
               SmoothingSmoother.setData(XDATA,YDATA);
              NNBandwidth BW = (NNBandwidth)SmoothingSmoother.getBandwidthMethod();
              FixedSmoothMethod SM  = (FixedSmoothMethod)BW.getSmoothMethod();
              DblMatrix SP = smoothingParameter.divideBy(smoothingParameter.plus(1.0));

              SM.setSmoothParameter(SP);
              BW.setSmoothMethod(SM);
            }
            else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
            {
              SmoothingpH = (DblMatrix)this.smoothingpHMap.get(mapkey1);
            }
          }
         
          // ComplexBufferPredictor cmplx = RhsSol.getComplexBufferPredictor();
//           Smoother smoother = cmplx.getSmoother();
//           DblMatrix[] XDATA = new DblMatrix[]{SmoothingpH};
//           DblMatrix YDATA = SmoothingCbResidual;
//
//           smoother.setData(XDATA,YDATA);
        }
       
        if (((Boolean)this.adjustForMap.get("adjustForSmoothingExpSS")).booleanValue())
        {
          smoothingDataIndex = 0;
        }
       
        String[] buffdnames = IconServer.splitDomainName(buffername);
        String[] expdnames = IconServer.splitDomainName(exp);
       
        ImageIcon buffDomainIcon = this.iconServer.getIconForDomain(buffdnames[0]);
        ImageIcon expDomainIcon =  this.iconServer.getIconForDomain(expdnames[0]);
       
       
        if (buffDomainIcon == null)
        {
          throw new RuntimeException("The icon for the buffer domain "+buffdnames[0]+" is null.");
        }
       
        if (expDomainIcon == null)
        {
          throw new RuntimeException("The icon for the experiment domain "+expdnames[0]+" is null.");
        }
       
        SLIconifiedAnnotation annot = new SLIconifiedAnnotation(null,null);
        annot.addAnnotation(buffDomainIcon);
        annot.addAnnotation("."+buffdnames[1]);
        annot.addAnnotation("*");
        annot.addAnnotation(expDomainIcon);
        annot.addAnnotation("."+expdnames[1]);
        annot.addAnnotation("*");
        annot.addAnnotation(ssid);
        annot.setText(buffername+"*"+exp+"*"+ssid);
       
        legendStrings.add(annot);
       
       
        //legendStrings.add(buffername+"*"+exp+"*"+ssid);
       
        //stop = System.currentTimeMillis();
        //System.out.println("Time it took3="+(stop-start));
        //start = stop;
       
        OBSNUM = this.transientStorage.getTitrationObservationNumbers(exp,ssid);
       
        //Need the initial volume for this titration in order to
        DblMatrix initialVolume = new DblMatrix(new Double(this.transientStorage.getInitialVolume(exp,ssid)));
        //param = this.mkParameterName(new String[]{"initialVolExp",buffername,exp});
       
        //initialpH_mean = initialpH.plus(initialpHExpdev).plus(initialpHExpSSdev);
       
        DblMatrix currentVolume = initialVolume.plus(0.0);
       
        DblMatrix DblCbThatShouldBeZero = new DblMatrix(OBSNUM.size());
        DblMatrix DblpH4CbThatShouldBeZero = new DblMatrix(OBSNUM.size());
       
       
        for (int k=0;k<OBSNUM.size();k++)
        {
       
          //long stop1 = System.currentTimeMillis();
          //long start1 = stop1;
         
         
          obsnum = (String)OBSNUM.get(k);
         
          //Parameters not used should be set to reasonable default values (Usually 0.0) by now.
          if (this.adjustForLatentpHLink())
          {
         
            String val = this.transientStorage.getpH(exp,ssid,obsnum);
            latentpHi = new DblMatrix(new Double(val));
            val = this.referenceStorage.getpH(exp,ssid,obsnum);
            DblMatrix obspH = new DblMatrix(new Double(val));
         
            //Implement the latent link equation...
            DblMatrix B0 = interceptpH.plus(interceptpHExp).plus(interceptpHExpSS);
            DblMatrix B1 = linearpH.plus(linearpHExp).plus(linearpHExpSS);
            DblMatrix B2 = quadraticpH.plus(quadraticpHExp).plus(quadraticpHExpSS);
            DblMatrix B3 = cubicpH.plus(cubicpHExp).plus(cubicpHExpSS);

            //DblMatrix centeredDiff = latentpHi.minus(B0);
            DblMatrix centeredDiff = latentpHi;
            DblMatrix centeredDiffSqrd = centeredDiff.times(centeredDiff);
            DblMatrix centeredDiffCubed = centeredDiffSqrd.times(centeredDiff);
           
            DblMatrix obspH_hat = B0.plus(B1.times(centeredDiff).plus(B2.times(centeredDiffSqrd)).plus(B3.times(centeredDiffCubed)));

            DblMatrix resid = obspH.minus(obspH_hat);

            pHresids.setDblAt(resid,like_index);

            this.normal.setMean(DblMatrix.ZERO);
            this.normal.setStd(sigmaCalib);
           
            DblMatrix likeval = this.normal.pdf(resid);
            if (DblMatrix.test(DblMatrix.isNaN(likeval)))
            {
              resid.show("residual");
              latentpHi.transpose().show("Latent pH");
              obspH.transpose().show("Observed pH");
              sigmaCalib.show("sigmaCalib");

              LIKE.replicate(DblMatrix.INF,LIKE.Size);

              //System.out.println("NaN in pH likelihood calc.");

              return(LIKE);
            }

            if (DblMatrix.test(likeval.eq(0.0)))
            {
              resid.show("residual");
              latentpHi.transpose().show("Latent pH");
              obspH.transpose().show("Observed pH");
              obspH_hat.transpose().show("Predicted pH");
              sigmaCalib.show("sigmaCalib");
              likeval.show("likeval","0.00E00");
              LIKE.replicate(DblMatrix.INF,LIKE.Size);
              //System.out.println("Zero in pH likelihood calc.");
              return(LIKE);
            }

            LIKE.setDblAt(likeval,like_index);
            like_index++;
          }
         
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took1a="+(stop1-start1));
          //start1 = stop1;
         
         
          //Bring the RhsSol up to date with the latest addition...
          String titrant = this.transientStorage.getTitrant(exp,ssid,obsnum);
          DblMatrix volAdded = new DblMatrix(new Double(this.transientStorage.getVolumeAdded(exp,ssid,obsnum)));
         
          DblMatrix conc = null;
          if (((Boolean)this.adjustForMap.get("adjustForTitrantConc")).booleanValue())
          {
            //Consider this the dilution of a unit concentration of titrant where the
            //unit concentration is given by the latent "C" parameter for this titrant.
            DblMatrix unitConcentration = new DblMatrix(1.0);
            DblMatrix unitConcentrationExpdev = new DblMatrix(0.0);
            DblMatrix unitConcentrationExpSSdev = new DblMatrix(0.0);

            param = this.mkParameterName(new String[]{"T",titrant,buffername});
            if (this.hasParameter(param))
            {
               unitConcentration = this.getParam(param);
            }

            param = this.mkParameterName(new String[]{"TExpdev",titrant,buffername,exp});
            if (this.hasParameter(param))
            {
               unitConcentrationExpdev = this.getParam(param);
            }

            param = this.mkParameterName(new String[]{"TExpSSdev",titrant,buffername,exp,ssid});
            if (this.hasParameter(param))
            {
               unitConcentrationExpSSdev = this.getParam(param);
            }

            conc = unitConcentration.plus(unitConcentrationExpdev).plus(unitConcentrationExpSSdev);
            DblMatrix unitFactor = new DblMatrix(new Double(this.transientStorage.getTitrantConcentration(exp,ssid,obsnum)));

         
            conc = conc.times(unitFactor);
          }
          else //Just take the recorded concentration as given...
          {
            conc = new DblMatrix(new Double(this.transientStorage.getTitrantConcentration(exp,ssid,obsnum)));
          }
         
         
          if (!this.titrantMap.containsKey(titrant))
          {
            throw new RuntimeException("Titrant map does not contain a mapping for the titrant "+titrant+".");
          }
         
          BufferSolution titr = (BufferSolution)this.titrantMap.get(titrant);
          if (titr == null)
          {
            throw new RuntimeException("Titrant map contains a null mapping for the titrant "+titrant+".");
          }
         
          titr.setConcentration(titrant,conc);
          //titr.show("titrant----------------");
          //Update the RhsSol for the latest addition of titrant.
          //System.out.println("Here is the repository of RhsSol:"+RhsSol.getRepository());
         
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took2a="+(stop1-start1));
          //start1 = stop1;
         
         
          RhsSol = BufferSolution.mixSol(RhsSol,currentVolume,titr,volAdded);
         
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took3a="+(stop1-start1));
          //start1 = stop1;
         
          //RhsSol.show("RhsSol after mix");
          //Remember to update the total volume after an addition of titrant.
          currentVolume = currentVolume.plus(volAdded);
         
          if (this.isSamplingObject("RandomBufferSolution"))
          {
            if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
            {
              String[] components = MarginalSol.getComponents();
              ComplexBufferPredictor cmplxPred =  MarginalSol.getSummaryBuffer();

              DblMatrix[] pKa = cmplxPred.getEstimatedpKa(buffername);
              DblMatrix[] pKb = cmplxPred.getEstimatedpKb(buffername);

              String ionstr = null;
              String groupstr = null;

             
              for (int ion=0;ion<pKa.length;ion++)
              {
                Integer ION = new Integer(ion);
                ionstr = ION.toString();

                if (!pKa[ion].isEmpty())
                {
                  for (int group=0;group<pKa[ion].getN();group++)
                  {
                    if (group == 0)
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();


                      DblMatrix meanpKa = pKa[ion].getDblAt(group);
                      DblMatrix pKaExpdev = new DblMatrix(0.0);
                      DblMatrix pKaExpSSdev = new DblMatrix(0.0);

                      if (!((Boolean)this.marginalizeMap.get("adjustForpKa")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKa",buffername,ionstr,groupstr});
                     
                        if (this.hasParameter(param))
                        {
                          meanpKa = this.getParam(param);
                        }
                      }
                     
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExp")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKaExpdev",buffername,exp,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKaExpdev = this.getParam(param);
                        }
                      }
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKaExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKaExpSSdev = this.getParam(param);
                        }
                      }


                      pKa[ion].setDblAt(meanpKa.plus(pKaExpdev).plus(pKaExpSSdev),group);
                    }
                    else
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix pKaToLeft = pKa[ion].getDblAt(group-1);

                      DblMatrix meanpKadiff = pKa[ion].getDblAt(group).minus(pKaToLeft);
                      DblMatrix pKadiffExpdev = new DblMatrix(0.0);
                      DblMatrix pKadiffExpSSdev = new DblMatrix(0.0);

                      if (!((Boolean)this.marginalizeMap.get("adjustForpKa")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKadiff",buffername,ionstr,groupstr});

                        if (this.hasParameter(param))
                        {
                          meanpKadiff = this.getParam(param);
                        }
                      }
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExp")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKadiffExpdev",buffername,exp,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKadiffExpdev = this.getParam(param);
                        }
                      }
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKadiffExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKadiffExpSSdev = this.getParam(param);
                        }
                      }
                     
                      DblMatrix pKaDiff = meanpKadiff.plus(pKadiffExpdev).plus(pKadiffExpSSdev);

                      pKa[ion].setDblAt(pKaToLeft.plus(pKaDiff),group);
                   
                  }
                }


                if (!pKb[ion].isEmpty())
                {
                  for (int group=0;group<pKb[ion].getN();group++)
                  {


                    if (group == 0)
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix meanpKb = pKb[ion].getDblAt(group);
                      DblMatrix pKbExpdev = new DblMatrix(0.0);
                      DblMatrix pKbExpSSdev = new DblMatrix(0.0);

                      if (!((Boolean)this.marginalizeMap.get("adjustForpKa")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKb",buffername,ionstr,groupstr});

                        if (this.hasParameter(param))
                        {
                          meanpKb = this.getParam(param);
                        }
                      }
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExp")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKb",buffername,exp,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKbExpdev = this.getParam(param);
                        }
                      }
                     
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKb",buffername,exp,ssid,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKbExpSSdev = this.getParam(param);
                        }
                      }


                      pKb[ion].setDblAt(meanpKb.plus(pKbExpdev).plus(pKbExpSSdev),group);
                    }
                    else
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix pKbToLeft = pKb[ion].getDblAt(group-1);

                      DblMatrix meanpKbdiff = pKb[ion].getDblAt(group).minus(pKbToLeft);
                      DblMatrix pKbdiffExpdev = new DblMatrix(0.0);
                      DblMatrix pKbdiffExpSSdev = new DblMatrix(0.0);

                      if (!((Boolean)this.marginalizeMap.get("adjustForpKa")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKbdiff",buffername,ionstr,groupstr});

                        if (this.hasParameter(param))
                        {
                          meanpKbdiff = this.getParam(param);
                        }
                      }
                     
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExp")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKbdiffExpdev",buffername,exp,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKbdiffExpdev = this.getParam(param);
                        }
                      }
                     
                      if (!((Boolean)this.marginalizeMap.get("adjustForpKaExpSS")).booleanValue())
                      {
                        param = this.mkParameterName(new String[]{"pKbdiffExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                        if (this.hasParameter(param))
                        {
                          pKbdiffExpSSdev = this.getParam(param);
                        }
                      }
                      DblMatrix pKbDiff = meanpKbdiff.plus(pKbdiffExpdev).plus(pKbdiffExpSSdev);

                      pKb[ion].setDblAt(pKbToLeft.plus(pKbDiff),group);
                   
                  }
                }
              }
             
             
              //Notice that we will always get the last one -- we only can generate a single realization
              //as a random sample...
             
              //Update the pKa for this component....

              if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
              {
                if (pKa.length>0)
                {
                 
                  // for (int w=0;w<pKa.length;w++)
//                   {
//                     pKa[w].show("Latest estimated pKa for MarginalSol "+w,"0.0000E00");
//                   }
                 
                  cmplxPred.setEstimatedpKa(buffername,pKa);
                  cmplxPred.setEstimatedpKb(buffername,pKb);
                }
              }

              MarginalSol.setSummaryBuffer(cmplxPred);
            }
         
          }//Finished updating pKa/pKb for marginal mean buffer random sample...
         
         
          //Update the pKa/pKb for all components...
          //We take care to maintain order-restricted inference on the pKa/pKb
          //even in the presence of experiment and subsample effects.
          //
         
          // String[] components = RhsSol.getComponents();
//           ComplexBufferPredictor cmplxPred =  RhsSol.getSummaryBuffer();
//           DblMatrix[] pKa = cmplxPred.getEstimatedpKa(buffername);
//           DblMatrix[] pKb = cmplxPred.getEstimatedpKb(buffername);
//          
          String[] components = RhsSol.getComponents();
          ComplexBufferPredictor cmplxPred =  RhsSol.getSummaryBuffer();
          DblMatrix[] pKa = cmplxPred.getEstimatedpKa(buffername);
          DblMatrix[] pKb = cmplxPred.getEstimatedpKb(buffername);
          if (pKa != null)
          {
            if (((Boolean)this.adjustForMap.get("adjustForpKa")).booleanValue())
            {
                    String ionstr = null;
                    String groupstr = null;

              for (int ion=0;ion<pKa.length;ion++)
              {
                Integer ION = new Integer(ion);
                ionstr = ION.toString();

                if (!pKa[ion].isEmpty())
                {
                  for (int group=0;group<pKa[ion].getN();group++)
                  {
                    if (group == 0)
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix meanpKa = pKa[ion].getDblAt(group);
                      DblMatrix pKaExpdev = new DblMatrix(0.0);
                      DblMatrix pKaExpSSdev = new DblMatrix(0.0);

                      param = this.mkParameterName(new String[]{"pKa",buffername,ionstr,groupstr});

                      if (this.hasParameter(param))
                      {
                        meanpKa = this.getParam(param);
                      }

                      param = this.mkParameterName(new String[]{"pKaExpdev",buffername,exp,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKaExpdev = this.getParam(param);
                      }

                      param = this.mkParameterName(new String[]{"pKaExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKaExpSSdev = this.getParam(param);
                      }

                      pKa[ion].setDblAt(meanpKa.plus(pKaExpdev).plus(pKaExpSSdev),group);
                    }
                    else
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix pKaToLeft = pKa[ion].getDblAt(group-1);

                      DblMatrix meanpKadiff = pKa[ion].getDblAt(group).minus(pKaToLeft);
                      DblMatrix pKadiffExpdev = new DblMatrix(0.0);
                      DblMatrix pKadiffExpSSdev = new DblMatrix(0.0);


                      param = this.mkParameterName(new String[]{"pKadiff",buffername,ionstr,groupstr});

                      if (this.hasParameter(param))
                      {
                        meanpKadiff = this.getParam(param);
                      }

                      param = this.mkParameterName(new String[]{"pKadiffExpdev",buffername,exp,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKadiffExpdev = this.getParam(param);
                      }
                      param = this.mkParameterName(new String[]{"pKadiffExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKadiffExpSSdev = this.getParam(param);
                      }
                      DblMatrix pKaDiff = meanpKadiff.plus(pKadiffExpdev).plus(pKadiffExpSSdev);

                      pKa[ion].setDblAt(pKaToLeft.plus(pKaDiff),group);
                   
                  }
                }


                if (!pKb[ion].isEmpty())
                {
                  for (int group=0;group<pKb[ion].getN();group++)
                  {


                    if (group == 0)
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix meanpKb = pKb[ion].getDblAt(group);
                      DblMatrix pKbExpdev = new DblMatrix(0.0);
                      DblMatrix pKbExpSSdev = new DblMatrix(0.0);


                      param = this.mkParameterName(new String[]{"pKb",buffername,ionstr,groupstr});

                      if (this.hasParameter(param))
                      {
                        meanpKb = this.getParam(param);
                      }

                      param = this.mkParameterName(new String[]{"pKb",buffername,exp,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKbExpdev = this.getParam(param);
                      }
                      param = this.mkParameterName(new String[]{"pKb",buffername,exp,ssid,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKbExpSSdev = this.getParam(param);
                      }


                      pKb[ion].setDblAt(meanpKb.plus(pKbExpdev).plus(pKbExpSSdev),group);
                    }
                    else
                    {
                      Integer GROUP = new Integer(group);
                      groupstr = GROUP.toString();

                      DblMatrix pKbToLeft = pKb[ion].getDblAt(group-1);

                      DblMatrix meanpKbdiff = pKb[ion].getDblAt(group).minus(pKbToLeft);
                      DblMatrix pKbdiffExpdev = new DblMatrix(0.0);
                      DblMatrix pKbdiffExpSSdev = new DblMatrix(0.0);


                      param = this.mkParameterName(new String[]{"pKbdiff",buffername,ionstr,groupstr});

                      if (this.hasParameter(param))
                      {
                        meanpKbdiff = this.getParam(param);
                      }

                      param = this.mkParameterName(new String[]{"pKbdiffExpdev",buffername,exp,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKbdiffExpdev = this.getParam(param);
                      }
                      param = this.mkParameterName(new String[]{"pKbdiffExpSSdev",buffername,exp,ssid,ionstr,groupstr});
                      if (this.hasParameter(param))
                      {
                        pKbdiffExpSSdev = this.getParam(param);
                      }
                      DblMatrix pKbDiff = meanpKbdiff.plus(pKbdiffExpdev).plus(pKbdiffExpSSdev);

                      pKb[ion].setDblAt(pKbToLeft.plus(pKbDiff),group);
                   
                  }
                }
              }
            }
          }
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took4a="+(stop1-start1));
          //start1 = stop1;
         
         
          //Update the pKa for this component....
          if (pKa != null)
          {
            if (pKa.length>0)
            {
              //pKa[3].show("Latest estimated pKa...");
              cmplxPred.setEstimatedpKa(buffername,pKa);
              cmplxPred.setEstimatedpKb(buffername,pKb);
            }
          }
         
          //RhsSol.show("RhsSol??");
          //Now we hope that the Cb of the right hand side solution when
          //evaluated at the latent pH is exactly equal to zero!
          HashMap Cb = null;
         
         
          if (this.adjustForLatentpHLink())
          {
            Cb = RhsSol.Cb(latentpHi,true);
            DblpH4CbThatShouldBeZero.setDblAt(latentpHi,k);
            if (this.adjustForSmoothingComponent())
            {
              SmoothingpH.setDblAt(latentpHi,smoothingDataIndex);
             
             
              //if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
              //{
              //  SmoothingpH.setDblAt(latentpHi,smoothingDataIndex);
              //}   
            }
           
          }
          else
          {
            String val = this.transientStorage.getpH(exp,ssid,obsnum);
            DblMatrix observedpHi = new DblMatrix(new Double(val));
            Cb = RhsSol.Cb(observedpHi,true);
            DblpH4CbThatShouldBeZero.setDblAt(observedpHi,k);
           
            //Setting the XData for the smoother...
            if (this.adjustForSmoothingComponent())
            {
             
              SmoothingpH.setDblAt(observedpHi,smoothingDataIndex);
             
              //if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
              //{
              //  SmoothingpH.setDblAt(observedpHi,smoothingDataIndex);
              //} 
            }
          }
         
         
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took5a="+(stop1-start1));
          //start1 = stop1;
         
         
          // Set keys = Cb.keySet();
//           Iterator iter = keys.iterator();
//           while (iter.hasNext())
//           {
//             System.out.println(iter.next());
//           }
          // System.out.println("buffername="+buffername);
//           ///
          //DblMatrix thisUntitledCb = (DblMatrix)Cb.get(buffername);
          //thisUntitledCb.show("thisUntitledCb","0.00E0");
          ///
         
          //DblMatrix thisTitrantCb = (DblMatrix)Cb.get("com.mockturtlesolutions.HCl");
          //thisTitrantCb.show("titrantCb","0.00E0");
         
          //DblMatrix thiswaterCb = (DblMatrix)Cb.get("com.mockturtlesolutions.water");
          //thiswaterCb.show("waterCb","0.00E0");
         
           DblMatrix thisPointCb = (DblMatrix)Cb.get("total");
          DblMatrix P0 = new DblMatrix(0.0);
          DblMatrix P1 = new DblMatrix(0.0);
          DblMatrix P2 = new DblMatrix(0.0);
          DblMatrix P3 = new DblMatrix(0.0);
         
          //Set the YData for the next go-round.
          if (this.adjustForSmoothingComponent())
          {
            if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.LOWESS_SMOOTHING)
            {
              SmoothingCbResidual.setDblAt(thisPointCb,smoothingDataIndex);
              SmoothingSmoother.useSufficient(false);
              DblMatrix complexCbContribution = SmoothingSmoother.predict(new DblMatrix[]{SmoothingpH.getDblAt(smoothingDataIndex)});
              thisPointCb = thisPointCb.minus(complexCbContribution);
           
              //System.out.println("Done with one!");
            }
            else if (((Integer)this.adjustForMap.get("adjustForSmoothingMethod")).intValue() == DefaultComplexBufferPredictorGenerator.POLYNOMIAL_SMOOTHING)
            { 
              DblMatrix pHcenter = SmoothingpH.getDblAt(smoothingDataIndex).minus(7.0);//Center about neutral pH as convention.
              DblMatrix pHcenterSq = pHcenter.times(pHcenter);
              DblMatrix pHcenterCd = pHcenter.times(pHcenterSq);
             
             
              if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.LINEAR_SMOOTHER)
              {
                param = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
                P0 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingSlope",buffername});
                P1 = this.getParam(param);
              }
              else if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.QUADRATIC_SMOOTHER)
              {
                param = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
                P0 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingSlope",buffername});
                P1 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingQuadratic",buffername});
                P2 = this.getParam(param);
              }
              else if (((Integer)this.adjustForMap.get("adjustForSmoothingModel")).intValue() == DefaultComplexBufferPredictorGenerator.CUBIC_SMOOTHER)
              {
                param = this.mkParameterName(new String[]{"smoothingIntercept",buffername});
                P0 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingSlope",buffername});
                P1 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingQuadratic",buffername});
                P2 = this.getParam(param);
                param = this.mkParameterName(new String[]{"smoothingCubic",buffername});
                P3 = this.getParam(param);
              }
              // P0.show("P0");
//               P1.show("P1");
//               P2.show("P2");
//               P3.show("P3");
             
              DblMatrix complexCbContribution = P0.plus(P1.times(pHcenter)).plus(P2.times(pHcenterSq)).plus(P3.times(pHcenterCd));
              //complexCbContribution.show("Complex contribution");
              thisPointCb = thisPointCb.plus(complexCbContribution);
            }
          }
         
          DblCbThatShouldBeZero.setDblAt(thisPointCb,k);
         
          this.normal.setMean(DblMatrix.ZERO);
          this.normal.setStd(sigmaCb);
          DblMatrix cblike = this.normal.pdf(thisPointCb);
          if (DblMatrix.test(DblMatrix.isNaN(cblike)))
          {
            throw new RuntimeException("NaN for Cb likelihood.");
          }
         
         
          LIKE.setDblAt(cblike,like_index);
          like_index++;
         
         
          if (this.adjustForSmoothingComponent())
          {
            smoothingDataIndex++;
          }
         
         
          // //If we are being asked to produce a random draw we add it as a
//           //report event.
//           if (this.isSamplingObject("RandomBufferSolution"))
//           {
//             ObjectReporter rep = this.objectReporter;
//             ObjectReportInstance ev = new ObjectReportInstance();
//             ev.setObject(RhsSol);
//             rep.addToReport(ev);
//           }
         
         
          //stop1 = System.currentTimeMillis();
          //System.out.println("Time it took6a="+(stop1-start1));
          //start1 = stop1;
         
        }
       
     
        //stop = System.currentTimeMillis();
        //System.out.println("Time it took4="+(stop-start));
        //start = stop;
       
       
        CbThatShouldBeZero.add(DblCbThatShouldBeZero);
        //If we are adjusting for calibration then the pH set here will be
        //the latent pH otherwise they are the observed pH.
        pH4CbThatShouldBeZero.add(DblpH4CbThatShouldBeZero);
       
      }
     
    }
   
   
    //DblMatrix.std(pHresids).show("Here is the empirical STD of pH residuals","0.000E0");
    //sigmaCalib.show("The current value of sigmaCalib:","0.000E0");
   
    //DblMatrix.Mean(pHresids).show("Here is the empirical MEAN of pH residuals");
   
   
    //DblMatrix EmpCbStd = DblMatrix.std(CbThatShouldBeZero);
    //EmpCbStd.show("Here is the empirical STD of Cb","0.000E0");
    //sigmaCb.show("The current value of sigmaCb:","0.000E0");
   
   
//   
//    DblMatrix EmpCbStd = DblMatrix.std(CbThatShouldBeZero);
//     if (DblMatrix.test(EmpCbStd.gt(sigmaCb.times(10.0))))
//     {
//       System.out.println("sigmaCb is probably too small.");
//       System.out.println("The empirical std. of Cb was found to be:"+EmpCbStd.getDoubleAt(0));
//       System.out.println("sigmaCb is currently:"+sigmaCb.getDoubleAt(0));
//       System.out.println("##");
//
//     }
//
//     if (DblMatrix.test(sigmaCb.gt(EmpCbStd.times(10.0))))
//     {
//       System.out.println("sigmaCb is probably too large.");
//       System.out.println("The empirical std. of Cb was found to be:"+EmpCbStd.getDoubleAt(0));
//       System.out.println("sigmaCb is currently:"+sigmaCb.getDoubleAt(0));
//       System.out.println("##");
//
//     }
//
    // DblMatrix someCb = new DblMatrix(10);
//     for (int i=0;i<someCb.getN();i++)
//     {
//       someCb.setDoubleAt(CbThatShouldBeZero.getDoubleAt(i),i);
//     }
   
    //someCb.show("CbThatShouldBeZero","0.00E00");
   
   
   
    ///////////////////////////////////////////////////////////////////////////////
    //Report on the residuals!!
   
    if ((this.likelihoodCalls % 1) == 0)
    {
   
      FigureReporter rep = this.getFigureReporter("Residuals");
     
      SLFigure fig = rep.getNewFigure();

      SLAxes ax = new SLAxes(fig);
      ax.setXLabel("pH");
      ax.setYLabel("Cb Residual");
      SLLegend legend = new SLLegend(ax,ax,SLLegend.ALPHA_ORDER);
      legend.setLegendLocale(SLLegend.LEGEND_SOUTH);

      pHtoolsPrefs prefs = new pHtoolsPrefs();
      prefs.initialize();
      DblMatrix Xref = new DblMatrix(2);
      //DblMatrix Yref;
      for (int r=0;r<pH4CbThatShouldBeZero.size();r++)
      {
        DblMatrix pHdata = (DblMatrix)pH4CbThatShouldBeZero.get(r);
        DblMatrix Cbdata = (DblMatrix)CbThatShouldBeZero.get(r);

        Xref.setDblAt(pHdata.min(),0);
        Xref.setDblAt(pHdata.max(),1);
        //Yref.setDblAt(DblMatrix.min(Cbdata),0);
        //Yref.setDblAt(DblMatrix.max(Cbdata),1);

        SLLine line = new SLLine(ax);
        line.setXData(pHdata);
        line.setYData(Cbdata);
        line.setMarkerEdgeColor(r);
        line.setLineColor(r);
        line.setMarkerType(r);
        line.updatePreferences("default",prefs);
       
        SLAnnotation annot = (SLAnnotation)legendStrings.get(r);
       
       
        legend.addLegend(annot.getText(),annot,line);
      }
     
      //System.out.println("updatePreferences for legend of Residuals");
     
      legend.updatePreferences("default",prefs);
      SLLine refline = new SLLine(ax);
      refline.setXData(Xref);
      refline.setYData(new DblMatrix(2));
      refline.setMarkerType(-1);//No Marker
      refline.setLineColor(Color.RED);

      FigureReportInstance ev = new FigureReportInstance();
      ev.setFigure(fig);
      ////


      ax.updatePreferences("default",prefs);
      fig.updatePreferences("default",prefs);
      refline.updatePreferences("default",prefs);
      ////

      rep.addToReport(ev);
      //////////////////////////////////////////////////////////////////////////////////

      ///////////////////////////////////////////////////////////////////////////////
      //Report on the predicted Cb!!
      rep = this.getFigureReporter("Predicted");
      if (rep != null)
      {
        fig = rep.getNewFigure();

        ax = new SLAxes(fig);
        ax.setXLabel("pH");
        ax.setYLabel("Cb");
        legend = new SLLegend(ax,ax,SLLegend.ALPHA_ORDER);
        legend.setLegendLocale(SLLegend.LEGEND_SOUTH);

        prefs = new pHtoolsPrefs();
        prefs.initialize();
        Xref = new DblMatrix(2);
        //DblMatrix Yref;
        for (int r=0;r<pH4CbThatShouldBeZero.size();r++)
        {

          DblMatrix pHdata = (DblMatrix)pH4CbThatShouldBeZero.get(r);
          //DblMatrix Cbdata = (DblMatrix)CbThatShouldBeZero.get(r);
          param = this.mkParameterName(new String[]{"C",buffername});
          DblMatrix thisConc = this.getParam(param);
          BufferSolution sol = new BufferSolution();
          sol.setConnection(this.connection);
          sol.setRepository(this.repository);
          sol.initialize();
          sol.add(this.transientStorage,thisConc);
          DblMatrix Cbdata = (DblMatrix)((HashMap)sol.Cb(pHdata)).get("total");//We take a peak at the Cb that would be given by the current parameterization.
          Cbdata = DblMatrix.abs(Cbdata);
          //We take absolute value here since generally we can't distinguish between +/- acid/base.

          Xref.setDblAt(pHdata.min(),0);
          Xref.setDblAt(pHdata.max(),1);
View Full Code Here

    while (iter.hasNext())
    {
      String paramname = (String)iter.next();
     
      String priorname = this.mkParameterName(new String[]{"prior","mean",paramname});
      DblMatrix MU = this.getPriorParam(priorname);
      priorname = this.mkParameterName(new String[]{"prior","sigma",paramname});
      DblMatrix SIGMA = this.getPriorParam(priorname);
      this.normal.setMean(MU);
      this.normal.setStd(SIGMA);
      DblMatrix priorprob = this.normal.pdf(this.getParam(paramname));
      //priorprob.show(("Prior for "+paramname),"0.000000000E00");
      OUT.setParam(paramname,DblMatrix.log(priorprob).times(-1.0));
   
    }
   
View Full Code Here

    this.bufferPredictor = comp; 
  }
 
  public HashMap species()
  {
    DblMatrix pH = DblMatrix.span(2,12,25);
    HashMap out = this.species(pH,null);
    return(out);
  }
View Full Code Here

 
 
 
  public HashMap species(DblMatrix pHIn,AdjCoef adj)
  {
    DblMatrix pH = DblMatrix.vec(pHIn);//Make pH a column vector.
    //pH.show("pH");
    DblMatrix H = DblMatrix.pow(10,pH.times(-1));
   
    //Set Names = this.bufferMap.keySet();
    String[] Names = bufferPredictor.getComponents();
   
    int num_bufs = Names.length; //Number of buffers in this solution.
    HashMap OUT = new HashMap();
   
    //Iterator iter = Names.iterator();
    String buffname;
    //BufferDOM buffer;
   
   
   
    //BufferDOM buffer;
    ComplexBufferComponent buffer;
    DblMatrix C;
    DblMatrix Species=new DblMatrix(H.getN());
    HashMap Coefs;
    DblMatrix[] KKa;
    DblMatrix[] KKb;
    DblMatrix[] SSaltType;
    DblMatrix Kw;
    BufferPredictor complex;
   
    //Calculate ion product constant of water Kw.
    //buffer = (BufferDOM)this.bufferMap.get("com.mockturtlesolutions.water");
    buffer = this.bufferPredictor.getComponent("com.mockturtlesolutions.water");
    if (buffer == null)
    {
      throw new IllegalArgumentException("Water must be a component of the solution.");
    }
   
    Coefs = this.bufferPredictor.getEstimatedKa("com.mockturtlesolutions.water");
    //C = (DblMatrix)this.concentrationMap.get("com.mockturtlesolutions.water");
   
    C = this.bufferPredictor.getEstimatedConcentration("com.mockturtlesolutions.water");
   
    KKa = (DblMatrix[])Coefs.get("Ka");
    Kw = KKa[0].times(C);
   
   
   
    ///
    String label = "";
    int charge=0;
    HashMap BufferSpecies,IonSpecies;//Holds concentrations for each named buffer component.
    DblMatrix uncharged;
    DblMatrix val;
   
    //while (iter.hasNext()) //For each named buffer in the solution...
    for (int j=0;j<Names.length;j++)
    { 
      BufferSpecies = new HashMap();
      //buffname = (String)iter.next();
     
      buffname = Names[j];
      buffer = this.bufferPredictor.getComponent(buffname);
     
      //buffer = (BufferDOM)this.bufferMap.get(buffname);
      //C = (DblMatrix)this.concentrationMap.get(buffname);
      C = this.bufferPredictor.getEstimatedConcentration(buffname);
      complex = buffer.getSmooth();
     
      if (complex != null) //This is a COMPLEX buffer.
      {
        System.out.println("This is a complex buffer!:");
      }
      else
      {
        Coefs = this.bufferPredictor.getEstimatedKa(buffname);
 
              KKa = (DblMatrix[])Coefs.get("Ka");
              KKb = (DblMatrix[])Coefs.get("Kb");
        SSaltType = (DblMatrix[])Coefs.get("SaltType");
       
        if (buffname.endsWith(".water"))
        {
          //C = (DblMatrix)this.concentrationMap.get(buffname);
          C = this.bufferPredictor.getEstimatedConcentration(buffname);
          uncharged = C.copy();
          DblMatrix OH = Kw.divideBy(H);
          BufferSpecies.put("m1",OH);
          uncharged = uncharged.minus(OH);
          BufferSpecies.put("p1",H);
          uncharged = uncharged.minus(H);
          BufferSpecies.put("m0",uncharged)
        }
        else
        {
       

          int num_pka,num_pkb,N,n;
          DblMatrix Ka;
         
          DblMatrix Numerator;
          DblMatrix Denominator;
         
          for (int k=0;k<KKa.length;k++) //For each ion...
         
         
            IonSpecies = new HashMap();
            //C = (DblMatrix)this.concentrationMap.get(buffname);
            C = this.bufferPredictor.getEstimatedConcentration(buffname);
           
            Numerator = new DblMatrix(H.getN());
                  Denominator = new DblMatrix(H.getN());
           
            num_pka = KKa[k].getN();
            num_pkb = KKb[k].getN();
           
            if ((num_pka == 0) && (num_pkb ==0))
            {
              //label = "lytes";
              int saltcharge=0;
              if (SSaltType[k].getN() == 1)
              {
                //System.out.println("Electrolyte"+k);
                //SSaltType[k].show("SaltType[k]");
                //Electrolytes don't contribute to buffering!
                //Setting to zero.
                saltcharge = SSaltType[k].getDoubleAt(0).intValue();
               
              }
              else
              {
                if (SSaltType[k].getN() > 1)
                {
                  throw new RuntimeException("SaltType of an electrolyte can not consist of more than one integer value.")
                }
                else
                {
                  System.out.println("Inert thing"+k);
                  //Would be something completely inert like glucose.
                  saltcharge = 0;
                }
              }
             
             
             
              if (saltcharge <= 0)
              {
                saltcharge = -(saltcharge);
               
                label = new String("m"+saltcharge);
              }
              else
              {
                label = new String("p"+saltcharge);
              }
             
              int[] reps = new int[2];
              reps[0] = H.getN();
              reps[1] = 1;
             
              val = DblMatrix.replicate(C,reps);
             
              IonSpecies.put(label,val);
              uncharged = new DblMatrix(new Double(0.0));//All electrolytes are charged.
             
            }
            else
            {
              uncharged = C.copy()//Start with total concentration
                    //of ion in it's uncharged form
                    //and we'll decrease as we figure
                    //the charged concentrations...
             
              N = num_pka + num_pkb;
              n = num_pka;
              Ka = KKa[k];
              //Ka.show("Ka");
              if (num_pkb > 0)
              {
                DblMatrix transKb = Kw.divideBy(KKb[k]);
                Ka = Ka.concat(transKb,2);
              }
              DblSort Sort = new DblSort(Ka,2);
              Sort.sort();
              Ka = Sort.getSorted();


              //Calculate numerator
              DblMatrix cumProdKa = Ka.cumProd(1);
              cumProdKa = cumProdKa.fliplr();
              DblMatrix temp;

              //Ka.show("Final Ka");
              for (int i=1;i<=N;i++)
              {
                temp = H.pow(i-1).times(cumProdKa.getDoubleAt(i-1));
                Denominator = Denominator.plus(temp);
                charge = -(n+1-i);
                if (charge <=0)
                { 
                  charge = -charge;
                  label = new String("m"+charge);
                }
                else
                {
                  label = new String("p"+charge);
                }
                IonSpecies.put(label,temp);
               
               
              }
              //Denominator gets one more term than numerator...
              Denominator = Denominator.plus(H.pow(N));
             
              DblMatrix avoidErr = new DblMatrix(uncharged.Size);
             
              for (int i=1;i<=N;i++)
              {
                charge = -(n+1-i);
                //System.out.println("charge:"+charge);
                if (charge <=0)
                {
                  charge = -charge;
                  label = new String("m"+charge);
                }
                else
                {
                  label = new String("p"+charge);
                }
               
               
                Numerator = (DblMatrix)IonSpecies.get(label);
                Species = Numerator.divideBy(Denominator);
                Species = C.times(Species);
               
                if (charge != 0)
                {
                  avoidErr = avoidErr.plus(Species);
                  //uncharged = uncharged.minus(Species);
                }
                IonSpecies.put(label,Species);
             
             
              //There are numerical issues with subtracting numbers that are very close.
              //We set any values that would lead to erroneous results to NaN.
              //Note that floating point errors _will_ occur prior to Double.MIN_VALUE
              //differences.
             
              DblMatrix Map = uncharged.leq(avoidErr);
              avoidErr = uncharged.minus(avoidErr);
             
              avoidErr.setMap(0.0,Map);
              //avoidErr.show("Concentrations");
              IonSpecies.put("m0",avoidErr);
View Full Code Here

    Vector pKaSet = new Vector();
    int ionStart=0;
    int ionStop=0;
    String ion;
    boolean readingIon=false;
    DblMatrix val;
    int k=0;
    while (k<pKa.length())
    {
      if (pKa.charAt(k)=='[')
      {
        if (readingIon)
        {
          throw new RuntimeException("Encountered extra '[' in buffer coefficients.")
        }
        readingIon = true;
        ionStart = k;
       
      }
      else
      {
        if (pKa.charAt(k)==']')
        {
          if (!readingIon)
          {
            throw new RuntimeException("Encountered extra ']' in buffer coefficients.")
          }
          ionStop = k+1;
          ion = pKa.substring(ionStart,ionStop);
          pKaSet.add(new DblMatrix(ion));
         
          readingIon = false;
        }
      }
      k++;
View Full Code Here

TOP

Related Classes of com.mockturtlesolutions.snifflib.datatypes.DblMatrix

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.