示例#1
0
int get_int_from_master(void)
{
  int x;
  int ptid=pvm_parent();
  // ***************  begin constant receive block *********************
  adpvm_slave_crecv(ptid);
  adpvm_unpack(x);
  adpvm_slave_end_creceive();
  // ***************  end receive block ***********************************
  return x;
}
示例#2
0
void main()
{

    /* enroll in pvm */
    mytid = pvm_mytid();
    master = pvm_parent();

    /* receive data from master */
    pvm_recv(master, DATA);
    pvm_upkint(&nproc, 1, 1);
    pvm_upkdouble(&lower, 1, 1);
    pvm_upkdouble(&upper, 1, 1);
    pvm_upkdouble(&delta_x, 1, 1);
    pvm_upkint(&partitions, 1, 1);
    pvm_upkint(tids, nproc, 1);

    /* determine which slave I am (0..nproc-1) */
    for(i=0; i<nproc; i++)
        if(mytid==tids[i]) {
            mynode = i;
            break;
        }

    /* start timiming */
    start = clock();

    /* calculate approximation */
    partitions_per_slave = partitions / nproc;
    first = lower + mynode * ((upper-lower)/nproc);
    last = first + partitions_per_slave * delta_x;

    x = first + (delta_x/2.0);
    while(x<last)
    {
        approx_result += f(x) * delta_x;
        x += delta_x;
    }

    /* end timing */
    elapse = (clock() - start) / clocks_per_sec;
    avg_time = elapse / partitions;

    /* send the results back to the master program */
    pvm_initsend(PvmDataDefault);
    pvm_pkdouble(&elapse, 1, 1);
    pvm_pkdouble(&approx_result, 1, 1);
    pvm_pkdouble(&avg_time, 1, 1);
    pvm_send(master, RESULTS);

    /* exit pvm */
    pvm_exit();
}
示例#3
0
void adpvm_manager::get_variable_values_from_master(void)
{
  int i,j;
  // ***************  begin constant receive block *************************
  int ptid=pvm_parent();
  adpvm_slave_crecv(ptid);
  // unpack all the variables
  for (j=1;j<=initial_params::num_initial_params;j++)
  {
    initial_params::varsptr[j-1]->pvm_unpack();
  }
  adpvm_slave_end_creceive();
  // ***************  end receive block ***********************************
}
示例#4
0
int
main(int argc, char* argv[])
{
	int my_tid;
	int sender_id;
	int n;
	int num_of_configs;
	int config_id;
	int* config;
	int config_fit;
	int master_id = pvm_parent();
	
	//printf("im a kid %d\n", master_id);
	my_tid = pvm_mytid();
	/* -1 for these arguments mean that it matches any task identification
	 * sent to it, and any message tag */
	pvm_recv(-1, -1);

	/* unpackage the information sent to us from the master about how many
	 * configurations will be recieved, and how large they are. */
	pvm_upkint(&num_of_configs, 1, 1);
	pvm_upkint(&n, 1, 1);
	//printf("tid=%d; %d %d\n", my_tid, num_of_configs, n);
	//fflush(stdout);
	
	config = malloc(sizeof(int) * n);

	/* takes information about configurations to be recieved and their size 
	 * and starts recieving the configurations themselves, with their
	 * identifier as the master knows them. Fitnesses are generated as they		 * are recieved and and fitness and id are then sent back to the master
	 */
	int i;
	pvm_recv(-1, -1);
	for (i = 0; i < num_of_configs; i++)
	{
		pvm_upkint(&config_id, 1, 1);
		pvm_upkint(config, n, 1);
		
		config_fit = fitness_test(n, config);
		
		pvm_initsend(PvmDataDefault);
		pvm_pkint(&config_id, 1, 1);
		pvm_pkint(&config_fit, 1, 1);
		pvm_send(master_id, 0);
	}
	pvm_exit();
	return 1;	
}
int main() {

	int in, out, diameter, total;
	int mytid = pvm_mytid();


	// Init messages (1)
	pvm_recv(-1, 1);
	pvm_upkint(&total, 1, 1);
	pvm_upkint(&diameter, 1, 1);
	pvm_upkint(&in, 1, 1);
	pvm_upkint(&out, 1, 1);

	// get output nodes
	int outNodes[out];
	memset(outNodes, -1, out * sizeof(int));

	pvm_upkint(outNodes, out, 1);

	// Election message (2)
	int max = mytid;
	int i;
	for (i = 0 ; i < diameter ; ++i) {
		// Advertise my max to everybody
		int j;
		for(j = 0 ; j < out ; j++){
			pvm_initsend(PvmDataRaw);
			pvm_pkint(&max, 1, 1);
			pvm_send(outNodes[j], 2);
		}

		// Get max from the neighbors
		for(j = 0 ; j < in ; j++){
			int tmp = 0;
			pvm_recv( -1, 2);
			pvm_upkint(&tmp, 1, 1);
			if(tmp>max)
				max = tmp;
		}
	}

	// Send my max to the parent
	pvm_initsend(PvmDataRaw);
	pvm_pkint(&max, 1, 1);
	pvm_send(pvm_parent(), 3);

	pvm_exit();
}
示例#6
0
main()
{
        int ptid;
        char greetings[100];

        ptid=pvm_parent(); /*get tid of task that started me*/
        strcpy(greetings,"Hello world from ");
        gethostname(greetings + strlen(greetings));

        pvm_initsend(PvmDataDefault); /*initialize send buffer*/
        pvm_pkstr(greetings); /*XDR encode string into send buffer*/
        pvm_send(ptid,1);

        pvm_exit(); /*disconnect from the PVM*/
        exit(0);
}
示例#7
0
main()
{
	int ptid;
	char buf[100];

	ptid = pvm_parent();

	strcpy(buf, "hello, world from ");
	gethostname(buf + strlen(buf), 64);

	pvm_initsend(PvmDataDefault);
	pvm_pkstr(buf);
	pvm_send(ptid, 1);

	pvm_exit();
	exit(0);
}
示例#8
0
void BBSDirect::check_pvm() {
	BBSImpl:use_pvm_ = pvm_parent() != PvmSysErr;
}
示例#9
0
void BBSDirect::start() {
	char* client = 0;
	int tid, host_mytid;
	int i, n, ncpu, nncpu;
	struct pvmhostinfo* hostp;
	if (started_) { return; }
	BBSImpl::start();
	mytid_ = pvm_mytid();
	nrnmpi_myid = 0;
	if (mytid_ < 0) { perror("start"); }
	host_mytid = pvm_tidtohost(mytid_);
	tid = pvm_parent();
	if (tid == PvmSysErr) {
		perror("start");
	}else if (tid == PvmNoParent) {
		is_master_ = true;
		pvm_catchout(stdout);
		pvm_setopt(PvmRoute, PvmRouteDirect);
		pvm_config(&n, NULL, &hostp);
		nncpu = 0;
		for (i=0; i < n; ++i) {
			ncpu = hostp[i].hi_speed;
			if (ncpu%1000) {
				hoc_warning(hostp[i].hi_name,
" speed in pvm configuration file is not a multiple of 1000. Assuming 1000.");
				ncpu = 1000;
			}
			nncpu += ncpu/1000;
		}
		nrnmpi_numprocs = nncpu;
		ncids = 0;
	}else{ // a worker, impossible
		assert(false);
	}
	if (nrnmpi_numprocs > 1 && tid == PvmNoParent) {
		char ** sargv;
	// args are workingdirectory specialOrNrniv -bbs_nhost nhost args
		sargv = new char*[nrn_global_argc + 4];
		for (i=1; i < nrn_global_argc; ++i) {
			sargv[i+3] = nrn_global_argv[i];
		}
		sargv[nrn_global_argc + 3] = 0;
		sargv[0] = rel_working_dir();
//printf("sargv[0]=|%s|\n", sargv[0]);
		sargv[1] = nrn_global_argv[0];
		sargv[2] = "-bbs_nhost";
		sargv[3] = new char[10];
		sprintf(sargv[3], "%d", nrnmpi_numprocs);
		cids = new int[nrnmpi_numprocs-1];
if (nrn_global_argv[nrn_global_argc] != 0) {
	printf("argv not null terminated\n");
	exit(1);
}

		BBSDirectServer::server_->start();
		bbs_sig_set();
		bbs_handle();

		//spawn according to number of cpu's (but master has one less)
//printf("%d total number of cpus on %d machines\n", nncpu, n);
		int icid = 0;
		bool first = true;
	    while (icid < nrnmpi_numprocs - 1) {
		for (i=0; i < n; ++i) {
			ncpu = hostp[i].hi_speed;
			if (ncpu%1000) {
				ncpu = 1000;
			}
			ncpu /= 1000;
//printf("%d cpu for machine %d (%s)\n", ncpu, i, hostp[i].hi_name);
			if (first && hostp[i].hi_tid == host_mytid) {
				// spawn one fewer on master first time through
				--ncpu;
			}
			if (icid + ncpu >= nrnmpi_numprocs) {
				ncpu = nrnmpi_numprocs - icid - 1;
			}
//printf("before spawn %d processes (icid=%d) for machine %d (%s)\n", ncpu, icid, i, hostp[i].hi_name);
			if (ncpu) {
				ncids = pvm_spawn("bbswork.sh", sargv,
					PvmTaskHost, hostp[i].hi_name, ncpu, cids + icid);
				if (ncids != ncpu) {
fprintf(stderr, "Tried to spawn %d tasks, only %d succeeded on %s\n", ncpu, ncids, hostp[i].hi_name);
hoc_execerror("Could not spawn all the requested tasks for", hostp[i].hi_name);
				}
//printf("spawned %d for %s with cids starting at %d\n", ncpu, hostp[i].hi_name, icid);
				icid += ncpu;
			}
			if (icid >= nrnmpi_numprocs) {
				break;
			}
		}
		first = false;
	    }
		ncids = icid;
printf("spawned %d more %s on %d cpus on %d machines\n", ncids, nrn_global_argv[0], nncpu, n);
		delete [] sargv[3];
		delete [] sargv;
	}
}
示例#10
0
int
main(int, char** argv) {
  int status = 0;
  int mytid = pvm_mytid();
  int masterid = pvm_parent();
  if(mytid < 0 || masterid < 0) {
    cerr << "\n" << argv[0] << ": Couldn't get slave/master IDs.  Aborting.\n";
    exit(1);
  }

  GA1DBinaryStringGenome genome(GENOME_LENGTH,GenomeEvaluator);
  GASteadyStateGA ga(genome);

  status = pvm_initsend(PvmDataDefault);
  status = pvm_send(masterid, MSG_READY);

  int done = 0;
  while(!done){
    int bufid = pvm_recv(-1, -1);
    int ival;
    if(bufid >= 0) {
      int bytes, msgtag, tid;
      status = pvm_bufinfo(bufid, &bytes, &msgtag, &tid);
      switch(msgtag) {
      case MSG_DONE:
	done = 1;
	break;

      case MSG_SET_POPULATION_SIZE:
	ival = gaDefPopSize;
	status = pvm_upkint(&ival, 1, 1);
	ga.populationSize(ival);
	break;

      case MSG_INITIALIZE:
	ga.initialize();
	break;

      case MSG_STEP:
	ival = 0;
	status = pvm_upkint(&ival, 1, 1);
	for(int i=0; i<ival; i++)
	  ga.step();
	ival = ga.generation();
	  status = pvm_initsend(PvmDataDefault);
	status = pvm_pkint(&ival, 1, 1);
	status = pvm_send(masterid, MSG_STEP_COMPLETE);
	break;

      case MSG_INCOMING_MIGRATION:
	RecvMigration(ga);
	break;

      case MSG_SEND_MIGRATION:
	{
	  int toid = 0, count = 0;
	  status = pvm_upkint(&toid, 1, 1);
	  status = pvm_upkint(&count, 1, 1);
	  SendMigration(toid, ga, count);
	}
	break;

      case MSG_SEND_POPULATION:
	SendPopulation(masterid, ga.population());
	break;

      case MSG_SEND_STATISTICS:
	SendStatistics(masterid, ga.statistics());
	break;

      default:
	cerr << argv[0] << ": unknown msgtag: " << msgtag << "\n";
	break;
      }
    }
    else {
      cerr << argv[0] << ": error from pvm_recv: " << bufid << "\n";
    }
  }

  pvm_exit();
  return 0;
}
示例#11
0
文件: pvmica.c 项目: caromk/binica
int slave() {
	int         i, datasize, id, ptid;
	tassign     assign;
	tresult     result;
	doublereal *bias, *data, *weights;
	integer    *signs, chans, frames, epochs;

#ifndef CRAY
	setpriority(PRIO_PROCESS,0,SLAVE_NICE);
#endif

	while (receive_assign(&assign)) {
		id         = assign.id;
		data       = assign.data;
		weights    = assign.weights;
		chans      = assign.chans;
		frames     = assign.frames;
		epochs     = assign.epochs;

		extended   = assign.extended;
		extblocks  = assign.extblocks;
		pdfsize    = assign.pdfsize;
		nsub       = assign.nsub;
		verbose    = assign.verbose;
		block      = assign.block;
		maxsteps   = assign.maxsteps;
		lrate      = assign.lrate;
		annealstep = assign.annealstep;
		annealdeg  = assign.annealdeg;
		nochange   = assign.nochange;
		momentum   = assign.momentum;

		if (assign.bias)
			bias = (doublereal*)malloc(chans*sizeof(doublereal));
		else
			bias = NULL;

		if (assign.signs)
			signs = (integer*)malloc(chans*sizeof(integer));
		else
			signs = NULL;

		runica(data,weights,chans,frames,epochs,bias,signs);
	
		result.id      = id;
		result.weights = weights;
		result.chans   = chans;
		result.bias    = bias;
		result.signs   = signs;
		result.lrate   = lrate;

		ptid = pvm_parent();
		send_result(ptid,&result);

		if (data != NULL) free(data);
		if (weights != NULL) free(weights);
		if (bias != NULL) free(bias);
		if (signs != NULL) free(signs);
	}

	printf("Process terminating!");
	return 0;
}
示例#12
0
int recvFilterData(FilterData *fData) {
	int bufId;
	int i, l, toFilter;
	char *cwd = (char *)malloc(MAX_CWD_LENGTH+1);
	int num = 0;
	int *tids = (int *)malloc(sizeof(int)*MAXINSTANCES);
	char *filterName         = (char *)malloc(MAX_FNAME_LENGTH);
	char *libName            = (char *)malloc(MAX_LNAME_LENGTH);
	char *hostname           = (char *)malloc(MAX_HNAME_LENGTH);
	char *labelStreamLibname = (char *)malloc(MAX_LNAME_LENGTH);

	int parentTid = pvm_parent();

#ifdef ATTACH
	// if im using attach i dont no if the
	// manager process is realy my father
	bufId = pvm_recv(-1, 0);
	int bytes, msgtag,tid;
	pvm_bufinfo(bufId, &bytes, &msgtag, &tid );
	printf("recvFilterData: bytes = %d msgtag = %d tid = %d\n", bytes, msgtag, tid);
#else
	//We receive one message with all data in it
	bufId = pvm_recv(parentTid, 0);
#endif
	//get the current working directory
	pvm_upkint(&l, 1, 1);
	pvm_upkbyte(cwd, l, 1);
	cwd[l] = '\0';
#ifdef DEBUG	
	printf("cwd = %s\n",cwd);
#endif	

	// filter id, useful for debugging
	pvm_upkint(&num, 1, 1);
	setFDIdFilter(fData, num);
	// get my rank
	pvm_upkint(&num, 1, 1);
	setFDRank(fData, num);
	// total number of instances of this filter
	pvm_upkint(&num, 1, 1);
	setFDNumInstances(fData, num);
	// get my brothers tids
	pvm_upkint(tids, num, 1);
	setFDTids(fData, tids);
#ifdef ATTACH
	// getting my parent Tid because if i'm a attached filter
	// i can be adopted for anyone.. so we do it for all filters..
	// just to make the code easy to understand..
	pvm_upkint(&parentTid, 1, 1);
	int attached;
	pvm_upkint(&attached, 1, 1);
	setFDAttached(fData, attached);
#endif
	// if you are not using Attach the parentTid still the same
	// or its equal to pvm_parent()
	setFDParentTid(fData, parentTid);

#ifdef BMI_FT
	int faultStatus, lastFilter;
	pvm_upkint(&faultStatus, 1, 1);
	setFDFaultStatus(fData, faultStatus);

	pvm_upkint(&lastFilter, 1, 1);
	setFDLastFilter(fData, lastFilter);
#endif

	// filtername
	pvm_upkint(&l, 1, 1);
	pvm_upkbyte(filterName, l, 1);
	filterName[l] = '\0';
	setFDName(fData, filterName);

	//machine declared memory: -1 autodetect, declared on XML
	pvm_upkint(&num, 1, 1);
	setFDMachineMem(fd, num);

	//number of brothers(+ me) I have on this machine, useful for memory management
	pvm_upkint(&num, 1, 1);
	setFDNumLocalInstances(fd, num);

#ifdef VOID_INST
	char instDir[MAX_IDIR_LENGTH];
	pvm_upkint(&l, 1, 1);
	pvm_upkbyte(instDir, l, 1);
	instDir[l] = '\0';
	setFDInstDir(fd, instDir);
#endif

	// receives shared lib name
	pvm_upkint(&l, 1, 1);
	pvm_upkbyte(libName, l, 1);
	libName[l] = '\0';
	setFDLibName(fData, libName);
	/*if (loadFDLibFunctions(fData) == -1){
	  char msg[1000];
	  sprintf(msg, "could not load shared library %s", libName);
	  pvm_initsend(PvmDataRaw);

	  pvm_pkbyte(msg, strlen(msg), 1);
	  pvm_send(pvm_parent(), MSGT_FERROR);
	  return -1;
	  }*/

	// set hostname
	gethostname(hostname, MAX_HNAME_LENGTH);
	setFDHostName(fData, hostname);

	// data received till now
	fprintf(stderr,"filter %s (rank: %d): pvm_tid:%d hostname:%s\n",
			fData->name, fData->myRank, pvm_mytid(), fData->hostName);

	//port data
	//Receive numOutputs
	pvm_upkint(&num, 1, 1);
	setFDNumOutputs(fData, num);
	//receive numInputs
	pvm_upkint(&num, 1, 1);
	setFDNumInputs(fData, num);

	// for each OutputPort
	for(i = 0; i < fData->numOutputPorts; i++) {
		int nOutHosts = 0, tag = 0;
		int numToSend;
		int *outTids  = NULL;
		int firstInstanceToWrite;
		char *portName = (char *)malloc(MAX_PTNAME_LENGTH + 1);
		char *writePolicyName = (char *)malloc(100);
		writePolicy_t wp;

		OutputPort *outputPort;

		pvm_upkint(&numToSend, 1, 1);
		//now we can create the port
		outputPort = createOutputPort(numToSend);

		//port data
		pvm_upkint(&l, 1, 1);
		pvm_upkbyte(portName, l, 1);  //portname
		portName[l] = '\0';
		setOPName(outputPort, portName);

		pvm_upkint(&tag, 1, 1); //get tag
		setOPTag(outputPort, tag);

		for( toFilter = 0; toFilter < numToSend; toFilter++ )
		{
			pvm_upkint(&nOutHosts, 1, 1); //number of tids it is connected

			setOPNumDestinations(outputPort, toFilter, nOutHosts);
			outTids = (int *) malloc(sizeof(int)*nOutHosts);
			pvm_upkint(outTids, nOutHosts, 1); //get tids
			setOPTidsDestinations(outputPort, toFilter, outTids);

			pvm_upkint(&l, 1, 1);
			pvm_upkbyte(writePolicyName, l, 1); // get write policy
			writePolicyName[l] = '\0';
			wp = getWritePolicyByName(writePolicyName);
			setOPWritePolicy(outputPort, toFilter, wp);

			// get LS sharedlib if policy is LS
			if (wp  == LABELED_STREAM ){
				pvm_upkint(&l, 1, 1);
				pvm_upkbyte(labelStreamLibname, l, 1);
				labelStreamLibname[l] = '\0';
				//set output port library name
				setOPLibName(outputPort, toFilter, labelStreamLibname);
				//load output port library for ls
				if (loadOPLSData(outputPort, toFilter) == -1 ){
					char msg[1000];
					sprintf(msg, "could not load LS shared library %s", labelStreamLibname);
					pvm_initsend(PvmDataRaw);

					pvm_pkbyte(msg, strlen(msg), 1);
					pvm_send(pvm_parent(), MSGT_FERROR);
					return -1;
				}
			}
			else if (wp == MULTICAST_LABELED_STREAM) {
				pvm_upkint(&l, 1, 1);
				pvm_upkbyte(labelStreamLibname, l, 1);
				labelStreamLibname[l] = '\0';
				//set output port library name
				setOPLibName(outputPort, toFilter, labelStreamLibname);
				//load output port library for ls
				if (loadOPMLSData(outputPort, toFilter) == -1){
					char msg[1000];
					sprintf(msg,"could not load MLS shared library %s", labelStreamLibname);
					pvm_initsend(PvmDataRaw);

					pvm_pkbyte(msg, strlen(msg), 1);
					pvm_send(pvm_parent(), MSGT_FERROR);
					return -1;
				}
			}
			else {
				//if not LS, we needa know who will be the first instance to receive msgs
				pvm_upkint(&firstInstanceToWrite, 1, 1); //the first instance to write
				setOPNextToSend(outputPort, toFilter,  firstInstanceToWrite);
			}

		}

		// and we finally add the port to our filterData structure
		addFDOutputPort(fData, outputPort);

		//free pointers
		free(outTids);
		free(portName);
		free(writePolicyName);
	}

	// foreach InputPort
	for(i = 0; i < fData->numInputPorts; i++) {
		int nInHosts = 0;
		int *inTids  = NULL;
		int inTag;
		char portName[MAX_PTNAME_LENGTH + 1];
		int l;

		InputPort *inputPort =  createInputPort();

		//get the portName
		pvm_upkint(&l, 1, 1);
		pvm_upkbyte(portName, l, 1);
		portName[l] = '\0';
		setIPName(inputPort, portName);

		// receive the number of tids of this port
		pvm_upkint(&nInHosts, 1, 1); // number of instances connected to this port
		setIPNumSources(inputPort, nInHosts);

		// get the tids
		inTids = (int *) malloc(sizeof(int)*nInHosts);
		pvm_upkint(inTids, nInHosts, 1); //get tids
		setIPTidsSources(inputPort, inTids);
		free(inTids);

		pvm_upkint(&inTag, 1, 1); //the port tag
		setIPTag(inputPort, inTag);
		int hasLabel;
		pvm_upkint(&hasLabel, 1, 1);

		toFilter = 0;
		// if it receives from a LS or MLS we have to have the library with
		// the function that extracts the label
		if (hasLabel){
			setIPLS(inputPort, 1);
			pvm_upkint(&l, 1, 1);
			pvm_upkbyte(labelStreamLibname, l, 1);
			labelStreamLibname[l] = '\0';
			//set output port library name
			setIPLibName(inputPort, toFilter, labelStreamLibname);
			//load output port library for ls
			if (loadIPLSData(inputPort, toFilter) == -1 ){
				char msg[1000];
				sprintf(msg, "could not load LS shared library %s", labelStreamLibname);
				pvm_initsend(PvmDataRaw);

				pvm_pkbyte(msg, strlen(msg), 1);
				pvm_send(pvm_parent(), MSGT_FERROR);
				return -1;
			}
		}

		//finally add the port to our filterData
		addFDInputPort(fData, inputPort);
	}


	free(tids);
	free(hostname);
	free(filterName);
	free(libName);
	free(labelStreamLibname);

	return 1;
}
示例#13
0
int main() {
     int n_out, n_in, i,j, msgtype,d,max_id,rcv_max,my_id;
     int *neighbor_out, *neighbor_in, *new_max_id;

     /* enroll in pvm */
     pvm_mytid();

     /* Receive data from master */
     msgtype = 0;
     pvm_recv( -1, msgtype );
     pvm_upkint(&n_out, 1, 1);
     pvm_upkint(&n_in, 1, 1);
     //malloc the array
     neighbor_out=malloc(n_out*sizeof(int));
     neighbor_in=malloc(n_in*sizeof(int));
     new_max_id=malloc(n_out*sizeof(int));
     if(neighbor_in==NULL || neighbor_out==NULL || new_max_id==NULL){
         printf("error malloc slave \n");
         exit(-1);
     }

     pvm_upkint(neighbor_out, n_out, 1);
     pvm_upkint(neighbor_in, n_in, 1);
     pvm_upkint(&d,1,1);
	pvm_upkint(&my_id,1,1);

	//initialize max_id
	max_id=my_id;

	 //loop d (diameter) times. necessary to abtain fixed point
     for(i=0; i<d; i++)
     {
		msgtype = 4;
		for(j=0; j<n_out;j++){
			//send max_id to every neighbor
			pvm_initsend( PvmDataRaw );
			pvm_pkint( &max_id, 1, 1 );
			pvm_send( neighbor_out[j], msgtype);
		}
		for(j=0; j<n_in;j++){
			//get max_id from every neighbor
			pvm_recv( neighbor_in[j], msgtype );
			pvm_upkint(&new_max_id[j], 1, 1 );
		}
		//compute the new max_id
		rcv_max=max(new_max_id,n_in);
		if(rcv_max>max_id)max_id=rcv_max;
     }

     /* Send result to master */
     pvm_initsend( PvmDataRaw );
     pvm_pkint( &max_id, 1, 1 );
     pvm_send( pvm_parent(), 5);

     /* Program finished. Exit PVM before stopping */
     pvm_exit();

     free(neighbor_in);
     free(neighbor_out);
     free(new_max_id);
     return 0;
}
示例#14
0
文件: slave.c 项目: Moeryn/PRCD-TP1
int main(int argc, char** argv){
  int parent_tid = pvm_parent();
  int my_tid = pvm_mytid();
  DEBUGA("[TID  %d] Slave starting ...",my_tid);
  /* Checking number of arguments */
  if(argc<=3){
    printf("Error in arguments");
    exit(1);
  }


  /* Getting password from arguments */
  int number_of_threads = atoi(argv[3]);
  int posi = atoi(argv[4]);
  int pass_size = atoi(argv[1]);

  char * password = malloc(sizeof(char)*(pass_size+1));
  password[0] = '\0';
  strncat(password,argv[2],pass_size);
  password[pass_size] = '\0';

  DEBUGA("[TID  %d] Password %s Size %d",my_tid,password,pass_size);


  char * temp_password = malloc(sizeof(char)*(pass_size+1));
  char * interval_start = malloc(sizeof(char)*(pass_size+1));
  char * interval_end = malloc(sizeof(char)*(pass_size+1));
  char * recv_buffer = malloc(sizeof(char)*MAX_SIZE);
  recv_buffer[0] = '\0';
  unsigned long long interval_size;

  int buf_size,mes_tag,mes_tid,buf_id;

    
  /* Ask parent for new interval */
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&my_tid,1,1);
  pvm_send(parent_tid,NEED_INTERVAL);
  buf_id = pvm_recv(parent_tid,-1);
  pvm_bufinfo(buf_id,&buf_size,&mes_tag,&mes_tid);

  if(mes_tag == NEW_INTERVAL){
    pvm_upkstr(recv_buffer);
  }
  else if(mes_tag == NO_NEW_INTERVAL){
    exit(1);
  }
  else{
    exit(1);
  }
 
  /* Extract data from buffer */
  interval_start[0] = '\0';
  interval_end[0] = '\0';
  temp_password[0]='\0';
  strncpy(interval_start,recv_buffer,pass_size);
  interval_start[pass_size] = '\0';
  strncpy(interval_end,recv_buffer+pass_size,pass_size);
  interval_end[pass_size] = '\0';
  
  pthread_mutex_lock(&mutex_i_manager);
  init_interval_manager(&i_manager,
			interval_start,
			interval_end,
			password,
			posi);
  pthread_mutex_unlock(&mutex_i_manager);


  /* Creating threads ... */
  pthread_t * threads = malloc(sizeof(pthread_t)*number_of_threads);
  pthread_attr_t attr;
  int c_thread = 0;
  for(c_thread = 0; c_thread < number_of_threads ; ++c_thread){
    pthread_create(&threads[c_thread],&attr,find_password_thread,(void*)NULL);
  }

    
  while(1){
    

    pthread_mutex_lock(&mutex_action);
    pthread_mutex_unlock(&mutex_slave_waiting);
    pthread_cond_wait(&cond_action,&mutex_action);
    pthread_mutex_lock(&mutex_slave_waiting);

    if(action == NEW_INTERVAL){
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&my_tid,1,1);
      pvm_send(parent_tid,NEED_INTERVAL);
      buf_id = pvm_recv(parent_tid,-1);
      pvm_bufinfo(buf_id,&buf_size,&mes_tag,&mes_tid);
      
      if(mes_tag == NEW_INTERVAL){
	pvm_upkstr(recv_buffer);
	interval_start[0] = '\0';
	interval_end[0] = '\0';
	strncpy(interval_start,recv_buffer,pass_size);
	interval_start[pass_size] = '\0';
	strncpy(interval_end,recv_buffer+pass_size,pass_size);
	interval_end[pass_size] = '\0';
	DEBUGA("New interval start interval : %s end interval : %s",interval_start,interval_end);
	pthread_mutex_lock(&mutex_i_manager);
	set_new_interval(&i_manager,interval_start,interval_end);
	pthread_mutex_unlock(&mutex_i_manager);

      }
      else if(mes_tag == NO_NEW_INTERVAL){
	
      }
      else{
      }
    }
    else if (action == FOUND_PASSWORD){
      pthread_mutex_lock(&mutex_f_password);
      pthread_mutex_lock(&mutex_f_c_password);
      
      DEBUGA("[TID  %d] Found Password",my_tid);
      pvm_initsend( PvmDataDefault );
      pvm_pkstr(found_char_password);
      pvm_send(parent_tid,FOUND_PASSWORD);
      pthread_mutex_unlock(&mutex_f_password);
      pthread_mutex_unlock(&mutex_f_c_password);
      break;

    }
    pthread_mutex_unlock(&mutex_action);
    

  }


 
  
  pvm_send(parent_tid,CHILD_TERMINATE);
  DEBUGA("[TID  %d] Terminating slave",my_tid);

  free(password);
  free(temp_password);
  free(interval_start);
  free(interval_end);
  free(recv_buffer);

  return EXIT_SUCCESS;
}
示例#15
0
void myInterrupt(int dummy)
	 
{
#ifdef PVM
  unsigned int	j = 0;
#endif
  
#ifndef PVM
  char		    choice = 'c';
  unsigned long	trials = 0;
  bool		      flag = TRUE;
  
  
  printf("\nActual optimization situation :\n");
  printf("\n-------------------------------\n\n");
  
  printf("\nGenCnt\t= %ld", eps.GenCnt);
  printf("\nTrlCnt\t= %ld\n", eps.TrlCnt);
  
  if((eps.XDim != 0) || (eps.DDim != 0)) {
	printf("AllBest\t= %g\n",eps.AllBst);
	printf("CurBst\t= %g\n",eps.CurBst);
	printf("CurAvg\t= %g\n",eps.CurAvg);
	printf("CurWst\t= %g\n\n",eps.CurWst);
  }
  if(eps.SigDim != 0) {
	printf("SigMin\t= %g\n",eps.SigMin);
	printf("SigAvg\t= %g\n",eps.SigAvg);
	printf("SigMax\t= %g\n\n",eps.SigMax);
  }
  if(eps.AlpDim != 0) {
	printf("CorMin\t= %g\n",eps.CorMin);
	printf("CorAvg\t= %g\n",eps.CorAvg);
	printf("CorMax\t= %g\n\n",eps.CorMax);
  }
  if(eps.PDim != 0) {
	printf("PMin\t= %g\n",eps.PMin);
	printf("PAvg\t= %g\n",eps.PAvg);
	printf("PMax\t= %g\n\n",eps.PMax);
  }
  
  printf("\nTotTrl\t= %ld",eps.TotTrl);
  while(flag) {
	printf("\nMore trials ? (0 / new number of trials)\n");
	scanf("%ld", &trials);
	if(trials != 0) {
	  if(trials <= eps.TrlCnt)
		printf("\nNumber of trials below TrlCnt\n");
	  else {
		eps.TotTrl = trials;
		printf("\nTotTrl set to %ld\n",eps.TotTrl);
		flag = FALSE;
	  }
	}
	else
	  flag = FALSE;
  }
  
  while(TRUE) {
	printf("\nTermination/Continuation ? (t/c)\n");
	scanf("%c", &choice);
	if((choice == 't') || (choice == 'c'))
	  break;
  }
  
  if(choice == 't') {
#endif

	fioTimeOut(&eps);
	dataBst(&eps, pop, ExpNbr);
	if(eps.GfxFlg)
	  gnQuitGnuPipe(&eps);
	if(eps.ObjFlg)
	  fclose(eps.FpObj);
	if(eps.DisFlg)
	  fclose(eps.FpDis);
	if(eps.SigFlg)
	  fclose(eps.FpSig);
	if(eps.AlpFlg)
	  fclose(eps.FpAlp);
	if(eps.RatFlg)
	  fclose(eps.FpRat);
	fclose(eps.FpOut);
	fclose(eps.FpLog);
	poDeletePopulation(pop);

#ifdef PVM
	if(pvm_initsend(PvmDataRaw) < 0)
	  panic(A_FATAL,"child-main", "initsend for group %d failed : %s : %d",
			eps.inst, __FILE__, __LINE__);
	
	if((ptid = pvm_parent()) == PvmNoParent)
	  panic(A_FATAL,"child-main", "pvm_parent for group %d failed : %s : %d",
			eps.inst, __FILE__, __LINE__);
	
	if(pvm_pkint(&(eps.tid), 1, 1) < 0)
	  panic(A_FATAL,"child-main", "packing of tid failed : %s : %d", 
			__FILE__, __LINE__);

	if(pvm_send(ptid, MSGTAG_END) < 0)
	  panic(A_WARN, "child-main", 
			"sending end message to master failed : %s : %d",
			__FILE__, __LINE__);
	pvm_barrier(eps.Group, eps.Tasks+1);
	pvm_lvgroup(eps.Group);
	
	for(j = 0; j < eps.Neighbours; j++)
	  inDeleteIndividual(MigrationBuffer[j]);
	free(MigrationBuffer);
#endif

	utGlobalTermination(&eps);
	
	printf("\n%s 1.0 terminated.\n", program_name);

#ifdef PVM
	pvm_exit();
#endif		

	exit(0);
	
#ifndef PVM
  }
  
  printf("\n%s 1.0 continued.\n", program_name);
  return;
#endif

}
示例#16
0
int 
main(void)
{
  struct p7trace_s *tr;         /* traceback of an alignment               */
  int      master_tid;		/* PVM TID of our master */
  char    *hmmfile;	        /* file to read HMM(s) from                */
  HMMFILE *hmmfp;               /* opened hmmfile for reading              */
  struct plan7_s *hmm;
  char    *seq;
  char    *dsq;
  int      len;
  int      nhmm;		/* number of HMM to work on                */
  float    sc;
  int      my_idx = -1;		/* my index, 0..nslaves-1 */
  float    globT;		/* T parameter: keep only hits > globT bits */
  double   globE;		/* E parameter: keep hits < globE E-value   */
  double   pvalue;		/* Z*pvalue = Evalue                        */
  int      Z;			/* nseq to base E value calculation on      */
  int      send_trace;		/* TRUE if score is significant             */
  int      do_xnu;		/* TRUE to do XNU filter on seq             */
  int      do_forward;		/* TRUE to use Forward() scores not Viterbi */
  int      do_null2;		/* TRUE to correct scores w/ ad hoc null2   */
  int      alphatype;		/* alphabet type, hmmAMINO or hmmNUCLEIC    */
  int      code;		/* return code after initialization         */

  
  /* Register leave_pvm() cleanup function so any exit() call
   * first calls pvm_exit().
   */
  if (atexit(leave_pvm) != 0) { pvm_exit(); Die("slave couldn't register leave_pvm()"); }

  /*****************************************************************
   * initialization.
   * Master broadcasts to us: 
   *     1) len of HMM file name        (int)
   *     2) name of HMM file            (string)
   *     3) length of sequence string   (int) 
   *     4) sequence                    (string)
   *     5) globT threshold
   *     6) globE threshold
   *     7) Z 
   *     8) do_xnu flag
   *     9) do_forward flag
   *    10) do_null2 flag
   *    11) alphabet type
   * We receive the broadcast and open the files.    
   ******************************************************************/

  master_tid = pvm_parent();	/* who's our master? */

  pvm_recv(master_tid, HMMPVM_INIT);
  pvm_upkint(&len, 1, 1);
  hmmfile = MallocOrDie(sizeof(char *) * (len+1));
  pvm_upkstr(hmmfile);
  pvm_upkint(&len, 1, 1);
  seq = MallocOrDie(sizeof(char *) * (len+1));
  pvm_upkstr(seq);
  pvm_upkfloat(&globT, 1, 1);
  pvm_upkdouble(&globE, 1, 1);
  pvm_upkint(&Z, 1, 1);
  pvm_upkint(&do_xnu, 1, 1);
  pvm_upkint(&do_forward, 1, 1);
  pvm_upkint(&do_null2, 1, 1);
  pvm_upkint(&alphatype, 1, 1);

  SetAlphabet(alphatype);
				/* Open HMM file (maybe in HMMERDB) */
  code = HMMPVM_OK;
  if ((hmmfp = HMMFileOpen(hmmfile, "HMMERDB")) == NULL)
    code = HMMPVM_NO_HMMFILE;
  else if (hmmfp->gsi == NULL)
    code = HMMPVM_NO_INDEX;
  
  /* report our status.
   */
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&code, 1, 1);	
  pvm_send(master_tid, HMMPVM_RESULTS);

  dsq = DigitizeSequence(seq, len);
  if (do_xnu) XNU(dsq, len);

  /*****************************************************************
   * Main loop.
   * Receive an integer 0..nhmm-1 for which HMM to search against.
   * If we receive a -1, we shut down. 
   *****************************************************************/ 
  
  for (;;) 
    {
      pvm_recv(master_tid, HMMPVM_WORK);
      pvm_upkint(&nhmm, 1, 1);
      if (my_idx < 0) my_idx = nhmm; /* first time thru, remember what index we are. */

      if (nhmm == -1) break;	/* shutdown signal */

      /* move to our assigned HMM in the HMM file, and read it
       */
      HMMFilePositionByIndex(hmmfp, nhmm);
      if (! HMMFileRead(hmmfp, &hmm)) Die("unexpected end of HMM file"); 
      if (hmm == NULL)                Die("unexpected failure to parse HMM file"); 
      P7Logoddsify(hmm, TRUE);
      
      /* Score sequence, do alignment (Viterbi), recover trace
       */
      if (P7ViterbiSize(len, hmm->M) <= RAMLIMIT)
	{
	  SQD_DPRINTF1(("P7Viterbi(): Estimated size %d Mb\n", P7ViterbiSize(len, hmm->M)));
	  sc = P7Viterbi(dsq, len, hmm, &tr);
	}
      else
	{
	  SQD_DPRINTF1(("P7SmallViterbi() called; %d Mb > %d\n", P7ViterbiSize(len, hmm->M), RAMLIMIT));
	  sc = P7SmallViterbi(dsq, len, hmm, &tr);
	}

      if (do_forward) sc  = P7Forward(dsq, len, hmm, NULL);
      if (do_null2)   sc -= TraceScoreCorrection(hmm, tr, dsq);
	
      pvalue = PValue(hmm, sc);
      send_trace = (sc > globT && pvalue * (float) Z < globE) ? 1 : 0;

      /* return output
       */
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&my_idx, 1, 1);	/* tell master who we are */
      pvm_pkstr(hmm->name);	/* double check that we did the right thing */
      pvm_pkfloat(&sc, 1, 1);
      pvm_pkdouble(&pvalue, 1, 1);
      pvm_pkint(&send_trace, 1, 1); /* flag for whether a trace structure is coming */
      if (send_trace) PVMPackTrace(tr);
      pvm_send(master_tid, HMMPVM_RESULTS);

      /* cleanup
       */
      FreePlan7(hmm);
      P7FreeTrace(tr);
    }

  /*********************************************** 
   * Cleanup, return.
   ***********************************************/

  HMMFileClose(hmmfp);
  free(seq);
  free(dsq);
  free(hmmfile);
  return 0;
}
示例#17
0
int main(int argc, char*argv[]){
	int parent;
	parent=pvm_parent();
	printf("Parent==%d\n",parent);
	return(0);
}
示例#18
0
int main(int argc, char **argv)
	 
{
  unsigned long	i = 1;
  char		Err[BUFSIZ];
#ifdef PVM
  unsigned int	j = 0L;
#endif

  
  /* There is no signal handling under parix. */
  if(((int)signal(SIGINT, (void (*)(int)) myInterrupt) == -1) ||
	 ((int)signal(SIGFPE, (void (*)(int)) Arithmetic) == -1))
	panic(A_FATAL, "child-main", "signal call went wrong :%s : %d",
		  __FILE__, __LINE__);
  
  strcpy(hlp, argv[0]);
  program_name = hlp;
  
  initDef(&eps);				/* initialize structure */
  ipOptPrc(&eps, argc, argv);	/* process options. */
  
#ifdef PVM
  eps.tid  = pvm_mytid();        /* tid of process. */
  strcpy(eps.Group, eps.Suffix); /* Create Group name. */
  if((eps.inst = pvm_joingroup(eps.Group)) < 0)
	panic(A_FATAL, "child-main", 
		  "pvm grouping for group %s failed : %s : %d\n",
		  eps.Group, __FILE__, __LINE__);

  printf("Slave with tid %d and inst %d started\n", eps.tid, eps.inst);

  /* To get more diversity, each Population gets other external parameters.*/
  
  if(eps.SigDim > 0)
	eps.SigStart += (0.1 * (double) eps.inst);

  /*
  if(eps.SigDim > 0) {
	if(eps.SigDim == 1)
	  eps.TauOne *= (0.1 * (double) eps.inst);
	else
	  eps.TauLcl *= (0.1 * (double) eps.inst);
  }
  
  if(eps.PDim > 0) {
	if(eps.PDim == 1) {
	  eps.GamOne *= (double) eps.inst;
	  eps.PStart *= (double) eps.inst;
	}
	else
	  eps.GamLcl *= (double) eps.inst;
  }
  
#ifdef DEBUG
  fprintf(stderr, "%d:Tau = %g, Gamma = %g\n",
          eps.inst, eps.TauLcl, eps.GamOne);
#endif 
  */

  sprintf(&hlp[strlen(hlp)], ".%d", eps.tid);
  if(pvm_barrier(eps.Group, eps.Tasks+1) < 0)
	panic(A_WARN, "child-main", "pvm barrier error : %s : %d\n",
		  __FILE__, __LINE__);
  printf("\n%s as instance %d activ.\n", program_name, eps.inst);
  
#endif /* PVM */
  
  if(ipOptChk(&eps, Err)) {	  /* check parameter consistency */
	fprintf(stderr,"%s",Err); /* print warning message */
	panic(A_FATAL, "ipOptPrc", "Parameter inconsistency :\n%s\n%s : %d", 
		  Err, __FILE__, __LINE__);
  }
  
#ifndef PVM
  printf("\n%s activ.\n", program_name);
#endif	
  
#ifdef PVM
  if(NULL == (MigrationBuffer = (individual_tPtr *)
			  calloc(eps.Neighbours, sizeof(individual_tPtr))))
	panic(E_FATAL, "main-child", "not enough memory : %s : %d",
		  __FILE__, __LINE__);
  
  for(j = 0; j < eps.Neighbours; j++)
	MigrationBuffer[j]= inNewIndividual(eps.XDim, eps.DDim, eps.SigDim,
										eps.AlpDim, eps.PDim);
#endif

  initSuffix(&eps);			/* initialize suffix,
							   here string from ES.in*/
  parsFormatString(&eps);	/* pars format string */
  
  pop = poNewPopulation(&eps);
  
  for (i = 1; i <= eps.TotExp; i++) {  /* experiment loop */
	
	ExpNbr = i;
	
	initPop(&eps, pop, i);

#ifdef PVM
	/* Initialization of MigrationBuffer. */
	for(j = 0; j < eps.Neighbours; j++) {
	  if(j < pop->mu)
		inCopyIndividual(poGetIndividual(j+1, pop),
						 MigrationBuffer[j]);
	  else
		inCopyIndividual(poGetIndividual(pop->mu, pop),
						 MigrationBuffer[j]);
	}
#endif
	
	dataParLog(&eps);		/* dump parameters */
	fioTimeOut(&eps);		/* get start time */
	
	PopulationEVAL(&eps, pop, "parents");
	dataCol(&eps, pop, i);
	if (eps.GfxFlg)
	  gnInitGnuPipe(&eps);
	
#ifdef PVM
	send_Best(&eps, pop);
#endif
	
	while (!termExp(&eps)) { /* ES main loop */
	  
	  eps.GenCnt++;
	  PopulationCREATE(&eps, pop);
	  /* recombination and mutation including the
		 concept of letal mutations. */
	  PopulationEVAL(&eps, pop, "offspring");
	  PopulationSELECT(&eps, pop);
	  dataCol(&eps, pop, i);
	  if(eps.GfxFlg && (eps.GenCnt % eps.GfxIvl == 0))
		gnPlotGnuPipe(&eps);     /* plot data */

#ifdef PVM
	  send_Best(&eps, pop);
	  if(eps.GenCnt % eps.IsolationTime == 0) {
		send_Neighbours(&eps, pop);
		if(eps.Communication == COMMUNICATION_SYNCHRON)
		  recv_sync(&eps, MigrationBuffer);
	  }
	  if(eps.Communication == COMMUNICATION_ASYNCHRON)
		recv_async(&eps, MigrationBuffer);
	  for(j = 0; j < eps.Neighbours && j < pop->mu; j++)
		inCopyIndividual(MigrationBuffer[j],
					     poGetIndividual(j+1, pop));
#endif

	}  /* end ES main loop */
	
	dataBst(&eps, pop, i); /* dump best ind. */
	fioTimeOut(&eps);	   /* get end time */
	
  } /* end experiment loop */
  
  if(eps.GfxFlg)
	gnQuitGnuPipe(&eps);	/* stop plotting */
  
  reportExperiments(&eps);
  
  pop = poDeletePopulation(pop);
  
#ifdef PVM
  if(pvm_initsend(PvmDataRaw) < 0)
	panic(A_FATAL,"child-main", "initsend for group %d failed : %s : %d",
		  eps.inst, __FILE__, __LINE__);
  
  if((ptid = pvm_parent()) == PvmNoParent)
	panic(A_FATAL,"child-main", "pvm_parent for group %d failed : %s : %d",
		  eps.inst, __FILE__, __LINE__);
  
  if(pvm_pkint(&(eps.tid), 1, 1) < 0)
	panic(A_FATAL,"child-main", "packing of tid failed : %s : %d",
		  __FILE__, __LINE__);
  
  if(pvm_send(ptid, MSGTAG_END) < 0)
	panic(A_WARN, "child-main", 
		  "sending end message to master failed : %s : %d",
		  __FILE__, __LINE__);
  pvm_barrier(eps.Group, eps.Tasks+1);
  pvm_lvgroup(eps.Group);
	
  for(j = 0; j < eps.Neighbours; j++)
	inDeleteIndividual(MigrationBuffer[j]);
  free(MigrationBuffer);
#endif
	
  utGlobalTermination(&eps);
	
  printf("\n%s 1.0 terminated.\n", program_name);

#ifdef PVM
  pvm_exit();
#endif

  exit(0);
}
示例#19
0
int main (int argc, char **argv)
 
{
	int Finish,dip=65;
        int nz;                 /* number of migrated depth samples */
        int nxo,nx;             /* number of midpoints  */
        int iz,iw,ix,ix2,ix3,ixshot;     /* loop counters*/
        int ntfft;        	/* fft size*/
        int nw;              /* number of frequency*/
        int mytid,msgtype,rc,parent_tid;


        float dt=0.004,dz;         /*time and depth sampling interval*/
        float dw;            /*frequency sampling interval */
        float fw;            /* first frequency*/
        float w;              /* frequency*/
        float dx;               /* spatial sampling interval*/
        float **cresult;    /*output data*/
        float v1;
        float para;
        double kz2;
        float **vp,**v;
        complex cshift2;
        complex **cp,**cp1;  /* complex input,output         */

	/*get my and father pids*/
	mytid=pvm_mytid();
	parent_tid=pvm_parent();

	/*receive global parameters*/
	msgtype=PARA_MSGTYPE;	
	rc=pvm_recv(-1,msgtype);
	rc=pvm_upkint(&nxo,1,1);
	rc=pvm_upkint(&nz,1,1);
	rc=pvm_upkint(&dip,1,1);
        rc=pvm_upkfloat(&para,1,1);
	
	/*allocate space for velocity profile and receive velocity from father*/
        vp=alloc2float(nxo,nz);
        msgtype=VEL_MSGTYPE;
        rc=pvm_recv(-1,msgtype);
        rc=pvm_upkfloat(vp[0],nxo*nz,1);

	/*allocate space for the storage of partial image and zero it out now*/ 
        cresult = alloc2float(nz,nxo);
	for(ix=0;ix<nxo;ix++)
	for(iz=0;iz<nz;iz++)
	cresult[ix][iz]=0.0;

/*loop over shotgather*/
loop:

	/*receive parameters for each shot gather*/
        msgtype=PARA_MSGTYPE;
        rc=pvm_recv(parent_tid,msgtype);
	rc=pvm_upkint(&Finish,1,1);
	if(Finish==FinalDone)goto end;

 	rc=pvm_upkint(&ntfft,1,1);
        rc=pvm_upkint(&ix2,1,1);
        rc=pvm_upkint(&ix3,1,1);
	rc=pvm_upkint(&ixshot,1,1);

	nx=ix3-ix2+1;	

	rc=pvm_upkfloat(&dx,1,1);
	rc=pvm_upkfloat(&dz,1,1);
 	rc=pvm_upkfloat(&dw,1,1);
        rc=pvm_upkfloat(&dt,1,1);

	/*allocate space for velocity profile within the aperature*/
	v=alloc2float(nx,nz);

	for(iz=0;iz<nz;iz++)
	for(ix=0;ix<nx;ix++){
	v[iz][ix]=vp[iz][ix+ix2];
	}




	while(1){
		/*receive parameters and data for processing*/
		msgtype=DATA_MSGTYPE;
		rc=pvm_recv(parent_tid,msgtype);
		rc=pvm_upkint(&Finish,1,1);

		if(Finish==Done) {free2float(v);goto loop; }
		rc=pvm_upkfloat(&fw,1,1);

		rc=pvm_upkint(&nw,1,1);
		cp = alloc2complex(nx,nw);
		cp1 = alloc2complex(nx,nw);
		rc=pvm_upkfloat((float *)cp[0],nx*nw*2,1);
		rc=pvm_upkfloat((float *)cp1[0],nx*nw*2,1);



        /* loops over depth */
        for(iz=0;iz<nz;++iz){

	/*the imaging condition*/
/*	for(ix=0;ix<nx;ix++){
	for(iw=0,w=fw;iw<nw;w+=dw,iw++){
		complex tmp;
		float ratio=10.0;

		if(fabs(ix+ix2-ixshot)*dx<ratio*iz*dz)
		tmp=cmul(cp[iw][ix],cp1[iw][ix]);
		else tmp=cmplx(0.0,0.0);
		cresult[ix+ix2][iz]+=tmp.r/ntfft;
	}
	}
*/


/* anothe imaging condition, slightly different from the above one, but not quite
slow*/


        for(iw=0,w=fw;iw<nw;w+=dw,iw++){ 
		float kk=0.0;
		complex tmp;
		float ratio=1.5;
		if(dip<80)ratio=1.5;
		else ratio=1.5;
        
		for(ix=0;ix<nx;ix++){
		kk+=(pow(cp1[iw][ix].i,2.0)+pow(cp1[iw][ix].r,2.0))/nx;
		}       
                
		for(ix=0;ix<nx;ix++){
		tmp=cmul(cp[iw][ix],cp1[iw][ix]);

		if(fabs(ix+ix2-ixshot)*dx<ratio*iz*dz)

		tmp=crmul(tmp,1.0/(kk+1.0e-10));

		else tmp=cmplx(0.0,0.0);

		cresult[ix+ix2][iz]+=tmp.r/ntfft;

		}
		}


		/*get the average velocity*/
		v1=0.0;
                for(ix=0;ix<nx;++ix)
		{v1+=v[iz][ix]/nx;}
		
		/*compute time-invariant wavefield*/
/*                for(ix=0;ix<nx;++ix)
                for(iw=0,w=fw;iw<nw;w+=dw,++iw) {
                        kz2=-(1.0/v1)*w*dz;
                        cshift2=cmplx(cos(kz2),sin(kz2));   
                        cp[iw][ix]=cmul(cp[iw][ix],cshift2);
                        cp1[iw][ix]=cmul(cp1[iw][ix],cshift2);
                }
*/
		/*wave-propagation using finite-difference method*/
                fdmig( cp, nx, nw,v[iz],fw,dw,dz,dx,dt,dip,para);
                fdmig( cp1,nx, nw,v[iz],fw,dw,dz,dx,dt,dip,para);

		/*apply thin lens term here*/                                
                for(ix=0;ix<nx;++ix)
                for(iw=0,w=fw;iw<nw;w+=dw,++iw){
		float Wi=-dw;
		kz2=-(1.0/v[iz][ix])*dz;
/*			kz2=-(1.0/v[iz][ix]-1.0/v1)*w*dz;
			cshift2=cmplx(cos(kz2),sin(kz2));*/
			cshift2=cexp(cmplx(-Wi*kz2,w*kz2));
			cp[iw][ix]=cmul(cp[iw][ix],cshift2);
			cp1[iw][ix]=cmul(cp1[iw][ix],cshift2);
		}
                
}

/*finish a portion of the data, request more*/
pvm_initsend(PvmDataDefault);
pvm_pkint(&mytid,1,1);
msgtype=COM_MSGTYPE;
pvm_send(parent_tid,msgtype);
         
free2complex(cp);
free2complex(cp1);

}


end:

/*everything done,send back partial image and wait for signal to kill itself*/
pvm_initsend(PvmDataDefault);
pvm_pkfloat(cresult[0],nxo*nz,1);
msgtype=RESULT_MSGTYPE;
pvm_send(parent_tid,msgtype);
msgtype=COM_MSGTYPE;
pvm_recv(-1,msgtype);
pvm_exit();
exit(0);
}
示例#20
0
int 
main(void)
{
  int      master_tid;		/* PVM TID of our master */
  int      slaveidx;		/* my slave index (0..nslaves-1) */
  struct plan7_s *hmm;		/* HMM to calibrate, sent from master */
  struct histogram_s *hist;     /* score histogram */
  int      hmmidx;		/* index of this HMM */
  char    *seq;			/* synthetic random sequence */
  char    *dsq;			/* digitized seq */
  int      len;			/* length of seq */
  float    sc;			/* score of seq aligned to HMM */
  float    max;			/* maximum score seen in sample */
  int      seed;		/* random number seed */
  int      nsample;		/* number of seqs to sample */
  int      fixedlen;		/* if nonzero, fixed length of seq */
  float    lenmean;		/* Gaussian mean length of seq */
  float    lensd;		/* Gaussian length std. dev. for seq */
  int      fitok;		/* TRUE if EVD fit was OK */
  float    randomseq[MAXABET];	/* iid frequencies of residues */
  float    p1;
  int      alphatype;		/* alphabet type, hmmAMINO or hmmNUCLEIC    */
  int      idx;
  int      code;

  /* Register leave_pvm() cleanup function so any exit() call
   * first calls pvm_exit().
   */
  if (atexit(leave_pvm) != 0) { pvm_exit(); Die("slave couldn't register leave_pvm()"); }

  /*****************************************************************
   * initialization.
   * Master broadcasts the problem to us: parameters of the
   * HMM calibration.  
   ******************************************************************/

  master_tid = pvm_parent();	/* who's our master? */

  pvm_recv(master_tid, HMMPVM_INIT);
  pvm_upkint(&nsample,  1, 1);
  pvm_upkint(&fixedlen, 1, 1);
  pvm_upkfloat(&lenmean,  1, 1);
  pvm_upkfloat(&lensd,    1, 1);

  /* tell the master we're OK and ready to go (or not)
   */
  code = HMMPVM_OK;
  pvm_initsend(PvmDataDefault);
  pvm_pkint(&code, 1, 1);	
  pvm_send(master_tid, HMMPVM_RESULTS);

  /*****************************************************************
   * Main loop.
   * Receive a random number seed, then an HMM to search against.
   * If we receive a -1 seed, we shut down. 
   *****************************************************************/ 
  
  slaveidx = -1;
  for (;;) 
    {
      pvm_recv(master_tid, HMMPVM_WORK);
      pvm_upkint(&seed, 1, 1);
      if (seed == -1) break;	/* shutdown signal */
      pvm_upkint(&hmmidx, 1, 1);
      pvm_upkint(&alphatype,1, 1);
      SetAlphabet(alphatype);
      hmm = PVMUnpackHMM();
      if (hmm == NULL) Die("oh no, the HMM never arrived");

      if (slaveidx == -1) slaveidx = hmmidx; 
      P7DefaultNullModel(randomseq, &p1);

      sre_srandom(seed);
      P7Logoddsify(hmm, TRUE);
      hist = AllocHistogram(-200, 200, 100);
      max  = -FLT_MAX;

      for (idx = 0; idx < nsample; idx++)
	{
  				/* choose length of random sequence */
	  if (fixedlen) len = fixedlen;
	  else do len = (int) Gaussrandom(lenmean, lensd); while (len < 1);
				/* generate it */
	  seq = RandomSequence(Alphabet, randomseq, Alphabet_size, len);
	  dsq = DigitizeSequence(seq, len);

	  if (P7ViterbiSize(len, hmm->M) <= RAMLIMIT)
	    sc = P7Viterbi(dsq, len, hmm, NULL);
	  else
	    sc = P7SmallViterbi(dsq, len, hmm, NULL);

	  AddToHistogram(hist, sc);
	  if (sc > max) max = sc;
	  
	  free(seq);
	  free(dsq);
	}

      /* Fit an EVD to the observed histogram.
       * The TRUE left-censors and fits only the right slope of the histogram.
       * The 9999. is an arbitrary high number that means we won't trim outliers
       * on the right.
       */
      fitok = ExtremeValueFitHistogram(hist, TRUE, 9999.);

      /* Return output to master.
       * Currently we don't send the histogram back, but we could.
       */
      pvm_initsend(PvmDataDefault);
      pvm_pkint(&slaveidx, 1, 1);
      pvm_pkint(&hmmidx, 1, 1);	
      PVMPackString(hmm->name);
      pvm_pkint(&fitok,  1, 1);
      pvm_pkfloat(&(hist->param[EVD_MU]), 1, 1);
      pvm_pkfloat(&(hist->param[EVD_LAMBDA]), 1, 1);
      pvm_pkfloat(&max, 1, 1);
      pvm_send(master_tid, HMMPVM_RESULTS);

      /* cleanup
       */
      FreeHistogram(hist);
      FreePlan7(hmm);
    }

  /*********************************************** 
   * Cleanup, return.
   ***********************************************/

  return 0;			/* pvm_exit() is called by atexit() registration. */
}
示例#21
0
文件: mandel-basic.c 项目: fip/FIP3A
int
main(int argc, char **argv)
{
    int tid;
    int parent;

    struct pvmhostinfo *hostp;
    int nhost, narch;

    tid = pvm_mytid();
    if(tid < 0) pvm_ferror("pvm_mytid", 1);

    parent = pvm_parent();

    if(parent == PvmNoParent || parent == PvmParentNotSet) {
        /* Processus pere */
        int nchildren, children[MAXCHILDREN];
        int i, j, res, rc;
      int bytes, tag, from_tid;


    /* Ask PVM for information about the virtual machine, and display
       it to the user. 
    */
    
        pvm_config(&nhost, &narch, &hostp);
        printf("I found the following %d hosts...\n",nhost);
		
		
        for (i = 0; i < nhost; i++)
          printf("%d. %s \t(%s)\n",i,hostp[i].hi_name,hostp[i].hi_arch);



        rc = pvm_spawn("pvm_mandel", NULL, PvmTaskDefault, NULL, 
                       NUMCHILDREN, children);
        if(rc < 0) pvm_ferror("pvm_spawn", 1);
        printf("%d enfants\n", rc);
        nchildren = 0;
        for(i = 0; i < NUMCHILDREN; i++) {
            printf("Enfant %d, tid = %d\n", i, children[i]);
            if(children[i] >= 0)
                nchildren++;
            if(nchildren < 1)
                pvm_ferror("Pas d'enfants", 0);
        }
        for(i = -MAXX; i <= MAXX; i++) {
            for(j = -MAXY; j <= MAXY; j++) {
               rc = pvm_recv(-1,-1);

              if (rc < 0) {
                printf("An error occurred when trying to receive a message.\n");
                break;
              }

      /* Find out who this message is from, and how big it is. */

               rc = pvm_bufinfo(rc,&bytes,&tag,&from_tid);

               /* printf("received message from %s of %d bytes, tag %d\n",
                  get_host_by_tid(hostp,nhost,from_tid), bytes, tag);
               */

                rc = pvm_upkint(&res, 1, 1);
                if(rc < 0) pvm_ferror("pvm_upkint", 1);
                cases[i + MAXX][j + MAXY] = res;
            }
        }
        dump_ppm("mandel.ppm", cases);
        printf("Fini.\n");
        pvm_exit();
        exit(0);
    } else if(parent >= 0) {
        /* On est l'un des fils */
        double x, y;
        int i, j, res, rc;
        printf("Fils: %d\n", tid);
        for(i = -MAXX; i <= MAXX; i++) {
            for(j = -MAXY; j <= MAXY; j++) {
                x = 2 * i / (double)MAXX;
                y = 1.5 * j / (double)MAXY;
                res = mandel(x, y);
                rc = pvm_initsend(PvmDataDefault);
                if(rc < 0) pvm_ferror("pvm_initsend", 1);
                rc = pvm_pkint(&res, 1, 1);
                if(rc < 0) pvm_ferror("pvm_pkint", 1);
                rc = pvm_send(parent, 0);
                if(rc < 0) pvm_ferror("pvm_send", 1);
            }
        }
        printf("Fils %d termine.\n", tid);
        pvm_exit();
        exit(0);
    } else
        pvm_ferror("pvm_parent", 1);

    assert(0);
}