Real SingleCurve3<Real>::GetTime (Real fLength, int iIterations,
    Real fTolerance) const
{
    if (fLength <= (Real)0.0)
    {
        return m_fTMin;
    }

    if (fLength >= GetTotalLength())
    {
        return m_fTMax;
    }

    // initial guess for Newton's method
    Real fRatio = fLength/GetTotalLength();
    Real fOmRatio = (Real)1.0 - fRatio;
    Real fTime = fOmRatio*m_fTMin + fRatio*m_fTMax;

    for (int i = 0; i < iIterations; i++)
    {
        Real fDifference = GetLength(m_fTMin,fTime) - fLength;
        if (Math<Real>::FAbs(fDifference) < fTolerance)
        {
            return fTime;
        }

        fTime -= fDifference/GetSpeed(fTime);
    }

    // Newton's method failed.  If this happens, increase iterations or
    // tolerance or integration accuracy.
    return Math<Real>::MAX_REAL;
}
void CStunUnknownAttributes::GetBuffer (char *pBuffer)
{
	unsigned short nAttributeType = htons (m_nAttributeType);
	unsigned short nAttributeLength = htons (GetAttributeLength ());

	int nOffset = 0, nSize = GetTotalLength ();

	memcpy_s (pBuffer, nSize, &nAttributeType, sizeof (nAttributeType));
	nOffset += sizeof (nAttributeType);

	memcpy_s (pBuffer + nOffset, nSize - nOffset, &nAttributeLength, sizeof (nAttributeLength));
	nOffset += sizeof (nAttributeLength);

	for (int i = 0; i < m_nAttributesCount; ++i)
	{
		nAttributeType = htons (m_UnknownAttributes [i]);

		memcpy_s (pBuffer + nOffset, nSize - nOffset, &nAttributeType, sizeof (nAttributeType));
		nOffset += sizeof (nAttributeType);		
	}

	if ((m_nAttributesCount % 2) == 1)
	{
		memcpy_s (pBuffer + nOffset, nSize - nOffset, &nAttributeType, sizeof (nAttributeType));
	}
}
void CStunAddressAttribute::GetBuffer(char *Buffer)
{
	unsigned short nAttributeType = htons (m_nAttributeType);
	unsigned short nAttributeLength = htons (GetAttributeLength ());
	unsigned char cTemp = htons (0);
	unsigned char byAddressFamily = m_byAddressFamily;
	unsigned short nPort = htons (m_nPort);
	unsigned int nIPAddress = m_nIPAddress;

	int nOffset = 0, nSize = GetTotalLength ();

	memcpy_s (Buffer, nSize, &nAttributeType, sizeof (nAttributeType));
	nOffset += sizeof (nAttributeType);

	memcpy_s (Buffer + nOffset, nSize - nOffset, &nAttributeLength, sizeof (nAttributeLength));
	nOffset += sizeof (nAttributeLength);

	memcpy_s (Buffer + nOffset, nSize - nOffset, &cTemp, sizeof (cTemp));
	nOffset += sizeof (cTemp);

	memcpy_s (Buffer + nOffset, nSize - nOffset, &byAddressFamily, sizeof (byAddressFamily));
	nOffset += sizeof (byAddressFamily);

	memcpy_s (Buffer + nOffset, nSize - nOffset, &nPort, sizeof (nPort));
	nOffset += sizeof (nPort);

	memcpy_s (Buffer + nOffset, nSize - nOffset, &nIPAddress, sizeof (nIPAddress));
}
Example #4
0
void String::ConvertToUnicode()
{
    if ( unicode ) return;

    unicode = true;
    Buffer new_buffer( GetTotalLengthInBytes() );
    CharToWChar( buffer.ptr.As< char >(), new_buffer.ptr.As< wchar_t >(), GetTotalLength() ); 
    buffer = new_buffer;
}
Example #5
0
void String::ConvertToAscii()
{
    if ( !unicode ) return;

    unicode = false;
    Buffer new_buffer( GetTotalLengthInBytes() );
    WCharToChar( buffer.ptr.As< wchar_t >(), new_buffer.ptr.As< char >(), GetTotalLength() ); 
    buffer = new_buffer;
}
Example #6
0
void MetropolisHastings::Initialize()
{
    Algorithm::Initialize();

    if (fBetas.empty())
        fBetas = { 1.0 };

//    const size_t nChainConfigs = fChains.size();
    const size_t nBetas = fBetas.size();

    // global start point in parameter space
    Sample startPoint( fParameterConfig.GetStartValues(false) );
    Evaluate( startPoint );
    startPoint.SetAccepted( true );

    // if not set by the user, instantiate default proposal function
    if (!fProposalFunction) {
        LOG(Info, "Using default proposal function 'ProposalGaussian'.");
        fProposalFunction = make_shared<ProposalNormal>();
    }

    // initialize chain configurations
    for (auto& chainConfig : fChainConfigs) {

        chainConfig.reset(
            new ChainConfig(nBetas, fParameterConfig, fProposalFunction.get()) );

        // for each PT (beta) chain, setup an individual parameter configuration
        const double initialErrorScaling = fParameterConfig.GetErrorScaling();
        for (size_t iBeta = 0; iBeta < nBetas; iBeta++) {

            // scale parameter configurations
            if (iBeta > 0)
                chainConfig->fDynamicParamConfigs[iBeta].SetErrorScaling(
                    initialErrorScaling / sqrt(fBetas[iBeta]) );

            // update proposal functions with parameter configuration
            chainConfig->fProposalFunctions[iBeta]->UpdateParameterConfig(
                chainConfig->fDynamicParamConfigs[iBeta] );
        }

        // setup start points
        for (auto& chain : chainConfig->fPtChains) {
            // if required, randomize the starting vector for each chain
            if (fRandomizeStartPoint) {
                startPoint.Values() = GetParameterConfig().GetStartValues(true);
                Evaluate( startPoint );
            }

            chain.reserve( GetTotalLength()+1 );

            chain.push_back( startPoint );
        }
    }
}
char *CStunMessage::GetBuffer()
{
	char *Buffer = new char [GetTotalLength ()];
	char *ptrBuffer = Buffer;

	m_StunHeader.SetMessageLength (GetTotalLength () - m_StunHeader.GetHeaderLength ());
	m_StunHeader.GetBuffer (ptrBuffer);
	ptrBuffer += m_StunHeader.GetHeaderLength ();

	for (int i = 0; i < MAX_ATTRIBUTES; ++i)
	{
		if (m_pArrAttributes [i])
		{
			m_pArrAttributes[i]->GetBuffer (ptrBuffer);
			ptrBuffer += m_pArrAttributes[i]->GetTotalLength ();
		}
	}

	string s = m_StunHeader.ToString ();
	return Buffer;
}
Example #8
0
void Curve<Real>::SubdivideByLength (int numPoints, Array1D_Vector3& points)
{
    assertion(numPoints >= 2, "Subdivision requires at least two points\n");
    points = new1<Vector3>(numPoints);

    Real delta = GetTotalLength() / (numPoints - 1);

    for (int i = 0; i < numPoints; ++i)
    {
        Real length = delta * i;
        Real t = GetTime(length, TIME_ITERATIONS, CURVE_TOLERANCE);
        points[i] = GetPosition(t);
    }
}
Example #9
0
    void Curve3<Real>::SubdivideByLength ( int numPoints,
                                           Vector3<Real>*& points ) const
    {
        assertion( numPoints >= 2, "Subdivision requires at least two points\n" );
        points = new1<Vector3<Real> >( numPoints );

        Real delta = GetTotalLength() / ( numPoints - 1 );

        for ( int i = 0; i < numPoints; ++i )
        {
            Real length = delta * i;
            Real t = GetTime( length );
            points[i] = GetPosition( t );
        }
    }
Example #10
0
Real SingleCurve3<Real>::GetTime (Real fLength, int iIterations,
    Real fTolerance) const
{
    if (fLength <= (Real)0.0)
    {
        return m_fTMin;
    }

    if (fLength >= GetTotalLength())
    {
        return m_fTMax;
    }

    // initial guess for Newton's method
    Real fRatio = fLength/GetTotalLength();
    Real fOmRatio = (Real)1.0 - fRatio;
    Real fTime = fOmRatio*m_fTMin + fRatio*m_fTMax;

    for (int i = 0; i < iIterations; i++)
    {
        Real fDifference = GetLength(m_fTMin,fTime) - fLength;
        if (Math<Real>::FAbs(fDifference) < fTolerance)
        {
            return fTime;
        }

        fTime -= fDifference/GetSpeed(fTime);
    }

    // Newton's method failed.  You might want to increase iterations or
    // tolerance or integration accuracy.  However, in this application it
    // is likely that the time values are oscillating, due to the limited
    // numerical precision of 32-bit floats.  It is safe to use the last
    // computed time.
    return fTime;
}
Example #11
0
void Curve<Real>::SubdivideByLengthTime (int numPoints, std::vector<Real> & times)
{
    assert(numPoints >= 2);
    times.resize(numPoints);

	double len = GetTotalLength();

	// degenerate curve check
	if( !IsFiniteNumber(len) ){
		for (int i = 0; i < numPoints; ++i)
			times[i] = double(i) / (numPoints - 1);
		return;
	}

    Real delta = len / (numPoints - 1);

    for (int i = 0; i < numPoints; ++i)
    {
        Real length = delta * i;
        times[i] = GetTime(length, TIME_ITERATIONS, CURVE_TOLERANCE);
    }
}
Example #12
0
Real SingleCurve2<Real>::GetTime (Real length, int iterations,
    Real tolerance) const
{
    if (length <= (Real)0)
    {
        return mTMin;
    }

    if (length >= GetTotalLength())
    {
        return mTMax;
    }

    // If L(t) is the length function for t in [tmin,tmax], the derivative is
    // L'(t) = |x'(t)| >= 0 (the magnitude of speed).  Therefore, L(t) is a
    // nondecreasing function (and it is assumed that x'(t) is zero only at
    // isolated points; that is, no degenerate curves allowed).  The second
    // derivative is L"(t).  If L"(t) >= 0 for all t, L(t) is a convex
    // function and Newton's method for root finding is guaranteed to
    // converge.  However, L"(t) can be negative, which can lead to Newton
    // iterates outside the domain [tmin,tmax].  The algorithm here avoids
    // this problem by using a hybrid of Newton's method and bisection.

    // Initial guess for Newton's method.
    Real ratio = length/GetTotalLength();
    Real oneMinusRatio = (Real)1 - ratio;
    Real t = oneMinusRatio*mTMin + ratio*mTMax;

    // Initial root-bounding interval for bisection.
    Real lower = mTMin, upper = mTMax;

    for (int i = 0; i < iterations; ++i)
    {
        Real difference = GetLength(mTMin, t) - length;
        if (Math<Real>::FAbs(difference) < tolerance)
        {
            // |L(t)-length| is close enough to zero, report t as the time
            // at which 'length' is attained.
            return t;
        }

        // Generate a candidate for Newton's method.
        Real tCandidate = t - difference/GetSpeed(t);

        // Update the root-bounding interval and test for containment of the
        // candidate.
        if (difference > (Real)0)
        {
            upper = t;
            if (tCandidate <= lower)
            {
                // Candidate is outside the root-bounding interval.  Use
                // bisection instead.
                t = ((Real)0.5)*(upper + lower);
            }
            else
            {
                // There is no need to compare to 'upper' because the tangent
                // line has positive slope, guaranteeing that the t-axis
                // intercept is smaller than 'upper'.
                t = tCandidate;
            }
        }
        else
        {
            lower = t;
            if (tCandidate >= upper)
            {
                // Candidate is outside the root-bounding interval.  Use
                // bisection instead.
                t = ((Real)0.5)*(upper + lower);
            }
            else
            {
                // There is no need to compare to 'lower' because the tangent
                // line has positive slope, guaranteeing that the t-axis
                // intercept is larger than 'lower'.
                t = tCandidate;
            }
        }
    }

    // A root was not found according to the specified number of iterations
    // and tolerance.  You might want to increase iterations or tolerance or
    // integration accuracy.  However, in this application it is likely that
    // the time values are oscillating, due to the limited numerical
    // precision of 32-bit floats.  It is safe to use the last computed time.
    return t;
}
HRESULT ui::UIScrollBar::Initialize(graphics::D3DInteropHelper *pD3DInteropHelper) {
#ifdef DEBUG_UISCROLLBAR
  LOG_ENTER(SEVERITY_LEVEL_DEBUG);
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetTotalWidth() = " << GetTotalThick();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetTotalLength() = " << GetTotalLength();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSlideAreaWidth() = " << GetSlideAreaThick();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSlideAreaLength() = " << GetSlideAreaLength();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSlideAreaMargin() = " << GetSlideAreaMargin();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetBarPosition() = " << GetBarPosition();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetBarLength() = " << GetBarLength();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetBarWidth() = " << GetBarThick();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetBarOffset() = " << GetBarOffset();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetArrowLength() = " << GetArrowLength();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetArrowWidth() = " << GetArrowThick();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetArrowMargin() = " << GetArrowMargin();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetArrow1Offset() = " << GetArrow1Offset();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetArrow2Offset() = " << GetArrow2Offset();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSplitterMargin() = " << GetSplitterMargin();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSplitterWidth() = " << GetSplitterThick();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSplitterHeight() = " << GetSplitterHeight();
  LOG(SEVERITY_LEVEL_DEBUG) << L"GetSplitterOffset() = " << GetSplitterOffset();
#endif
  m_body->SetX(0.0f);
  m_body->SetY(0.0f);
  m_body->SetWidth(GetWidth());
  m_body->SetHeight(GetHeight());
  m_body->SetRadius(m_direction == SCROLLBAR_DIRECTION_HORIZONTAL ? GetHeight() / 2.0f : GetWidth() / 2.0f);
  m_body->SetColor(graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 0.0f, 0.0f, 0.2f, 1.0f),
                   graphics::color::COLOR_PATTERN_CONVEX);
  m_body->SetShadow(true);
  m_body->SetShadowColor(std::make_shared<graphics::color::SolidColor>(
      graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 190.0f, 1.0f, 1.0f, 1.0f)));
  m_body->Initialize(pD3DInteropHelper);

  if (m_direction == SCROLLBAR_DIRECTION_HORIZONTAL) {
    m_arrow1->SetX(GetArrow1Offset());
    m_arrow1->SetY(GetArrowMargin());
    m_arrow1->SetWidth(GetArrowLength());
    m_arrow1->SetHeight(GetArrowThick());
    m_arrow1->SetDirection(graphics::figure::TriangleFigure::TRIANGLE_DIRECTION_LEFT);
  } else {
    m_arrow1->SetX(GetArrowMargin());
    m_arrow1->SetY(GetArrow1Offset());
    m_arrow1->SetWidth(GetArrowThick());
    m_arrow1->SetHeight(GetArrowLength());
    m_arrow1->SetDirection(graphics::figure::TriangleFigure::TRIANGLE_DIRECTION_TOP);
  }
  m_arrow1->SetColor(graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 32.0f, 0.0f, 0.5f, 1.0f),
                     graphics::color::COLOR_PATTERN_CONVEX);
  m_arrow1->Initialize(pD3DInteropHelper);

  if (m_direction == SCROLLBAR_DIRECTION_HORIZONTAL) {
    m_arrow2->SetX(GetArrow2Offset());
    m_arrow2->SetY(GetArrowMargin());
    m_arrow2->SetWidth(GetArrowLength());
    m_arrow2->SetHeight(GetArrowThick());
    m_arrow2->SetDirection(graphics::figure::TriangleFigure::TRIANGLE_DIRECTION_RIGHT);
  } else {
    m_arrow2->SetX(GetArrowMargin());
    m_arrow2->SetY(GetArrow2Offset());
    m_arrow2->SetWidth(GetArrowThick());
    m_arrow2->SetHeight(GetArrowLength());
    m_arrow2->SetDirection(graphics::figure::TriangleFigure::TRIANGLE_DIRECTION_BOTTOM);
  }
  m_arrow2->SetColor(graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 32.0f, 0.0f, 0.5f, 1.0f),
                     graphics::color::COLOR_PATTERN_CONVEX);
  m_arrow2->Initialize(pD3DInteropHelper);

  if (m_direction == SCROLLBAR_DIRECTION_HORIZONTAL) {
    m_slideArea->SetX(GetSlideAreaOffset());
    m_slideArea->SetY(GetSlideAreaMargin());
    m_slideArea->SetWidth(GetSlideAreaLength());
    m_slideArea->SetHeight(GetSlideAreaThick());
  } else {
    m_slideArea->SetX(GetSlideAreaMargin());
    m_slideArea->SetY(GetSlideAreaOffset());
    m_slideArea->SetWidth(GetSlideAreaThick());
    m_slideArea->SetHeight(GetSlideAreaLength());
  }
  m_slideArea->SetColor(
      graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 190.0f, 1.0f, 0.3f, 1.0f),
      graphics::color::COLOR_PATTERN_CONVEX);
  m_slideArea->Initialize(pD3DInteropHelper);

  if (m_direction == SCROLLBAR_DIRECTION_HORIZONTAL) {
    m_bar->SetX(GetBarOffset());
    m_bar->SetY(GetSlideAreaMargin());
    m_bar->SetWidth(GetBarLength());
    m_bar->SetHeight(GetBarThick());
  } else {
    m_bar->SetX(GetSlideAreaMargin());
    m_bar->SetY(GetBarOffset());
    m_bar->SetWidth(GetBarThick());
    m_bar->SetHeight(GetBarLength());
  }
  m_bar->SetColor(graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 190.0f, 1.0f, 0.7f, 1.0f),
                  graphics::color::COLOR_PATTERN_CONVEX_METAL);
  m_bar->SetShadow(true);
  m_bar->SetShadowColor(std::make_shared<graphics::color::SolidColor>(
      graphics::color::ColorValue(graphics::color::ColorValue::COLOR_TYPE_HSBA, 190.0f, 1.0f, 1.0f, 1.0f)));
  m_bar->Initialize(pD3DInteropHelper);

#ifdef DEBUG_UISCROLLBAR
  LOG_LEAVE(SEVERITY_LEVEL_DEBUG);
#endif
  return S_OK;
}
void CodonMutSelSBDPPhyloProcess::Read(string name, int burnin, int every, int until)	{

	ifstream is((name + ".chain").c_str());
	if (! is)	{
		cerr << "error: did not find " << name << ".chain\n";
		exit(1);
	}
	//cerr << "In CodonMutSelDPPhyloProcess. GetDim() is : " << GetDim() << "\n";
	int Nstate = CodonMutSelSBDPSubstitutionProcess::GetNstate();
	//cerr << "Nstate is: " << Nstate << "\n";
	//cerr.flush();
	double TOOSMALL = 1e-20;
	int Ncat = 241;
	double min = -30;
	double max = 30;
	double step = 0.25;

	double meanlength = 0;
	double varlength = 0;
	double** PosteriorMeanSiteCodonP = new double*[ProfileProcess::GetNsite()];
	double** sshistoMut = new double*[ProfileProcess::GetNsite()];
	double** sshistoSub = new double*[ProfileProcess::GetNsite()];
	double** sshistoNonsynMut = new double*[ProfileProcess::GetNsite()];
	double** sshistoNonsynSub = new double*[ProfileProcess::GetNsite()];
	double** sshistoSynMut = new double*[ProfileProcess::GetNsite()];
	double** sshistoSynSub = new double*[ProfileProcess::GetNsite()];
	for (int site = 0; site < ProfileProcess::GetNsite(); site++)        {
		PosteriorMeanSiteCodonP[site] = new double[GetDim()];
		sshistoMut[site] = new double[Ncat];
		sshistoSub[site] = new double[Ncat];
		sshistoNonsynMut[site] = new double[Ncat];
		sshistoNonsynSub[site] = new double[Ncat];
		sshistoSynMut[site] = new double[Ncat];
		sshistoSynSub[site] = new double[Ncat];
		for (int a = 0; a < GetDim(); a++)   {
			PosteriorMeanSiteCodonP[site][a] = 0;
		}
		for (int a = 0; a < Ncat; a++)	{
			sshistoMut[site][a] = 0;
			sshistoSub[site][a] = 0;
			sshistoNonsynMut[site][a] = 0;
			sshistoNonsynSub[site][a] = 0;
			sshistoSynMut[site][a] = 0;
			sshistoSynSub[site][a] = 0;
		}
	}
	double* meanNucStat = new double[Nnuc];
	for (int i=0; i<Nnuc; i++)	{
		meanNucStat[i]=0.0;
	}
	double* meanNucRR = new double[Nnucrr];
	for (int i=0; i<Nnucrr; i++)	{
		meanNucRR[i] = 0.0;
	}
	
	double* ghistoMut = new double[Ncat];
	double* ghistoSub = new double[Ncat];
	double* ghistoNonsynMut = new double[Ncat];
	double* ghistoNonsynSub = new double[Ncat];
	double* ghistoSynMut = new double[Ncat];
	double* ghistoSynSub = new double[Ncat];

	double* shistoMut = new double[Ncat];
	double* shistoSub = new double[Ncat];
	double* shistoNonsynMut = new double[Ncat];
	double* shistoNonsynSub = new double[Ncat];
	double* shistoSynMut = new double[Ncat];
	double* shistoSynSub = new double[Ncat];

	double* tsshistoMut = new double[Ncat];
	double* tsshistoSub = new double[Ncat];
	double* tsshistoNonsynMut = new double[Ncat];
	double* tsshistoNonsynSub = new double[Ncat];
	double* tsshistoSynMut = new double[Ncat];
	double* tsshistoSynSub = new double[Ncat];
	for (int c = 0; c < Ncat; c++)	{
		ghistoMut[c] = 0;
		ghistoSub[c] = 0;
		ghistoNonsynMut[c] = 0;
		ghistoNonsynSub[c] = 0;
		ghistoSynMut[c] = 0;
		ghistoSynSub[c] = 0;
	}
	//const double* stat;
	double* stat = new double[Nstate];
	int pos, nucFrom, nucTo, nucRRIndex, c;
	double statMutRate, S, statSubRate, totalMut, totalSub, totalNonsynMut, totalNonsynSub, totalSynMut, totalSynSub, siteTotalMut, siteTotalSub, siteTotalNonsynMut, siteTotalNonsynSub, siteTotalSynMut, siteTotalSynSub, Z;
	cerr << "Ncat is " << Ncat << "\n";
	cerr << "burnin : " << burnin << "\n";
	cerr << "until : " << until << '\n';
	int i=0;
	while ((i < until) && (i < burnin))	{
		cerr << ".";
		cerr.flush();
		FromStream(is);
		i++;
	}
	int samplesize = 0;
	while (i < until)	{
		// cerr << ".";
		cerr.flush();
		samplesize++;
		FromStream(is);
		i++;
		QuickUpdate();
		//UpdateMatrices();
		//Trace(cerr);
		double length = GetTotalLength();
		// int nocc = process->GetNOccupiedComponent();
		meanlength += length;
		varlength += length * length;
		for (int a=0; a<Nnuc; a++)	{
			meanNucStat[a] += GetNucStat(a);
		}
		for (int a=0; a<Nnucrr; a++)	{
			meanNucRR[a] += GetNucRR(a);
		}
		totalMut = 0;
		totalSub = 0;
		totalNonsynMut = 0;
		totalNonsynSub = 0;
		totalSynMut = 0;
		totalSynSub = 0;
		for (c = 0; c < Ncat; c++)	{
			shistoMut[c] = 0;
			shistoSub[c] = 0;
			shistoNonsynMut[c] = 0;
			shistoNonsynSub[c] = 0;
			shistoSynMut[c] = 0;
			shistoSynSub[c] = 0;
		}
		for (int site=0; site<ProfileProcess::GetNsite(); site++)	{
			siteTotalMut = 0;
			siteTotalSub = 0;
			siteTotalNonsynMut = 0;
			siteTotalNonsynSub = 0;
			siteTotalSynMut = 0;
			siteTotalSynSub = 0;
			
			for (c = 0; c < Ncat; c++)	{
				tsshistoMut[c] = 0;
				tsshistoSub[c] = 0;
				tsshistoNonsynMut[c] = 0;
				tsshistoNonsynSub[c] = 0;
				tsshistoSynMut[c] = 0;
				tsshistoSynSub[c] = 0;
			}
			for (int a=0; a<GetDim(); a++)	{
				PosteriorMeanSiteCodonP[site][a] += profile[alloc[site]][a]; 
			}
			Z = 0;
			for (int s=0; s<Nstate; s++)	{
				stat[s] = 	GetNucStat(GetCodonStateSpace()->GetCodonPosition(0, s)) *
						GetNucStat(GetCodonStateSpace()->GetCodonPosition(1, s)) *
						GetNucStat(GetCodonStateSpace()->GetCodonPosition(2, s)) *
						profile[alloc[site]][s];
				Z += stat[s];
			}
			for (int s=0; s<Nstate; s++)	{
				stat[s] /= Z;
			}
			//stat = GetStationary(site);
			//stat = matrixarray[alloc[site]]->GetStationary();
			for (int codonFrom = 0; codonFrom<Nstate; codonFrom++)	{
				for (int codonTo = 0; codonTo<Nstate; codonTo++)	{
					pos = GetCodonStateSpace()->GetDifferingPosition(codonFrom, codonTo);				
					if ((pos != -1) && (pos != 3))  {
						nucFrom = GetCodonStateSpace()->GetCodonPosition(pos, codonFrom);
						nucTo = GetCodonStateSpace()->GetCodonPosition(pos, codonTo);
						if (nucFrom<nucTo)	{
							nucRRIndex = (2 * Nnuc - nucFrom - 1) * nucFrom / 2 + nucTo - nucFrom - 1;
						}
						else {
							nucRRIndex = (2 * Nnuc - nucTo - 1) * nucTo / 2 + nucFrom - nucTo - 1;
						}
						statMutRate = GetNucRR(nucRRIndex) * GetNucStat(nucTo) * stat[codonFrom];
						S = log(profile[alloc[site]][codonTo]/profile[alloc[site]][codonFrom]);

						if (fabs(S) < TOOSMALL)	{
							statSubRate = statMutRate * 1.0/( 1.0 - (S / 2) );
						}
						else {
							statSubRate = statMutRate * (S/(1-(profile[alloc[site]][codonFrom]/profile[alloc[site]][codonTo])));
						}
						if (S < min)	{
							c = 0;
						}
						else if (S > max)	{
							c = Ncat-1;
						}
						else {
							c = 0;
							double tmp = min + ((double)c * step) - step/2 + step;
							do	{
								c++;
								tmp = min + ((double)(c) * step) - step/2 + step;
							} while (tmp < S );
						}
						if (c == Ncat)	{
							cout << "error, c==Ncat.\n";
							cout.flush();
						}
	
						shistoMut[c] += statMutRate;
						shistoSub[c] += statSubRate;
						tsshistoMut[c] += statMutRate;
						tsshistoSub[c] += statSubRate;
						if (!GetCodonStateSpace()->Synonymous(codonFrom, codonTo))	{
							shistoNonsynMut[c] += statMutRate;
							shistoNonsynSub[c] += statSubRate;
							totalNonsynMut += statMutRate;
							totalNonsynSub += statSubRate;

							tsshistoNonsynMut[c] += statMutRate;
							tsshistoNonsynSub[c] += statSubRate;
							siteTotalNonsynMut += statMutRate;
							siteTotalNonsynSub += statSubRate;
						}
						else	{
							shistoSynMut[c] += statMutRate;
							shistoSynSub[c] += statSubRate;
							totalSynMut += statMutRate;
							totalSynSub += statSubRate;

							tsshistoSynMut[c] += statMutRate;
							tsshistoSynSub[c] += statSubRate;
							siteTotalSynMut += statMutRate;
							siteTotalSynSub += statSubRate;
							
						}
						totalMut += statMutRate;
						totalSub += statSubRate;
						siteTotalMut += statMutRate;
						siteTotalSub += statSubRate;
					}
				}
			}

			for (c=0; c<Ncat; c++)	{
				sshistoMut[site][c] += tsshistoMut[c]/siteTotalMut;
				sshistoSub[site][c] += tsshistoSub[c]/siteTotalSub;
				sshistoNonsynMut[site][c] += tsshistoNonsynMut[c]/siteTotalNonsynMut;
				sshistoNonsynSub[site][c] += tsshistoNonsynSub[c]/siteTotalNonsynSub;
				sshistoSynMut[site][c] += tsshistoSynMut[c]/siteTotalSynMut;
				sshistoSynSub[site][c] += tsshistoSynSub[c]/siteTotalSynSub;
			}
		}	

		for (c=0; c<Ncat; c++)	{
			ghistoMut[c] += shistoMut[c]/totalMut;
			ghistoSub[c] += shistoSub[c]/totalSub;
			ghistoNonsynMut[c] += shistoNonsynMut[c]/totalNonsynMut;
			ghistoNonsynSub[c] += shistoNonsynSub[c]/totalNonsynSub;
			ghistoSynMut[c] += shistoSynMut[c]/totalSynMut;
			ghistoSynSub[c] += shistoSynSub[c]/totalSynSub;
		}

		int nrep = 1;
		while ((i<until) && (nrep < every))	{
			FromStream(is);
			i++;
			nrep++;
		}
	}
	cerr << '\n';
	meanlength /= samplesize;
	varlength /= samplesize;
	varlength -= meanlength * meanlength;

	cerr << "mean length : " << meanlength << " +/- " << sqrt(varlength) << '\n';

	double* ppvhistoMut = new double[Ncat];
	double* ppvhistoSub = new double[Ncat];
	double* ppvhistoNonsynMut = new double[Ncat];
	double* ppvhistoNonsynSub = new double[Ncat];
	for (c=0; c<Ncat; c++)	{
		ppvhistoMut[c] = 0;
		ppvhistoSub[c] = 0;
		ppvhistoNonsynMut[c] = 0;
		ppvhistoNonsynSub[c] = 0;
	}
	
	totalMut = 0;
	totalSub = 0;
	totalNonsynMut = 0;
	totalNonsynSub = 0;

	ofstream codonp_os( (name + ".codonp").c_str(), std::ios::out);
	for (int site=0; site<ProfileProcess::GetNsite(); site++)	{
		for (int a=0; a<GetDim(); a++)	{
			codonp_os << PosteriorMeanSiteCodonP[site][a] / samplesize << "\t";
		}
		codonp_os << "\n";

		Z = 0;
		for (int s=0; s<Nstate; s++)	{
			stat[s] = 	(meanNucStat[GetCodonStateSpace()->GetCodonPosition(0, s)] *
					meanNucStat[GetCodonStateSpace()->GetCodonPosition(1, s)] *
					meanNucStat[GetCodonStateSpace()->GetCodonPosition(2, s)] *
					PosteriorMeanSiteCodonP[site][s]) / samplesize;
			Z += stat[s];
		}
		for (int s=0; s<Nstate; s++)	{
			stat[s] /= Z;
		}
		for (int codonFrom = 0; codonFrom<Nstate; codonFrom++)	{
			for (int codonTo = 0; codonTo<Nstate; codonTo++)	{
				pos = GetCodonStateSpace()->GetDifferingPosition(codonFrom, codonTo);				
				if ((pos != -1) && (pos != 3))  {
					nucFrom = GetCodonStateSpace()->GetCodonPosition(pos, codonFrom);
					nucTo = GetCodonStateSpace()->GetCodonPosition(pos, codonTo);
					if (nucFrom<nucTo)	{
						nucRRIndex = (2 * Nnuc - nucFrom - 1) * nucFrom / 2 + nucTo - nucFrom - 1;
					}
					else {
						nucRRIndex = (2 * Nnuc - nucTo - 1) * nucTo / 2 + nucFrom - nucTo - 1;
					}
					statMutRate = meanNucRR[nucRRIndex] * meanNucStat[nucTo] * stat[codonFrom];
					double expS = (PosteriorMeanSiteCodonP[site][codonTo]/samplesize)/(PosteriorMeanSiteCodonP[site][codonFrom]/samplesize);
					S = log(expS);
					statSubRate = statMutRate * (S/(1-((PosteriorMeanSiteCodonP[site][codonFrom]/samplesize)/(PosteriorMeanSiteCodonP[site][codonTo]/samplesize))));
					if (S < min)	{
						c = 0;
					}
					else if (S > max)	{
						c = Ncat-1;
					}
					else {
						c = 0;
						double tmp = min + ((double)c * step) - step/2 + step;
						do	{
							c++;
							tmp = min + ((double)(c) * step) - step/2 + step;
						} while (tmp < S );
					}
					if (c == Ncat)	{
						cout << "error, c==Ncat.\n";
						cout.flush();
					}

					ppvhistoMut[c] += statMutRate;
					ppvhistoSub[c] += statSubRate;
					if (!GetCodonStateSpace()->Synonymous(codonFrom, codonTo))	{
						ppvhistoNonsynMut[c] += statMutRate;
						ppvhistoNonsynSub[c] += statSubRate;
						totalNonsynMut += statMutRate;
						totalNonsynSub += statSubRate;
					}
					totalMut += statMutRate;
					totalSub += statSubRate;
				}
			}
		}
	}	

	
	ofstream mutmutsel_os( (name + ".mutsel").c_str(), std::ios::out);
	ofstream mutsubsel_os( (name + ".subsel").c_str(), std::ios::out);
	ofstream nonsynmutmutsel_os( (name + ".nonsynmutsel").c_str(), std::ios::out);
	ofstream nonsynmutsubsel_os( (name + ".nonsynsubsel").c_str(), std::ios::out);
	ofstream synmutmutsel_os( (name + ".synmutsel").c_str(), std::ios::out);
	ofstream synmutsubsel_os( (name + ".synsubsel").c_str(), std::ios::out);

	ofstream sitemutmutsel_os( (name + ".sitemutsel").c_str(), std::ios::out);
	ofstream sitemutsubsel_os( (name + ".sitesubsel").c_str(), std::ios::out);
	ofstream sitenonsynmutmutsel_os( (name + ".sitenonsynmutsel").c_str(), std::ios::out);
	ofstream sitenonsynmutsubsel_os( (name + ".sitenonsynsubsel").c_str(), std::ios::out);
	ofstream sitesynmutmutsel_os( (name + ".sitesynmutsel").c_str(), std::ios::out);
	ofstream sitesynmutsubsel_os( (name + ".sitesynsubsel").c_str(), std::ios::out);

	ofstream ppvmutmutsel_os( (name + ".ppvmutsel").c_str(), std::ios::out);
	ofstream ppvmutsubsel_os( (name + ".ppvsubsel").c_str(), std::ios::out);
	ofstream ppvnonsynmutmutsel_os( (name + ".ppvnonsynmutsel").c_str(), std::ios::out);
	ofstream ppvnonsynmutsubsel_os( (name + ".ppvnonsynsubsel").c_str(), std::ios::out);
	for (c = 0; c < Ncat; c++)	{
		mutmutsel_os << (min + (c * step)) << "\t" << (ghistoMut[c]/samplesize) << '\n';
		mutsubsel_os << (min + (c * step)) << "\t" << (ghistoSub[c]/samplesize) << '\n';
		nonsynmutmutsel_os << (min + (c * step)) << "\t" << (ghistoNonsynMut[c]/samplesize) << '\n';
		nonsynmutsubsel_os << (min + (c * step)) << "\t" << (ghistoNonsynSub[c]/samplesize) << '\n';
		synmutmutsel_os << (min + (c * step)) << "\t" << (ghistoSynMut[c]/samplesize) << '\n';
		synmutsubsel_os << (min + (c * step)) << "\t" << (ghistoSynSub[c]/samplesize) << '\n';

		ppvmutmutsel_os << (min + (c * step)) << "\t" << (ppvhistoMut[c]/totalMut) << '\n';
		ppvmutsubsel_os << (min + (c * step)) << "\t" << (ppvhistoSub[c]/totalSub) << '\n';
		ppvnonsynmutmutsel_os << (min + (c * step)) << "\t" << (ppvhistoNonsynMut[c]/totalNonsynMut) << '\n';
		ppvnonsynmutsubsel_os << (min + (c * step)) << "\t" << (ppvhistoNonsynSub[c]/totalNonsynSub) << '\n';
		for (int site = 0; site < ProfileProcess::GetNsite(); site++)	{
			if (site == 0) 	{
				sitemutmutsel_os << (min + (c * step)) << '\t' << (sshistoMut[site][c]/samplesize) << '\t';
				sitemutsubsel_os << (min + (c * step)) << '\t' << (sshistoSub[site][c]/samplesize) << '\t';
				sitenonsynmutmutsel_os << (min + (c * step)) << '\t' << (sshistoNonsynMut[site][c]/samplesize) << '\t';
				sitenonsynmutsubsel_os << (min + (c * step)) << '\t' << (sshistoNonsynSub[site][c]/samplesize) << '\t';
				sitesynmutmutsel_os << (min + (c * step)) << '\t' << (sshistoSynMut[site][c]/samplesize) << '\t';
				sitesynmutsubsel_os << (min + (c * step)) << '\t' << (sshistoSynSub[site][c]/samplesize) << '\t';
			}
			else if (site == ProfileProcess::GetNsite() - 1)	{
				sitemutmutsel_os << (sshistoMut[site][c]/samplesize) << '\n';
				sitemutsubsel_os << (sshistoSub[site][c]/samplesize) << '\n';
				sitenonsynmutmutsel_os << (sshistoNonsynMut[site][c]/samplesize) << '\n';
				sitenonsynmutsubsel_os << (sshistoNonsynSub[site][c]/samplesize) << '\n';
				sitesynmutmutsel_os << (sshistoSynMut[site][c]/samplesize) << '\n';
				sitesynmutsubsel_os << (sshistoSynSub[site][c]/samplesize) << '\n';
			}
			else {
				sitemutmutsel_os << (sshistoMut[site][c]/samplesize) << '\t';
				sitemutsubsel_os << (sshistoSub[site][c]/samplesize) << '\t';
				sitenonsynmutmutsel_os << (sshistoNonsynMut[site][c]/samplesize) << '\t';
				sitenonsynmutsubsel_os << (sshistoNonsynSub[site][c]/samplesize) << '\t';
				sitesynmutmutsel_os << (sshistoSynMut[site][c]/samplesize) << '\t';
				sitesynmutsubsel_os << (sshistoSynSub[site][c]/samplesize) << '\t';
			}
		}
	}

	cerr << samplesize << '\n';
	for (int site = 0; site < GetNmodeMax(); site++)        {
		delete[] PosteriorMeanSiteCodonP[site];
		delete[] sshistoMut[site];
		delete[] sshistoSub[site];
		delete[] sshistoNonsynMut[site];
		delete[] sshistoNonsynSub[site];
		delete[] sshistoSynMut[site];
		delete[] sshistoSynSub[site];
	}
	delete[] PosteriorMeanSiteCodonP;
	delete[] sshistoMut;
	delete[] sshistoSub;
	delete[] sshistoNonsynMut;
	delete[] sshistoNonsynSub;
	delete[] sshistoSynMut;
	delete[] sshistoSynSub;
	delete[] tsshistoMut;
	delete[] tsshistoSub;
	delete[] tsshistoNonsynMut;
	delete[] tsshistoNonsynSub;
	delete[] tsshistoSynMut;
	delete[] tsshistoSynSub;
	delete[] ghistoMut;
	delete[] ghistoSub;
	delete[] ghistoNonsynMut;
	delete[] ghistoNonsynSub;
	delete[] ghistoSynMut;
	delete[] ghistoSynSub;
	delete[] shistoMut;
	delete[] shistoSub;
	delete[] shistoNonsynMut;
	delete[] shistoNonsynSub;
	delete[] shistoSynMut;
	delete[] shistoSynSub;
	delete[] ppvhistoMut;
	delete[] ppvhistoSub;
	delete[] ppvhistoNonsynMut;
	delete[] ppvhistoNonsynSub;
	delete[] stat;
	delete[] meanNucStat;
	delete[] meanNucRR;
}