示例#1
0
int randomEMinit(double **x, int n, int p, int nclass, double *pi,
		 double **Mu, double **LTSigma)
{
  int *ordr,i,j,*clas,*nc;
  /* This is a bug. Modified by Wei-Chen Chen on 2009/03/13.
    MAKE_VECTOR(ordr,n);
  */
  MAKE_VECTOR(ordr, nclass);
  MAKE_VECTOR(clas, n);
  MAKE_VECTOR(nc, nclass);
  do {
    /* This is a bug. Modified by Wei-Chen Chen on 2009/03/13.
      i=srswor(n, n, ordr);
    */
    i=srswor(n, nclass, ordr);
    for(i=0;i<nclass;i++){
      for(j=0;j<p;j++) Mu[i][j]=x[ordr[i]][j];
    }
    for(i=0;i<n;i++) clas[i]=assign_closest(x[i],p,nclass,Mu);
    j=initials(x,n,p,nclass,nc,Mu,LTSigma,clas);
  } while (j==0);
  for(i=0;i<nclass;i++) pi[i]=1.*nc[i]/n;
  FREE_VECTOR(nc);
  FREE_VECTOR(clas);
  FREE_VECTOR(ordr);
  return 0;
}
示例#2
0
文件: initials.c 项目: mum4k/cs50
/* Asks the user to enter their name and returns the initials.
 *
 * Returns 0 on success.
 */
int main(void)
{   
    char* result = initials(GetString());
    if (result == NULL)
    {
        printf("An error occurred!\n");
        return 1;
    }
    printf("%s\n", result);
    free(result);
    return 0;
}
示例#3
0
int
main(void)
{
    // ask for input until valid
    do
        name = GetString();
    while (check() == false);

    // initialize the name and output the answer
    initials();

    // free the heep
    free(name);

    return 0;
}
示例#4
0
/* This function is called by ss_shortems().
   Mu[0, ..., labK-1] should be assigned before calling this function.
*/
void ss_randomEMinit(double **x, int n, int p, int nclass, double *pi,
   double **Mu, double **LTSigma,
   int *lab, int labK, int nonlab_total, int *lab_index){
  int *ordr, i, j, *clas, *nc;
  int new_nclass = nclass - labK;
  double labMu[labK][p];
  
  for(i = 0; i < labK; i++){
    for(j = 0; j < p; j++) labMu[i][j] = Mu[i][j];
  }
  
  /* Initial centers for all other unknown clusters. */
  MAKE_VECTOR(ordr, new_nclass);
  MAKE_VECTOR(clas, n);
  MAKE_VECTOR(nc, nclass);
  do{
    for(i = 0; i < labK; i++){
      for(j = 0; j < p; j++) Mu[i][j] = labMu[i][j];
    }
    i = srswor(nonlab_total, new_nclass, ordr);
    for(i = labK; i < nclass; i++){
      for(j = 0; j < p; j++) Mu[i][j] = x[lab_index[ordr[i - labK]]][j];
    }
    for(i = 0; i < n; i++){
      if(lab[i] == -1){
        clas[i] = assign_closest(x[i], p, nclass, Mu);
      } else{
        clas[i] = lab[i];
      }
    } 
    j = initials(x, n, p, nclass, nc, Mu, LTSigma, clas);
  } while(j == 0);
  for(i = 0; i < nclass; i++) pi[i] = 1. * nc[i] / n;
  FREE_VECTOR(nc);
  FREE_VECTOR(clas);
  FREE_VECTOR(ordr);
} /* End of ss_randomEMinit(). */
示例#5
0
文件: sym.c 项目: EtchedPixels/FUZIX
/**
 * declare a static variable
 * @param type
 * @param storage
 * @param mtag tag of struct whose members are being declared, or zero
 * @param otag tag of struct object being declared. only matters if mtag is non-zero
 * @param is_struct struct or union or no meaning
 * @return 1 if a function was parsed
 */
int declare_global(int type, int storage, TAG_SYMBOL *mtag, int otag, int is_struct) {
    int     dim, identity;
    char    sname[NAMESIZE];

    FOREVER {
        FOREVER {
            if (endst ())
                return 0;
            dim = 1;
            if (match ("*")) {
                identity = POINTER;
            } else {
                identity = VARIABLE;
            }
            if (!symname (sname))
                illname ();
            if (match ("(")) {
                /* FIXME: We need to deal with pointer types properly here */
                if (identity == POINTER)
                    type = CINT;
                newfunc_typed(storage, sname, type);
                /* Can't int foo(x){blah),a=4; */
                return 1;
            }
            /* FIXME: we need to deal with extern properly here */
            if (find_global (sname) > -1)
                multidef (sname);
            if (identity == VARIABLE)
                notvoid(type);
            if (match ("[")) {
                dim = needsub ();
                //if (dim || storage == EXTERN) {
                    identity = ARRAY;
                //} else {
                //    identity = POINTER;
                //}
            }
            // add symbol
            if (mtag == 0) { // real variable, not a struct/union member
                identity = initials(sname, type, identity, dim, otag);
                add_global (sname, identity, type, (dim == 0 ? -1 : dim), storage);
                if (type == STRUCT) {
                    symbol_table[current_symbol_table_idx].tagidx = otag;
                }
                break;
            } else if (is_struct) {
                // structure member, mtag->size is offset
                add_member(sname, identity, type, mtag->size, storage);
                // store (correctly scaled) size of member in tag table entry
                if (identity == POINTER)
                    type = CINT;
                scale_const(type, otag, &dim);
                mtag->size += dim;
            }
            else {
                // union member, offset is always zero
                add_member(sname, identity, type, 0, storage);
                // store maximum member size in tag table entry
                if (identity == POINTER)
                    type = CINT;
                scale_const(type, otag, &dim);
                if (mtag->size < dim)
                    mtag->size = dim;
            }
        }
        if (!match (","))
            return 0;
    }
}
示例#6
0
 int runge(double EPS, const char*filename)
{
    struct vect v; // основной вектор координат
	struct vect k[DIM]; // числа Рунгe

	//*инициализация чисел Рунге */
	for (int i=0;i<DIM;i++)
    	init(k + i,RK_NUM);
    
    /* Вектор функций и расчётные коэффициенты */
    double (*f[DIM]) (struct vect v, double t);
	struct vect a, p, pp; 
	struct vect b[RK_NUM];

	/* инициализация вектора функций и коэффициентов */
	Create_Vect_func(f); //
	RK_koeff(b,&a,&p,&pp);


    double h = H_0; // шаг
    double t = 0; // время
	
    double errflag = 0;

    
    FILE *file = fopen(filename, "w");

    if (file == NULL) errflag = -1;
    else{
        fprintf(file, "t \t x \t y\n");

        /* вводим начальные условия */
        initials(&v);
        printf("%d\n",a.length);
        print(v);
        		//runge_step(&h,v,t, f, b, a, k);// вводим начальные значения чисел Рунге
	    
	    //h = new_h(EPS,h,k,v); // обновляем шаг
        
        //new_k(h,k,x,y,u,v); // ежели он изменился -- обновим числа Рунге

        for (t = 0;t<=WORK_TIME+h;t+=h){
            // если мы в нужной точке T, 3T/4, T/2, T/4, то flag == 1 

        	/* обновим координаты */

    
    /*    	

    		fprintf(file, "%e", t);
            fprint(v,file);
            fprintf(file, "\n");
    */
            h = new_step( EPS,  h,  t,  v,  k,  a,  b,  p,  pp, f);
			
			/* обновляем числа Рунге */
    

//   printf("(!)\n" );
            fprintf(file, "%e", t);
            fprint(v,file);
            fprintf(file, "\n");


            runge_step(h,v,t, f, b, a, k);

            new_parametrs(h,t,&v,k,p);

            if (h<H_DEFAULT) {errflag = -3; break;} // на случай особых точек
        }
    }
    printf("final step = %e;\n", h);
    fclose(file);
    return errflag;
}
示例#7
0
// ********* MAIN ************
int main()
{
	struct initializations init = initials();

	truncate_file();

	// spacetime
	Metric metric(init.m, init.a, init.q);
	cout << endl << metric.name << ":" << endl
		<< "m = " << metric.m << endl
		<< "a = " << metric.a << endl
		<< "q = " << metric.q << endl
		<< endl;

	// emfield
	EMField emfield(metric);

	// particle
	init.u[init.change] = find_u(metric, &init, init.x, init.u);
	Particle initparticle(0, init.teilchen_masse, init.teilchen_ladung,
		init.x, init.u, metric);

	// spectrum
	myfloat emin = 2.0;
	myfloat emax = 13.0;
	myfloat start_u0 = initparticle.u[0];
	vector<myfloat> freqmult(10000);
	for (unsigned i = 0; i < freqmult.size(); i++){
		// E = u0 * freqmult
		myfloat energy = i * (emax - emin) / freqmult.size() + emin;
		freqmult[i] = energy / start_u0;
	}
	Spectrum spec(freqmult, &metric);

	ofstream specfile("globalspec.dat");
	specfile << scientific;


	// per-ray data
	int nrays;
	for (nrays = init.nrays - 1; nrays >= 0; nrays--) {
		cout << "===========================================" << endl
			<< "Ray index: " << nrays << endl
			<< endl;
		// particle
		Particle particle(0, init.teilchen_masse, init.teilchen_ladung,
				init.x, init.u, metric);
		init.change = 1;
		init.umin = init.umin_inc;
		init.umax = init.umax_inc;
		particle.u[0] = start_u0;
		particle.u[3] = init.u[3] + nrays * init.u3_inc;
		particle.u[init.change] = find_u(metric, &init, particle.x,
				particle.u);

		cout << endl;
		for (unsigned mu = 0; mu < metric.dim; mu++) {
			cout << "x" << mu << " = " << particle.x[mu] << '\t';
			cout << "u" << mu << " = " << particle.u[mu] << endl;
		}
		cout << endl;

		stringstream nrays_str;
		nrays_str << nrays;
		string plotfilename;
		plotfilename = "globalplot.dat/plot";
		plotfilename += nrays_str.str();
		plotfilename += ".dat";

		// Iterate
		absorb = 0;
		go_ray(init, spec, metric, particle, emfield, plotfilename);

		cout << endl;
		for (unsigned mu = 0; mu < metric.dim; mu++) {
			cout << "x" << mu << " = " << particle.x[mu] << '\t';
			cout << "u" << mu << " = " << particle.u[mu] << endl;
		}
		cout << endl;

		if (absorb && (absorb != absorb_max)){
			cerr << "Error detected" << endl;
			exit(1);
		}

		cout << endl;
	}


	for (unsigned i = 0; i < spec.cnts.size(); i++){
		specfile << freqmult[i] * start_u0 << '\t'
			<< spec.cnts[i] << endl;
	}
	specfile.close();


	return 0;
}
    double ParallelOptimize::optimize(stereo_base::Depth &result, const int max_iter) const {
        typedef CompactLabelSpace Space;
        typedef ParallelFusionPipeline<Space> Pipeline;

        bool victorMethod = true;
        result.initialize(width, height, -1);
        const int kFusionSize = 4;

        ParallelFusionOption pipelineOption;
        pipelineOption.num_threads = num_threads + 1;
        pipelineOption.max_iteration = model->nLabel / num_threads / kFusionSize * max_iter;
        const int kLabelPerThread = model->nLabel / pipelineOption.num_threads;

        Pipeline::GeneratorSet generators((size_t)pipelineOption.num_threads);
        Pipeline::SolverSet solvers((size_t)pipelineOption.num_threads);
        vector<Space> initials((size_t)pipelineOption.num_threads);
        vector<ThreadOption> threadOptions((size_t)pipelineOption.num_threads);

        vector<vector<int> > labelSubSpace;
        splitLabel(labelSubSpace);

        const int kPix = model->width * model->height;

        //slave threads
        const int kOtherThread = std::min(num_threads-1, 1);
        for(auto i=0; i<pipelineOption.num_threads - 1; ++i){
            const int startid = labelSubSpace[i].front();
            initials[i].init(kPix, vector<int>(1, startid));
            threadOptions[i].kTotal = kFusionSize + kOtherThread;
            threadOptions[i].kOtherThread = kOtherThread;
            threadOptions[i].solution_exchange_interval = 1;
            if(multiway) {
                generators[i] = shared_ptr<ProposalGenerator<Space> >(new MultiwayStereoGenerator(kPix, labelSubSpace[i]));
                solvers[i] = shared_ptr<FusionSolver<Space> >(new MultiwayStereoSolver(model));
            }else{
                generators[i] = shared_ptr<ProposalGenerator<Space> >(new SimpleStereoGenerator(kPix, labelSubSpace[i]));
                solvers[i] = shared_ptr<FusionSolver<Space> >(new SimpleStereoSolver(model));
            }

            printf("Initial energy on thread %d: %.5f\n", i, solvers[i]->evaluateEnergy(initials[i]));
        }

        //monitor thread
        threadOptions.back().is_monitor = true;
        solvers.back() = shared_ptr<FusionSolver<Space> >(new SimpleStereoMonitor(model));
        generators.back() = shared_ptr<ProposalGenerator<Space> >(new DummyGenerator());

        StereoPipeline parallelFusionPipeline(pipelineOption);
        float t = (float)getTickCount();
        printf("Start runing parallel optimization\n");
        parallelFusionPipeline.runParallelFusion(initials, generators, solvers, threadOptions);
        t = ((float)getTickCount() - t) / (float)getTickFrequency();

        SolutionType<Space > solution;
        parallelFusionPipeline.getBestLabeling(solution);

        printf("Done! Final energy: %.5f, running time: %.3fs\n", solution.first, t);

        std::dynamic_pointer_cast<SimpleStereoMonitor>(solvers.back())->dumpData(file_io.getDirectory() + "/temp");

        dumpOutData(parallelFusionPipeline, file_io.getDirectory()+"/temp/plot_"+method);

        for(auto i=0; i<model->width * model->height; ++i){
            result.setDepthAtInd(i, solution.second(i,0));
        }
        return solution.first;
    }
示例#9
0
int  main(void)
{	
	char  line[1024];           
	
	int mode;
	process * root;
	
	char  curDir[100];
	getcwd(curDir,100);
	
	pinfo *head;
	head=NULL;
	while (1)
	{     
		global_pipes=0;
		initials(curDir); 
		mode=0;            
		
		fflush(stdin);
		fflush(stdout);
		
		gets(line);              /*   read in the command line     */
		//printf("line ==%s\n",line);
		
		if (*line == '\0') 
			continue;

		printf("\n");
		
		int i=0;
		
		while((line[i]) != '\0')
		{
			if(line[i] == '&')
			{
				mode++;
				//line[i]='\0';
			}	
			i++;
		}
		
		//jobs
		if(strcmp(line, "jobs") == 0)
		{
			head=display(head);
			continue;
		}
			
		root=parse(line); 
		
		/*
		int p=0;
		while(argv[p] != NULL)
		{
			printf("argv = %s\n",argv[p]);
			p++;
		}    
		
		p=0	;
		while(out[p] !=NULL)
		{
			printf("out = %s\n",root->out);
			p++;
		} 
		p=0	;
		while(in[p] !=NULL)
		{
			printf("in = %s\n",root->in);
			p++;
		}
		*/
		//pinfo 
		if(strcmp(line, "pinfo") == 0)
		{	
			fflush(stdin);
			fflush(stdout);
			ppinfo(root-> argv);
			continue;	
		}
		
		//overkill
		if(strcmp(root->argv[0],"overkill")==0)
		{
			head=overkill(head);
			continue;
		}
		
		//fg
		else if(strcmp(root->argv[0],"fg")==0)
		{
			head=fg(head,root->argv);
			continue;
		}
		
		//kjob
		else if(strcmp(root->argv[0],"kjob")==0)
		{
			head=kjob(head,root->argv);
			continue;
		}	
		
		//exit
		else if (strcmp(root->argv[0], "quit") == 0) 
			exit(0);           			  
		
		//cd		
		if (strcmp(root->argv[0], "cd") == 0)
		{
				chdir(root->argv[1]);
				continue;
		}
		else
		{	if(global_pipes != 0)
				head=executepipes(root,head,mode);  
			else
				head=execute(root,head,mode);
		}
	}
}