Beispiel #1
0
size_t CExperimentSet::keyToIndex(const std::string & key) const
{
  const CExperiment * pExp = dynamic_cast<const CExperiment *>(CRootContainer::getKeyFactory()->get(key));

  if (!pExp) return C_INVALID_INDEX;

  size_t i, imax = size();

  for (i = 0; i < imax; i++)
    if (pExp == getExperiment(i)) return i;

  return C_INVALID_INDEX;
}
/**
 * @brief Run the analysis.
 */
void CNAnalysisMethodMosaicism::run()
{
    Verbose::out(1, "CNAnalysisMethodMosaicism::run(...) start");
    isSetup();
        determineLocalProbeSets();

    m_vSegments.deleteAll();
    vector<int> vChromosomes = getChromosomes(getProbeSets());
    int iLastChromosome = vChromosomes[vChromosomes.size() - 1];
    Verbose::progressBegin(1,"CNAnalysisMethodMosaicism::run(...) ", iLastChromosome, 1, iLastChromosome);

    for (int i = 0; (i < vChromosomes.size()); i++)
    {
        int iChromosome = vChromosomes[i];
        if (iChromosome == 255) {continue;}
        if (iChromosome == m_iYChromosome && !m_bRunYChromosome) {
          continue;
        }
        int iProbeSetCount = getProbeSetCount(iChromosome, getProbeSets());
        if (iProbeSetCount == 0) continue; // probably 23 or Y
        Verbose::progressStep(1);

        // debug: for later use
        m_current_experiment=getExperiment()->getExperimentName();
        m_current_chr=ToStr(vChromosomes[i]);

        std::vector<int> vPositions(iProbeSetCount);
        double* pLog2Ratios = new double[iProbeSetCount];
        int iStartChromosome = getChrBounds(iChromosome, getProbeSets()).first;
        m_iStartIndex = 0;
        m_iEndIndex = (iProbeSetCount - 1);
        CNProbeSetArray* psets = getProbeSets();
        for (int j = 0; (j < iProbeSetCount); j++)
        {
            vPositions[j] = psets->at(iStartChromosome + j)->getPosition();
            pLog2Ratios[j] = psets->at(iStartChromosome + j)->getLog2Ratio();
        }
        double* pRunMean = new double[iProbeSetCount];
        int iMarkerBandwidth = Min(iProbeSetCount, m_iMarkerBandwidth);
        runmean(pLog2Ratios, pRunMean, &iProbeSetCount, &iMarkerBandwidth);

        // debug - this has been ruled out.
#ifdef MOSAICISM_DEBUG_MEANS
        writeRunningMeans(m_current_experiment+".chr"+m_current_chr+".means.tsv",
                          iProbeSetCount,
                          pLog2Ratios,
                          pRunMean);
#endif

        CNSegmentArray vSegments;
        newSegments((unsigned char)iChromosome, pRunMean, iProbeSetCount, vPositions, vSegments);
        // dont need this anymore.
        delete[] pRunMean;

        // debug
#ifdef MOSAICISM_DEBUG
        vSegments.writeToTsv(m_current_experiment+"-chr"+m_current_chr+".newseg1.tsv");
#endif
        //
        cleanSegments(vSegments);

        // Set marker count and median marker distance.
        for (int iSegmentIndex = 0; (iSegmentIndex < vSegments.getCount()); iSegmentIndex++)
        {
            CNSegment* p = vSegments.getAt(iSegmentIndex);
            p->setStartPosition(vPositions[p->getStartIndex()]);
            p->setEndPosition(vPositions[p->getEndIndex()]);
            calculateSegmentConfidence(pLog2Ratios, p);
            int iMarkerCount = 0;
            for (unsigned int iProbeSetIndex = 0; (iProbeSetIndex < vPositions.size()); iProbeSetIndex++)
            {
                if ((vPositions[iProbeSetIndex] >= p->getStartPosition()) && (vPositions[iProbeSetIndex] <= p->getEndPosition()))
                {
                    iMarkerCount++;
                }
            }
            if (iMarkerCount < 2)
            {
                p->setMarkerCount(iMarkerCount);
                p->setMeanMarkerDistance(0);
            }
            else
            {
                AffxMultiDimensionalArray<int> vMarkerDistances(iMarkerCount - 1);
                int iIndex = 0;
                for (unsigned int iProbeSetIndex = 1; (iProbeSetIndex < vPositions.size()); iProbeSetIndex++)
                {
                    int iPrevPosition = vPositions[iProbeSetIndex - 1];
                    int iNextPosition = vPositions[iProbeSetIndex];
                    if ((iPrevPosition >= p->getStartPosition()) && (iNextPosition <= p->getEndPosition()))
                    {
                        getProbeSets()->getAt(iStartChromosome + iProbeSetIndex - 1)->setMosaicismMixture(p->getMixtureAsDouble());
                        getProbeSets()->getAt(iStartChromosome + iProbeSetIndex)->setMosaicismMixture(p->getMixtureAsDouble());
                        vMarkerDistances.set(iIndex, (iNextPosition - iPrevPosition));
                        iIndex++;
                    }
                }
                p->setMarkerCount(iMarkerCount);
                p->setMeanMarkerDistance(vMarkerDistances.mean());
            }
            // transfer of ownership from vSegments to m_vSegments
            m_vSegments.add(p);
        }

#ifdef MOSAICISM_DEBUG
        vSegments.writeToTsv(m_current_experiment+"-chr"+m_current_chr+".seg2.tsv");
#endif
        // why "nullAll()" instead of "deleteAll()"?
        // because the pointers were copied to m_vSegments above and
        // AffxArray will delete the pointers in vSegments when it goes out of scope.
        vSegments.nullAll();
        delete[] pLog2Ratios;
    }
    Verbose::progressEnd(1, "Done");
    Verbose::out(1, "CNAnalysisMethodMosaicism::run(...) end");
}
Beispiel #3
0
const CMatrix< C_FLOAT64 > & CExperimentSet::getDependentData(const size_t & index) const
{return getExperiment(index)->getDependentData();}
Beispiel #4
0
const CTaskEnum::Task & CExperimentSet::getExperimentType(const size_t & index) const
{return getExperiment(index)->getExperimentType();}
/**
 * @brief Create new segments
 * @param int - The segment type to create
 * @param CNSegmentArray& - The segment vector to load
 * @param int - The affx sex code
 * @param int - The X chromosome numeric value
 * @param int - The Y chromosome numeric value
 * @return int - The number of new segments created
 */
int CNAnalysisMethodSegment::newSegments(    int iSegmentType,
                                              CNProbeSetArray* vProbeSets,
                                             int iMinSegSeparation   )
{
    AffxMultiDimensionalArray<int> vMarkerDistances(vProbeSets->getCount());
    int iPrevMarkerPosition = 0;
    if (vProbeSets->getCount() == 0) {return 0;}
    int iSegmentCount = 0;
    int iMarkerCount = 0;
    double dSumConfidence = 0.0;
    double dConfidence=0.0;
    int iHetsInSegment=0;
    int iHomsInSegment=0;
    CNSegment* pobjSegment = NULL;
    CNProbeSet* pobjProbeSet = NULL;
    int iStartIndex = 0;
    // If Segment type loh-segment, loh-cyto2, cn-neutral-log, normal-diploid
    if ((iSegmentType == 2) || (iSegmentType == 3) || (iSegmentType == 4) || (iSegmentType == 5))
    {
        for (;(iStartIndex < vProbeSets->getCount()); iStartIndex++)
        {
            pobjProbeSet = vProbeSets->getAt(iStartIndex);
            if ((double)pobjProbeSet->getLoh() == (double)pobjProbeSet->getLoh()) // Not = NaN
            {
                break;
            }
        }
    }
    int iCurrCNState = -1;
    bool cytoScanHD = m_pEngine->getOptBool("cytoscan-hd");
    if (iStartIndex < vProbeSets->getCount())
    {
        pobjProbeSet = vProbeSets->getAt(iStartIndex);
        if (cytoScanHD)
        {
            // Case 1: SNP marker with CN=-1 sits at the beginning of the chromosome
            unsigned char currentChromosome = pobjProbeSet->getChromosome();
            for (int iIndex = iStartIndex; (iIndex < vProbeSets->getCount()); iIndex++)
            {
                if (currentChromosome != vProbeSets->getAt(iIndex)->getChromosome()) break;
                if (vProbeSets->getAt(iIndex)->getCNState() != -1)
                {
                    iCurrCNState = vProbeSets->getAt(iIndex)->getCNState();
                    break;
                }
            }
        }
        char cCall = pobjProbeSet->getSegmentTypeCall(iSegmentType, getExperiment()->getCNCallGenderAsInt(), m_iXChromosome, m_iYChromosome);
        float fConfidence = pobjProbeSet->getSegmentTypeConfidence(iSegmentType);
        bool bPar = pobjProbeSet->isPseudoAutosomalRegion();
        if (cytoScanHD)
        {
            // Override cCall in the two cases where CN state makes a difference.
		    if (iSegmentType == 4) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 1)) ? (char)1 : (char)0); // CNNeutralLOH
		    if (iSegmentType == 5) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 0)) ? (char)1 : (char)0); // Normal Diploid
        }

        pobjSegment = new CNSegment;
        pobjSegment->setSegmentType(iSegmentType);
        pobjSegment->setChromosome(pobjProbeSet->getChromosome());
        pobjSegment->setStartPosition(pobjProbeSet->getPosition());
        pobjSegment->setEndPosition(pobjProbeSet->getPosition());
        pobjSegment->setCall(cCall);
        pobjSegment->setConfidence((float)0.5);
        pobjSegment->setPseudoAutosomalRegion(bPar);
        iMarkerCount = 0;
        dSumConfidence = 0;
        iPrevMarkerPosition = pobjProbeSet->getPosition();

        for (int iIndex = iStartIndex; (iIndex < vProbeSets->getCount()); iIndex++)
        {
            pobjProbeSet = vProbeSets->getAt(iIndex);
            cCall = pobjProbeSet->getSegmentTypeCall(iSegmentType, getExperiment()->getCNCallGenderAsInt(), m_iXChromosome, m_iYChromosome);
            fConfidence = pobjProbeSet->getSegmentTypeConfidence(iSegmentType);
            bPar = pobjProbeSet->isPseudoAutosomalRegion();
			
            // Case 2: If a SNP marker falls within a CN segment (including CN or SNP), assign SNP marker with the same CN state
            // Case 3: If a SNP marker falls outside any CN segment, assign CN state for this SNP marker based on the CN segment just right before it.
			if (pobjProbeSet->getCNState() != -1) {iCurrCNState = pobjProbeSet->getCNState();}

			if (cytoScanHD)
			{
                // Override cCall in the two cases where CN state makes a difference.
		        if (iSegmentType == 4) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 1)) ? (char)1 : (char)0); // CNNeutralLOH
		        if (iSegmentType == 5) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 0)) ? (char)1 : (char)0); // Normal Diploid
			}
            if ((iSegmentType == 2) || (iSegmentType == 3) || (iSegmentType == 4) || (iSegmentType == 5))
            {
                if ((double)pobjProbeSet->getLoh() != (double)pobjProbeSet->getLoh()) // NaN
                {
                    continue;
                }
            }
            bool newSegmentTestFlag = false;
            if(iSegmentType == 2)
            { 
                newSegmentTestFlag = (	
                    (pobjProbeSet->getChromosome() != pobjSegment->getChromosome()) 
                 || (cCall != pobjSegment->getCall()) 
                 || ((getExperiment()->getCNCallGenderAsInt() == affx::Male) && (iSegmentType == 1) && (bPar != pobjSegment->isPseudoAutosomalRegion()))
                 || (fabs((float)iPrevMarkerPosition - (float) (pobjProbeSet->getPosition())) > (float) iMinSegSeparation) 
                                     );
            }
            else
            {
                newSegmentTestFlag = (
                    (pobjProbeSet->getChromosome() != pobjSegment->getChromosome()) 
                 || (cCall != pobjSegment->getCall()) 
                 || ((getExperiment()->getCNCallGenderAsInt() == affx::Male) && (iSegmentType == 1) && (bPar != pobjSegment->isPseudoAutosomalRegion()))
                                     ); 
            }

            if (newSegmentTestFlag)
            {
                pobjSegment->setMeanMarkerDistance((float)vMarkerDistances.mean(iMarkerCount - 1));
                pobjSegment->setSegmentName(affxutil::Guid::GenerateNewGuid());
                pobjSegment->setMarkerCount(iMarkerCount);
                pobjSegment->setConfidence((float)(dSumConfidence / (double)iMarkerCount));

                if(cytoScanHD)
                {
                    if(iSegmentType==2)
                    {
                        dConfidence = assignConfidenceSigmoidal(	iHetsInSegment,
                                                                        iHetsInSegment + iHomsInSegment,
                                                                        getExperiment()->getHetFrequency(),
                                                                        getExperiment()->getPError(),
                                                                        3,
                                                                        10);
                        pobjSegment->setConfidence((float) dConfidence); 
                    }
                    if(iSegmentType==4)
                    {
                        dConfidence = assignConfidenceSigmoidal(	iHetsInSegment,
                                                                        iHetsInSegment + iHomsInSegment,
                                                                        getExperiment()->getHetFrequency(),
                                                                        getExperiment()->getPError(),
                                                                        3,
                                                                        10);
                        pobjSegment->setConfidence((float) (dConfidence/2.0));
                    }

               }

                m_vSegments.add(pobjSegment);
                iSegmentCount++;

                if (cytoScanHD && pobjProbeSet->getChromosome() != pobjSegment->getChromosome())
                {
                    // Case 1: SNP marker with CN=-1 sits at the beginning of the chromosome
                    iCurrCNState = -1;
                    unsigned char currentChromosome = pobjProbeSet->getChromosome();
                    for (int iInner = iIndex; (iInner < vProbeSets->getCount()); iInner++)
                    {
                        if (currentChromosome != vProbeSets->getAt(iIndex)->getChromosome()) break;
                        if (vProbeSets->getAt(iInner)->getCNState() != -1)
                        {
                            iCurrCNState = vProbeSets->getAt(iInner)->getCNState();
                            break;
                        }
                    }
                     // Override cCall in the two cases where CN state makes a difference.
	                if (iSegmentType == 4) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 1)) ? (char)1 : (char)0); // CNNeutralLOH
	                if (iSegmentType == 5) cCall = (((iCurrCNState == 2) && (pobjProbeSet->getLoh() == 0)) ? (char)1 : (char)0); // Normal Diploid
                }

                pobjSegment = new CNSegment;
                pobjSegment->setSegmentType(iSegmentType);
                pobjSegment->setChromosome(pobjProbeSet->getChromosome());
                pobjSegment->setStartPosition(pobjProbeSet->getPosition());
                pobjSegment->setCall(cCall);
                pobjSegment->setConfidence((float)0.5);
                pobjSegment->setPseudoAutosomalRegion(bPar);
                iHetsInSegment=0;
                iHomsInSegment=0;
                iMarkerCount = 0;
                dSumConfidence = 0;
                iPrevMarkerPosition = pobjProbeSet->getPosition();
            }
            iMarkerCount++;

            if(pobjProbeSet->getGenotypeCall() == (char) 2 || pobjProbeSet->getGenotypeCall() == (char) 0)
            {
                iHomsInSegment++;
            }

            if(pobjProbeSet->getGenotypeCall() == (char) 1 )
            {
                iHetsInSegment++;
            }


            dSumConfidence += fConfidence;
            pobjSegment->setEndPosition(pobjProbeSet->getPosition());
            if (iMarkerCount > 1) {vMarkerDistances.set((iMarkerCount - 2), (pobjProbeSet->getPosition() - iPrevMarkerPosition));}
            iPrevMarkerPosition = pobjProbeSet->getPosition();
        }
    }
    if (pobjSegment != NULL)
    {
        pobjSegment->setConfidence((float)(dSumConfidence / (double)iMarkerCount));

        if(cytoScanHD)
        { 
            if(iSegmentType==2)
            {
                dConfidence = assignConfidenceSigmoidal(	iHetsInSegment,
                                                                iHetsInSegment + iHomsInSegment,
                                                                getExperiment()->getHetFrequency(),
                                                                getExperiment()->getPError(),
                                                                3,
                                                                10);
                 pobjSegment->setConfidence((float) dConfidence);
            }
            if(iSegmentType==4)
            {
                dConfidence = assignConfidenceSigmoidal(	iHetsInSegment,
                                                                iHetsInSegment + iHomsInSegment,
                                                                getExperiment()->getHetFrequency(),
                                                                getExperiment()->getPError(),
                                                                3,
                                                                10);
                pobjSegment->setConfidence((float) (dConfidence/2.0));
            }
        }  

        pobjSegment->setMeanMarkerDistance((float)vMarkerDistances.mean(iMarkerCount - 1));
        pobjSegment->setMarkerCount(iMarkerCount);
        pobjSegment->setSegmentName(affxutil::Guid::GenerateNewGuid());
        m_vSegments.add(pobjSegment); iSegmentCount++;
    }
    return iSegmentCount;
}
Beispiel #6
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QLocale::setDefault(QLocale::English);
    //setAttribute(Qt::WA_DeleteOnClose,true);
    ui->setupUi(this);
    experimentSettings=new QSettings (QSettings::IniFormat,QSettings::UserScope,QApplication::organizationName(),"experiment",this);
    experiment=new Experiment();

    tcp=new TcpServer(this);
    tcp->setExperiment(experiment);
    udp=new UdpServer(this);
    udp->setExperiment(experiment);

    connect(tcp,SIGNAL(warning(QString)),SLOT(warning(QString)));
    connect(tcp,SIGNAL(notify(QString)),SLOT(notify(QString)));

    //bind tcp socket to local port 25050
    tcp->bind(25050);

    connect(experiment,SIGNAL(statusChanged(bool)),tcp,SLOT(experimentStatusChanged(bool)));
    connect(experiment,SIGNAL(intervalChanged(int)),tcp,SLOT(experimentIntervalChanged(int)));
    connect(experiment,SIGNAL(TcpForbidden(QString)),tcp,SLOT(experimentForbidden(QString)));


    connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(close()));
    connect(ui->actionFullscreen,SIGNAL(triggered(bool)),this,SLOT(setFullscreen(bool)));
    connect(ui->actionAbout_Qt,SIGNAL(triggered()),this,SLOT(showAboutQt()));
    connect(ui->actionNew_experiment,SIGNAL(triggered()),this,SLOT(getExperiment()));
    connect(ui->actionSave,SIGNAL(triggered()),experiment,SLOT(saveFile()));
    connect(ui->actionSave_as,SIGNAL(triggered()),this,SLOT(getFile()));
    connect(ui->actionStartMeasure,SIGNAL(toggled(bool)),experiment,SLOT(start(bool)));
    connect(ui->actionMeasuring_interval,SIGNAL(triggered()),this,SLOT(changeMeasureIntervalDialog()));
    connect(ui->actionControls,SIGNAL(triggered()),SLOT(showExperimentControlMangement()));
    connect(ui->actionData,SIGNAL(triggered()),SLOT(showData()));

    connect(experiment,SIGNAL(statusChanged(bool)),ui->actionStartMeasure,SLOT(setChecked(bool)));
    connect(experiment,SIGNAL(statusChanged(bool)),this,SLOT(statusChanged(bool)));
    connect(experiment,SIGNAL(experimentChanged(QString)),this,SLOT(setExperiment(QString)));
    connect(experiment,SIGNAL(measured(QString)),ui->plainTextEdit,SLOT(appendPlainText(QString)));
    connect(experiment,SIGNAL(fileChanged(QString)),this,SLOT(setFile(QString)));
    connect(experiment,SIGNAL(Notify(QString)),SLOT(notify(QString)));
    connect(experiment,SIGNAL(intervalChanged(int)),SLOT(setMeasureInterval(int)));
    connect(experiment,SIGNAL(updateProgress(int)),ui->measureIntervalProgressBar,SLOT(setValue(int)));

    connect(tcp,SIGNAL(clientCountChanged(int)),&tcpClientsLabel,SLOT(setNum(int)));

    experiment->setInterval(2000);

    // Additional ui preparation
    experimentLabel.setToolTip("Experiment configuration");
    statusLabel.setToolTip("Experiment status:\nR - running\nS - stopped");
    QFont font(statusLabel.font());
    font.setBold(true);
    statusLabel.setFont(font);
    //set experiment status to stopped
    statusChanged(false);
    tcpClientsLabel.setToolTip("Number of tcp clients");
    tcpClientsLabel.setNum(0);

    statusBar()->addPermanentWidget(&tcpClientsLabel);
    statusBar()->addPermanentWidget(&fileLabel);
    statusBar()->addPermanentWidget(&experimentLabel);
    statusBar()->addPermanentWidget(&statusLabel);

    // Ask user to select experiment
    getExperiment();
}
/**
 * @brief Preprocess the genotype calls to get the marker count cutoff and the het call cutoff
 * @param std::vector<char>& - The vector of hom and/or het calls
 * @param int& - The marker count cutoff to calculate
 * @param int& - The het call cutoff to calculate
 * @return bool - Was the function successful or not (true = successful)
 */
bool CNAnalysisMethodLOHCytoScan::lohPreProcessing(std::vector<char>& vHomHet, int& iMarkerCount, int& iHetCutoff)
{
    int iHetCount = 0;
    int iCallCount = 0;
    int iNoCallCount = 0;
    double dMaximumGenotypeConfidence = 0;
    int iSnpCount = 0;
    for (int iIndex = 0; (iIndex < (int)getProbeSets()->size()); iIndex++)
    {
        CNProbeSet* pobjProbeSet = getProbeSets()->at(iIndex);
        pobjProbeSet->setLoh(numeric_limits<float>::quiet_NaN());
        if (pobjProbeSet->processAsSNP()) {iSnpCount++;}
        vHomHet[iIndex] = pobjProbeSet->getGenotypeCall();
        if (vHomHet[iIndex] == (char)2) {vHomHet[iIndex] = (char)0;}
        if (pobjProbeSet->getGenotypeConfidence() > m_dLohCNNoCallThreshold) {vHomHet[iIndex] = (char)-1;}
        if (vHomHet[iIndex] == 1) {iHetCount++;}
        if (vHomHet[iIndex] >= 0)
        {
            iCallCount++;
            dMaximumGenotypeConfidence = Max((float)dMaximumGenotypeConfidence, pobjProbeSet->getGenotypeConfidence());
        }
        else
        {
            if (pobjProbeSet->processAsSNP()) {iNoCallCount++;}
        }
    }
    double dErrorRate = m_dLohCNErrorRate;
    if (((dMaximumGenotypeConfidence * 1.1) >= m_dLohCNNoCallThreshold) && (m_dLohCNNoCallThreshold == 0.05))
    {
        dErrorRate = ((double)iNoCallCount / (double)iSnpCount);
        dErrorRate = (0.002926 + 6.607106 * dErrorRate);
        dErrorRate = ceil(dErrorRate * 100) / 100.0;
        if (dErrorRate < m_dLohCNErrorRate) {dErrorRate = m_dLohCNErrorRate;}
    }
    double dHetRate = ((double)iHetCount / (double) iCallCount);
    if (dHetRate > 0.5) {dHetRate = 0.5;}
    if (dHetRate < 0.2) {dHetRate = 0.2;}
    int iIterations = 1;
    int iStart = 20;
    int n = 0;
    while (iIterations < 3)
    {
        iHetCutoff = AffxStatistics::binoinv((1 - m_dLohCNAlpha), iStart, dErrorRate);
        double a = AffxStatistics::norminv(m_dLohCNBeta);
        double sqrtn = (-a * 0.5 * sqrt(1 - dHetRate) / sqrt(dHetRate) + sqrt(a * a * (1 - dHetRate) / (4 * dHetRate) + iHetCutoff / dHetRate));
        n = (int)ceil(sqrtn * sqrtn);
        if (n == iStart) {break;}
        else {iStart = n;}
        iIterations++;
    }
    iMarkerCount = Max(n, m_iLohCNMinimumMarkerCount);
    if ((iMarkerCount % 2) == 0) {iMarkerCount++;}
    if (iMarkerCount < 3)
    {
        throw(Except("MarkerCount must be >= 3.")); return false;
    }



    // The hetRate is used in the CNAnalysisMethodSegment method to assign a confidence to the loh determination.  In order
    // that this value is accessible there we pass it to the CNExperiment object. Note that the het frequency is also 
    // computed and stored in a postprocessing function in the CNCytoEngine.  The two computations are the same.
    // We also need the dErrorRate when calculating confidences.  This value is also passed to the experiment object and then accessed
    // when segmenting.
    getExperiment()->setHetFrequency(dHetRate);
    getExperiment()->setPError(dErrorRate);

    return true;
}
void CNAnalysisMethodLOHCytoScan::imputeMissingLOHCalls()
{        
        std::vector<CNProbeSet*> vLOHProbeSets; 
        for (int iIndex = 0; (iIndex < (int)getProbeSets()->size()); iIndex++)
        {
                CNProbeSet* pProbeSet = getProbeSets()->getAt(iIndex); 
                if( pProbeSet->processAsSNP() )
                {
                        vLOHProbeSets.push_back(pProbeSet);   
                } 
        }

        // This is code to dump out the loh status before the impute algorithm is invoked.
        bool testFlag = false;
        if(testFlag)
        {
                affx::TsvFile *tsv = new affx::TsvFile;
                tsv->writeTsv(getExperiment()->getExperimentName() + ".LohProbes.txt");
                tsv->defineColumn(    0,0,"position", affx::TSV_TYPE_DOUBLE);
                tsv->defineColumn(    0,1,"lohState", affx::TSV_TYPE_DOUBLE);
                tsv->defineColumn(    0,2,"Chromosome", affx::TSV_TYPE_DOUBLE);
                tsv->defineColumn(    0,3,"Genotype", affx::TSV_TYPE_DOUBLE);

            for (int iIndex = 0; iIndex < vLOHProbeSets.size(); iIndex++)
            {
                CNProbeSet* pProbeSet = vLOHProbeSets[iIndex];
                tsv->set(0,0,pProbeSet->getPosition());
                tsv->set(0,1,pProbeSet->getLoh());
                tsv->set(0,2,pProbeSet->getChromosome());
                tsv->set(0,3,pProbeSet->getGenotypeCall());
                tsv->writeLevel(0);
            }
            delete tsv;
        }


        int iLeftIndex=0;
        int iRightIndex=1;
                

        int iLeftLohStatus=0;  
        int iRightLohStatus=0;  
        CNProbeSet* pLeftProbeSet = NULL;      
        CNProbeSet* pRightProbeSet =  NULL;     

        while(iRightIndex < vLOHProbeSets.size())
        {


                pLeftProbeSet = vLOHProbeSets[iLeftIndex];      
                pRightProbeSet =  vLOHProbeSets[iRightIndex];     

                iLeftLohStatus=pLeftProbeSet->getLoh();  
                iRightLohStatus=pRightProbeSet->getLoh();  

                if(!pLeftProbeSet->lohCalled())
                {
                        if(!pRightProbeSet->lohCalled() ) 
                        {
                                // If we don't get an loh call on the right we advance.
                                iRightIndex++;
                                // If we have advanced beyond the collection of probesets we clean up since we never get back in the loop. 
                                if(iRightIndex == vLOHProbeSets.size())
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(0);         
                                        }
                                }
                                continue;
                        } 
                        else
                        {
                        //  At this point we have just finished advancing the right pointer and thus 3 things can happen.  
                        //  RightIndex passes out of the chromosome or over the centromere.
                        //  Or hits a marker with valid loh call.
                        //  Note that we put the 3rd case last since we can get a valid loh call across a boundary but want to 
                        //  deal with it as in the first two cases.
                        //  Note that the right pointer cannot point outside the array since that is the condition on the while loop.
                                if( (vLOHProbeSets[iRightIndex]->getPosition() - vLOHProbeSets[iRightIndex-1]->getPosition()) > m_iLohCNSeparation)
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(0);
                                        }
                                        // Note that iRightIndex points across a boundary so we do not set it's loh. ie. < not <= in above for loop. 
                                        iLeftIndex=iRightIndex;
                                        iRightIndex=iLeftIndex+1;
                                        // Note that here we can be pointing beyond the array bounds, but even though we never
                                        // get back in the loop we have cleaned up. i.e. set the last set of markers to have non-loh.
                                        continue;                             
                                }
                                if( vLOHProbeSets[iRightIndex]->getChromosome() != vLOHProbeSets[iRightIndex-1]->getChromosome() )
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(0);
                                        }
                                        iLeftIndex=iRightIndex;
                                        iRightIndex=iLeftIndex+1;
                                        continue;                             
                                }
                                // We now have an loh call on the right but none on the left.
                                {
                                        for(int iIndex = iLeftIndex; iIndex <= iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(iRightLohStatus);
                                        }
                                        // We now move the left and right indices.  Note that how they move depends on whether or not we
                                        // are within a chromsome or if the right index is at the end of a chromsome.  In the first case
                                        // we advance the left to the right index since we need this points loh status to continue. In the
                                        // second case we advance both left and right to the first two positions in the next chromsome.
                                        if(iRightIndex+1 == vLOHProbeSets.size()) 
                                        {
                                                iRightIndex++;
                                                continue;
                                        }
                                        if
                                        (    
                                             ( vLOHProbeSets[iRightIndex+1]->getChromosome() != vLOHProbeSets[iRightIndex]->getChromosome() ) 
                                                 ||   
                                             ( (vLOHProbeSets[iRightIndex+1]->getPosition()- vLOHProbeSets[iRightIndex]->getPosition()) > m_iLohCNSeparation )  
                                        )
                                        {     
                                                iLeftIndex=iRightIndex+1;
                                                iRightIndex=iLeftIndex+1;
                                        }
                                        else
                                        { 
                                                iLeftIndex=iRightIndex;
                                                iRightIndex=iLeftIndex+1;
                                        }
                                        continue;                         
                                }

                        }   
                }
                else
                {
                        if(!pRightProbeSet->lohCalled() )
                        {
                                iRightIndex++;
                                if(iRightIndex == vLOHProbeSets.size())                                                  
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(iLeftLohStatus);
                                        }  
                                        continue;                
                                }
                        }
                        else
                        {
                         // Again, at this point 3 things can happen.   
                         // RightIndex passes out of the chromosome or over the centromere.
                         // Or hits a marker with valid loh call.
                         // Note that we put the 3rd case last since we can get a valid loh call across a boundary but want to 
                         // deal with it as in the first two cases.
                              
                               if( (vLOHProbeSets[iRightIndex]->getPosition() - vLOHProbeSets[iRightIndex-1]->getPosition()) > m_iLohCNSeparation)
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(iLeftLohStatus);
                                        }
                                         
                                        iLeftIndex=iRightIndex;
                                        iRightIndex=iLeftIndex+1;
                                        // Note that here we can be pointing beyond the array bounds, but even though we never
                                        // get back in the loop we have cleaned up. i.e. set the last set of markers to have non-loh.
                                        continue;
                                }
                                if( vLOHProbeSets[iRightIndex]->getChromosome() != vLOHProbeSets[iRightIndex-1]->getChromosome() )
                                {
                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                        {
                                                vLOHProbeSets[iIndex]->setLoh(iLeftLohStatus);
                                        }
                                        iLeftIndex=iRightIndex;
                                        iRightIndex=iLeftIndex+1;
                                        continue;
                                }
                                // We now have an loh call on the left and the right.
                                {
                                        // At this point we have 2 cases.  The left and right probesets have the same loh state 
                                        // Or one has loh the other non-loh.
                                        if(iRightLohStatus==iLeftLohStatus)
                                        {
                                                for(int iIndex = iLeftIndex; iIndex <= iRightIndex; iIndex++)
                                                {
                                                        vLOHProbeSets[iIndex]->setLoh(iLeftLohStatus);
                                                }
                                        }
                                        else
                                        {
                                                if(iRightLohStatus==0)
                                                {
                                                        for(int iIndex = iLeftIndex+1; iIndex <= iRightIndex; iIndex++)
                                                        {
                                                                vLOHProbeSets[iIndex]->setLoh(0);
                                                        }
                                                }
                                                else
                                                {
                                                        for(int iIndex = iLeftIndex; iIndex < iRightIndex; iIndex++)
                                                        {
                                                                vLOHProbeSets[iIndex]->setLoh(0);
                                                        }
                                                }
                                        }
                                        if(iRightIndex+1 == vLOHProbeSets.size())
                                        {
                                                iRightIndex++;
                                                continue;
                                        }
                                       if
                                        (
                                             ( vLOHProbeSets[iRightIndex+1]->getChromosome() != vLOHProbeSets[iRightIndex]->getChromosome() )
                                                 ||
                                             ( (vLOHProbeSets[iRightIndex+1]->getPosition()- vLOHProbeSets[iRightIndex]->getPosition()) > m_iLohCNSeparation )
                                        )
                                        { 
                                                iLeftIndex=iRightIndex+1;
                                                iRightIndex=iLeftIndex+1;
                                        }
                                        else
                                        { 
                                                iLeftIndex=iRightIndex;
                                                iRightIndex=iLeftIndex+1;
                                        }
                                        continue;
                                }
                        }
               }
        }
}