コード例 #1
0
ファイル: ADMMCut.cpp プロジェクト: lock794779857/FrameFab
void ADMMCut::MakeLayers()
{
	// Initial Cutting Edge Setting
	InitState();

	debug_ = false;
	int cut_count = 0;
	vector<double> cut_energy;
	vector<double> res_energy;
	do
	{
		/* Recreate dual graph at the beginning of each cut */
		SetStartingPoints(cut_count);
		CreateA();

		ptr_stiff_->CalculateD(D_, x_, 0, 0, cut_count);

		///* for rendering */
		//if (cut_count == 0)
		//{
		//	WriteWeight();
		//	WriteStiffness("offset1.txt", "rotation1.txt");
		//	getchar();
		//}
		//if (cut_count == 4)
		//{
		//	WriteStiffness("offset2.txt", "rotation2.txt");
		//	getchar();
		//}
		//if (cut_count == 6)
		//{
		//	WriteStiffness("offset3.txt", "rotation3.txt");
		//	getchar();
		//}

		/* set x for intial cut setting */
		SetBoundary();

		/*
		* energy specify:
		* cut		 energy : | A * x |
		* defomation energy : norm(K D - F)
		*/
		ptr_stiff_->CreateGlobalK(x_);
		ptr_stiff_->CreateF(x_);
		SpMat K_init = *(ptr_stiff_->WeightedK());
		VX	  F_init = *(ptr_stiff_->WeightedF());


		double icut_energy = 0;
		VX V_Cut = A_ * x_;
		for (int i = 0; i < Md_; i++)
		{
			icut_energy += abs(V_Cut[i]);
		}
		double ideform_energy = (K_init * D_ - F_init).norm();

		cout << "****************************************" << endl;
		cout << "ADMMCut Round : " << cut_count << endl;
		cout << "Initial cut energy before entering ADMM: " << icut_energy << endl;
		cout << "Initial Lagrangian energy before entering ADMM: " << ideform_energy << endl;
		cout << "---------------------------------" << endl;

		int rew_count = 0;
		VX x_prev;
		VX D_prev;

		/* Output energy list for reweighting process in a single
		graph cut problem, energy.size() = number of reweighting
		process performed.
		cut energy = |A_ * x_| = sum_{e_ij} w_ij * |x_i - x_j|
		res energy = (K(x)D - F(x)).norm()
		*/

		cut_energy.clear();
		res_energy.clear();

		cut_energy.push_back(icut_energy);
		res_energy.push_back(ideform_energy);

		do
		{
			/* Reweighting loop for cut */

			int ADMM_count = 0;
			x_prev = x_;
			CreateC(cut_count, rew_count);

			do
			{
				cout << "ADMMCut Round: " << cut_count << ", reweight iteration:" << rew_count
					<< ", ADMM " << ADMM_count << " iteration." << endl;

				/*-------------------ADMM loop-------------------*/
				CalculateX();

				D_prev = D_;
				CalculateD();

				UpdateLambda();

				/*-------------------Residual Calculation-------------------*/
				SpMat Q_prev;
				SpMat Q_new;
				CalculateQ(D_prev, Q_prev);
				CalculateQ(D_, Q_new);

				/* Update K reweighted by new x */
				ptr_stiff_->CreateGlobalK(x_);
				ptr_stiff_->CreateF(x_);
				SpMat K_new = *(ptr_stiff_->WeightedK());
				VX    F_new = *(ptr_stiff_->WeightedF());

				dual_res_ = penalty_ * (D_prev - D_).transpose() * K_new.transpose() * Q_prev
					+ lambda_.transpose() * (Q_prev - Q_new);
				primal_res_ = K_new * D_ - F_new;

				/*-------------------Screenplay-------------------*/
				double new_cut_energy = x_.dot(H1_ * x_);

				cout << "new quadratic func value record: " << new_cut_energy << endl;
				cout << "dual_residual : " << dual_res_.norm() << endl;
				cout << "primal_residual(KD-F) : " << primal_res_.norm() << endl;

				cout << "---------------------" << endl;
				ADMM_count++;
			} while (!TerminationCriteria(ADMM_count));

			/* One reweighting process ended! */
			/* Output energy and residual */

			double energy = 0;
			VX V_Cut = A_ * x_;
			for (int i = 0; i < Md_; i++)
			{
				energy += ptr_dualgraph_->Weight(i) * abs(V_Cut[i]);
			}

			/*-------------------Screenplay-------------------*/
			double res_tmp = primal_res_.norm();
			cout << "Cut " << cut_count << " Reweight " << rew_count << " completed." << endl;
			cout << "Cut Energy :" << energy << endl;
			cout << "Res Energy :" << res_tmp << endl;
			cout << "<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-<-" << endl;

			cut_energy.push_back(energy);
			res_energy.push_back(res_tmp);

			/* write x distribution to a file */
			string str_x = "Cut_" + to_string(cut_count) + "_Rew_" + to_string(rew_count) + "_x";
			Statistics tmp_x(str_x, x_);
			tmp_x.GenerateVectorFile();

			rew_count++;
		} while (!UpdateR(x_prev, rew_count));

		/* Output reweighting energy history for last cut process */
		string str_eC = "Cut_" + to_string(cut_count) + "_Cut_Energy";
		Statistics s_eC(str_eC, cut_energy);
		s_eC.GenerateStdVecFile();

		string str_eR = "Cut_" + to_string(cut_count) + "_Res_Energy";
		Statistics s_eR(str_eR, res_energy);
		s_eR.GenerateStdVecFile();

		/* Update New Cut information to Rendering (layer_label_) */

		UpdateCut();

		fprintf(stdout, "ADMMCut No.%d process is Finished!\n", cut_count);
		cut_count++;

	} while (!CheckLabel(cut_count));

	fprintf(stdout, "All done!\n");
}
コード例 #2
0
ファイル: structure.c プロジェクト: Tritlo/structure
int main (int argc, char *argv[])
{
    /*data--------- */
    int *Geno;                    /*NUMINDSxLINES: genotypes */
    float *R;                    /*NUMINDS */
    float *Mapdistance;          /*NUMLOCI */
    float *Phase;                /*NUMLOCI*NUMINDS */
    int *Phasemodel=NULL;         /*NUMINDS */
    char *Markername;             /*GENELEN*NUMLOCI */

    struct IND *Individual;       /*NUMINDS: records for each individual */
    int *Translation;             /*NUMLOCIxMAXALLELES: value of each coded allele */
    int *NumAlleles;              /*NUMLOCI: number of alleles at each locus */

    /* only used for recessive or inbreeding models: */
    int *PreGeno=
        NULL;           /*NUMINDSxLINESxNUMLOCI; diploid genotype if recessive alleles */
    int *Recessive=
        NULL;         /*NUMLOCI recessive allele at each locus, or -1 if there is none */


    /*Basic parameters */
    int *Z;                       /*NUMINDSx2xNUMLOCI: Z=pop of origin for each allele */
    int *Z1;
    float *Q;                    /*NUMINDSxMAXPOPS:  Q=ancestry of individuals */
    float *P;                    /*NUMLOCIxMAXPOPSxMAXALLELES: P=population allele freqs */
    float *Epsilon;              /*NUMLOCIxMAXALLELES: Dirichlet parameter for allele
                                  frequencies. This is either LAMBDA (if uncorrelated), or
                                  ancestral allele freqs if they are correlated */
    float *Fst;          /*MAXPOPS: Factor multiplied by epsilon under the Fst model */
    float *Alpha;                /*MAXPOPS: Dirichlet parameter for degree of admixture.
                                  Start this at ALPHA, and possibly change
                                  (if INFERALPHA==1) */
    float *lambda;                /*Dirichlet prior parameter for allele frequencies;
                                   start this at LAMBDA, and update if INFERLAMBDA*/
    float *sumlambda;
    /*Summaries */
    int    *NumLociPop;           /*NUMINDSxMAXPOPS: Number of alleles from each pop (by ind) */
    float *PSum;                 /*NUMLOCIxMAXPOPSxMAXALLELES: sum of AlFreqs */
    float *QSum;                 /*NUMINDSxMAXPOPS:  sum of Ancestries */
    float *FstSum;               /*MAXPOPS:  Sum of Fst */
    float *SumEpsilon=
        NULL;      /*NUMLOCIxMAXALLELES: sum of ancestral allele freqs*/
    float *sumAlpha;              /*MAXPOPS*/
    float *sumR;                 /*NUMINDS */
    float *varR;                 /*NUMINDS */
    float recomblikelihood=0.0;
    float *like;                  /*current likelihood value */
    float *sumlikes;              /*sum of likelihood values */
    float *sumsqlikes;            /*sum of squared likelihoods */

    int *popflags; /*The populationflags of individuals*/
    unsigned int *randGens;


    /*Melissa added 7/12/07 for calculating DIC*/
    float *sumIndLikes, *indLikesNorm;

    int    *AncestDist=
        NULL;      /*NUMINDS*MAXPOPS*NUMBOXES histogram of Q values */
    float *UsePopProbs=
        NULL;     /*NUMINDS*MAXPOPS*(GENSBACK+1) This is used when the
                                  population info is used.  It stores the probability that an
                                  individual has each of a specified set of ancestry amounts */
    /*loop variables-------------- */
    int rep;                      /*MCMC iterations so far */
    int savefreq;                 /*frequency of saving to file */
    int ind;

    /*Melissa's new variables added 7/12/07 to use priors based on sampling location*/
    float *LocPrior=NULL, *sumLocPrior=NULL, LocPriorLen=0;

    /* ======================= GPU Structure ======================== */
    /*Dict to that keeps track of CL info */
    /*CLDict *clDict = NULL;*/
    float * randomArr; /* array of random numbers */
    int POPFLAGINDS = 0;
    float invsqrtnuminds;
    /* enum BUFFER buffers[5]; */
    /* char         *names[5]; */
    /* size_t        sizes[5]; */
    /* void         *dests[5]; */

    float  *reduceresult;
    int *Numafrompopscl;
    int *Numlocipopscl;

    if (signal(SIGINT, catch_function) == SIG_ERR) {
        fputs("An error occurred while setting a signal handler.\n", stderr);
        return EXIT_FAILURE;
    }

    clDict = malloc(sizeof (*clDict));
    sumlikes = calloc(1,sizeof(float));
    sumsqlikes = calloc(1,sizeof(float));
    like = calloc(1,sizeof(float));
    /*=====Code for getting started=============================*/

    Welcome (stdout);             /*welcome */
    GetParams (0,argc,argv);      /*read in parameter values */

    CheckParamCombinations();     /*check that some parameter combinations are valid*/

    Mapdistance = calloc (NUMLOCI, sizeof (float));
    Phase = calloc (NUMLOCI * NUMINDS, sizeof (float));


    if (LINES ==2 && PHASED ==0) {
        Phasemodel=calloc(NUMINDS,sizeof(int));
        for (ind=0; ind<NUMINDS; ind++) {
            if (MARKOVPHASE) {
                Phasemodel[ind]=0;
            } else {
                Phasemodel[ind]=1;
            }
        }
    }

    lambda=calloc(MAXPOPS, sizeof (float));
    sumlambda=calloc(MAXPOPS, sizeof (float));

    Markername = calloc (GENELEN*NUMLOCI, sizeof (char));
    Geno = calloc (LINES * NUMLOCI * NUMINDS, sizeof (int));
    if (RECESSIVEALLELES) {
        PreGeno = calloc (LINES * NUMLOCI * NUMINDS, sizeof (int));
        Recessive = calloc (NUMLOCI, sizeof (int));
        if (PreGeno == NULL || Recessive == NULL) {
            printf ("Error (3) in assigning memory\n");
            Kill ();
        }
    }

    Individual = calloc (NUMINDS, sizeof (struct IND));
    if (Geno == NULL || Individual == NULL || Mapdistance == NULL
            || Markername == NULL) {
        printf ("Error in assigning memory (not enough space?)\n");
        Kill ();
    }
    Randomize(RANDOMIZE, &SEED);

    /*read in data file */
    if (RECESSIVEALLELES) {
        ReadInputFile(PreGeno, Mapdistance, Markername, Individual, Phase, Recessive);
    } else {
        ReadInputFile (Geno, Mapdistance, Markername, Individual, Phase, Recessive);
    }

    if (RECESSIVEALLELES) {
        MAXALLELES = FindMaxAlleles (PreGeno, Recessive);
    } else {
        MAXALLELES = FindMaxAlleles (Geno, Recessive);
    }


    /*=============set aside memory space=====================*/
    Translation = calloc (NUMLOCI * MAXALLELES, sizeof (int));
    NumAlleles = calloc (NUMLOCI, sizeof (int));
    Z = calloc (NUMINDS * LINES * NUMLOCI, sizeof (int));
    Z1 = calloc (NUMINDS * LINES * NUMLOCI, sizeof (int));
    Q = calloc (NUMINDS * MAXPOPS, sizeof (float));
    P = calloc (NUMLOCI * MAXPOPS * MAXALLELES, sizeof (float));
    R = calloc (NUMINDS, sizeof (float));
    sumR = calloc (NUMINDS, sizeof (float));
    varR = calloc (NUMINDS, sizeof (float));
    Epsilon = calloc (NUMLOCI * MAXALLELES, sizeof (float));
    if (FREQSCORR) {
        SumEpsilon = calloc (NUMLOCI * MAXALLELES, sizeof (float));
    }
    Fst = calloc (MAXPOPS, sizeof (float));
    FstSum = calloc (MAXPOPS, sizeof (float));
    NumLociPop = calloc (NUMINDS * MAXPOPS, sizeof (int));
    PSum = calloc (NUMLOCI * MAXPOPS * MAXALLELES, sizeof (float));
    QSum = calloc (NUMINDS * MAXPOPS, sizeof (float));


    if (ANCESTDIST) {
        AncestDist = calloc (NUMINDS * MAXPOPS * NUMBOXES, sizeof (int));
    }
    if (USEPOPINFO) {
        UsePopProbs = calloc (NUMINDS * MAXPOPS * (GENSBACK + 1), sizeof (float));
    }

    /*Melissa added 7/12/07*/
    if (LOCDATA>0 || LOCISPOP) {
        GetNumLocations(Individual);
    }

    /*Allocate the LocPrior vector.
      For no-admixture, it contains r, and the vectors nu and gamma.
      For admixture, it contains gamma.  The alphas_locals are stored with alpha global*/
    if (LOCPRIOR) {
        if (NOADMIX) {
            LocPriorLen = 1+MAXPOPS*(NUMLOCATIONS+1);
        } else {
            LocPriorLen=1;
        }
        LocPrior = malloc(LocPriorLen*sizeof(float));
        sumLocPrior = malloc(LocPriorLen*sizeof(float));
    }

    if (LOCPRIOR && NOADMIX==0) {
        Alpha = malloc(MAXPOPS*(NUMLOCATIONS+1)*sizeof(float));
        sumAlpha = malloc(MAXPOPS*(NUMLOCATIONS+1)*sizeof(float));
    } else {
        Alpha = calloc(MAXPOPS, sizeof (float));
        sumAlpha = calloc(MAXPOPS, sizeof (float));
    }

    /* this is for DIC */
    sumIndLikes = malloc(NUMINDS*sizeof(float));
    indLikesNorm = malloc(NUMINDS*sizeof(float));

    if ((Translation == NULL) || (NumAlleles == NULL) || (Z == NULL)
            || (Z1 == NULL) || (Q == NULL) ||
            (P == NULL) || (R == NULL) || (sumR == NULL) || (varR == NULL)
            || (Epsilon == NULL) ||
            (Fst == NULL) || (NumLociPop == NULL) ||
            (PSum == NULL) || (QSum == NULL) ||  (FstSum == NULL) ||
            ((ANCESTDIST) && (AncestDist == NULL)) ||
            ((USEPOPINFO) && (UsePopProbs == NULL))||(Alpha == NULL)||(sumAlpha==NULL)||
            ((FREQSCORR) && (SumEpsilon == NULL)) ||
            (LocPriorLen>0 && (LocPrior==NULL || sumLocPrior==NULL)) ||
            sumIndLikes==NULL || indLikesNorm==NULL) {

        printf ("Error in assigning memory (not enough space?)\n");
        FreeAll(Mapdistance, Phase, Phasemodel, lambda, sumlambda, Markername, Geno,
                PreGeno, Recessive,
                Individual, Translation, NumAlleles, Z, Z1, Q, P,  R, sumR, varR, Epsilon,
                SumEpsilon,
                Fst, FstSum, NumLociPop, PSum, QSum,  AncestDist, UsePopProbs, LocPrior,
                sumLocPrior, Alpha, sumAlpha, sumIndLikes, indLikesNorm, clDict);
        Kill ();
    }
    /*=========done setting aside memory space=====================*/

    /*initialize variables and arrays */
    Initialization (Geno, PreGeno, Individual, Translation, NumAlleles, Z, Z1,
                    Epsilon, SumEpsilon,
                    Fst, PSum, Q, QSum, FstSum, AncestDist, UsePopProbs, Alpha,
                    sumAlpha, sumR, varR, sumlikes, sumsqlikes, &savefreq, R, lambda,
                    sumlambda,Phase,Recessive, LocPrior, sumLocPrior, LocPriorLen, sumIndLikes,
                    indLikesNorm, clDict);

    /* ==================== GPU Structure ==================== */

    /*Allocate an array of random numbers. Primarily used so that we can compare
     CL implementation to the original */
    randomArr = calloc(RANDSIZE,sizeof(float));
    randGens = calloc(NUMRANDGENS,sizeof(unsigned int));

    Numafrompopscl = calloc(NUMLOCI*MAXPOPS*MAXALLELES,sizeof(int));
    Numlocipopscl = calloc(NUMINDS*MAXPOPS,sizeof(int));

    /* ====== OpenCL initialized ====== */

    printf ("\n\n--------------------------------------\n\n");
    printf ("Finished initialization; starting MCMC \n");
    printf ("%d iterations + %d burnin\n\n", NUMREPS, BURNIN);

    /*=====Main MCMC loop=======================================*/

    writeBuffer(clDict,Numafrompopscl,sizeof(int) * NUMLOCI*MAXPOPS*MAXALLELES,NUMAFROMPOPSCL,"NumAFromPops");
    writeBuffer(clDict,Numlocipopscl,sizeof(int)*NUMINDS*MAXPOPS,NUMLOCIPOPSCL,"NUMLOCIPOPS");
    /* init buffers on GPU */
    writeBuffer(clDict,P,sizeof(float) * PSIZE,PCL,"P");
    writeBuffer(clDict,Z,sizeof(int)*ZSIZE,ZCL,"Z");
    writeBuffer(clDict,Q, sizeof(float) * QSIZE,QCL, "Q");
    writeBuffer(clDict,NumAlleles,sizeof(int) * NUMLOCI,NUMALLELESCL,"NumAlleles");
    writeBuffer(clDict,lambda,sizeof(float) * MAXPOPS,LAMBDACL,"LAMBDA");
    if(!RECESSIVEALLELES){
        writeBuffer(clDict,Geno,sizeof(int)*GENOSIZE,GENOCL,"Geno");
    }

    popflags = calloc(NUMINDS,sizeof(int));
    for(ind = 0; ind < NUMINDS;ind++){
        popflags[ind] = Individual[ind].PopFlag;
        if (!((USEPOPINFO) && (Individual[ind].PopFlag))) {
            POPFLAGINDS++;
        }
    }

    printf("Setting updatealpha arg\n");
    setKernelArgExplicit(clDict,UpdateAlphaKernel,sizeof(int),&POPFLAGINDS,7);

    printf("Setting invsqrtnuminds arg\n");
    invsqrtnuminds = 1.0/sqrt(NUMINDS);
    setKernelArgExplicit(clDict,NonIndUpdateEpsilonKernel,sizeof(float),&invsqrtnuminds,6);

    writeBuffer(clDict,popflags,sizeof(int)*NUMINDS,POPFLAGCL,"popflags");

    writeBuffer(clDict,Alpha,sizeof(float) *MAXPOPS,ALPHACL,"Alpha");
    reduceresult = calloc(NUMINDS*NUMLOCI*MAXGROUPS,sizeof(float));
    if(reduceresult == NULL){
        printf("Failed to allocate reduce result\n");
    }
    printf("Writing reduce results\n");
    writeBuffer(clDict,reduceresult,sizeof(float)*MAXGROUPS*NUMINDS*NUMLOCI,REDUCERESULTSCL,"result");
    printf("Done writing reduce results\n");

    writeBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
    writeBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");

    writeBuffer(clDict,like, sizeof(float),LIKECL, "like");
    writeBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
    writeBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");

    writeBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "qsum");
    writeBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "psum");
    writeBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
    if(ANCESTDIST){
        writeBuffer(clDict,AncestDist, sizeof(int)*NUMINDS*MAXPOPS*NUMBOXES,ANCESTDISTCL, "ancest dist");
    }

    if (FREQSCORR) {
        writeBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST");
        writeBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
        writeBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,
                    "EPSILON");
    }
    /*printf("%d, %d\n",INFERALPHA,INFERLAMBDA);*/
    /*printf("%d\n",USEPOPINFO);*/
    /*printf("%d\n",RECESSIVEALLELES);*/
    /*printf("%d\n",LINKAGE);*/
    /*printf("%d\n",COMPUTEPROB);*/
    /*printf("%d\n",POPALPHAS);*/
    /*printf("%d\n",NOADMIX);*/
    /*printf("%d\n",LOCPRIOR);*/
    /*handleCLErr(1,clDict,"heyhey");*/

    /*Initialize Q */
    initQ(Q);
    initRandGens(clDict,randGens);
    finishWaitList(clDict);
    printf("Waitlist finished!\n");
    for (rep = 0; rep < (NUMREPS + BURNIN); rep++) {
        breakP(clDict);

        /*FillArrayWithRandomCL(clDict,randomArr,NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM);*/
        /*FillArrayWithRandom(randomArr,NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM);*/
        /*FillArrayWithRandom(randomArr,RANDSIZE);*/

        /* if(DEBUGCOMPARE) { */
        /*     readBuffer(clDict,randomArr, */
        /*             sizeof(float) * NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM,RANDCL, */
        /*             "randomArr"); */
        /*     comparePCLandP(clDict,P,Epsilon, Fst, NumAlleles, Geno, Z, */
        /*                    lambda, Individual, randomArr); */
        /* } */
        /* if (USEWORKINGCL) { */
            /* clear buffer */
            writeBuffer(clDict,Numafrompopscl,sizeof(int) * NUMLOCI*MAXPOPS*MAXALLELES,NUMAFROMPOPSCL,"NumAFromPops");
            UpdatePCL (clDict,P, Epsilon, Fst, NumAlleles, Geno, Z, lambda,
                       Individual,
                       randomArr);
        /* }  else { */
        /*     readBuffer(clDict,randomArr, */
        /*             sizeof(float) * NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM,RANDCL, */
        /*             "randomArr"); */
        /*     UpdateP (P, Epsilon, Fst, NumAlleles, Geno, Z, lambda, Individual, */
        /*              randomArr); */
        /* } */

        /* Update Q */
        /*FillArrayWithRandomCL(clDict,randomArr,NUMINDS+NUMINDS*MAXRANDOM);*/
        if (LINKAGE && rep >= ADMBURNIN) {
            UpdateQMetroRecombine (Geno, Q, Z, P, Alpha, rep,
                                   Individual, Mapdistance, R, Phase,Phasemodel,randomArr);
        } else {
            writeBuffer(clDict,Numlocipopscl,sizeof(int)*NUMINDS*MAXPOPS,NUMLOCIPOPSCL,"NUMLOCIPOPS");
            UpdateQCL (clDict,Geno, PreGeno, Q, P, Z, Alpha, rep, Individual, UsePopProbs,
                     Recessive, LocPrior,randomArr);
        }

        if (LOCPRIOR && UPDATELOCPRIOR) {
            UpdateLocPrior(Q, LocPrior, Alpha, Individual);
        }

        if (RECESSIVEALLELES) {
            UpdateGeno (PreGeno, Geno, P, Z, Recessive, NumAlleles, Q);
            writeBuffer(clDict,Geno,sizeof(int) * GENOSIZE,GENOCL,"Geno");
            /*The Zs are not correct after UpdateGeno, until UpdateZ is run */
        }

        if (LINKAGE && rep > ADMBURNIN) {
            if (!INDIVIDUALR) {
                recomblikelihood = UpdateZandSingleR(Z,  Q, P, Geno,
                                                     R, Mapdistance, rep, Phase, Z1,Phasemodel, rep+1 > BURNIN? sumIndLikes : NULL,
                                                     indLikesNorm);
            } else {
                recomblikelihood = UpdateZandR(Z,  Q, P, Geno, R,
                                               Mapdistance, rep, Phase, Z1,Phasemodel, rep+1 > BURNIN ? sumIndLikes:NULL,
                                               indLikesNorm);
            }
        } else {
            /*FillArrayWithRandomCL(clDict,randomArr,NUMINDS*NUMLOCI*LINES);*/
            /* if (DEBUGCOMPARE) { */
            /*     readBuffer(clDict,randomArr, */
            /*             sizeof(float) * NUMINDS*NUMLOCI*LINES,RANDCL, */
            /*             "randomArr"); */
            /*     compareZCLandZ(clDict,Z,Q,P,Geno,randomArr); */
            /* } */
            /* if (USEWORKINGCL) { */
                UpdateZCL (clDict,Z,  Q, P, Geno,randomArr);
                /* Not needed */
                /*readBuffer(clDict,Z,sizeof(int)*ZSIZE,ZCL,"Z");*/
            /* } else { */
            /*     readBuffer(clDict,randomArr, */
            /*             sizeof(float) * NUMINDS*NUMLOCI*LINES,RANDCL, */
            /*             "randomArr"); */
            /*     UpdateZ (Z,  Q, P, Geno,randomArr); */
            /* } */
            /*      printf("done updatez alpha[2]=%e\n", Alpha[2]); */
        }


        if (LOCPRIOR && NOADMIX==0) {
            UpdateAlphaLocPrior(Q, Alpha, LocPrior, Individual);
        } else if (INFERALPHA) {

            UpdateAlphaCL (clDict,Q, Alpha, Individual, rep,POPFLAGINDS);

            /* readBuffer(clDict,Q, sizeof(float) * QSIZE,QCL, "Q"); */
            /* readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */

            /* UpdateAlpha(Q, Alpha, Individual, rep); */

            /* writeBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */
        }

        if (INFERLAMBDA) {
            readBuffer(clDict,P,sizeof(float) * PSIZE,PCL,"P");
            if  (POPSPECIFICLAMBDA) {
                UpdatePopLambda(P,lambda,NumAlleles);
            } else {
                UpdateLambda (P,Epsilon,lambda, NumAlleles);
            }
            writeBuffer(clDict,lambda,sizeof(float) * MAXPOPS,LAMBDACL,"LAMBDA");
        }

        if (FREQSCORR) {
            UpdateEpsilonCL(clDict,P,Epsilon,Fst,NumAlleles,lambda[0]);

            UpdateFstCL (clDict,Epsilon, Fst, P, NumAlleles);

            /* readBuffer(clDict,P, sizeof(float) * PSIZE,PCL, "P"); */
            /* readBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST"); */
            /* readBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,"eps"); */

            /* UpdateEpsilon(P,Epsilon,Fst,NumAlleles,lambda[0]); */

            /* UpdateFst (Epsilon, Fst, P, NumAlleles); */

            /* writeBuffer(clDict,Epsilon,sizeof(float) * NUMLOCI*MAXALLELES,EPSILONCL,"eps"); */
            /* writeBuffer(clDict,Fst,sizeof(float) * MAXPOPS,FSTCL,"FST"); */
        }

        /*====book-keeping stuff======================*/
        if (rep + 1 > BURNIN) {
            /*buffers[0] = PCL;
            names[0] = "P"; dests[0] = P; sizes[0] = sizeof(float) * PSIZE;
            buffers[1] = QCL;
            names[1] = "Q"; dests[1] = Q; sizes[1] = sizeof(float) * QSIZE;

            readBuffers(clDict,dests,sizes,buffers,names,2);*/
            /*readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
            if(rep % 100 == 0){
            printf("%f",Alpha[0]);
            }*/
            DataCollectionCL (clDict,Geno, PreGeno, Q, QSum, Z, Z1,  P, PSum,
                            Fst, FstSum, NumAlleles,
                            AncestDist, Alpha, sumAlpha, sumR, varR, like,
                            sumlikes, sumsqlikes, R, Epsilon,SumEpsilon,recomblikelihood,
                            lambda, sumlambda, Recessive, LocPrior, sumLocPrior, LocPriorLen, sumIndLikes,
                            indLikesNorm, rep);
        }


        if ((savefreq) && ((rep + 1) > BURNIN)
                && (((rep + 1 - BURNIN) % savefreq) == 0)
                && ((rep + 1) != NUMREPS + BURNIN)) {
            /* readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha"); */
            readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
            readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
            readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
            readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
            readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
            readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
            readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlike");
            readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            OutPutResults (Geno, rep + 1, savefreq, Individual, PSum, QSum,
                           FstSum, AncestDist, UsePopProbs, *sumlikes,
                           *sumsqlikes, sumAlpha, sumR, varR,
                           NumAlleles, Translation, 0, Markername, R,
                           SumEpsilon,
                           lambda,sumlambda,sumLocPrior, LocPriorLen,
                           sumIndLikes, indLikesNorm, argc,argv);
        }


        if (PRINTLIKES) {
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            PrintLike (*like, rep, Geno, PreGeno, Q, P,recomblikelihood);
        }

        if (((rep + 1) % UPDATEFREQ) == 0) {
            readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
            readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
            readBuffer(clDict,like, sizeof(float),LIKECL, "like");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlike");
            readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            /*readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
            readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
            readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
            readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
            readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
            readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");*/
            PrintUpdate (rep + 1, Geno, PreGeno, Alpha, Fst, P, Q, *like,
                         *sumlikes, *sumsqlikes, NumAlleles, R, lambda,Individual,
                         recomblikelihood, Recessive, LocPrior, LocPriorLen);
        }
        finishWaitList(clDict);
    }

    /*====final book-keeping====================================*/
    if ((rep % UPDATEFREQ) != 0) {
        readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
        readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
        readBuffer(clDict,like, sizeof(float),LIKECL, "like");
        readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
            readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");
        /*readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
        readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
        readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
        readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
        readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
        readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");*/
        PrintUpdate (rep, Geno, PreGeno, Alpha, Fst, P, Q, *like, *sumlikes,
                     *sumsqlikes, NumAlleles,R, lambda, Individual,recomblikelihood,
                     Recessive, LocPrior, LocPriorLen);
    }


    readBuffer(clDict,Alpha, sizeof(float) * MAXPOPS,ALPHACL, "alpha");
    readBuffer(clDict,Fst, sizeof(float) * MAXPOPS,FSTCL, "fst");
    readBuffer(clDict,sumAlpha, sizeof(float) * MAXPOPS,ALPHASUMCL, "alphasum");
    readBuffer(clDict,sumlambda, sizeof(float) * MAXPOPS,LAMBDASUMCL, "lambdasum");
    readBuffer(clDict,FstSum, sizeof(float) * MAXPOPS,FSTSUMCL, "fstsum");
    readBuffer(clDict,QSum, sizeof(float) * QSIZE,QSUMCL, "Qsum");
    readBuffer(clDict,PSum, sizeof(float) * PSIZE,PSUMCL, "Psum");
    readBuffer(clDict,SumEpsilon, sizeof(float) * NUMLOCI*MAXALLELES,EPSILONSUMCL, "epssum");
    readBuffer(clDict,like, sizeof(float),LIKECL, "like");
    readBuffer(clDict,sumsqlikes, sizeof(float),SUMSQLIKESCL, "sumsqlikes");
    readBuffer(clDict,sumlikes, sizeof(float),SUMLIKESCL, "sumlikes");
    OutPutResults (Geno, rep, savefreq, Individual, PSum, QSum,
                   FstSum, AncestDist, UsePopProbs,
                   *sumlikes, *sumsqlikes,
                   sumAlpha, sumR, varR, NumAlleles, Translation, 1,
                   Markername, R, SumEpsilon,
                   lambda,sumlambda,sumLocPrior, LocPriorLen,
                   sumIndLikes, indLikesNorm,
                   argc,argv);

    /*=====Closing everything down==============================*/
    FreeAll(Mapdistance, Phase, Phasemodel, lambda, sumlambda, Markername, Geno,
            PreGeno, Recessive,
            Individual, Translation, NumAlleles, Z, Z1, Q, P, R, sumR, varR, Epsilon,
            SumEpsilon,
            Fst, FstSum, NumLociPop, PSum, QSum,  AncestDist, UsePopProbs, LocPrior,
            sumLocPrior, Alpha, sumAlpha, sumIndLikes, indLikesNorm, clDict);
    free(randomArr);
    free(randGens);
    free(like);
    free(sumsqlikes);
    free(sumlikes);
    free(reduceresult);
    printf("Structure seed: %d\n", SEED);
    return (0);
}
void LidarSegmentationWidget::SharedConstructor()
{
  // Setup the GUI and connect all of the signals and slots
  setupUi(this);

  this->ProgressDialog = new QProgressDialog();
  this->ProgressDialog->setMinimum(0);
  this->ProgressDialog->setMaximum(0);
  this->ProgressDialog->setWindowModality(Qt::WindowModal);
  connect(&this->FutureWatcher, SIGNAL(finished()), this, SLOT(slot_SegmentationComplete()));
  connect(&this->FutureWatcher, SIGNAL(finished()), this->ProgressDialog , SLOT(cancel()));
  
  // Global settings
  this->Flipped = false;
  this->Debug = true;
  
  // Qt connections
  // connect( this->sldHistogramBins, SIGNAL( valueChanged(int) ), this, SLOT(sldHistogramBins_valueChanged()));
  connect( this->sldLambda, SIGNAL( valueChanged(int) ), this, SLOT(UpdateLambda()));
  connect( this->txtLambdaMax, SIGNAL( textEdited(QString) ), this, SLOT(UpdateLambda()));

  // Setup backgrounds
  this->BackgroundColor[0] = 0;
  this->BackgroundColor[1] = 0;
  this->BackgroundColor[2] = .5;

  // Left pane
  this->OriginalImageData = vtkSmartPointer<vtkImageData>::New();
  this->OriginalImageSliceMapper = vtkSmartPointer<vtkImageSliceMapper>::New();
  this->OriginalImageSliceMapper->SetInputData(this->OriginalImageData);
  this->OriginalImageSlice = vtkSmartPointer<vtkImageSlice>::New();
  // Make the pixels sharp instead of blurry when zoomed
  this->OriginalImageSlice->GetProperty()->SetInterpolationTypeToNearest();
  this->OriginalImageSlice->SetMapper(this->OriginalImageSliceMapper);

  this->LeftStack = vtkSmartPointer<vtkImageStack>::New();
  this->LeftStack->AddImage(this->OriginalImageSlice);
  
  this->LeftRenderer = vtkSmartPointer<vtkRenderer>::New();
  this->LeftRenderer->GradientBackgroundOn();
  this->LeftRenderer->SetBackground(this->BackgroundColor);
  this->LeftRenderer->SetBackground2(1,1,1);
  this->qvtkWidgetLeft->GetRenderWindow()->AddRenderer(this->LeftRenderer);

  this->LeftRenderer->AddViewProp(this->LeftStack);

  this->LeftInteractorStyle = vtkSmartPointer<vtkInteractorStyleScribble>::New();
  this->LeftInteractorStyle->AddObserver(this->LeftInteractorStyle->ScribbleEvent,
                                         this, &LidarSegmentationWidget::ScribbleEventHandler);
  this->LeftInteractorStyle->SetCurrentRenderer(this->LeftRenderer);
  this->qvtkWidgetLeft->GetInteractor()->SetInteractorStyle(this->LeftInteractorStyle);

  // Right pane
  this->ResultImageData = vtkSmartPointer<vtkImageData>::New();
  this->ResultImageSliceMapper = vtkSmartPointer<vtkImageSliceMapper>::New();
  this->ResultImageSliceMapper->SetInputData(this->ResultImageData);
  this->ResultImageSlice = vtkSmartPointer<vtkImageSlice>::New();
  this->ResultImageSlice->SetMapper(this->ResultImageSliceMapper);
  this->ResultImageSlice->VisibilityOff();
  this->RightStack = vtkSmartPointer<vtkImageStack>::New();

  this->RightStack->AddImage(this->ResultImageSlice);

  this->RightRenderer = vtkSmartPointer<vtkRenderer>::New();
  this->RightRenderer->GradientBackgroundOn();
  this->RightRenderer->SetBackground(this->BackgroundColor);
  this->RightRenderer->SetBackground2(1,1,1);
  this->qvtkWidgetRight->GetRenderWindow()->AddRenderer(this->RightRenderer);

  this->RightInteractorStyle = vtkSmartPointer<InteractorStyleImageNoLevel>::New();
  this->RightInteractorStyle->SetCurrentRenderer(this->RightRenderer);
  this->qvtkWidgetRight->GetInteractor()->SetInteractorStyle(this->RightInteractorStyle);

  // Both panes
  this->SourceSinkImageData = vtkSmartPointer<vtkImageData>::New();
  
  this->LeftSourceSinkImageSliceMapper = vtkSmartPointer<vtkImageSliceMapper>::New();
  this->LeftSourceSinkImageSliceMapper->SetInputData(this->SourceSinkImageData);
  
  this->LeftSourceSinkImageSlice = vtkSmartPointer<vtkImageSlice>::New();
  // Make the pixels sharp instead of blurry when zoomed
  this->LeftSourceSinkImageSlice->GetProperty()->SetInterpolationTypeToNearest(); 
  this->LeftSourceSinkImageSlice->SetMapper(this->LeftSourceSinkImageSliceMapper);

  this->LeftStack->AddImage(this->LeftSourceSinkImageSlice);

  this->RightSourceSinkImageSliceMapper = vtkSmartPointer<vtkImageSliceMapper>::New();
  this->RightSourceSinkImageSliceMapper->SetInputData(this->SourceSinkImageData);

  this->RightSourceSinkImageSlice = vtkSmartPointer<vtkImageSlice>::New();
  // Make the pixels sharp instead of blurry when zoomed
  this->RightSourceSinkImageSlice->GetProperty()->SetInterpolationTypeToNearest(); 
  this->RightSourceSinkImageSlice->SetMapper(this->RightSourceSinkImageSliceMapper);

  this->RightStack->AddImage(this->RightSourceSinkImageSlice);

  this->RightRenderer->AddViewProp(this->RightStack);
  
  // Default GUI settings
  this->radForeground->setChecked(true);

  // Setup toolbar
  // Open file buttons
  QIcon openIcon = QIcon::fromTheme("document-open");
  actionOpenImage->setIcon(openIcon);
  this->toolBar->addAction(actionOpenImage);

  UpdateLambda();
  
  // Save buttons
  QIcon saveIcon = QIcon::fromTheme("document-save");
  actionSaveSegmentation->setIcon(saveIcon);
  this->toolBar->addAction(actionSaveSegmentation);

  // Initialize GUI components
  //sldHistogramBins_valueChanged();
  //QTimer::singleShot(0, this, SLOT(sldHistogramBins_valueChanged()));
  //QTimer::singleShot(0, this, SLOT(sldHistogramBins_sliderMoved()));
  this->lblHistogramBins->setNum(this->sldHistogramBins->value());
  
  this->Image = ImageType::New();
}