示例#1
0
void dTensorBase::init()
{
    assert_printf(size>=0, "size=%d", size);
    vec = new double[size];
#ifdef CHECK_INIT
    setall(std::numeric_limits<double>::quiet_NaN());
    // setall(0./0); // initialize all entries to nan
#endif
}
示例#2
0
long ignlgi(void)
/*
**********************************************************************
     long ignlgi(void)
               GeNerate LarGe Integer
     Returns a random integer following a uniform distribution over
     (1, 2147483562) using the current generator.
     This is a transcription from Pascal to Fortran of routine
     Random from the paper
     L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
     with Splitting Facilities." ACM Transactions on Mathematical
     Software, 17:98-111 (1991)
**********************************************************************
*/
{
#define numg 32L
extern void gsrgs(long getset,long *qvalue);
extern void gssst(long getset,long *qset);
extern void gscgn(long getset,long *g);
extern void inrgcm(void);
extern long Xm1,Xm2,Xa1,Xa2,Xcg1[],Xcg2[];
extern long Xqanti[];
long ignlgi,curntg,k,s1,s2,z;
long qqssd,qrgnin;
/*
     IF THE RANDOM NUMBER PACKAGE HAS NOT BEEN INITIALIZED YET, DO SO.
     IT CAN BE INITIALIZED IN ONE OF TWO WAYS : 1) THE FIRST CALL TO
     THIS ROUTINE  2) A CALL TO SETALL.
*/
    gsrgs(0L,&qrgnin);
    if(!qrgnin) inrgcm();
    gssst(0,&qqssd);
    if(!qqssd) setall(1234567890L,123456789L);
/*
     Get Current Generator
*/
    gscgn(0L,&curntg);
    s1 = *(Xcg1+curntg-1);
    s2 = *(Xcg2+curntg-1);
    k = s1/53668L;
    s1 = Xa1*(s1-k*53668L)-k*12211;
    if(s1 < 0) s1 += Xm1;
    k = s2/52774L;
    s2 = Xa2*(s2-k*52774L)-k*3791;
    if(s2 < 0) s2 += Xm2;
    *(Xcg1+curntg-1) = s1;
    *(Xcg2+curntg-1) = s2;
    z = s1-s2;
    if(z < 1) z += (Xm1-1);
    if(*(Xqanti+curntg-1)) z = Xm1-z;
    ignlgi = z;
    return ignlgi;
#undef numg
}
示例#3
0
static PyObject *
random_set_seeds(PyObject *self, PyObject *args)
{
  long seed1, seed2;

  if (!PyArg_ParseTuple(args, "ll", &seed1, &seed2)) return NULL;


  setall(seed1, seed2);
  if (PyErr_Occurred ()) return NULL;
  Py_INCREF(Py_None);
  return (PyObject *)Py_None;
}
示例#4
0
    void Seeder(int RanSeed, time_t curTime)
    {
      //time_t curTime = time(0);
#ifndef _NO_SPRNG
      //init_sprng(SPRNG_LCG, static_cast<int>(curTime) , SPRNG_DEFAULT);
      init_sprng(SPRNG_LCG, RanSeed , SPRNG_DEFAULT);
#else
      //std::cerr << "Ranlib!!!!\n\n";
      //srandom(static_cast<unsigned int>(curTime));
      srandom(RanSeed);
#endif
      long seed1, seed2;
      phrtsd(ctime(&curTime), &seed1, &seed2);
      setall(seed1, seed2);
    }
示例#5
0
void gfmUserDefd_InitializeChain(void)
{
	long temp1, temp2;
	
	if(gUseSameSeeds == 1) {
		setall((long)gC->Seed1, (long)gC->Seed2);
	}
	else {
		getsd(&temp1, &temp2);
		gC->Seed1 = temp1;
		gC->Seed2 = temp2;
	}
	InitializeChain(gC);
	
	
}
示例#6
0
int main(int argc, char *argv[])
{	
	char File[100];
	int temp,priorchoice;
	double temp_d;
	enum prior_type PiP = JEFFREYS, ThP = JEFFREYS;
	char gnog;
	int DoAsBurnIn = 0, DoAsReps = 0,i,g;
	time_t StartTime, CurrTime, LastTime, RealRepStartTime;
	cli_opts *CL_Opts=NULL;
	int tempSeed1,tempSeed2;
	
	hyb_data *D;
	hyb_prior *P;
	hyb_chain *C;
	
	gPiFixed = 0;  /* default is not fixed */
	
	if(argc>1) {
		CL_Opts = Get_NewHybs_CLI_Opts(argc,argv);
		
		fprintCL_Probs(stdout, CL_Opts);
	}

	else { 
		#ifdef COMPILE_NEW_HYB_WITH_NO_GUI
			fprintf(stderr,"\n\nThis version of NewHybrids was compiled with COMPILE_NEW_HYB_WITH_NO_GUI defined.  Therefore\n");
			fprintf(stderr,"you must use the command-line interface to run it.  Issue the --help option for more information.\n\n");
			exit(1);
		#endif
	
	    /* if no command line options, then do it interactively */
		/* the very first thing that we want to do is get the current working directory
			and store it in a global variable, because when it enters the GLUT 
			interface it is going to forget about that altogether... */
		sprintf(gPWD,"%s/",getenv("PWD"));
		
		printf("Welcome to the program currently named \"NewHybrids\" Version 1.1 beta");
		printf("\nPre-Released 2 OCTOBER 2002.");
		printf("\nwritten by Eric C. Anderson ([email protected])");
		printf("\nCopyright (c) by The Regents of the University of California\n");
		printf("Please see user documentation for full software agreement.");
		
			
		printf("\n-----------------------\nEnter a \n\t0 to load \"TestDat.txt\"");
		printf("\n\t1 to load \"TestDatWithOptions.dat\"");
		printf("\n\t2 to load \"TestAFLP.dat\"");
		printf("\n\t3 to load \"TestAFLPWithOptions.dat\"");
		printf("\nas the Data File\n");
		printf("\nOr enter the name of the file you wish to use.");
		printf("\n\nRemember that file must be in the directory in which\nthe program resides.\n\n->");

		
		

		/*  read the DATA FILE name or a 0 */
		temp = erdGetNext(File,&temp_d,stdin);
		
		if(temp == 1 && temp_d == 0.0) {  /*  if input was an int equal to zero set File to "TestDat.txt" */
			sprintf(File,"TestDat.dat");
		}
		if(temp == 1 && temp_d == 1.0) { 
			sprintf(File,"TestDatWithOptions.dat");
		}
		if(temp == 1 && temp_d == 2.0) {  
			sprintf(File,"TestAFLP.dat");
		}
		if(temp == 1 && temp_d == 3.0) {  
			sprintf(File,"TestAFLPWithOptions.dat");
		}
		/*  get the DATA: */
		D = GetData(File);

		
		/* Now Process Cline Info */
		ProcessClineOptions(D, gClines);
		
		
		
		/*  now read in the gtyp freq categories */
		printf("\n\n-----------------\n");
		printf("\nNow enter a 0 to read the genotype frequency classes in the file");
		printf("\"TwoGensGtypFreq.txt\".  Or enter the name of the file holding your");
		printf("\nown definitions of genotype frequency classes.\n\n->");
		
		/*  read the GTYP FILE name or a 0 */
		temp = erdGetNext(File,&temp_d,stdin);
		
		if(temp == 1 && temp_d == 0.0) {  /*  if input was an int equal to zero set File to "TestDat.txt" */
			sprintf(File,"TwoGensGtypFreq.txt");
		}
		GetGtypFreqCats(D,File);

		
		/*  now we can process the individual options a little bit  */
		ProcessIndivOptions(D);
		
		/* put alleles from indivs known to be in Purebred categories into the 
			"PriorizedAllelesPile" */
		PriorizeAllelesFromFixedZ(D);
		
		AddPriorizeAllelesFromFile(D, NULL);
		
			
				
		printf("\n\nGive me two small integers (>0) for random number seeds\n\n");
		scanf("%d%d",&tempSeed1,&tempSeed2);
		setall((long)tempSeed1,(long)tempSeed2);
		
		
		
		printf("\n\nEnter the choices for prior type for pi (mixing proportion):\n\t0 for Jeffreys\n\t1 for Uniform\n\t2 to specify it with fixed values\n->");
		scanf("%d",&priorchoice);


		switch(priorchoice) {
			case(0): 
				PiP = JEFFREYS;
				break;
			case(1):
				PiP = UNIFORM;
				break;
			case(2):
				PiP=FIXED_PRIOR;  /* I have to make a new enum for this that reports it properly */
				gPiFixed = 1; 
				gPiFixedValues = (double *)ECA_CALLOC(D->Gn->v,sizeof(double));
				temp_d = 0.0;
				printf("\nEnter values for fixed components of Pi.\nThese will be rescaled so as to sum to 1.0 if necessary.\n");
				CYCLE_g(D)
					printf("%s?  --> ",D->CategoryNames[g]);
					scanf("%lf",&(gPiFixedValues[g]));
					temp_d += gPiFixedValues[g];
				END1CYCLE
				
				printf("\nThank You! Using values:\n");
				CYCLE_g(D)
					gPiFixedValues[g] /= temp_d;
					printf("%s:  %f\n",D->CategoryNames[g],gPiFixedValues[g]);
				END1CYCLE
				break;
			default:
				PiP = JEFFREYS;
				printf("\n\nInvalid choice.  Pi Prior set to Jeffreys by default.\n\n");
		}


		P = CreatePriors(D,PiP,ThP);
		C = CreateLatentChain(D,P);
		InitializeChain(C);
		C->Seed1 = tempSeed1;
		C->Seed2 = tempSeed2;
		
		printf("\n\nData all read and ready!!!\n\n");
		
		printf("\n\nEntering GLUT interface...\n\n");
	}
	
	
	if(CL_Opts != NULL)  {  /* if we didn't do it all interactively, then we have to copy some variables, etc., over */
		/*  get the DATA: */
		printf("DATA_INITIALIZATION: Preparing to read data from %s\n",CL_Opts->DataFilePath);
		D = GetData(CL_Opts->DataFilePath);
		
		/* Now Process Cline Info */
		printf("DATA_INITIALIZATION: Processing cline options (if any)\n");
		ProcessClineOptions(D, gClines);
		
		/* then initialize the gtyp frequency category probabilities */
		printf("DATA_INITIALIZATION: Initializing genotype frequency category probabilities\n");
		if(strlen(CL_Opts->GtypCatFilePath)>0) {
			GetGtypFreqCats(D,CL_Opts->GtypCatFilePath);
		}
		else {
			CopyGtypFreqCatsFromCL(D,CL_Opts);
		}
		
		/*  now we can process the individual options a little bit  */
		ProcessIndivOptions(D);
		
		/* put alleles from indivs known to be in Purebred categories into the 
			"PriorizedAllelesPile" */
		PriorizeAllelesFromFixedZ(D);
		
		/* then add them in from a file, if there is one */
		if(strcmp(CL_Opts->AlleFreqPriorPath,"UNSET") != 0) {
			AddPriorizeAllelesFromFile(D, CL_Opts->AlleFreqPriorPath);
		}
		
		/* and copy across information about the pi priors */
		PiP = CL_Opts->PiPriType;
		ThP = CL_Opts->ThetaPriType;
		if(PiP==FIXED_PRIOR) { int i;
			gPiFixed = 1; 
			gPiFixedValues = (double *)ECA_CALLOC(D->Gn->v,sizeof(double));
			for(i=0;i<D->Gn->v;i++)  {
				gPiFixedValues[i] = CL_Opts->PiFixedValues[i];
			}
		}
		
		
		/* copy across the Trace Report request to the D structure */
		D->PiTraceReport = CL_Opts->PiTraceReport;
		
		
		P = CreatePriors(D,PiP,ThP);
		C = CreateLatentChain(D,P);
		
		if(CL_Opts->Seed1==0 && CL_Opts->Seed2==0) {
			SeedFromFile("newhyb_seeds");
		}
		else {
			printf("SEEDS_FROM_COMMAND_LINE : %ld  %ld\n",CL_Opts->Seed1,CL_Opts->Seed2);
			setall(CL_Opts->Seed1,CL_Opts->Seed1);
			C->Seed1 = (int)CL_Opts->Seed1;
			C->Seed2 = (int)CL_Opts->Seed2;
		}
		
		InitializeChain(C);
	}
	

	/* Here this is set up so that if you use the interactive version, you end up having to use the
	GUI, for now.  You have the choice if you use the command line */
	if(CL_Opts==NULL || CL_Opts->NoGui==0) {
	
		#ifndef COMPILE_NEW_HYB_WITH_NO_GUI
		/*  make the global pointer point to where it ought to */
		gC = C;
		/*  then allocate space for a sliding trace struct that holds up to 1,000 entries */
		gCompleteDataLogLike = gfduAllocSlidingTrace(1000,1);
			

		/*  here must call glutInit from within main, with the command line option */
		/*  pointer, and then call gfmInitGFM, and that does it.   */
		glutInit(&argc, argv);
		gfmInitGFM();
		#else
			fprintf(stderr,"\n\nThis version of NewHybrids was compiled with COMPILE_NEW_HYB_WITH_NO_GUI defined.  Therefore\n");
			fprintf(stderr,"it MUST be invoked with the --no-gui option.  Try adding --no-gui to your last command line.  Cheers.\n\n");
			exit(1);
		#endif
	}
	else {int dummy;
		dummy = RunWithoutGraphics(C, CL_Opts->NumBurnIn, CL_Opts->NumPostBurnIn);
	}


	return(1);
}
示例#7
0
void apprcirc(long *n, double *Hurst, double *L, int *cum, long *seed1, 
              long *seed2, double *output) {
  /* function that generates a fractional Brownian motion or fractional  */
  /* Gaussian noise sample using the approximate circulant method.       */
  /* Input:  *n      determines the sample size N by N=2^(*n)            */
  /*         *Hurst  the Hurst parameter of the trace                    */
  /*         *L      the sample is generated on [0,L]                    */
  /*         *cum    = 0: fractional Gaussian noise is produced          */
  /*                 = 1: fractional Brownian motion is produced         */
  /*         *seed1  seed1 for the random generator                      */
  /*         *seed2  seed2 for the random generator                      */
  /* Output: *seed1  new seed1 of the random generator                   */
  /*         *seed2  new seed2 of the random generator                   */
  /*         *output the resulting sample is stored in this array        */
  long i, N, halfN, generator;
  double scaling, H;
  double *pow_spec;
  double aux;
  complex *a;
  
  halfN = pow(2,*n);
  H = *Hurst;
  N = 2*halfN;
  
  /* set random generator and seeds */
  snorm(); 
  generator = 1;
  gscgn(1, &generator);
  setall(*seed1,*seed2);
  
  /* allocate memory */
  pow_spec = (double*) malloc((halfN+1)*sizeof(double));
  
  /* approximate spectral density */
  FGN_spectrum(pow_spec,halfN,H);
 
  a = malloc(N*sizeof(complex)); 
  a[0].re = sqrt(2*(pow(N,2*H)-pow(N-1,2*H)))*snorm();
  a[0].im = 0.;
  a[halfN].re = sqrt(2*pow_spec[halfN])*snorm();
  a[halfN].im = 0.;
  for(i=1; i<halfN; i++) {
    aux = sqrt(pow_spec[i]);
    a[i].re = aux*snorm();
    a[i].im = aux*snorm();
  }
  for(i=halfN+1; i<N; i++) {
    a[i].re = a[N-i].re;
    a[i].im = -a[N-i].im;
  }
  
  /* real part of Fourier transform of a_re + i a_im gives sample path */
  fft(N,a,1,1.0);
  
  /* rescale to obtain a sample of size 2^(*n) on [0,L] */
  scaling = pow(*L/halfN,H)/sqrt(2*N);
  for(i=0;i<halfN;i++) {
    output[i] = scaling*(a[i].re);
    if (*cum && i>0) {
      output[i] += output[i-1];
    }
  }
  
  /* store the new random seeds and free memory */
  getsd(seed1,seed2);
  
  free(pow_spec);
  free(a);
}
示例#8
0
integer main(int argc, char *argv[])
{
    integer i, j, k, code, dummy;
    struct tm *newtime;
    time_t  long_time;

    remove("success.qo");
    remove("failure.qo");
    if (argc <= 2) {
        sprintf(errmsg, "Usage: %s infile outfile1 [outfile2]\n", argv[0]);
        fatal_error(errmsg);
    }
    fp = fopen(argv[1], "rb");
    if (fp == NULL) {
        sprintf(errmsg, "Error reading problem definition file: %s\n", argv[1]);
        fatal_error(errmsg);
    }
    op = fopen(argv[2], "wb");
    if (op == NULL) {
        sprintf(errmsg, "Error writing output file: %s\n", argv[2]);
        fatal_error(errmsg);
    }
    clrecflag = (argc >= 4);    /* Flag indicating if classical record needed */
    if (clrecflag) {
        cp = fopen(argv[3], "wb");
        if (cp == NULL) {
            sprintf(errmsg, "Error writing output file: %s\n", argv[3]);
            fatal_error(errmsg);
        }
    }
    fread(&code, sizeof(integer), 1, fp);
    if (code != 2001) {
        sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 2001, code);
        fatal_error(errmsg);
    }
    fread(&N, sizeof(integer), 1, fp);  /* Size of sparse matrices */
    if (N <= 0) {
        fatal_error("Size of problem must be >0.\n");
    }
    RHS.N = N;
    fread(&RHS.nterms, sizeof(integer), 1, fp); /* Number of RHS terms */
    if (RHS.nterms <= 0) {
        fatal_error("Number of terms on RHS must be >0.\n");
    }
    fread(&ncollapses, sizeof(integer), 1, fp); /* Number of collapse
                                                 * operators */
    if (ncollapses < 0) {
        fatal_error("Number of collapse operators must be >=0.\n");
    }
    if (ncollapses > 0) {
        Cprobs = vector(1, ncollapses);
        collapses = (struct FS *) calloc(ncollapses, sizeof(struct FS));
        collapses--;
        for (i = 1; i <= ncollapses; i++) {
            collapses[i].N = N;
            fread(&collapses[i].nterms, sizeof(integer), 1, fp);
            if (collapses[i].nterms <= 0) {
                sprintf(errmsg, "Invalid number of terms for collapse operator %d.\n", i);
                fatal_error(errmsg);
            }
        }
    }
    fread(&nopers, sizeof(integer), 1, fp);
    opers = (struct FS *) calloc(nopers, sizeof(struct FS));
    opers--;
    for (i = 1; i <= nopers; i++) {
        opers[i].N = N;
        fread(&opers[i].nterms, sizeof(integer), 1, fp);
        if (opers[i].nterms <= 0) {
            sprintf(errmsg, "Invalid number of terms for average operator %d.\n", i);
            fatal_error(errmsg);
        }
    }

/* First read in terms on RHS of evolution equation */

    file2FS(fp, &RHS);

/* Next read in collapse operator terms */

    if (ncollapses > 0) {
        for (i = 1; i <= ncollapses; i++)
            file2FS(fp, &collapses[i]);
    }
/* Next read in operator terms for averages */

    if (nopers > 0) {
        for (i = 1; i <= nopers; i++)
            file2FS(fp, &opers[i]);
    }
    /* Read in intial conditions */

    fread(&code, sizeof(integer), 1, fp);
    if (code != 2003) {
        sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 2003, code);
        fatal_error(errmsg);
    }
    ystart = N_VNew(2 * N, NULL); /* Get memory for initial condition */
    if (ystart == NULL) {
        fatal_error("Memory allocation failure for initial condition.\n");
    }
    y = N_VNew(2 * N, NULL);    /* Get memory for dependent vector */
    if (y == NULL) {
        fatal_error("Memory allocation failure for state vector.\n");
    }
    fread(N_VDATA(ystart), sizeof(real), N, fp);  /* Read in real parts of
                                                   * initial value */
    fread(N_VDATA(ystart) + N, sizeof(real), N, fp);  /* Read in imaginary
                                                       * parts of initial
                                                       * value */

    fread(&ntimes, sizeof(integer), 1, fp);
    tlist = N_VNew(ntimes, NULL); /* Get memory for time vector */
    if (tlist == NULL) {
        fatal_error("Memory allocation failure for time vector.\n");
    }
    fread(N_VDATA(tlist), sizeof(real), ntimes, fp);
    fread(&iseed, sizeof(integer), 1, fp);
    fread(&ntraj, sizeof(integer), 1, fp);  /* Number of trajectories to
                                             * compute */
    fread(&ftraj, sizeof(integer), 1, fp);  /* Frequency at which expectation */
    /* values are written */
    fread(&dummy, sizeof(integer), 1, fp);  /* Unused parameter */

/* Read in options for differential equation solver */

    method = 0;
    itertype = 0;
    reltol = RELTOL;
    abstol = ABSTOL;
    abstolp = &abstol;
    nabstol = 1;


    if (fread(&code, sizeof(integer), 1, fp) > 0) {
        if (code != 1001) {
            sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 1001, code);
            fatal_error(errmsg);
        }
        fread(&method, sizeof(integer), 1, fp);
        fread(&itertype, sizeof(integer), 1, fp);
        fread(&reltol, sizeof(real), 1, fp);
        fread(&nabstol, sizeof(integer), 1, fp);
        if (nabstol == 1)
            fread(&abstol, sizeof(real), 1, fp);
        else if (nabstol == N) {/* Vector of absolute tolerances */
            abstolv = N_VNew(2 * N, NULL);
            if (abstolv == NULL) {
                fatal_error("Memory allocation failure for absolute tolerance vector.\n");
            }
            fread(N_VDATA(abstolv), sizeof(real), N, fp);
            for (i = 1; i <= N; i++)
                Ith(abstolv, N + i) = Ith(abstolv, i);
            abstolp = abstolv;
        } else {
            fatal_error("Absolute tolerance vector has invalid length.\n");
        }
        fread(&iopt[MAXORD], sizeof(integer), 1, fp);
        fread(&iopt[MXSTEP], sizeof(integer), 1, fp);
        fread(&iopt[MXHNIL], sizeof(integer), 1, fp);
        fread(&ropt[H0],   sizeof(real), 1, fp);
        fread(&ropt[HMAX], sizeof(real), 1, fp);
        fread(&ropt[HMIN], sizeof(real), 1, fp);
    }
/* Allocate arrays for expectation values */

    if (nopers > 0) {
        opr = (N_Vector *) calloc(nopers, sizeof(N_Vector));
        opi = (N_Vector *) calloc(nopers, sizeof(N_Vector));
        if (opr == NULL || opi == NULL) {
            fatal_error("Allocation failure for expectation value array pointers.\n");
        }
        opr--;
        opi--;
        for (i = 1; i <= nopers; i++) {
            opr[i] = N_VNew(ntimes, NULL);
            opi[i] = N_VNew(ntimes, NULL);
            if (opr[i] == NULL || opi[i] == NULL) {
                fatal_error("Allocation failure for expectation value arrays.\n");
            }
        }
    }
/* Set up the random seeds */
    setall(abs(iseed ^ 1234567890L), abs(iseed ^ 987654321L));
    progress = 0;
    if (ncollapses > 0) {       /* Use quantum trajectory algorithm */
        fprintf(stderr, "Integrating differential equation, %d trajectories, %d times.\n", ntraj, ntimes);
        fprintf(stderr, "Progress: ");
        q = N_VNew(2 * N, NULL);/* Get memory for temporary storage */
        if (nopers == 0)        /* Calculate and store wave functions */
            for (i = 1; i <= ntraj; i++)
                mcwfalg(i, ntraj);
        else {                  /* Only store averages of specified operators */
            j = 0;
            while (j < ntraj) {
                clearaver();
                for (i = 1; i <= ftraj; i++) {
                    j++;
                    mcwfalg(j, ntraj);
                }
                writeaver(j);
            }
        }
        N_VFree(q);
    } else {
        fprintf(stderr, "Integrating differential equation, %d times.\n", ntimes);
        fprintf(stderr, "Progress: ");
        integrate();            /* Use direct integration */
    }
    fprintf(stderr, "\n");

/* Tidy up at end of algorithm */

    if (nopers > 0) {
        for (i = 1; i <= nopers; i++) {
            N_VFree(opr[i]);
            N_VFree(opi[i]);
        }
        opr++;
        free(opr);
        opi++;
        free(opi);
    }
    N_VFree(tlist);
    N_VFree(y);
    N_VFree(ystart);


    fclose(fp);
    fclose(op);
    if (clrecflag)
        fclose(cp);

    /* Indicate successful completion */
    time(&long_time);           /* Get time as long integer. */
    newtime = localtime(&long_time);  /* Convert to local time. */
    fp = fopen("success.qo", "w");
    fprintf(fp, "SUCCESS\nSOLVEMC succeeded at %19s\n", asctime(newtime));
    fclose(fp);

    return 0;
}
示例#9
0
int main(void)
{	
	char File[100], DatFile[100], GtypFile[100];
	int temp;
	double temp_d;
	enum prior_type PiP = JEFFREYS, ThP = JEFFREYS;
	int DoAsBurnIn = 0, DoAsReps = 0,i,g;
	time_t StartTime, CurrTime, LastTime, RealRepStartTime, DummyTime;
	double SecondsPerSweep, SecondsRemain;
	int priorchoice;
	long Seed1, Seed2;
	int boing;
	
	hyb_data *D;
	hyb_prior *P;
	hyb_chain *C;
	
	printf("Welcome to the program currently named \"NewHybrids\" Version 1.1 beta");
	printf("\nPre-Released 2 OCTOBER 2002.");
	printf("\nwritten by Eric C. Anderson ([email protected])");
	printf("\nCopyright (c) by The Regents of the University of California\n");
	printf("Please see user documentation for full software agreement.");
	
		
	printf("\n-----------------------\nEnter a \n\t0 to load \"TestDat.txt\"");
	printf("\n\t1 to load \"TestDatWithOptions.dat\"");
	printf("\n\t2 to load \"TestAFLP.dat\"");
	printf("\n\t3 to load \"TestAFLPWithOptions.dat\"");
	printf("\nas the Data File\n");
	printf("\nOr enter the name of the file you wish to use.");
	printf("\n\nRemember that file must be in the directory in which\nthe program resides.\n\n->");

	
	
	
	/*  read the DATA FILE name or a 0 */
	temp = erdGetNext(File,&temp_d,stdin);
	
	if(temp == 1 && temp_d == 0.0) {  /*  if input was an int equal to zero set File to "TestDat.txt" */
		sprintf(File,"TestDat.dat");
	}
	if(temp == 1 && temp_d == 1.0) { 
		sprintf(File,"TestDatWithOptions.dat");
	}
	if(temp == 1 && temp_d == 2.0) {  
		sprintf(File,"TestAFLP.dat");
	}
	if(temp == 1 && temp_d == 3.0) {  
		sprintf(File,"TestAFLPWithOptions.dat");
	}
	/*  get the DATA: */
	D = GetData(File);
	
	sprintf(DatFile,"%s",File);
	
	
	/*  now read in the gtyp freq categories */
	printf("\n\n-----------------\n");
	printf("\nNow enter a 0 to read the genotype frequency classes in the file");
	printf("\"TwoGensGtypFreq.txt\".  Or enter the name of the file holding your");
	printf("\nown definitions of genotype frequency classes.\n\n->");
	
	/*  read the GTYP FILE name or a 0 */
	temp = erdGetNext(File,&temp_d,stdin);
	
	if(temp == 1 && temp_d == 0.0) {  /*  if input was an int equal to zero set File to "TestDat.txt" */
		sprintf(File,"TwoGensGtypFreq.txt");
	}
	GetGtypFreqCats(D,File);
	sprintf(GtypFile,"%s",File);
	
	
	/*  now we can process the individual options a little bit  */
	ProcessIndivOptions(D);
	
	/* put alleles from indivs known to be in Purebred categories into the 
		"PriorizedAllelesPile" */
	PriorizeAllelesFromFixedZ(D);
	AddPriorizeAllelesFromFile(D);
	
	
	printf("\n\nGive me two small integers (>0) for random number seeds\n\n");
	scanf("%d%d",&Seed1,&Seed2);
	setall((long)Seed1,(long)Seed2);
	
	
	
	printf("\n\nEnter the choices for prior type for pi (mixing proportion):\n\t0 for Jeffreys\n\t1 for Uniform\n->");
	scanf("%d",&priorchoice);
	switch(priorchoice) {
		case(0): 
			PiP = JEFFREYS;
			break;
		case(1):
			PiP = UNIFORM;
			break;
		default:
			PiP = JEFFREYS;
			printf("\n\nInvalid choice.  Pi Prior set to Jeffreys by default.\n\n");
	}
	
	printf("\n\nEnter the choices for theta type for pi (mixing proportion):\n\t0 for Jeffreys\n\t1 for Uniform\n->");
	scanf("%d",&priorchoice);
	switch(priorchoice) {
		case(0): 
			ThP = JEFFREYS;
			break;
		case(1):
			ThP = UNIFORM;
			break;
		default:
			ThP = JEFFREYS;
			printf("\n\nInvalid choice.  Theta Prior set to Jeffreys by default.\n\n");
	}
		
	P = CreatePriors(D,PiP,ThP);
	C = CreateLatentChain(D,P);
	
	C->Seed1 = Seed1;
	C->Seed2 = Seed2;
		
	InitializeChain(C);
	
	printf("\n\nData all read and ready!!!\n\n");
	
	
	printf("\n\nEntering Graphics-Free version...\n\n");
	
	printf("\nPlease enter the number of sweeps for BurnIn (must be an integer) \n->");
	scanf("%d",&DoAsBurnIn);
	
	printf("\nPlease enter the number of sweeps to be done after BurnIn (must be an integer) \n->");
	scanf("%d",&DoAsReps);
	
	
	StartTime = time(NULL);
	LastTime = time(NULL);
	
	printf("\nStarting execution at %s\n\n",ctime(&StartTime));
	
	/* then start doing the burn-in reps */
	for(i=0;i<DoAsBurnIn;i++)  {

		SingleSweep(C);
		IncrementValues(C,1);

		if(i%300==0 && i > 0) {
			OutputHistograms(C);
			fprint_PofZ(C);
		}
		
		CurrTime = time(NULL);
		if(difftime(CurrTime,LastTime) > 5.0)  {  /* if it has been 5 seconds since a report */
			LastTime = time(NULL);
			printf("\n\n\n\n\n\nNewHybrids started: %s", ctime(&StartTime));
			printf("\nData = %s, GtypFile = %s, PiPrior = %s, ThetaPrior = %s, Seeds = %d %d",DatFile,GtypFile, PriorType2str(PiP), PriorType2str(ThP), Seed1, Seed2);
			printf("\nCurrently on BurnIn Sweep %d of %d",i,DoAsBurnIn);
			SecondsPerSweep = difftime(LastTime,StartTime)/(double)i;
			printf("\nSweeps per second = %f     Seconds per sweep = %f  ",1.0/SecondsPerSweep,SecondsPerSweep);
			SecondsRemain = (SecondsPerSweep * (double)(DoAsBurnIn-i));
			printf("\nShould finish BurnIn in %.0f seconds.  %.2f minutes.  %.4f hours.   %.4f days.", 
					SecondsRemain,SecondsRemain/60,SecondsRemain/3600,SecondsRemain/(3600*24)); 
					
			/* print out the current pi and the average pi */
			printf("\n\nCurrent Pi:\n");
			CYCLE_g(C->Dat)
				printf("  %.4f",C->Lat->Pi[g]->v);
			END1CYCLE
			
			printf("\nAverage Pi:\n");
			CYCLE_g(C->Dat)
				printf("  %.4f",C->Lat->Pi[g]->Ave);
			END1CYCLE
			printf("\n\n\n\n\n\n");
			fflush(stdout);
		}
	}
	
	printf("\n\n\n************************\n\nDone with %d Burn-In Sweeps\n\n\n*********************\n\n",DoAsBurnIn); 
	/* then reset the averages */
	ResetAllAveragesEtc(C);
	
	printf("\n\n\n\nAverages reset...\n\nStarting data accumulation reps...\n\n");
	
	
	/* then do the actual data collection reps */
	for(i=0;i<DoAsReps;i++)  {

		SingleSweep(C);

		IncrementValues(C,1);

		printf("%d ",i);

		if(i%300==0 && i > 0) {

			OutputHistograms(C);
			fprint_PofZ(C);
		
			printf("\n\n\n\n\n\n\n\n\nNewHybrids Proceeding:");
			printf("\nData = %s, GtypFile = %s, PiPrior = %s, ThetaPrior = %s, Seeds = %d %d",DatFile,GtypFile, PriorType2str(PiP), PriorType2str(ThP), Seed1, Seed2);
			printf("\nCurrently on Sweep %d of %d",i,DoAsReps);
			
			/* print out the current pi and the average pi */
			printf("\n\nCurrent Pi:\n");
			CYCLE_g(C->Dat)
				printf("  %.4f",C->Lat->Pi[g]->v);
			END1CYCLE
			
			printf("\nAverage Pi:\n");
			CYCLE_g(C->Dat)
				printf("  %.4f",C->Lat->Pi[g]->Ave);
			END1CYCLE
			printf("\n\n\n\n\n\n");
			fflush(stdout);
		}
		
	}
	
	/* output the final bits of information */
	OutputHistograms(C);
	fprint_PofZ(C);
	
	/* then let the user know it has finished */
	printf("\n\nProgram New Hybrids completed. ");
	printf("\nData = %s, GtypFile = %s, PiPrior = %s, ThetaPrior = %s, Seeds = %d %d",DatFile,GtypFile, PriorType2str(PiP), PriorType2str(ThP), Seed1, Seed2);

	printf("\n\nOutput is in the following files:");
	printf("\n\taa-LociAndAlleles.txt  --- A listing of loci and alleles read");
	printf("\n\taa-Pi.hist  ---  text file of a histogram representation for");
	printf("\n\t\tthe posterior distribution of Pi");
	printf("\n\taa-PofZ.txt  ---  for each individual in the sample, the posterior probability");
	printf("\n\t\tthat it falls into each of the genotype frequency categories");
	printf("\n\taa-Theta.hist  ---- a histogram representation of the posterior distributions");
	printf("\n\t\tof the allele frequencies in the different populations");
	printf("\n\n");
	
	printf("\n\n\nEnter any integer to exit\n->");
	scanf("%d",&boing);
	
	return(0);
}
示例#10
0
int main(int argc, const char * argv[]){
	int i,j,k, totalSimCount;
	float tempSite;
	int lastBreak;
	double nextTime, currentFreq, probAccept;
	
	
	
	getParameters(argc,argv);
	double N = EFFECTIVE_POPN_SIZE; // effective population size
	setall(seed1, seed2 );

	//Hudson style header
	for(i=0;i<argc;i++)printf("%s ",argv[i]);
	printf("\n%ld %ld\n", seed1, seed2);
	
	i = 0;
        totalSimCount = 0;
	currentTrajectory = malloc(sizeof(float) * TRAJSTEPSTART);
	assert(currentTrajectory);

	while(i < sampleNumber){
		currentTime=0;
		nextTime=999;
		currentSize[0]=1.0;
		currentFreq = 1.0 - (1.0 / (2.0 * N * currentSize[0])); //just to initialize the value
//		printf("popnsize[0]:%d",popnSizes[0]);
		maxTrajSteps = TRAJSTEPSTART;
		
		
		
		initialize();

		j=0;
		activeSweepFlag = 0;
		for(j=0;j<eventNumber && alleleNumber > 1;j++){
			currentEventNumber=j; //need this annoying global for trajectory generation
			if(j == eventNumber - 1){
				nextTime = MAXTIME;
				}
			else{
				nextTime = events[j+1].time;
			}
			// printf("type: %c popID: %d size: %f currentTime: %f nextTime: %f alleleNumber: %d\n",events[j].type,events[j].popID,events[j].popnSize,
			//	currentTime,nextTime,alleleNumber);	
			switch(events[j].type){
				case 'n':
				currentTime = events[j].time;
				currentSize[events[j].popID] = events[j].popnSize;
				//for(i=0;i<npops;i++)
				//	for(j=0;j<npops;j++) printf("%f\n",migMat[i][j]);
				if(activeSweepFlag == 0){
					if(recurSweepMode ==0){
						currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode, currentSize);
					}
				}
				else{
					if(recurSweepMode ==0){
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 		currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                               		currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 		currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                               		currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode, currentSize);
					}
				}
			//	printf("pn0:%d pn1:%d alleleNumber: %d sp1: %d sp2: %d \n", popnSizes[0],popnSizes[1], alleleNumber,sweepPopnSizes[1],
			//							sweepPopnSizes[0]);
				break;
				case 's':
				assert(activeSweepFlag == 0);
				currentTime = events[j].time;
				if (partialSweepMode == 1){
					currentFreq = MIN(partialSweepFinalFreq,1.0 - (1.0 / (2.0 * N * currentSize[0])));
				}
				else{
					currentFreq = 1.0 - (1.0 / (2.0 * N * currentSize[0]));
				}
			//	printf("event%d currentTime: %f nextTime: %f popnSize: %f\n",j,currentTime,nextTime,currentSize);

				//generate a proposed trajectory
				probAccept = proposeTrajectory(currentEventNumber, currentTrajectory, currentSize, sweepMode, currentFreq, &currentFreq, alpha, f0, currentTime);
				while(ranf()>probAccept){
					probAccept = proposeTrajectory(currentEventNumber, currentTrajectory, currentSize, sweepMode, currentFreq, &currentFreq, alpha, f0, currentTime);
					//printf("probAccept: %lf\n",probAccept);
				}
				
				currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
				//printf("currentFreqAfter: %f alleleNumber:%d currentTime:%f\n",currentFreq,alleleNumber,currentTime);
				//printf("pn0:%d pn1:%d alleleNumber: %d sp1: %d sp2: %d \n", popnSizes[0],popnSizes[1], alleleNumber,sweepPopnSizes[1],
				//			sweepPopnSizes[0]);
				if (currentTime < nextTime)
                                        currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
						
				break;
				case 'p': //merging populations
				currentTime = events[j].time;
				//printf("here at P flag time=%f\n",currentTime);
				mergePopns(events[j].popID, events[j].popID2);

				if(activeSweepFlag == 0){
					if(recurSweepMode ==0){
						currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode, currentSize);
					}
				}
				else{
					if(recurSweepMode ==0){
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
						 	currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                        		currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 		currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                               		currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode, currentSize);
					}
				}
				break;
				case 'a':
				currentTime = events[j].time;
				admixPopns(events[j].popID, events[j].popID2, events[j].popID3, events[j].admixProp);
				if(activeSweepFlag == 0){
					if(recurSweepMode ==0){
						currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode,currentSize);
					}
				}
				else{
					if(recurSweepMode ==0){
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
						 	currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
	                                        	currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 		currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                               		currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode,currentSize);
					}
				}
				break;
				case 'A':
				currentTime = events[j].time;
				//printAllActiveNodes();
				addAncientSample(events[j].lineageNumber, events[j].popID, events[j].time, activeSweepFlag, currentFreq);
				//printAllActiveNodes();
				if(activeSweepFlag == 0){
					if(recurSweepMode ==0){
						currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode,currentSize);
					}
				}
				else{
					if(recurSweepMode ==0){
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
						 	currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
	                                        	currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, currentSize);
					}
					else{
						currentTime = sweepPhaseEventsConditionalTrajectory(&breakPoints[0], currentTime, nextTime, sweepSite, \
					 		currentFreq, &currentFreq, &activeSweepFlag, alpha, currentSize, sweepMode, f0, uA);
						if (currentTime < nextTime)
                                               		currentTime = recurrentSweepPhaseGeneralPopNumber(&breakPoints[0], currentTime, nextTime, &currentFreq, alpha, sweepMode,currentSize);
					}
				}
				break;
			}
			
		}
		//finish up the coalescing action!
		if(alleleNumber > 1){
			currentTime = neutralPhaseGeneralPopNumber(&breakPoints[0], currentTime, MAXTIME, currentSize);
		}
		//assign root
	//	root = nodes[0];
		//add Mutations
		if(untilMode==0)
			dropMutations();
		else
			dropMutationsUntilTime(uTime);	

		if(condRecMode == 0){
			if(treeOutputMode == 1){
				//output newick trees
				qsort(breakPoints, breakNumber, sizeof(breakPoints[0]), compare_floats);
				lastBreak = 0;
				printf("\n//\n");
				for(k=0;k<breakNumber;k++){
					tempSite = ((float) breakPoints[k] / nSites) - (0.5/nSites) ; //padding

					if(breakPoints[k] - lastBreak > 0){
						printf("[%d]",breakPoints[k] - lastBreak);
						printTreeAtSite(tempSite); 
						lastBreak = breakPoints[k];
					}
				}
				printf("[%d]",nSites- lastBreak);
				printTreeAtSite(1.0 - (1.0/nSites)); 

			}
			else{
				//Hudson style output
				//errorCheckMutations();
				makeGametesMS(argc,argv);
			}
			//printf("rep: %d\n",i);
                        i++;
		}
		else{
			if(condRecMet == 1){
                                i++;
				makeGametesMS(argc,argv);
				condRecMet = 0;
			}
	
		}
		
		freeTree(nodes[0]);
                totalSimCount += 1;
	}
        if(condRecMode == 1)
        {
            fprintf(stderr, "Needed run %d simulations to get %d with a recombination event within the specified bounds.\n", totalSimCount, i);
        }
	free(currentTrajectory);
	free(currentSize);
	return(0);
}
示例#11
0
文件: ex_io.c 项目: n-t-roff/ex-3.6
/*
 * Read a file from the world.
 * C is command, 'e' if this really an edit (or a recover).
 */
void
rop(int c)
{
	register int i;
	struct stat stbuf;
	short magic;
	static int ovro;	/* old value(READONLY) */
	static int denied;	/* 1 if READONLY was set due to file permissions */

	io = open(file, O_RDONLY);
	if (io < 0) {
		if (c == 'e' && errno == ENOENT) {
			edited++;
			/*
			 * If the user just did "ex foo" he is probably
			 * creating a new file.  Don't be an error, since
			 * this is ugly, and it screws up the + option.
			 */
			if (!seenprompt) {
				ex_printf(" [New file]");
				noonl();
				return;
			}
		}
		syserror();
	}
	if (fstat(io, &stbuf))
		syserror();
	switch (stbuf.st_mode & S_IFMT) {

	case S_IFBLK:
		error(" Block special file");

	case S_IFCHR:
		if (isatty(io))
			error(" Teletype");
		if (samei(&stbuf, "/dev/null"))
			break;
		error(" Character special file");

	case S_IFDIR:
		error(" Directory");

	case S_IFREG:
#ifdef CRYPT
		if (xflag)
			break;
#endif
		i = read(io, (char *) &magic, sizeof(magic));
		lseek(io, 0l, SEEK_SET);
		if (i != sizeof(magic))
			break;
		switch (magic) {

		case 0405:	/* Interdata? overlay */
		case 0407:	/* unshared */
		case 0410:	/* shared text */
		case 0411:	/* separate I/D */
		case 0413:	/* VM/Unix demand paged */
		case 0430:	/* PDP-11 Overlay shared */
		case 0431:	/* PDP-11 Overlay sep I/D */
			error(" Executable");

		/*
		 * We do not forbid the editing of portable archives
		 * because it is reasonable to edit them, especially
		 * if they are archives of text files.  This is
		 * especially useful if you archive source files together
		 * and copy them to another system with ~%take, since
		 * the files sometimes show up munged and must be fixed.
		 */
#if 0
		case 0177545:
		case 0177555:
			error(" Archive");
#endif

		default:
#ifndef BIT8
			if (magic & 0100200)
				error(" Non-ascii file");
#endif
			break;
		}
	}
	if (c != 'r') {
		if (value(READONLY) && denied) {
			value(READONLY) = ovro;
			denied = 0;
		}
		if ((stbuf.st_mode & 0222) == 0 || access(file, 2) < 0) {
			ovro = value(READONLY);
			denied = 1;
			value(READONLY) = 1;
		}
	}
	if (value(READONLY)) {
		ex_printf(" [Read only]");
		flush();
	}
	if (c == 'r')
		setdot();
	else
		setall();
	if (FIXUNDO && inopen && c == 'r')
		undap1 = undap2 = dot + 1;
	rop2();
	rop3(c);
}
void BreakpointDialog::on_bkptClrA_clicked()
{
  setall(false);
}
示例#13
0
/************************ end self doc ***********************************/ 
void main (int argc, char **argv)   
{
   /* declaration of variables */
   FILE *fp;                  /* file pointer */
   char *covarFile = " ";     /* covariance file */
   char *MAPFile = " ";       /* MAP model file */
   int i, j, k;               /* counters */
   int nL;                    /* number of layers */
   int cl;                    /* correlation length */ 
   int pWave;                 /* P-wave flag */
   int sWave;                 /* S-wave flag */
   int density;               /* density flag */
   int nVar;                  /* dimension of the problem */
   int seed;                  /* input seed */ 
   int lim[2];                /* integer limits for target zone */
   int exponential;           /* exponential flag */
   int impedance;             /* impedance flag */
   int verbose;               /* dialogue flag */
   int nPar;                  /* number of active parameters */
   int shift, shift1;         /* used in simulation of more than one */
                              /* parameter */
   long seed1, seed2;         /* seed for random generator */
   float limZ[2];             /* depth limits of target zone */
   float *thick, *alpha, *beta, *rho;
                              /* medium parameters */
   float *buffer;             /* working buffer */
   float aux1, aux2;          /* auxiliar variables */
   float *parm;     	      /* paramter vector */
   float *mean;     	      /* mean vector */
   float *work;               /* working area */
   float **covar;             /* correlation matrix */
   float **covarExp;          /* exponential correlation matrix */
   float *deviate;            /* random gaussian realization */
   float dz;                  /* depth discretization level */
   float depth;               /* current depth */
   
   /* input parameters */
   initargs(argc, argv);
   requestdoc(0);
   
   /* dimension of the problem */
   if (!getparstring("covariance", &covarFile)) covarFile = "covar";
   if (!getparstring("mean", &MAPFile)) MAPFile = "mean";
   if (!getparint("exponential", &exponential)) exponential = 0;
   if (!getparint("impedance", &impedance)) impedance = 0;
   if (!getparint("p", &pWave)) pWave = 1;
   if (!getparint("s", &sWave)) sWave = 1;
   if (!getparint("r", &density)) density = 1;
   if (!getparfloat("dz", &dz)) dz = .5;
   nPar = pWave + sWave + density;
   if (!getparfloat("targetbeg", &limZ[0])) limZ[0] = 0.5; 
   if (!getparfloat("targetend", &limZ[1])) limZ[1] = 1.0;
   if (!getparint("verbose", &verbose)) verbose = 0;

   
   /* random generator seeding */
   seed = getpid();

   fp = fopen(MAPFile, "r");
   if (fp == NULL) err("No model file!\n");
   nL = 0;
   while (fscanf(fp, "%f %f %f %f %f %f\n", 
		 &aux1, &aux1, &aux1, &aux1, &aux1, &aux1) != EOF)
      nL++;
   nL--;
   rewind(fp);

   /* memory allocation */
   alpha = alloc1float(nL + 1);
   beta = alloc1float(nL + 1);
   rho = alloc1float(nL + 1);
   thick = alloc1float(nL + 1);

   if (verbose)
      fprintf(stderr,"  Thickness     rho     vP     qP    vS     qS\n");
   
   for (k = 0; k < nL + 1; k++)
   {
      fscanf(fp, "%f %f %f %f %f %f\n", &thick[k], &rho[k], &alpha[k], 
	     &aux1, &beta[k], &aux2);
      if (verbose)
	 fprintf(stderr,"   %7.4f      %4.3f   %3.2f  %5.1f  %3.2f  %5.1f\n",
		 thick[k], rho[k], alpha[k], aux1, beta[k], aux2);

      if (impedance)
      {
         alpha[k] *= rho[k];
	 beta[k] *= rho[k];
      }
   }
   fclose(fp);

   /* setting lim[0] and lim[1] */
   for (depth = thick[0], i = 1; i <= nL; depth += thick[i], i++)
   {
      if (NINT(depth / dz) <= NINT(limZ[0] / dz)) lim[0] = i;
      if (NINT(depth / dz) < NINT(limZ[1] / dz)) lim[1] = i;
   }

   /* total dimension */
   nVar = nPar * (lim[1] - lim[0] + 1);
   if (verbose)
      fprintf(stderr, "Total dimension of the problem: %d\n", nVar);
   
   /* more memory allocation */
   covar = alloc2float(nVar, nVar);
   covarExp = alloc2float(nVar, nVar);
   parm = alloc1float(nVar * (nVar + 3) / 2 + 1);
   work = alloc1float(nVar);
   mean = alloc1float(nVar);
   deviate = alloc1float(nVar);
   buffer = alloc1float(nPar * (nL + 1));
   
   fp = fopen(covarFile, "r");
   if (fp == NULL) err("No covariance file!\n");
   fread(&covar[0][0], sizeof(float), nVar * nVar, fp);
   fclose(fp);
   
   /* building the mean */
   shift = 0;
   if (pWave)
   {
      for (k = 0, i = lim[0]; i <= lim[1]; i++, k++)
	 mean[k] = alpha[i];
      shift = nVar / nPar;
   }
   if (sWave)
   {
      for (k = 0, i = lim[0]; i <= lim[1]; i++, k++)
	 mean[k + shift] = beta[i];
      shift += nVar / nPar;
   }
   if (density)
   {
      for (k = 0, i = lim[0]; i <= lim[1]; i++, k++)
	 mean[k + shift] = beta[i];
   }

   /* fitting an exponential model */
   if (exponential)
   {
      for (i = 0; i < nVar; i++) 
	 for (j = 0; j < nVar; j++) 
	    covarExp[i][j] = 0;

      for (i = 0; i < nVar; i++)
      {
	 for (cl = 0, j = i; j < nVar; j++, cl++)
	 {
	    if (covar[i][j] / covar[i][i] < 1. / EULER)  break;
	 }
	 
	 for (j = 0; j < nVar; j++) 
	 {
	    covarExp[i][j] += .5 * covar[i][i] * 
	       exp(-(float) ABS(i - j) / (float) cl);
	 }
	 for (j = 0; j < nVar; j++) 
	 {
	    covarExp[j][i] += .5 * covar[i][i] * 
	       exp(-(float) ABS(i - j) / (float) cl);
	 }
      }
      
      for (i = 0; i < nVar; i++)
	 for (j = 0; j < nVar; j++)
	    covar[i][j] = covarExp[i][j];
   }
     
   /* reseting */
   for (i = 0; i < nVar * (nVar + 3) / 2 + 1; i++)
   {
      parm[i] = 0;
      if (i < nVar)
      {
         work[i] = 0;
         deviate[i] = 0;
      }
   }
  
   /* input data for generating realization of the multivariate */
   /* gaussian */
   setgmn(mean, covar[0], nVar, parm); 
   seed1 = (long) seed; seed2 = (long) seed * seed;
   setall(seed1, seed2);  
   
   /* generating the realization */
   genmn(parm, deviate, work);

   /* copying to buffer */
   shift = 0;
   shift1 = 0;

   if (pWave)
   {
      for (j = 0; j < lim[0]; j++)
	 buffer[j] = alpha[j];
      for (k = 0, j = lim[0]; j <= lim[1]; j++, k++)
	 buffer[j] = deviate[k];
      for (j = lim[1]; j < nL + 1; j++)
	 buffer[j] = alpha[j];
      shift = nL;
      shift1 = nVar / nPar;
   }
   
   if (sWave)
   {
      for (j = 0; j < lim[0]; j++)
	 buffer[j + shift] = beta[j];
      for (k = 0, j = lim[0]; j <= lim[1]; j++, k++)
	 buffer[j + shift] = deviate[k + shift1];
      for (j = lim[1]; j < nL + 1; j++)
	 buffer[j + shift] = beta[j];
      shift += nL;
      shift1 += nVar / nPar;
   }
   if (density)
   {
      for (j = 0; j < lim[0]; j++)
	 buffer[j + shift] = rho[j];
      for (k = 0, j = lim[0]; j <= lim[1]; j++, k++)
	 buffer[j + shift] = deviate[k + shift1];
      for (j = lim[1]; j < nL + 1; j++)
	 buffer[j + shift] = rho[j];
   }
   /* outputting */
   fwrite(buffer, sizeof(float), nPar * (nL + 1), stdout);
}
示例#14
0
文件: ex_cmds.c 项目: n-t-roff/ex-3.6
/*
 * Main loop for command mode command decoding.
 * A few commands are executed here, but main function
 * is to strip command addresses, do a little address oriented
 * processing and call command routines to do the real work.
 */
void
commands(bool noprompt, bool exitoneof)
{
	register line *addr;
	register int c;
	register int lchng;
	int given;
	int seensemi;
	int cnt;
	bool hadpr;

	resetflav();
	nochng();
	for (;;) {
		/*
		 * If dot at last command
		 * ended up at zero, advance to one if there is a such.
		 */
		if (dot <= zero) {
			dot = zero;
			if (dol > zero)
				dot = one;
		}
		shudclob = 0;

		/*
		 * If autoprint or trailing print flags,
		 * print the line at the specified offset
		 * before the next command.
		 */
		if (pflag ||
		    (lchng != chng && value(AUTOPRINT) && !inglobal && !inopen && endline)) {
			pflag = 0;
			nochng();
			if (dol != zero) {
				addr1 = addr2 = dot + poffset;
				if (addr1 < one || addr1 > dol)
error("Offset out-of-bounds|Offset after command too large");
				setdot1();
				goto print;
			}
		}
		nochng();

		/*
		 * Print prompt if appropriate.
		 * If not in global flush output first to prevent
		 * going into pfast mode unreasonably.
		 */
		if (inglobal == 0) {
			flush();
			if (!hush && value(PROMPT) && !globp && !noprompt && endline) {
				ex_putchar(':');
				hadpr = 1;
			}
			TSYNC();
		}

		/*
		 * Gobble up the address.
		 * Degenerate addresses yield ".".
		 */
		addr2 = 0;
		given = seensemi = 0;
		do {
			addr1 = addr2;
			addr = address(0);
			c = getcd();
			if (addr == 0) {
				if (c == ',')
					addr = dot;
				else if (addr1 != 0) {
					addr2 = dot;
					break;
				} else
					break;
			}
			addr2 = addr;
			given++;
			if (c == ';') {
				c = ',';
				dot = addr;
				seensemi = 1;
			}
		} while (c == ',');
		if (c == '%') {
			/* %: same as 1,$ */
			addr1 = one;
			addr2 = dol;
			given = 2;
			c = ex_getchar();
		}
		if (addr1 == 0)
			addr1 = addr2;
		if (c == ':')
			c = ex_getchar();

		/*
		 * Set command name for special character commands.
		 */
		tailspec(c);

		/*
		 * If called via : escape from open or visual, limit
		 * the set of available commands here to save work below.
		 */
		if (inopen) {
			if (c=='\n' || c=='\r' || c==CTRL('d') || c==EOF) {
				if (addr2)
					dot = addr2;
				if (c == EOF)
					return;
				continue;
			}
			if (any(c, "o"))
notinvis:
				tailprim(Command, 1, 1);
		}
		switch (c) {

		case 'a':

			switch(peekchar()) {
			case 'b':
/* abbreviate */
				tail("abbreviate");
				setnoaddr();
				mapcmd(0, 1);
				anyabbrs = 1;
				continue;
			case 'r':
/* args */
				tail("args");
				setnoaddr();
				eol();
				pargs();
				continue;
			}

/* append */
			if (inopen)
				goto notinvis;
			tail("append");
			setdot();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2));
			inappend = 0;
			nochng();
			continue;

		case 'c':
			switch (peekchar()) {

/* copy */
			case 'o':
				tail("copy");
				vmacchng(0);
				move();
				continue;

#ifdef CHDIR
/* cd */
			case 'd':
				tail("cd");
				goto changdir;

/* chdir */
			case 'h':
				ignchar();
				if (peekchar() == 'd') {
					register char *p;
					tail2of("chdir");
changdir:
					if (savedfile[0] == '/' || !value(WARN))
						ignore(exclam());
					else
						ignore(quickly());
					if (skipend()) {
						p = getenv("HOME");
						if (p == NULL)
							error("Home directory unknown");
					} else
						getone(), p = file;
					eol();
					if (chdir(p) < 0)
						filioerr(p);
					if (savedfile[0] != '/')
						edited = 0;
					continue;
				}
				if (inopen)
					tailprim("change", 2, 1);
				tail2of("change");
				break;

#endif
			default:
				if (inopen)
					goto notinvis;
				tail("change");
				break;
			}
/* change */
			aiflag = exclam();
			setCNL();
			vmacchng(0);
			setin(addr1);
			delete(0);
			inappend = 1;
			ignore(append(gettty, addr1 - 1));
			inappend = 0;
			nochng();
			continue;

/* delete */
		case 'd':
			/*
			 * Caution: dp and dl have special meaning already.
			 */
			tail("delete");
			c = cmdreg();
			setCNL();
			vmacchng(0);
			if (c)
				YANKreg(c);
			delete(0);
			appendnone();
			continue;

/* edit */
/* ex */
		case 'e':
			tail(peekchar() == 'x' ? "ex" : "edit");
editcmd:
			if (!exclam() && chng)
				c = 'E';
			filename(c);
			if (c == 'E') {
				ungetchar(lastchar());
				ignore(quickly());
			}
			setnoaddr();
doecmd:
			init();
			addr2 = zero;
			laste++;
			ex_sync();
			rop(c);
			nochng();
			continue;

/* file */
		case 'f':
			tail("file");
			setnoaddr();
			filename(c);
			noonl();
/*
			synctmp();
*/
			continue;

/* global */
		case 'g':
			tail("global");
			global(!exclam());
			nochng();
			continue;

/* insert */
		case 'i':
			if (inopen)
				goto notinvis;
			tail("insert");
			setdot();
			nonzero();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2 - 1));
			inappend = 0;
			if (dot == zero && dol > zero)
				dot = one;
			nochng();
			continue;

/* join */
		case 'j':
			tail("join");
			c = exclam();
			setcount();
			nonzero();
			ex_newline();
			vmacchng(0);
			if (given < 2 && addr2 != dol)
				addr2++;
			join(c);
			continue;

/* k */
		case 'k':
casek:
			pastwh();
			c = ex_getchar();
			if (endcmd(c))
				serror("Mark what?|%s requires following letter", Command);
			ex_newline();
			if (!islower(c))
				error("Bad mark|Mark must specify a letter");
			setdot();
			nonzero();
			names[c - 'a'] = *addr2 &~ 01;
			anymarks = 1;
			continue;

/* list */
		case 'l':
			tail("list");
			setCNL();
			ignorf(setlist(1));
			pflag = 0;
			goto print;

		case 'm':
			if (peekchar() == 'a') {
				ignchar();
				if (peekchar() == 'p') {
/* map */
					tail2of("map");
					setnoaddr();
					mapcmd(0, 0);
					continue;
				}
/* mark */
				tail2of("mark");
				goto casek;
			}
/* move */
			tail("move");
			vmacchng(0);
			move();
			continue;

		case 'n':
			if (peekchar() == 'u') {
				tail("number");
				goto numberit;
			}
/* next */
			tail("next");
			setnoaddr();
			ckaw();
			ignore(quickly());
			if (getargs())
				makargs();
			next();
			c = 'e';
			filename(c);
			goto doecmd;

/* open */
		case 'o':
			tail("open");
			oop();
			pflag = 0;
			nochng();
			continue;

		case 'p':
		case 'P':
			switch (peekchar()) {

/* put */
			case 'u':
				tail("put");
				setdot();
				c = cmdreg();
				eol();
				vmacchng(0);
				if (c)
					putreg(c);
				else
					put();
				continue;

			case 'r':
				ignchar();
				if (peekchar() == 'e') {
/* preserve */
					tail2of("preserve");
					eol();
					if (preserve() == 0)
						error("Preserve failed!");
					else
						error("File preserved.");
				}
				tail2of("print");
				break;

			default:
				tail("print");
				break;
			}
/* print */
			setCNL();
			pflag = 0;
print:
			nonzero();
			if (CL && span() > EX_LINES) {
				flush1();
				vclear();
			}
			plines(addr1, addr2, 1);
			continue;

/* quit */
		case 'q':
			tail("quit");
			setnoaddr();
			c = quickly();
			eol();
			if (!c)
quit:
				nomore();
			if (inopen) {
				vgoto(WECHO, 0);
				if (!ateopr())
					vnfl();
				else {
					tostop();
				}
				flush();
				setty(normf);
			}
			cleanup(1);
			ex_exit(0);

		case 'r':
			if (peekchar() == 'e') {
				ignchar();
				switch (peekchar()) {

/* rewind */
				case 'w':
					tail2of("rewind");
					setnoaddr();
					if (!exclam()) {
						ckaw();
						if (chng && dol > zero)
							error("No write@since last chage (:rewind! overrides)");
					}
					eol();
					erewind();
					next();
					c = 'e';
					ungetchar(lastchar());
					filename(c);
					goto doecmd;

/* recover */
				case 'c':
					tail2of("recover");
					setnoaddr();
					c = 'e';
					if (!exclam() && chng)
						c = 'E';
					filename(c);
					if (c == 'E') {
						ungetchar(lastchar());
						ignore(quickly());
					}
					init();
					addr2 = zero;
					laste++;
					ex_sync();
					recover();
					rop2();
					revocer();
					if (status == 0)
						rop3(c);
					if (dol != zero)
						change();
					nochng();
					continue;
				}
				tail2of("read");
			} else
				tail("read");
/* read */
			if (savedfile[0] == 0 && dol == zero)
				c = 'e';
			pastwh();
			vmacchng(0);
			if (peekchar() == '!') {
				setdot();
				ignchar();
				unix0(0);
				filter(0);
				continue;
			}
			filename(c);
			rop(c);
			nochng();
			if (inopen && endline && addr1 > zero && addr1 < dol)
				dot = addr1 + 1;
			continue;

		case 's':
			switch (peekchar()) {
			/*
			 * Caution: 2nd char cannot be c, g, or r
			 * because these have meaning to substitute.
			 */

/* set */
			case 'e':
				tail("set");
				setnoaddr();
				set();
				continue;

/* shell */
			case 'h':
				tail("shell");
				setNAEOL();
				vnfl();
				putpad(TE);
				flush();
				unixwt(1, unixex("-i", (char *) 0, 0, 0));
				vcontin(0);
				continue;

/* source */
			case 'o':
#ifdef notdef
				if (inopen)
					goto notinvis;
#endif
				tail("source");
				setnoaddr();
				getone();
				eol();
				source(file, 0);
				continue;
#ifdef SIGTSTP
/* stop, suspend */
			case 't':
				tail("stop");
				goto suspend;
			case 'u':
				tail("suspend");
suspend:
				if (!dosusp)
					error("Old tty driver|Not using new tty driver/shell");
				c = exclam();
				eol();
				if (!c)
					ckaw();
				onsusp(0);
				continue;
#endif

			}
			/* fall into ... */

/* & */
/* ~ */
/* substitute */
		case '&':
		case '~':
			Command = "substitute";
			if (c == 's')
				tail(Command);
			vmacchng(0);
			if (!substitute(c))
				pflag = 0;
			continue;

/* t */
		case 't':
			if (peekchar() == 'a') {
				tail("tag");
				tagfind(exclam());
				if (!inopen)
					lchng = chng - 1;
				else
					nochng();
				continue;
			}
			tail("t");
			vmacchng(0);
			move();
			continue;

		case 'u':
			if (peekchar() == 'n') {
				ignchar();
				switch(peekchar()) {
/* unmap */
				case 'm':
					tail2of("unmap");
					setnoaddr();
					mapcmd(1, 0);
					continue;
/* unabbreviate */
				case 'a':
					tail2of("unabbreviate");
					setnoaddr();
					mapcmd(1, 1);
					anyabbrs = 1;
					continue;
				}
/* undo */
				tail2of("undo");
			} else
				tail("undo");
			setnoaddr();
			markDOT();
			c = exclam();
			ex_newline();
			undo(c);
			continue;

		case 'v':
			switch (peekchar()) {

			case 'e':
/* version */
				tail("version");
				setNAEOL();
				ex_printf("@(#) Version 3.6, 11/3/80"
				    " (4.0BSD).  git "
				    "160803 14:24"
				    +5);
				noonl();
				continue;

/* visual */
			case 'i':
				tail("visual");
				if (inopen) {
					c = 'e';
					goto editcmd;
				}
				vop();
				pflag = 0;
				nochng();
				continue;
			}
/* v */
			tail("v");
			global(0);
			nochng();
			continue;

/* write */
		case 'w':
			c = peekchar();
			tail(c == 'q' ? "wq" : "write");
wq:
			if (skipwh() && peekchar() == '!') {
				pofix();
				ignchar();
				setall();
				unix0(0);
				filter(1);
			} else {
				setall();
				wop(1);
				nochng();
			}
			if (c == 'q')
				goto quit;
			continue;

/* xit */
		case 'x':
			tail("xit");
			if (!chng)
				goto quit;
			c = 'q';
			goto wq;

/* yank */
		case 'y':
			tail("yank");
			c = cmdreg();
			setcount();
			eol();
			vmacchng(0);
			if (c)
				YANKreg(c);
			else
				yank();
			continue;

/* z */
		case 'z':
			zop(0);
			pflag = 0;
			continue;

/* * */
/* @ */
		case '*':
		case '@':
			c = ex_getchar();
			if (c=='\n' || c=='\r')
				ungetchar(c);
			if (any(c, "@*\n\r"))
				c = lastmac;
			if (isupper(c))
				c = tolower(c);
			if (!islower(c))
				error("Bad register");
			ex_newline();
			setdot();
			cmdmac(c);
			continue;

/* | */
		case '|':
			endline = 0;
			goto caseline;

/* \n */
		case '\n':
			endline = 1;
caseline:
			notempty();
			if (addr2 == 0) {
				if (UP != NOSTR && c == '\n' && !inglobal)
					c = CTRL('k');
				if (inglobal)
					addr1 = addr2 = dot;
				else {
					if (dot == dol)
						error("At EOF|At end-of-file");
					addr1 = addr2 = dot + 1;
				}
			}
			setdot();
			nonzero();
			if (seensemi)
				addr1 = addr2;
			ex_getline(*addr1);
			if (c == CTRL('k')) {
				flush1();
				destline--;
				if (hadpr)
					shudclob = 1;
			}
			plines(addr1, addr2, 1);
			continue;

/* " */
		case '"':
			comment();
			continue;

/* # */
		case '#':
numberit:
			setCNL();
			ignorf(setnumb(1));
			pflag = 0;
			goto print;

/* = */
		case '=':
			ex_newline();
			setall();
			if (inglobal == 2)
				pofix();
			ex_printf("%d", lineno(addr2));
			noonl();
			continue;

/* ! */
		case '!':
			if (addr2 != 0) {
				vmacchng(0);
				unix0(0);
				setdot();
				filter(2);
			} else {
				unix0(1);
				pofix();
				putpad(TE);
				flush();
				unixwt(1, unixex("-c", uxb, 0, 0));
				vclrech(1);	/* vcontin(0); */
				nochng();
			}
			continue;

/* < */
/* > */
		case '<':
		case '>':
			for (cnt = 1; peekchar() == c; cnt++)
				ignchar();
			setCNL();
			vmacchng(0);
			shift(c, cnt);
			continue;

/* ^D */
/* EOF */
		case CTRL('d'):
		case EOF:
			if (exitoneof) {
				if (addr2 != 0)
					dot = addr2;
				return;
			}
			if (!isatty(0)) {
				if (intty)
					/*
					 * Chtty sys call at UCB may cause a
					 * input which was a tty to suddenly be
					 * turned into /dev/null.
					 */
					onhup(0);
				return;
			}
			if (addr2 != 0) {
				setlastchar('\n');
				putnl();
			}
			if (dol == zero) {
				if (addr2 == 0)
					putnl();
				notempty();
			}
			ungetchar(EOF);
			zop(hadpr);
			continue;

		default:
			if (!isalpha(c))
				break;
			ungetchar(c);
			tailprim("", 0, 0);
		}
		ierror("What?|Unknown command character '%c'", c);
	}
}
示例#15
0
/*
 * Read a file from the world.
 * C is command, 'e' if this really an edit (or a recover).
 */
void
rop(int c)
{
	int i;
	struct stat64 stbuf;
	short magic;
	static int ovro;	/* old value(vi_READONLY) */
	static int denied;	/* 1 if READONLY was set due to file permissions */

	io = open(file, 0);
	if (io < 0) {
		if (c == 'e' && errno == ENOENT) {
			edited++;
			/*
			 * If the user just did "ex foo" they're probably
			 * creating a new file.  Don't be an error, since
			 * this is ugly, and it messes up the + option.
			 */
			if (!seenprompt) {
				viprintf(gettext(" [New file]"));
				noonl();
				return;
			}
		}

		if (value(vi_READONLY) && denied) {
			value(vi_READONLY) = ovro;
			denied = 0;
		}
		syserror(0);
	}
	if (fstat64(io, &stbuf))
		syserror(0);
	switch (FTYPE(stbuf) & S_IFMT) {

	case S_IFBLK:
		error(gettext(" Block special file"));
		/* FALLTHROUGH */

	case S_IFCHR:
		if (isatty(io))
			error(gettext(" Teletype"));
		if (samei(&stbuf, "/dev/null"))
			break;
		error(gettext(" Character special file"));
		/* FALLTHROUGH */

	case S_IFDIR:
		error(gettext(" Directory"));

	}
	if (c != 'r') {
		if (value(vi_READONLY) && denied) {
			value(vi_READONLY) = ovro;
			denied = 0;
		}
		if ((FMODE(stbuf) & 0222) == 0 || access((char *)file, 2) < 0) {
			ovro = value(vi_READONLY);
			denied = 1;
			value(vi_READONLY) = 1;
		}
	}
	if (hush == 0 && value(vi_READONLY)) {
		viprintf(gettext(" [Read only]"));
		flush();
	}
	if (c == 'r')
		setdot();
	else
		setall();

	/* If it is a read command, then we must set dot to addr1
	 * (value of N in :Nr ).  In the default case, addr1 will
	 * already be set to dot.
	 *
	 * Next, it is necessary to mark the beginning (undap1) and
	 * ending (undap2) addresses affected (for undo).  Note that
	 * rop2() and rop3() will adjust the value of undap2.
	 */
	if (FIXUNDO && inopen && c == 'r') {
		dot = addr1;
		undap1 = undap2 = dot + 1;
	}
	rop2();
	rop3(c);
}
示例#16
0
void float4::zero() { setall(0); };
示例#17
0
float4::float4(const f32 v)
{
	setall(v);
};
void BreakpointDialog::on_bkptSA_clicked()
{
  setall(true);
}
示例#19
0
文件: wav2rtp.c 项目: pol51/wav2rtp
int main(int argc, char ** argv)
{


    wr_rtp_filter_t wavfile_filter;

    wr_rtp_filter_t gamma_delay_filter;
    wr_rtp_filter_t uniform_delay_filter;

    wr_rtp_filter_t markov_losses_filter;
    wr_rtp_filter_t independent_losses_filter;

    wr_rtp_filter_t log_filter;
    wr_rtp_filter_t pcap_filter;
    wr_rtp_filter_t wavfile_output_filter;
    wr_rtp_filter_t sipp_filter;
    wr_rtp_filter_t sort_filter;

    wr_errorcode_t retval;

    /* parse options */
    retval = get_options(argc, argv, NULL, NULL);
    if (retval == WR_FATAL){
        fprintf(stderr, "FATAL ERROR: %s\n", wr_error);
        return retval;
    }else if (retval == WR_STOP){
        return 0;
    }

    /* initialize random number generator */
    {
        unsigned seed;
        struct timeval tv;
        gettimeofday(&tv, NULL);
        memcpy(&seed, &tv, sizeof(seed));
        srandom(seed);
        setall(random(), random());
    }

    wr_rtp_filter_create(&wavfile_filter, "input wav file filter", &wr_do_nothing_on_notify);

    wr_rtp_filter_create(&gamma_delay_filter, "gamma delay intermediate filter", &wr_gamma_delay_filter_notify);
    wr_rtp_filter_create(&uniform_delay_filter, "uniform_delay intermediate filter", &wr_uniform_delay_filter_notify);

    wr_rtp_filter_create(&markov_losses_filter, "markov_losses intermediate filter", &wr_markov_losses_filter_notify);
    wr_rtp_filter_create(&independent_losses_filter, "independent_losses intermediate filter", &wr_independent_losses_filter_notify);

    wr_rtp_filter_create(&log_filter, "log intermediate filter", &wr_log_filter_notify);
    wr_rtp_filter_create(&pcap_filter, "pcap output filter", &wr_pcap_filter_notify);
    wr_rtp_filter_create(&log_filter, "log filter", &wr_log_filter_notify);
    wr_rtp_filter_create(&sipp_filter, "sipp filter", &wr_sipp_filter_notify);
    wr_rtp_filter_create(&sort_filter, "sort filter", &wr_sort_filter_notify);
    wr_rtp_filter_create(&wavfile_output_filter, "sort filter", &wr_wavfile_output_filter_notify);
   
    wr_rtp_filter_append_observer(&wavfile_filter, &gamma_delay_filter);
    wr_rtp_filter_append_observer(&gamma_delay_filter, &uniform_delay_filter);
    wr_rtp_filter_append_observer(&uniform_delay_filter, &sort_filter);
    wr_rtp_filter_append_observer(&sort_filter, &markov_losses_filter);
    wr_rtp_filter_append_observer(&markov_losses_filter, &independent_losses_filter);

    wr_rtp_filter_append_observer(&independent_losses_filter, &log_filter);
    wr_rtp_filter_append_observer(&independent_losses_filter, &pcap_filter);
    wr_rtp_filter_append_observer(&independent_losses_filter, &wavfile_output_filter);
    wr_rtp_filter_append_observer(&independent_losses_filter, &sipp_filter);
   
    wr_wavfile_filter_start(&wavfile_filter);

    return 0; 
}
示例#20
0
int main(int argc, char * argv[])
{
	int i;
	parameters ap;

	long seed1=0,seed2=0; 

	simplmat <long> nTotal;
	simplmat <long> NTotal;
	simplmat <long> nOcupado;
	simplmat <long> NOcupado;
	bool priPro=false;
	
   	if( argc==2 )
   	{
        if( readParms(argv[1],ap) )
        {
        	cerr << "bad parms file " << argv[1] << endl;
        	exit(1);
        }
		seed1 = ap.rndSeed;
		if(seed1==-1)
			seed1=time(0);
		seed2 = (seed1+1);

		setall(seed1,seed2);

		nTotal.resize(ap.tFinal+1);
		nTotal.fill(0);
		NTotal.resize(ap.tFinal+1);
		NTotal.fill(0);
		NOcupado.resize(ap.tFinal+1);
		NOcupado.fill(0);
		nOcupado.resize(ap.tFinal+1);
		nOcupado.fill(0);
		double timeOcupa;
		
		if( ap.pomac )
		{
			ifstream pomacIn;
			while( ReadPomacParms(pomacIn,ap) )
					timeOcupa = DeterministicInvasion(ap,nTotal,NTotal,nOcupado,NOcupado);
		}
		else
		{
			if( ap.fullStoch )
				timeOcupa = StochasticInvasion(ap,nTotal,NTotal,nOcupado,NOcupado);
			else
				timeOcupa = DeterministicInvasion(ap,nTotal,NTotal,nOcupado,NOcupado);
		}	
		
		if(!ap.pomac)
		{
			ostringstream fname;
			fname << ap.fName << ".out"<< ends;

            
			fstream datafile;
			datafile.open(fname.str().c_str(),ios::in);
			if(!datafile )
				priPro=true;
			datafile.close();
			datafile.clear();
			datafile.open(fname.str().c_str(), ios::out | ios::app);
			if( !datafile )
				{
					cerr << "Cannot open file: " << ap.fName << endl;
					return 0;
				}
				if( priPro )
				{
					datafile << "DimX\tDimY\ttFinal\tg\tdj0\tdj1\talfa\tb\tda\tdensIni\tTime\tJuv\tAd\tJuvOcupa\tAdOcupa" << endl;				
					priPro = false;
				}

			for(i=0; i<ap.tFinal+1; i++)
			{
//				if(nOcupado(i)==0 && NOcupado(i)==0)
//					break;
				datafile << ap.DimX << "\t"
					<< ap.DimY << "\t"
					<< ap.tFinal << "\t"
					<< ap.g << "\t"
					<< ap.dj0 << "\t"
					<< ap.dj1 << "\t"
					<< ap.alfa << "\t"
					<< ap.b << "\t"
					<< ap.da << "\t"
					<< ap.densIni << "\t"
					<< i << "\t"
					<< nTotal(i) << "\t"
					<< NTotal(i) << "\t"
					<< nOcupado(i) << "\t"
					<< NOcupado(i) << endl;
			}	

			datafile << ap.DimX << "\t"
					<< ap.DimY << "\t"
					<< ap.tFinal << "\t"
					<< ap.g << "\t"
					<< ap.dj0 << "\t"
					<< ap.dj1 << "\t"
					<< ap.alfa << "\t"
					<< ap.b << "\t"
					<< ap.da << "\t"
					<< ap.densIni << "\t"
					<< "Time50%\t" 
					<< timeOcupa << endl;

		}

		return(0);

	}
	else
	{
        cerr << "Syntaxis: inva parms.dat" << endl;
    	exit(1);
    }
        
	return 0;
}
示例#21
0
文件: semip_gcc.c 项目: caitouwh/kod
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  
// Local variables for the gateway function

// semip_gc(bdraw,adraw,pdraw,sdraw,rdraw,vmean,amean,zmean,yhat,
// y,x,W,ndraw,nomit,nsave,n,k,m,mobs,a,nu,d0,rval,mm,kk,detval,ngrid,TI,TIc)
     
	// (The inputs are passed to the subroutine and the outputs
	//  are extracted from the subroutine and passed back to Matlab.)

  double *bdraw,*adraw,*pdraw,*sdraw,*rdraw,*vmean,*amean,*zmean,*yhat;
  double *y,*x,*W,*a,nu,d0,rval,mm,kk,*detval,ngrid,*TI,*TIc,*m_obs;
  int i,ndraw,nomit,nsave,n,k,m,*mobs;
  
  long *Seed1, *Seed2;
  int buflen, status, flag;
  char *phrase;
  static char phrase2[8];
  
    phrase2[0] = 'h';
    phrase2[1] = 'h';
    phrase2[2] = 'i';
    phrase2[3] = 't';
    phrase2[4] = 'h';
    phrase2[5] = 'e';
    phrase2[6] = 'r';
    phrase2[7] = 'e';



  /* Check for proper number of arguments. */

  if(nrhs == 20) {  
     flag = 0;
    phrase = phrase2;
  } else if (nrhs == 21){
    flag = 1;
  } else {
    mexErrMsgTxt("semip_gc: 20 or 21 inputs required.");
  }

 
  if(nlhs != 9) {
    mexErrMsgTxt("semip_gcc: 9 output arguments needed");
  }


    if (flag == 1) {

    // input must be a string
    if ( mxIsChar(prhs[20]) != 1)
      mexErrMsgTxt("semip_gc: seed must be a string.");
    // input must be a row vector
    if (mxGetM(prhs[20])!=1)
      mexErrMsgTxt("semip_gc: seed input must be a row vector.");

    // get the length of the input string
    buflen = (mxGetM(prhs[20]) * mxGetN(prhs[20])) + 1;

    // allocate memory for input string
    phrase = mxCalloc(buflen, sizeof(char));

    // copy the string data from prhs[0] into a C string input_ buf.
    // If the string array contains several rows, they are copied,
    // one column at a time, into one long string array.
    //
    status = mxGetString(prhs[20], phrase, buflen);
    if(status != 0)
      mexWarnMsgTxt("semip_gc: Not enough space. seed string truncated.");
    }
    
    // allow the user to set a seed or rely on clock-based seed
   if (flag == 0) {
    setSeedTimeCore(phrase);
   } else {
	phrtsd(phrase,&Seed1,&Seed2);
    setall(Seed1,Seed2);
   }


//  Parse input arguments

// semip_gcc(y,x,W,ndraw,nomit,nsave,n,k,m,mobs,a,nu,d0,rval,mm,kk,detval,ngrid,TI,TIc);

     y = mxGetPr(prhs[0]);
     x = mxGetPr(prhs[1]);
	 W = mxGetPr(prhs[2]);
	 ndraw = (int) mxGetScalar(prhs[3]);
	 nomit = (int) mxGetScalar(prhs[4]);
	 nsave = (int) mxGetScalar(prhs[5]);
	 n = (int) mxGetScalar(prhs[6]);
	 k = (int) mxGetScalar(prhs[7]);
	 m = (int) mxGetScalar(prhs[8]);
	 m_obs = mxGetPr(prhs[9]);
     a = mxGetPr(prhs[10]);
	 nu = mxGetScalar(prhs[11]);
	 d0 = mxGetScalar(prhs[12]);
	 rval = mxGetScalar(prhs[13]);
	 mm = mxGetScalar(prhs[14]);
	 kk = mxGetScalar(prhs[15]);
	 detval = mxGetPr(prhs[16]);
	 ngrid = (int) mxGetScalar(prhs[17]);	 
	 TI = mxGetPr(prhs[18]);
	 TIc = mxGetPr(prhs[19]);
	 

	// no need for error checking on inputs
	// since this was done in the matlab function

	  // Transfer m_obs into an integer vector

	 //(1) Make integer vector storage
	 
	 mobs = ivector(0,m-1);

	 //(2) Put m_obs into mobs

	for(i=0; i<m; i++){
		mobs[i] = (int) m_obs[i];
	}
			

    /* Create matrix mxArrays for the return arguments */
	 //[bdraw,adraw,pdraw,sdraw,rdraw,vmean,amean,zmean,yhat,cntr]

    plhs[0] = mxCreateDoubleMatrix(nsave,k, mxREAL);	// beta draws
	plhs[1] = mxCreateDoubleMatrix(nsave,m, mxREAL);	// a-draws
	plhs[2] = mxCreateDoubleMatrix(nsave,1, mxREAL);	// rho draws
	plhs[3] = mxCreateDoubleMatrix(nsave,1, mxREAL);	// sige draws
	plhs[4] = mxCreateDoubleMatrix(nsave,1, mxREAL);	// r-draws
	plhs[5] = mxCreateDoubleMatrix(m,1, mxREAL);		// v-means
	plhs[6] = mxCreateDoubleMatrix(m,1, mxREAL);		// a-means
	plhs[7] = mxCreateDoubleMatrix(n,1, mxREAL);		// z-means
	plhs[8] = mxCreateDoubleMatrix(n,1, mxREAL);		// yhat-means


	// Get pointers to the data in the mxArrays for the C-subroutine


    bdraw = mxGetPr(plhs[0]);
	adraw = mxGetPr(plhs[1]);
	pdraw = mxGetPr(plhs[2]);	
	sdraw = mxGetPr(plhs[3]);
	rdraw = mxGetPr(plhs[4]);
	vmean = mxGetPr(plhs[5]);
	amean = mxGetPr(plhs[6]);
	zmean = mxGetPr(plhs[7]);
	yhat  = mxGetPr(plhs[8]);

// Call the Subroutine

    semip_gc(bdraw,adraw,pdraw,sdraw,rdraw,vmean,amean,zmean,yhat,y,x,W,ndraw,nomit,nsave,n,k,m,mobs,a,nu,d0,rval,mm,kk,detval,ngrid,TI,TIc);

// free up mobs
	
	free_ivector(mobs,0);


}
示例#22
0
integer main(integer argc, char *argv[])
{
    integer i, j, l, code;
    struct tm *newtime;
    time_t  long_time;

    remove("success.qo");
    remove("failure.qo");
    if (argc <= 2) {
        sprintf(errmsg, "Usage: %s infile outfile1 [outfile2]\n", argv[0]);
        fatal_error(errmsg);
    }
    fp = fopen(argv[1], "rb");
    if (fp == NULL) {
        sprintf(errmsg, "Error reading problem definition file: %s\n", argv[1]);
        fatal_error(errmsg);
    }
    op = fopen(argv[2], "wb");

    if (op == NULL) {
        sprintf(errmsg, "Error writing output file: %s\n", argv[2]);
        fatal_error(errmsg);
    }
    photocurflag = (argc >= 4); /* Flag indicating if photocurrent record
                                 * needed */
    if (photocurflag) {
        php = fopen(argv[3], "wb");
        if (php == NULL) {
            sprintf(errmsg, "Error writing output file: %s\n", argv[3]);
            fatal_error(errmsg);
        }
    }
    fread(&code, sizeof(integer), 1, fp);
    if (code != 3001) {
        sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 3001, code);
        fatal_error(errmsg);
    }
    fread(&N, sizeof(integer), 1, fp);  /* Size of sparse matrices */
    RHS.N = N;
    fread(&RHS.nterms, sizeof(integer), 1, fp); /* Number of RHS terms */

    fread(&nhomodyne, sizeof(integer), 1, fp);  /* Number of homodyne
                                                 * operators */
    homodyne = (struct FS *) calloc(nhomodyne, sizeof(struct FS));
    homodyne--;
    for (i = 1; i <= nhomodyne; i++) {
        homodyne[i].N = N;
        fread(&homodyne[i].nterms, sizeof(integer), 1, fp);
    }

    fread(&nheterodyne, sizeof(integer), 1, fp);  /* Number of heterodyne
                                                   * operators */
    heterodyne = (struct FS *) calloc(nheterodyne, sizeof(struct FS));
    heterodyne--;
    for (i = 1; i <= nheterodyne; i++) {
        heterodyne[i].N = N;
        fread(&heterodyne[i].nterms, sizeof(integer), 1, fp);
    }

    fread(&ncollapses, sizeof(integer), 1, fp); /* Number of collapse
                                                 * operators */
    if (ncollapses > 0) {
        fatal_error("Jump processes are not currently supported.");
    }
    Cprobs = vector(1, ncollapses);
    collapses = (struct FS *) calloc(ncollapses, sizeof(struct FS));
    collapses--;
    for (i = 1; i <= ncollapses; i++) {
        collapses[i].N = N;
        fread(&collapses[i].nterms, sizeof(integer), 1, fp);
    }

    fread(&nopers, sizeof(integer), 1, fp); /* Number of operators for which
                                             * to calculate averages */
    opers = (struct FS *) calloc(nopers, sizeof(struct FS));
    opers--;
    for (i = 1; i <= nopers; i++) {
        opers[i].N = N;
        fread(&opers[i].nterms, sizeof(integer), 1, fp);
    }

/* First read in terms on RHS of evolution equation */

    file2FS(fp, &RHS);

/* Next read in homodyne operator terms */

    if (nhomodyne > 0) {
        h**o = vector(1, nhomodyne);
        for (i = 1; i <= nhomodyne; i++)
            file2FS(fp, &homodyne[i]);
    }
/* Next read in heterodyne operator terms */

    if (nheterodyne > 0) {
        heteror = vector(1, nheterodyne);
        heteroi = vector(1, nheterodyne);
        for (i = 1; i <= nheterodyne; i++)
            file2FS(fp, &heterodyne[i]);
    }
/* Next read in collapse operator terms */

    if (ncollapses > 0) {
        for (i = 1; i <= ncollapses; i++)
            file2FS(fp, &collapses[i]);
    }
/* Finally read in operator terms for averages */

    if (nopers > 0) {
        for (i = 1; i <= nopers; i++)
            file2FS(fp, &opers[i]);
    }
/* Read in intial conditions */

    fread(&code, sizeof(integer), 1, fp);
    if (code != 2003) {
        sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 2003, code);
        fatal_error(errmsg);
    }
    ystart = N_VNew(2 * N, NULL); /* Get memory for initial condition */
    if (ystart == NULL) {
        fatal_error("Memory allocation failure for initial condition.\n");
    }
    y = N_VNew(2 * N, NULL);    /* Get memory for dependent vector */
    if (y == NULL) {
        fatal_error("Memory allocation failure for state vector.\n");
    }
    fread(N_VDATA(ystart), sizeof(real), N, fp);  /* Read in real parts of
                                                   * initial value */
    fread(N_VDATA(ystart) + N, sizeof(real), N, fp);  /* Read in imaginary
                                                       * parts of initial
                                                       * value */

    fread(&ntimes, sizeof(integer), 1, fp);
    tlist = N_VNew(ntimes, NULL); /* Get memory for time vector */
    if (tlist == NULL) {
        fatal_error("Memory allocation failure for time vector.\n");
    }
    fread(N_VDATA(tlist), sizeof(real), ntimes, fp);

/* Check that the list of times is equally spaced */

    top = Ith(tlist, 1);
    deltat = (Ith(tlist, ntimes) - top) / (ntimes - 1);
    for (i = 1; i <= ntimes; i++) {
        if (fabs(Ith(tlist, i) - top - (i - 1) * deltat) > 0.01 * deltat) {
            fatal_error("List of times must be equally spaced.\n");
        }
    }

    fread(&iseed, sizeof(integer), 1, fp);
    fread(&ntraj, sizeof(integer), 1, fp);  /* Number of trajectories to
                                             * compute */
    fread(&ftraj, sizeof(integer), 1, fp);  /* Frequency at which expectation
                                             * values are written */
    fread(&refine, sizeof(integer), 1, fp); /* Substeps between entries in
                                             * tlist over which noise is
                                             * constant */

    /* Calculate internal step size and noise amplitudes */
    dt = deltat / refine;
    namplr = 1.0 / sqrt(dt);
    namplc = 1.0 / sqrt(2.0 * dt);
    head = 0;

/* Allocate memory for noise buffers */

    if (nhomodyne > 0) {
        homnoise = N_VNew(nhomodyne, NULL);
        if (homnoise == NULL) {
            fatal_error("Memory allocation failure for homodyne noise buffer.\n");
        }
    }
    if (nheterodyne > 0) {
        hetnoiser = N_VNew(nheterodyne, NULL);
        hetnoisei = N_VNew(nheterodyne, NULL);
        if (hetnoiser == NULL || hetnoisei == NULL) {
            fatal_error("Memory allocation failure for heterodyne noise buffer.\n");
        }
    }
/* Read in options for differential equation solver */

    method = 0;
    itertype = 0;
    reltol = RELTOL;
    abstol = ABSTOL;
    abstolp = &abstol;
    nabstol = 1;

    if (fread(&code, sizeof(integer), 1, fp) > 0) {
        if (code != 1001) {
            sprintf(errmsg, "Invalid code in %s, expected %d, found %d.\n", argv[0], 1001, code);
            fatal_error(errmsg);
        }
        fread(&method, sizeof(integer), 1, fp);
        fread(&itertype, sizeof(integer), 1, fp);
        fread(&reltol, sizeof(real), 1, fp);
        fread(&nabstol, sizeof(integer), 1, fp);
        if (nabstol == 1)
            fread(&abstol, sizeof(real), 1, fp);
        else if (nabstol == N) {/* Vector of absolute tolerances */
            abstolv = N_VNew(2 * N, NULL);
            if (abstolv == NULL) {
                fatal_error("Memory allocation failure for absolute tolerance vector.\n");
            }
            fread(N_VDATA(abstolv), sizeof(real), N, fp);
            for (i = 1; i <= N; i++)
                Ith(abstolv, N + i) = Ith(abstolv, i);
            abstolp = abstolv;
        } else {
            fatal_error("Absolute tolerance vector has invalid length.\n");
        }
        fread(&iopt[MAXORD], sizeof(integer), 1, fp);
        fread(&iopt[MXSTEP], sizeof(integer), 1, fp);
        fread(&iopt[MXHNIL], sizeof(integer), 1, fp);
        fread(&ropt[H0],   sizeof(real), 1, fp);
        fread(&ropt[HMAX], sizeof(real), 1, fp);
        fread(&ropt[HMIN], sizeof(real), 1, fp);
    }
/* Allocate arrays for expectation values */

    if (nopers > 0) {
        opr = (N_Vector *) calloc(nopers, sizeof(N_Vector));
        opi = (N_Vector *) calloc(nopers, sizeof(N_Vector));
        if (opr == NULL || opi == NULL) {
            fatal_error("Allocation failure for expectation value array pointers.\n");
        }
        opr--;
        opi--;
        for (i = 1; i <= nopers; i++) {
            opr[i] = N_VNew(ntimes, NULL);
            opi[i] = N_VNew(ntimes, NULL);
            if (opr[i] == NULL || opi[i] == NULL) {
                fatal_error("Allocation failure for expectation value arrays.\n");
            }
        }
    }
    /* Set up the random seeds */
    setall(abs(iseed ^ 1234567890L), abs(iseed ^ 987654321L));

    pl = vector(1, 2 * N);      /* Storage for complex wave function */
    q = vector(1, 2 * N);       /* Temporary complex storage */

    fprintf(stderr, "Integrating stochastic differential equation, %d trajectories, %d times:\n", ntraj, ntimes);
    progress = 0;
    fprintf(stderr, "Progress: ");

    if (nopers == 0)
        for (i = 1; i <= ntraj; i++)
            sdesim(i, ntraj);
    else {
        j = 0;
        while (j < ntraj) {
            clearaver();
            for (i = 1; i <= ftraj; i++) {
                j++;
                sdesim(j, ntraj);
            }
            writeaver(j);
        }
    }

    fprintf(stderr, "\n");

/* Tidy up at end of algorithm */

    if (nopers > 0) {
        for (i = 1; i <= nopers; i++) {
            N_VFree(opr[i]);
            N_VFree(opi[i]);
        }
        opr++;
        free(opr);
        opi++;
        free(opi);
    }
    N_VFree(tlist);
    N_VFree(y);
    N_VFree(ystart);

    fclose(fp);
    fclose(op);

    free_vector(q, 1, 2 * N);
    free_vector(pl, 1, 2 * N);

    if (photocurflag)
        fclose(php);
    if (clrecflag)
        fclose(cp);

    /* Indicate successful completion */
    time(&long_time);           /* Get time as long integer. */
    newtime = localtime(&long_time);  /* Convert to local time. */
    fp = fopen("success.qo", "w");
    fprintf(fp, "SOLVESDE succeeded at %19s\n", asctime(newtime));
    fclose(fp);

    return 0;
}
示例#23
0
文件: wzq.cpp 项目: piaocoder/Gobang
/*_____________________________________________________________________________________*/
CPoint wzq::getmax(bool color)
{
	CPoint turnback(0,0);
	setall();
	begin:
	bool x = 0;
	int fx = 0, fy = 1;
	for (int ix = 0; ix < 15; ix++)
		{
			for (int iy = 0; iy <15; iy++)
			{
				if (wzq::nicest[ix][iy] == 0)
				{
					if (get_victory2(ix,iy,fx,fy,false) == true)
						fx = ix,fy = iy,x = 1;
				}
			}	
		}
	//找最大
	if (x == 0)
	{
		for (int ix = 0; ix < 15; ix++)
		{
			for (int iy  =0; iy < 15; iy++)
			{
				if (wzq::nicest[ix][iy] != 1/*不输*/)
				{
					if (get_victory2(ix,iy,turnback.x,turnback.y,false) == true)
						turnback.x = ix,turnback.y = iy,x = 1;
				}
			}
		}
		if (x==0)
		{
			for (int ix = 0; ix <= 14; ix++)
			{
				for (int iy = 0; iy <= 14; iy++)
				{
					if (get_victory2(ix,iy,turnback.x,turnback.y,false) == true)
						turnback.x=ix,turnback.y=iy,x=1;
				}
			}
		}
		if (x==0)
			turnback.x =7,turnback.y =7;
		return turnback;
	}//找完
	for (ix = 0; ix < 15; ix++)
	{
		for (int iy = 0; iy < 15; iy++)
		{
			wzq::trygo[ix][iy] = wzq::map[ix][iy];
		}
	}
	//填
	wzq::checkgo(fx,fy, color,1,fx,fy);
	//预测
	if (nicest[fx][fy] == 2)//win
	{
		turnback.x = fx,turnback.y = fy;
		return turnback;
	}
	else
	{
		goto begin;//重来一次
	}
	//判断
}
示例#24
0
int main(int ARGC, char *ARGV[]) {
  double loglik,bestloglik;
  int iter;
  int D;
  int K;
  int** M;
  int* N;
  int V;
  double alpha;
  double eta;
  double psi;
  double phi;
  double** post_beta;
  double** post_theta;
  double* post_gamma;
  double* post_pi;
  int*** w;
  int*** s;     /* Stop words */
  int*** z;
  int*** best_z;
  int** labels;
  int malloc_dim_1;
  int malloc_dim_2;
  int malloc_dim_3;
  int nIter;
  int dumpInterval;

  if(ARGC != 5) {
    fprintf(stderr, "usage %s <entities> <labels> <nIter> <dumpInterval>\n", ARGV[0]);
    exit(1);
  }

  fprintf(stderr, "-- This program was automatically generated using HBC (v 0.7 beta) from LDA.hier\n--     see http://hal3.name/HBC for more information\n");
  fflush(stderr);
  setall(time(0),time(0));   /* initialize random number generator */


  /* variables defined with --define */
  K = 40;
  //alpha = 0.1;
  alpha = 1.0;
  psi = 1.0;
  phi = 1.0;
  eta = 0.1;

  fprintf(stderr, "Loading data...\n");
  fflush(stderr);
  /* variables defined with --loadD */
  w = load_discrete3(ARGV[1], &D, &N, &M, &V);
  labels = load_labels(ARGV[2], &D, &K);
  nIter = atoi(ARGV[3]);
  dumpInterval = atoi(ARGV[4]);

  /* variables defined with --loadM or --loadMI */

  fprintf(stderr, "Allocating memory...\n");
  fflush(stderr);

  post_gamma = (double *) malloc(sizeof(double) * (V + 1));
  
  post_pi = (double *) malloc(sizeof(double) * (2 + 1));  

  post_beta = (double**) malloc(sizeof(double*) * (1+(K)-(1)));
  for (malloc_dim_1=1; malloc_dim_1<=K; malloc_dim_1++) {
    post_beta[malloc_dim_1-1] = (double*) malloc(sizeof(double) * (1+((V) + (1))-(1)));
  }

  post_theta = (double**) malloc(sizeof(double*) * (1+(D)-(1)));
  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    post_theta[malloc_dim_1-1] = (double*) malloc(sizeof(double) * (1+((K) + (1))-(1)));
  }

  s = (int***) malloc(sizeof(int**) * (1+(D)-(1)));
  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    s[malloc_dim_1-1] = (int**) malloc(sizeof(int*) * (1+(N[malloc_dim_1-1])-(1)));
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      s[malloc_dim_1-1][malloc_dim_2-1] = (int*) malloc(sizeof(int) * (1+((M[malloc_dim_1-1][malloc_dim_2-1]) + (1))-(1)));
    }
  }

  z = (int***) malloc(sizeof(int**) * (1+(D)-(1)));
  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    z[malloc_dim_1-1] = (int**) malloc(sizeof(int*) * (1+(N[malloc_dim_1-1])-(1)));
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      z[malloc_dim_1-1][malloc_dim_2-1] = (int*) malloc(sizeof(int) * (1+((M[malloc_dim_1-1][malloc_dim_2-1]) + (1))-(1)));
    }
  }

  best_z = (int***) malloc(sizeof(int**) * (1+(D)-(1)));
  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    best_z[malloc_dim_1-1] = (int**) malloc(sizeof(int*) * (1+(N[malloc_dim_1-1])-(1)));
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      best_z[malloc_dim_1-1][malloc_dim_2-1] = (int*) malloc(sizeof(int) * (1+((M[malloc_dim_1-1][malloc_dim_2-1]) + (1))-(1)));
    }
  }


  fprintf(stderr, "Initializing variables...\n");
  fflush(stderr);
  initialize_z(z, D, M, N, K);
  initialize_s(s, D, M, N);
  initialize_post_beta(post_beta, D, K, M, N, V, w, z);
  initialize_post_theta(post_theta, D, K, M, N, z);
  initialize_post_gamma(post_gamma, D, M, N, V, w, s);
  initialize_post_pi(post_pi, D, M, N, s);

  for (iter=1; iter<=nIter; iter++) {
    fprintf(stderr, "iter %d", iter);
    fflush(stderr);
    resample_z(D, M, N, alpha, eta, psi, post_beta, post_theta, w, z, s, labels, K, V);
    resample_s(D, M, N, alpha, eta, psi, phi, post_beta, post_theta, post_gamma, post_pi, w, z, s, labels, K, V);

    loglik = compute_log_posterior(D, K, M, N, V, alpha, post_beta, eta, post_theta, w, z);
    assert(!isnan(loglik));
    fprintf(stderr, "\t%g", loglik);
    if ((iter==1)||(loglik>bestloglik)) {
      bestloglik = loglik;
      fprintf(stderr, " *");
      best_z = (int***) realloc(best_z, sizeof(int**) * ((D) - (1) + 1));
      for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
        best_z[malloc_dim_1-1] = (int**) realloc(best_z[malloc_dim_1-1], sizeof(int*) * ((N[malloc_dim_1-1]) - (1) + 1));
        for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
          best_z[malloc_dim_1-1][malloc_dim_2-1] = (int*) realloc(best_z[malloc_dim_1-1][malloc_dim_2-1], sizeof(int) * ((M[malloc_dim_1-1][malloc_dim_2-1]) - (1) + 1));
          for (malloc_dim_3=1; malloc_dim_3<=M[malloc_dim_1-1][malloc_dim_2-1]; malloc_dim_3++) {
            best_z[malloc_dim_1-1][malloc_dim_2-1][malloc_dim_3-1] = z[malloc_dim_1-1][malloc_dim_2-1][malloc_dim_3-1];
          }
        }
      }
    }

    if(iter % dumpInterval == 0) {
      dump_z(D, M, N, z);
      dump_s(D, M, N, s);
    }

    fprintf(stderr, "\n");
    fflush(stderr);
  }

  //printf("ll = %g\n", bestloglik);
  //dump_z(D, M, N, best_z);
  //dump_z(D, M, N, z);

  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      free(best_z[malloc_dim_1-1][malloc_dim_2-1]);
    }
    free(best_z[malloc_dim_1-1]);
  }
  free(best_z);

  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      free(z[malloc_dim_1-1][malloc_dim_2-1]);
    }
    free(z[malloc_dim_1-1]);
  }
  free(z);

  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    for (malloc_dim_2=1; malloc_dim_2<=N[malloc_dim_1-1]; malloc_dim_2++) {
      free(w[malloc_dim_1-1][malloc_dim_2-1]);
    }
    free(w[malloc_dim_1-1]);
  }
  free(w);

  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    free(post_theta[malloc_dim_1-1]);
  }
  free(post_theta);

  for (malloc_dim_1=1; malloc_dim_1<=K; malloc_dim_1++) {
    free(post_beta[malloc_dim_1-1]);
  }
  free(post_beta);

  free(N);

  for (malloc_dim_1=1; malloc_dim_1<=D; malloc_dim_1++) {
    free(M[malloc_dim_1-1]);
  }
  free(M);


  return 0;
}
示例#25
0
int main (int argc, char *argv[]) {
	int i, j;
    int last_i;
    // Original Lorenz equation result data
    double lorenz[N][DIM];
    // Calculation limits for vector variation
    double strt[DIM];
    double fnsh[DIM];
    double base_x, base_y, base_z;
    // Current element
	double curr[DIM];
	double next[DIM];
	double tran[DIM];
    double points_d, points_s;
    double diff_d, diff_s;
    double resolution;
	double h, a, b, c;
	double sigma, dw, rand;
    // Distance from origin
    double orig_dist;
    double curr_dist;
    // Report differences
    double last_sum_diff;
    double sum_diff;
	FILE *output;
	struct exp_header header;
	
	h = 0.01;
	a = 10.0;
	b = 28.0;
	c = 8.0/3.0;

	if (argc != 8) {
		fprintf(stderr, "Number of parameters incorrect: %d.\n", argc);
        fprintf(stderr, "./%s x y z dr ds r file\n", argv[0]);
		return -1;
	}
    
    // Initialize base execution elements
	base_x = atof(argv[1]);
	base_y = atof(argv[2]);
	base_z = atof(argv[3]);
    points_d = atof(argv[4]);
	points_s = atof(argv[5]);
    resolution = atof(argv[6]);
    diff_d = resolution/points_d;
    diff_s = 1.0/points_s;
    
    // Initialize exploration limits
    strt[X] = base_x - 1;
    strt[Y] = base_y - 1;
    strt[Z] = base_z - 1;
    fnsh[X] = base_x + 1;
    fnsh[Y] = base_y + 1;
    fnsh[Z] = base_z + 1;
    
	if ( (output = fopen(argv[7], "w")) == NULL) {
		fprintf(stderr, "Results file creation failed.\n");
		fclose(output);
		return -1;
	}
    
	setall(SEED1, SEED2);
    
    // Initialize the vector for Lorenz results
    for (i = 0; i < N; i++)
        for (j = 0; j < DIM; j++)
            lorenz[i][j] = 0;
	
    // Step 1: store the standard Lorenz equation
    fprintf(stdout, "Calculating original Lorenz equations at %f, %f, %f.\n",
            base_x, base_y, base_z);
    
    curr[X] = base_x;
    curr[Y] = base_y;
    curr[Z] = base_z;
    
    for (i = 0; i < N; i++) {
        lorenz[i][X] = curr[X];
        lorenz[i][Y] = curr[Y];
        lorenz[i][Z] = curr[Z];
        
        next[X] = curr[X] + h*a*(curr[Y] - curr[X]);
        next[Y] = curr[Y] + h*(curr[X]*(b - curr[Z]) - curr[Y]);
        next[Z] = curr[Z] + h*(curr[X]*curr[Y] - c*curr[Z]);
        
        curr[X] = next[X];
        curr[Y] = next[Y];
        curr[Z] = next[Z];
    }
    
    // Print headers
    fprintf(output, "X0 Y0 Z0 XK YK ZK sigma OD S NL XL YL ZL\n");
    
    // Setp 2: calculate all possible scenarios and their accumulated difference
    
    fprintf(stdout, "Parameter sweep...\n");
    
    for (j = 0; j < RAND_ITERS; j++) {
        fprintf(stdout, "Iteration %i \n", j);
        // Reset for each run
        curr[X] = strt[X];
        curr[Y] = strt[Y];
        curr[Z] = strt[Z];
        
        while (curr[X] <= fnsh[X]) {
            while (curr[Y] <= fnsh[Y]) {
                while (curr[Z] <= fnsh[Z]) {
                    // Calculate distance from origin to current scenario
                    orig_dist = distance(base_x, curr[X], base_y, curr[Y],
                                         base_z, curr[Z]);
                    
		    #pragma omp parallel for
                    for (sigma = 0; sigma <= 1.0; sigma += diff_s) {
                        
                        // Difference starts at 0
                        sum_diff = 0;
                        // Calculation and comparison against Lorenz
                        tran[X] = curr[X];
                        tran[Y] = curr[Y];
                        tran[Z] = curr[Z];
                        
                        
                        for (i = 0; i < N; i++) {
                            last_sum_diff = sum_diff;
                            
                            sum_diff += distance(lorenz[i][X], tran[X],
                                                   lorenz[i][Y], tran[Y],
                                                   lorenz[i][Z], tran[Z]);
                            
                            if(! isfinite(sum_diff)) {
                                sum_diff = last_sum_diff;
                                i = i - 1;
                                break;
                            }
                            
                            rand = gennor(0, 1);
                            dw = sqrt(h)*rand;
                            
                            next[X] = tran[X] 
					+ h*a*(tran[Y] - tran[X]) 
					+ sigma*tran[X]*dw;
                            next[Y] = tran[Y] 
					+ h*(tran[X]*(b - tran[Z]) - tran[Y]) 
					+ sigma*tran[Y]*dw;
                            next[Z] = tran[Z] 
					+ h*(tran[X]*tran[Y] 
					- c*tran[Z]) 
					+ sigma*tran[Z]*dw;

                            tran[X] = next[X];
                            tran[Y] = next[Y];
                            tran[Z] = next[Z];
                            
                        }

                        // Write results
			#pragma omp atomic
                        fprintf(output, "%f %f %f %f %f %f %f %f %.7e %i %.7e %.7e %.7e\n",
                                base_x, base_y, base_z,
                                curr[X], curr[Y], curr[Z],
                                sigma, orig_dist, sum_diff,
                                i, tran[X], tran[Y], tran[Z]);
                    }
                    curr[Z] += diff_d;
                }
                curr[Z] = strt[Z];
                curr[Y] += diff_d;
            }
            curr[Y] = strt[Y];
            curr[X] += diff_d;
        }
    }
    
	fclose(output);

	return 0;
}
示例#26
0
文件: ex_re.c 项目: n-t-roff/ex-2.2
void
global(bool k)
{
	register char *gp;
	register int c;
	register line *a1;
	char globuf[GBSIZE], *Cwas;
	int lines = lineDOL();
	char *oglobp = globp;

	Cwas = Command;
	if (inglobal)
		error("Global within global@not allowed");
	markDOT();
	setall();
	nonzero();
	if (skipend())
		error("Global needs re|Missing regular expression for global");
	c = ex_getchar();
	ignore(compile(c, 0));
	savere(scanre);
	gp = globuf;
	while ((c = ex_getchar()) != '\n') {
		switch (c) {

		case EOF:
			c = '\n';
			goto brkwh;

		case '\\':
			c = ex_getchar();
			switch (c) {

			case '\\':
				ungetchar(c);
				break;

			case '\n':
				break;

			default:
				*gp++ = '\\';
				break;
			}
			break;
		}
		*gp++ = c;
		if (gp >= &globuf[GBSIZE - 2])
			error("Global command too long");
	}
brkwh:
	ungetchar(c);
	ex_newline();
	*gp++ = c;
	*gp++ = 0;
	inglobal = 1;
	for (a1 = one; a1 <= dol; a1++) {
		*a1 &= ~01;
		if (a1 >= addr1 && a1 <= addr2 && execute(0, a1) == k)
			*a1 |= 01;
	}
	/* should use gdelete from ed to avoid n**2 here on g/.../d */
	saveall();
	if (inopen)
		inopen = -1;
	for (a1 = one; a1 <= dol; a1++) {
		if (*a1 & 01) {
			*a1 &= ~01;
			dot = a1;
			globp = globuf;
			commands(1, 1);
			a1 = zero;
		}
	}
	globp = oglobp;
	inglobal = 0;
	endline = 1;
	Command = Cwas;
	netchHAD(lines);
	setlastchar(EOF);
	if (inopen) {
		ungetchar(EOF);
		inopen = 1;
	}
}
示例#27
0
/*
 * Read a file from the world.
 * C is command, 'e' if this really an edit (or a recover).
 */
void
rop(int c)
{
	struct stat stbuf;
#ifndef __sun
	register int i;
	struct exec head;
#endif
	static int ovro;	/* old value(READONLY) */
	static int denied;	/* 1 if READONLY was set due to file permissions */
#ifdef	FLOCKFILE
	int *lp, *iop;
#endif

	io = open(file, O_RDONLY);
	if (io < 0) {
		if (c == 'e' && errno == ENOENT) {
			edited++;
			/*
			 * If the user just did "ex foo" he is probably
			 * creating a new file.  Don't be an error, since
			 * this is ugly, and it screws up the + option.
			 */
			if (!seenprompt) {
				ex_printf(" [New file]");
				noonl();
				return;
			}
		}
		syserror();
	}
	if (fstat(io, &stbuf))
		syserror();
	switch (stbuf.st_mode & S_IFMT) {

	case S_IFBLK:
		error(" Block special file");

	case S_IFCHR:
		if (isatty(io))
			error(" Teletype");
		if (samei(&stbuf, _PATH_DEVNULL))
			break;
		error(" Character special file");

	case S_IFDIR:
		error(" Directory");

#ifndef __sun
	case S_IFREG:
#ifdef CRYPT
		if (xflag)
			break;
#endif
		i = read(io, (char *)&head, sizeof(head));
		(void)lseek(io, 0L, L_SET);
		if (i != sizeof(head))
			break;
#ifndef vms
		switch (
#if defined N_MAGIC
		    N_MAGIC(
#elif defined N_GETMAGIC
		    N_GETMAGIC(
#else
# error
#endif
		    head)) {

		case 0405:	/* data overlay on exec */
		case OMAGIC:	/* unshared */
		case NMAGIC:	/* shared text */
		case 0411:	/* separate I/D */
		case ZMAGIC:	/* VM/Unix demand paged */
		case 0430:	/* PDP-11 Overlay shared */
		case 0431:	/* PDP-11 Overlay sep I/D */
			error(" Executable");

		/*
		 * We do not forbid the editing of portable archives
		 * because it is reasonable to edit them, especially
		 * if they are archives of text files.  This is
		 * especially useful if you archive source files together
		 * and copy them to another system with ~%take, since
		 * the files sometimes show up munged and must be fixed.
		 */
		case 0177545:
		case 0177555:
			error(" Archive");
		case 070707:
			error(" Cpio file");

		default:
			{
				char *bp = (char *)&head;
				if ((u_char)bp[0] == (u_char)'\037' &&
				    (u_char)bp[1] == (u_char)'\235')
					error(" Compressed file");
#ifdef ARCHIVES_ARE_OK
				if (!strncmp(bp, "!<arch>\n__.SYMDEF", 17)
				    || !strncmp(bp, "!<arch>\n", 8))
					error(" Archive");
#endif
			}
			break;
		}
#endif /* __sun */
#endif
	}
	if (c != 'r') {
		if (value(READONLY) && denied) {
			value(READONLY) = ovro;
			denied = 0;
		}
		if ((stbuf.st_mode & 0222) == 0 || access(file, 2) < 0) {
			ovro = value(READONLY);
			denied = 1;
			value(READONLY) = 1;
		}
	}
	if (value(READONLY)) {
		ex_printf(" [Read only]");
		flush();
	}
#ifdef	FLOCKFILE
	/*
	 * Attempt to lock the file. We use an sharable lock if reading
	 * the file, and an exclusive lock if editting a file.
	 * The lock will be released when the file is no longer being
	 * referenced. At any time, the editor can have as many as
	 * three files locked, and with different lock statuses.
	 */
	/*
	 * if this is either the saved or alternate file or current file,
	 * point to the appropriate descriptor and file lock status.
	 */
	if (strcmp (file,savedfile) == 0) {
		if (!io_savedfile) io_savedfile = dup(io) ;
		lp = &lock_savedfile ;	iop = &io_savedfile ;
	} else if (strcmp (file,altfile) == 0) {
		if (!io_altfile) io_altfile = dup(io) ;
		lp = &lock_altfile ;	iop = &io_altfile ;
	} else {
		/* throw away current lock, accquire new current lock */
		if (io_curr) close (io_curr) ;
		io_curr = dup(io) ;
		lp = &lock_curr ;	iop = &io_curr ;
		lock_curr = 0 ;
	}
	if (c == 'r' || value(READONLY) || *lp == 0) {
		/* if we have a lock already, don't bother */
		if (!*lp) {
			/* try for a shared lock */
			if (flock(*iop, LOCK_SH|LOCK_NB) < 0
			&& errno == EWOULDBLOCK) {
				ex_printf (
			" [FILE BEING MODIFIED BY ANOTHER PROCESS]") ;
				flush();
				goto fail_lock ;
			} else *lp = LOCK_SH ;
		}
	}
	if ( c != 'r'  && !value(READONLY) && *lp != LOCK_EX) {
		/* if we are editting the file, upgrade to an exclusive lock. */
		if (flock(*iop, LOCK_EX|LOCK_NB) < 0 && errno == EWOULDBLOCK) {
			ex_printf (" [File open by another process]") ;
			flush();
		} else *lp = LOCK_EX ;
	}
fail_lock:
#endif
	if (c == 'r')
		setdot();
	else
		setall();
	if (FIXUNDO && inopen && c == 'r')
		undap1 = undap2 = dot + 1;
	rop2();
	rop3(c);
}