Beispiel #1
0
/**
   Convert PSD into time series.*/
dmat* psd2time(const dmat *psdin, rand_t *rstat, double dt, int nstepin){
    if(!psdin){
	error("psdin cannot be null\n");
    }
    long nstep=nextpow2(nstepin);
    double df=1./(dt*nstep);
    dmat *fs=dlinspace(0, df, nstep);
    dmat *psd=NULL;
    if(psdin->ny==1){//[alpha, beta, fmin, fmax] discribes power law with cut on/off freq.
	psd=dnew(nstep, 1);
	double alpha=psdin->p[0];
	double beta=psdin->p[1];
	long i0=1, imax=nstep;
	if(psdin->nx>2){
	    i0=(long)round(psdin->p[2]/df);
	    if(i0<1) i0=1;
	}
	if(psdin->nx>3){
	    imax=(long)round(psdin->p[3]/df);
	}
	dbg("fmin=%g, fmax=%g, df=%g, i0=%ld, imax=%ld\n", 
	     psdin->p[2], psdin->p[3], df, i0, imax);
	for(long i=i0; i<imax; i++){
	    psd->p[i]=beta*pow(i*df, alpha);
	}
    }else if(psdin->ny==2){
	if(psdin->nx<2){ 
	    error("Invalid PSD\n");
	}
	psd=dinterp1(psdin, 0, fs, 1e-40);
	psd->p[0]=0;/*disable pistion. */
    }else{
	error("psdin is invalid format.\n");
    }
    cmat *wshat=cnew(nstep, 1);
    //cfft2plan(wshat, -1);
    for(long i=0; i<nstep; i++){
	wshat->p[i]=sqrt(psd->p[i]*df)*COMPLEX(randn(rstat), randn(rstat));
    }
    cfft2(wshat, -1);
    dmat *out=NULL;
    creal2d(&out, 0, wshat, 1);
    cfree(wshat);
    dfree(psd);
    dfree(fs);
    dresize(out, nstepin, 1);
    return out;
}
Beispiel #2
0
int
sum_mod (uint_10 a, uint_10 b, uint_10 c, uint_10 d, uint_10 * result)
{
  sum_mod_State *__top = (sum_mod_State *) calloc (1, sizeof (sum_mod_State));
  __top->sum_mod_entry = 1;
  __top->a = a;
  __top->b = b;
  __top->c = c;
  __top->d = d;
  while (!__top->sum_mod_exit)
    {
      __top = sum_mod_ (__top);
    }
  *result = __top->result;
  cfree (__top);
  return AASUCCESS;
}
Beispiel #3
0
int main(int argc, char *argv[]) {
    if(argc<7) {
        info("Usage: %s loc.bin amp.bin cov.bin ncomp pttr wvl1 wvl2 ...\n", argv[0]);
        exit(0);
    }
    enum {
        P_EXE,
        P_LOC,
        P_AMP,
        P_COV,
        P_NCOMP,
        P_PTTR,
        P_WVL
    };
    loc_t *loc=locread("%s",argv[P_LOC]);
    dmat *amp=NULL;
    if(strcmp(argv[P_AMP],"NULL")) {
        amp=dread("%s",argv[P_AMP]);
    } else {
        amp=dnew(loc->nloc,1);
        dset(amp,1);
    }
    dmat *cov=dread("%s",argv[P_COV]);
    long ncomp=strtol(argv[P_NCOMP], NULL, 10);
    long pttr=strtol(argv[P_PTTR], NULL, 10);
    cmat *otf=otf=cnew(ncomp, ncomp);
    dmat *psf=NULL;
    for(int iwvl=0; iwvl<argc-P_WVL; iwvl++) {
        double wvl=strtod(argv[iwvl+P_WVL], NULL);
        double dtheta=wvl/(ncomp*loc->dx);
        genotf(&otf, loc, amp, NULL, NULL, 0, wvl, dtheta, cov, 0, 0, ncomp, ncomp, 1, pttr);
        writebin(otf, "%s_otf_%g.bin", argv[P_COV], wvl);
        cfftshift(otf);
        cfft2i(otf, 1);
        cfftshift(otf);
        creal2d(&psf, 0, otf, 1);
        writebin(psf, "%s_psf_%g.bin", argv[P_COV], wvl);
    }
    cfree(otf);
    dfree(psf);
    dfree(cov);
    dfree(amp);
    locfree(loc);
}
Beispiel #4
0
dmat *psd1d(const dmat *v, /**<[in] The data sequence*/
	    long nseg      /**<[in] Number of overlapping segments*/
    ){
    long nx;
    long ncol;
    if(v->nx==1){
	nx=v->ny;
	ncol=1;
    }else{
	nx=v->nx;
	ncol=v->ny;
    }
    if(nseg<=1) nseg=1;
    const int lseg2=nx/(nseg+1);
    const int lseg=lseg2*2;
    dmat *psd=dnew(lseg2+1, ncol);
    cmat *hat=cnew(lseg, 1);
    //cfft2plan(hat, -1);
    for(long icol=0; icol<ncol; icol++){
	double *ppsd=psd->p+icol*(lseg2+1);
	for(int iseg=0; iseg<nseg; iseg++){
	    double* p=v->p+icol*nx+iseg*lseg2;
	    for(int ix=0; ix<lseg; ix++){
		hat->p[ix]=p[ix]*W_J(ix, lseg2);
	    }
	    cfft2(hat, -1);
	    ppsd[0]+=cabs2(hat->p[0]);
	    for(int ix=1; ix<lseg2; ix++){
		ppsd[ix]+=cabs2(hat->p[ix])+cabs2(hat->p[lseg-ix]);
	    }
	    ppsd[lseg2]+=cabs2(hat->p[lseg2]);
	}
    }
    double sumwt=0;
    for(int ix=0; ix<lseg; ix++){
	sumwt+=pow(W_J(ix, lseg2), 2);
    }
    sumwt*=lseg*nseg;
    dscale(psd, 1./sumwt);
    cfree(hat);
    return psd;
}
//
// função para escrever ficheiro de imagem pgm
//	
void writepgm(unsigned char **p, int width, int height, char *filename)
{
    unsigned char *data,*dp;
    int c,i,j,datasize,level;
    FILE *fp;

    if(!(fp=fopen(filename,"wb"))) { /* 2nd parameter must be equal to "rb" in Windows! */
	fprintf(stderr,"writepgm: error opening output file\n");
	exit(0);
    }
  
    fprintf(fp,"P5\n");
    
    fprintf(fp,"%d %d\n",width,height);
   
    fprintf(fp,"%d\n",255);
    
    datasize=width*height;

    
    if(!(data=(unsigned char *)calloc(sizeof(char),datasize))){
	fprintf(stderr,"writepgm: calloc error\n");
	exit(0);
    }
    
    dp=data;
    for(i=0;i<height;i++)
      for(j=0;j<width;j++){
	    *dp++=p[i][j];
      }
    if(!fwrite(data,sizeof(unsigned char),datasize,fp)) {
	fprintf(stderr,"writepgm: write error\n");
	exit(0);
    }
    
    cfree(data);

    fclose(fp);
}
Beispiel #6
0
static
reap_children()
{
    CHILD_DATA *child;
    int statusp;
    int pid;

    for (;;) {
        if ((pid = wait3(&statusp, WNOHANG, NULL)) <= 0)
            return;

        if (reap_ht != NULL) {
            if ((child = (CHILD_DATA *)htgetdata((char *)&pid, reap_ht))
                    != NULL) {
                if (child->routine != NULL)
                    (*(child->routine))(pid, statusp, child->data);
                htdelete((char *)&pid, reap_ht);
                cfree(child);
            }
        }
    }
}
Beispiel #7
0
pointer ICONV(context *ctx, int n, pointer *argv)
{ int cd, ret, malloced=NULL;
  char *srcstrp, *deststrp, *deststrpv, deststr[1024];
  size_t srcstrlen, deststrlen;
  pointer dest;

  ckarg(2);
  cd=bigintval(argv[0]);
  if (!isstring(argv[1])) error(E_NOSTRING);
  srcstrp=argv[1]->c.str.chars;
  srcstrlen=strlength(argv[1]);
  deststrlen=2*srcstrlen;
  if (deststrlen>=1024) {
    deststrp=malloc(deststrlen);
    malloced=1;}
  else deststrp=deststr;
  deststrpv=deststrp;
  ret=iconv(cd, &srcstrp, &srcstrlen, &deststrpv, &deststrlen);
  if (ret== -1) { dest=NIL; goto iconvend;}
  dest=makestring(deststrp, 2*strlength(argv[1])-deststrlen);
  iconvend:
  if (malloced) cfree(deststrp);
  return(dest);
  }
Beispiel #8
0
void load_texture(char *filename,unsigned int tid)
{
	printf("%s\n",filename);
	FILE *fptr;
	unsigned char buf[512];
	int im_size,im_width,im_height,max_color;
	unsigned char *texture_bytes,*parse;
	
	fptr = fopen(filename,"r");
	fgets(buf,512,fptr);
	printf("%s\n",buf);
	do{
		fgets(buf,512,fptr);
	} while(buf[0] == '#');
	parse = strtok(buf," \t");
	im_width = atoi(parse);
	
	parse = strtok(NULL," \n");
	im_height = atoi(parse);
	
	fgets(buf,512,fptr);
	parse = strtok(buf," \n");
	max_color = atoi(parse);
	
	im_size = im_width*im_height;
	texture_bytes = (unsigned char *)calloc(3,im_size);
	fread(texture_bytes,3,im_size,fptr);
	fclose(fptr);
	printf("%d %d %d\n",im_width,im_height,im_size);
	//printf("%s",texture_bytes);
	glBindTexture(GL_TEXTURE_2D,tid);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,im_width,im_height,0,GL_RGB,GL_UNSIGNED_BYTE,texture_bytes);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
	cfree(texture_bytes);
}
Beispiel #9
0
/*
  run database lifecycle
*/
void
Database_run(void) {
    Connection     *conn;
    Address        *record = malloc(sizeof(Address));

    check(record, "address alloc failed");

    if (fopen(TESTDB, "r"))
        conn = Connection_open(TESTDB, 'w');
    else
        conn = Connection_open(TESTDB, 'c');

    check(conn, "database connection failure");

    Database_list(conn);

    for (int i = -1; i < 5; i++)
        Address_print(Database_getbyidx(conn, i));

    strcpy(record->nickname, "Joe");
    strcpy(record->name, "Hans Glück");
    strcpy(record->email, "*****@*****.**");

    check(!(Database_set(conn, record)), "database set() record");

    strcpy(record->nickname, "Grit");
    strcpy(record->name, "Gretel Glück");
    strcpy(record->email, "*****@*****.**");

    check(!(Database_set(conn, record)), "database set() record");

    strcpy(record->nickname, "rs");
    strcpy(record->name, "Rumpelstilzchen");
    strcpy(record->email, "*****@*****.**");

    check(!(Database_set(conn, record)), "database set() record");

    Database_list(conn);

    /* avoid memory leak */
    cfree(record);
    /* reuse record */
    record = Database_getbyidx(conn, 1);

    check(!(Database_set(conn, record)), "database set() record");

    Database_list(conn);

    for (int i = 0; i < MAXRECORDS; i++)
        if (conn->db->records[i].set)
            check(!(Database_writebyidx(conn, i)), "write-by-idx error");

    Database_list(conn);

    check(!(Connection_close(conn)), "connection close failed");
    /* leaves record as dangling pointer, hence reset it */
    record = NULL;

    return;
error:
    exit(-1);
}
Beispiel #10
0
void
VS_Delete (String str)
{
    cfree (str->buffer);
    xfree (str);
}
Beispiel #11
0
/**
   Setup the detector transfer functions. See maos/setup_powfs.c
 */
static void setup_powfs_dtf(POWFS_S *powfs, const PARMS_S* parms){
    const int npowfs=parms->maos.npowfs;
    for(int ipowfs=0; ipowfs<npowfs; ipowfs++){
	const int ncomp=parms->maos.ncomp[ipowfs];
	const int ncomp2=ncomp>>1;
	const int embfac=parms->maos.embfac[ipowfs];
	const int pixpsa=parms->skyc.pixpsa[ipowfs];
	const double pixtheta=parms->skyc.pixtheta[ipowfs];
	const double blur=parms->skyc.pixblur[ipowfs]*pixtheta;
	const double e0=exp(-2*M_PI*M_PI*blur*blur);
	const double dxsa=parms->maos.dxsa[ipowfs];
	const double pixoffx=parms->skyc.pixoffx[ipowfs];
	const double pixoffy=parms->skyc.pixoffy[ipowfs];
	const double pxo=-(pixpsa/2-0.5+pixoffx)*pixtheta;
	const double pyo=-(pixpsa/2-0.5+pixoffy)*pixtheta;
	loc_t *loc_ccd=mksqloc(pixpsa, pixpsa, pixtheta, pixtheta, pxo, pyo);
	powfs[ipowfs].dtf=mycalloc(parms->maos.nwvl,DTF_S);
	for(int iwvl=0; iwvl<parms->maos.nwvl; iwvl++){
	    const double wvl=parms->maos.wvl[iwvl];
	    const double dtheta=wvl/(dxsa*embfac);
	    const double pdtheta=pixtheta*pixtheta/(dtheta*dtheta);
	    const double du=1./(dtheta*ncomp);
	    const double du2=du*du;
	    const double dupth=du*pixtheta;
	    cmat *nominal=cnew(ncomp,ncomp);
	    //cfft2plan(nominal,-1);
	    //cfft2plan(nominal,1);
	    cmat* pn=nominal;
	    const double theta=0;
	    const double ct=cos(theta);
	    const double st=sin(theta);
	    for(int iy=0; iy<ncomp; iy++){
		int jy=iy-ncomp2;
		for(int ix=0; ix<ncomp; ix++){
		    int jx=ix-ncomp2;
		    double ir=ct*jx+st*jy;
		    double ia=-st*jx+ct*jy;
		    IND(pn,ix,iy)=sinc(ir*dupth)*sinc(ia*dupth)
			*pow(e0,ir*ir*du2)*pow(e0,ia*ia*du2)
			*pdtheta;
		}
	    }
	    if(parms->skyc.fnpsf1[ipowfs]){
		warning("powfs %d has additional otf to be multiplied\n", ipowfs);
		dcell *psf1c=dcellread("%s", parms->skyc.fnpsf1[ipowfs]);
		dmat *psf1=NULL;
		if(psf1c->nx == 1){
		    psf1=dref(psf1c->p[0]);
		}else if(psf1c->nx==parms->maos.nwvl){
		    psf1=dref(psf1c->p[iwvl]);
		}else{
		    error("skyc.fnpsf1 has wrong dimension\n");
		}
		dcellfree(psf1c);
		if(psf1->ny!=2){
		    error("skyc.fnpsf1 has wrong dimension\n");
		}
		dmat *psf1x=dnew_ref(psf1->nx, 1, psf1->p);
		dmat *psf1y=dnew_ref(psf1->nx, 1, psf1->p+psf1->nx);
		dmat *psf2x=dnew(ncomp*ncomp, 1);
		for(int iy=0; iy<ncomp; iy++){
		    int jy=iy-ncomp2;
		    for(int ix=0; ix<ncomp; ix++){
			int jx=ix-ncomp2;
			psf2x->p[ix+iy*ncomp]=sqrt(jx*jx+jy*jy)*dtheta;
		    }
		}
		info("powfs %d, iwvl=%d, dtheta=%g\n", ipowfs, iwvl, dtheta*206265000);
		writebin(psf2x, "powfs%d_psf2x_%d", ipowfs,iwvl);
		dmat *psf2=dinterp1(psf1x, psf1y, psf2x, 0);
		normalize_sum(psf2->p, psf2->nx*psf2->ny, 1);
		psf2->nx=ncomp; psf2->ny=ncomp;
		writebin(psf2, "powfs%d_psf2_%d", ipowfs,iwvl);
		cmat *otf2=cnew(ncomp, ncomp);
		//cfft2plan(otf2, -1);
		ccpd(&otf2, psf2);//peak in center
		cfftshift(otf2);//peak in corner
		cfft2(otf2, -1);
		cfftshift(otf2);//peak in center
		writebin(otf2, "powfs%d_otf2_%d", ipowfs, iwvl);
		writebin(nominal, "powfs%d_dtf%d_nominal_0",ipowfs,iwvl);
		for(int i=0; i<ncomp*ncomp; i++){
		    nominal->p[i]*=otf2->p[i];
		}
		writebin(nominal, "powfs%d_dtf%d_nominal_1",ipowfs,iwvl);
		dfree(psf1x);
		dfree(psf1y);
		dfree(psf2x);
		dfree(psf1);
		cfree(otf2);
		dfree(psf2);
	    }
	    cfftshift(nominal);//peak in corner
	    cfft2(nominal,-1);
	    cfftshift(nominal);//peak in center
	    cfft2i(nominal,1);
	    warning_once("double check nominal for off centered skyc.fnpsf1\n");
	    /*This nominal will multiply to OTF with peak in corner. But after
	      inverse fft, peak will be in center*/
	    ccp(&powfs[ipowfs].dtf[iwvl].nominal, nominal);
	    cfree(nominal);

	    loc_t *loc_psf=mksqloc(ncomp, ncomp, dtheta, dtheta, -ncomp2*dtheta, -ncomp2*dtheta);
	    powfs[ipowfs].dtf[iwvl].si=mkh(loc_psf,loc_ccd,0,0,1);
	    locfree(loc_psf);
	    if(parms->skyc.dbg){
		writebin(powfs[ipowfs].dtf[iwvl].nominal,
		       "%s/powfs%d_dtf%d_nominal",dirsetup,ipowfs,iwvl);
		writebin(powfs[ipowfs].dtf[iwvl].si,
			"%s/powfs%d_dtf%d_si",dirsetup,ipowfs,iwvl);
	    }
	    powfs[ipowfs].dtf[iwvl].U=cnew(ncomp,1);
	    dcomplex *U=powfs[ipowfs].dtf[iwvl].U->p;

	    for(int ix=0; ix<ncomp; ix++){
		int jx=ix<ncomp2?ix:(ix-ncomp);
		U[ix]=COMPLEX(0, -2.*M_PI*jx*du);
	    }
	}/*iwvl */
	locfree(loc_ccd);
    }/*ipowfs */
}
void control_set_mol_params(ATOMMAPS *atommaps,CPOPTS *cpopts,
                         CPCOEFFS_INFO *cpcoeffs_info,CP_PARSE *cp_parse,
                         CLASS_PARSE *class_parse,
                         BONDED *bonded,SURFACE *surface,
                         FILENAME_PARSE *filename_parse,
                         FREE_PARSE *free_parse,
                         DICT_MOL *dict_mol,DICT_WORD *word,
                         char *fun_key,int *nfun_key,
                         int iextend,double t_ext,int ifirst,int pi_beads)
/*=======================================================================*/
{/*begin routine*/
/*=======================================================================*/
/*             Local variable declarations                               */

  int   nline,nkey,i,num,ierr;
  FILE *fp;
  int  *mol_ind_chk;                                 /* Index check      */
  int  *ifound;

  int nmol_typ            = atommaps->nmol_typ;
  int *nmol_jmol_typ      = atommaps->nmol_jmol_typ;
  int *nres_1mol_jmol_typ = atommaps->nres_1mol_jmol_typ;

  int num_fun_dict        = dict_mol->num_fun_dict;
  char *molsetname        = filename_parse->molsetname;

  int bond_free_num       = bonded->bond_free.num;
  int bend_free_num       = bonded->bend_free.num;
  int tors_free_num       = bonded->tors_free.num;
  int rbar_sig_free_iopt  = bonded->rbar_sig_free.iopt;

  int *imoltyp_rbar1_free;
  int *imoltyp_rbar2_free;
  int *imol_rbar1_free;
  int *imol_rbar2_free;
  int *ires_rbar1_free;
  int *ires_rbar2_free;
  int nbar_bond;

  int *imoltyp_bond_free = free_parse->imoltyp_bond_free;
  int *imol_bond_free     = free_parse->imol_bond_free;
  int *ires_bond_free    = free_parse->ires_bond_free;
  int *iatm_bond_free    = free_parse->iatm_bond_free;

  int *imoltyp_bend_free = free_parse->imoltyp_bend_free;
  int *imol_bend_free     = free_parse->imol_bend_free;
  int *ires_bend_free    = free_parse->ires_bend_free;
  int *iatm_bend_free    = free_parse->iatm_bend_free;

  int *imoltyp_tors_free = free_parse->imoltyp_tors_free;
  int *imol_tors_free     = free_parse->imol_tors_free;
  int *ires_tors_free    = free_parse->ires_tors_free; 
  int *iatm_tors_free    = free_parse->iatm_tors_free;

/*=======================================================================*/
/* 0) Set up molecular index checking memory                             */

  mol_ind_chk     = (int *) cmalloc(nmol_typ*sizeof(int))-1;
  ifound          = (int *) cmalloc(num_fun_dict*sizeof(int))-1;
  for(i=1;i<=nmol_typ;i++){ mol_ind_chk[i]=0;}
  for(i=1;i<=num_fun_dict;i++){ ifound[i]=0;}

/*=======================================================================*/
/* I) Fetch a valid functional key word from molset file                 */

  fp = cfopen(molsetname,"r");

  nline          = 1;
  *nfun_key      = 0;
  word->iuset    = 0;
  word->key_type = 0;
  while(get_fun_key(fp,fun_key,&nline,nfun_key,molsetname)){
    get_fun_key_index(fun_key,dict_mol->num_fun_dict,dict_mol->fun_dict,
                      nline,*nfun_key,molsetname,&num);

/*=======================================================================*/
/* II) Fetch the key words and key args of the functional key word       */
/*     and stick them into the correct dictionary                        */

    if(num==1){
      set_mol_dict(&(dict_mol->mol_dict),&(dict_mol->num_mol_dict),
                 iextend,class_parse->tau_nhc_def,t_ext,ifirst);
    }
    nkey=0;
    while(get_word(fp,word,&nline,&nkey,*nfun_key,molsetname)){
      switch(num){
      case 1:
       put_word_dict(word,dict_mol->mol_dict,dict_mol->num_mol_dict,
                    fun_key,nline,nkey,*nfun_key,molsetname);
       break;
      case 2:
       put_word_dict(word,dict_mol->wave_dict,
                    dict_mol->num_wave_dict,fun_key,nline,nkey,
                    *nfun_key,molsetname);
       break;
      case 3:
       put_word_dict(word,dict_mol->bond_free_dict,
                    dict_mol->num_bond_free_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 4:
       put_word_dict(word,dict_mol->bend_free_dict,
                    dict_mol->num_bend_free_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 5:
       put_word_dict(word,dict_mol->tors_free_dict,
                    dict_mol->num_tors_free_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 6:
       put_word_dict(word,dict_mol->def_base_dict,
                    dict_mol->num_def_base_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 7:
       put_word_dict(word,dict_mol->user_base_dict,
                    dict_mol->num_user_base_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 8:
       put_word_dict(word,dict_mol->rbar_free_dict,
                    dict_mol->num_rbar_free_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      case 9:
       put_word_dict(word,dict_mol->surface_dict,
                    dict_mol->num_surface_dict,fun_key,nline,
                    nkey,*nfun_key,molsetname);
       break;
      } /* end switch dictionary fills*/
    } /* endwhile fetching keywords and keyargs*/
  
/*=====================================================================*/
/* III) Assign the key args of the key words to the appropriate        */
/*      program variables                                              */

    ifound[num]=1;
    switch(num){
    case 1:
      set_mol_params(filename_parse,fun_key,dict_mol->mol_dict,
                   dict_mol->num_mol_dict,
                   class_parse,atommaps,mol_ind_chk,pi_beads);
      break;

    case 2:
      set_wave_params(molsetname,fun_key,
                    dict_mol->wave_dict,dict_mol->num_wave_dict,
                    cpopts,cpcoeffs_info,cp_parse);
      break;
      
    case 3:
      set_bond_free_params(molsetname,fun_key,
                        dict_mol->bond_free_dict,
                        dict_mol->num_bond_free_dict,
                        &(bonded->bond_free),free_parse,
                        atommaps->nmol_typ);
      break;
    case 4:
      set_bend_free_params(molsetname,fun_key,
                        dict_mol->bend_free_dict,
                        dict_mol->num_bend_free_dict,
                        &(bonded->bend_free),free_parse,
                        atommaps->nmol_typ);
      break;
      
    case 5:
      set_tors_free_params(molsetname,fun_key,
                        dict_mol->tors_free_dict,
                        dict_mol->num_tors_free_dict,
                        &(bonded->tors_free),free_parse,
                        atommaps->nmol_typ);
      break;
    case 6:
      set_def_base_params(filename_parse,dict_mol->def_base_dict,
                       dict_mol->num_def_base_dict);
      break;
    case 7:
      set_user_base_params(filename_parse,dict_mol->user_base_dict,
                        dict_mol->num_user_base_dict);
      break;
    case 8:
      set_rbar_free_params(molsetname,fun_key,
                        dict_mol->rbar_free_dict,
                        dict_mol->num_rbar_free_dict,
                        &(bonded->rbar_sig_free),free_parse,
                        atommaps->nmol_typ);
      break;
    case 9:
      set_surf_params(molsetname,fun_key,
                      dict_mol->surface_dict,
                      dict_mol->num_surface_dict,
                      surface); 
      break;
    } /* end switch assigning dict stuff to variables */

  } /*endwhile getting functional keywords data*/

/*=====================================================================*/
/* IV) Make sure everything that is required has been found            */ 
/*     if it hasn't either die or define defaults                      */ 

  if(ifound[1]==0){
    printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    printf("  Required functional keyword %s not found     \n",
              dict_mol->fun_dict[1].keyword);
    printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    fflush(stdout);
    exit(1);
  }/*endif*/
  if(ifound[6]==0){
    set_def_base_params(filename_parse,dict_mol->def_base_dict,
                     dict_mol->num_def_base_dict);
  }/*endif*/
  if(ifound[7]==0){
    set_user_base_params(filename_parse,dict_mol->user_base_dict,
                      dict_mol->num_user_base_dict);
  }/*endif*/
  
/*=======================================================================*/
/* IV) Check  indices                                                    */

  for(i = 1;i<=nmol_typ;i++){
    if(mol_ind_chk[i]!=1){
      printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@  \n");
      printf("Molecule number %d specified %d times in file %s \n",
              i,mol_ind_chk[i],molsetname);
      printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@  \n");
      fflush(stdout);
      exit(1);
    }/*endif*/
  } /*endfor*/

/*=======================================================================*/
/* V) Check  free energy indices                                         */

  ierr = 0;

  if(bond_free_num>0){
    for(i=1;i<=2;i++){
      if(imol_bond_free[i]>nmol_jmol_typ[imoltyp_bond_free[i]]){ierr=i;}
      if(ires_bond_free[i]>MAX(nres_1mol_jmol_typ[imoltyp_bond_free[i]],1))
                                                               {ierr=i;}
    }/*endfor*/
  }/*endif*/

  if(bend_free_num>0){
    for(i=1;i<=3;i++){
      if(imol_bend_free[i]>nmol_jmol_typ[imoltyp_bend_free[i]]){ierr=i;}
      if(ires_bend_free[i]>MAX(nres_1mol_jmol_typ[imoltyp_bend_free[i]],1))
                                                               {ierr=i;}
    }/*endfor*/
  }/*endif*/

  if(tors_free_num>0){tors_free_num=bonded->tors_free.num;}
  if(tors_free_num==1){
    for(i=1;i<=4;i++){
      if(imol_tors_free[i]>nmol_jmol_typ[imoltyp_tors_free[i]]){ierr=i;}
      if(ires_tors_free[i]>MAX(nres_1mol_jmol_typ[imoltyp_tors_free[i]],1))
                                                               {ierr=i;}
    }/*endfor*/
  }/*endif*/
  if(tors_free_num==2){
    for(i=1;i<=8;i++){
      if(imol_tors_free[i]>nmol_jmol_typ[imoltyp_tors_free[i]]){ierr=i;}
      if(ires_tors_free[i]>MAX(nres_1mol_jmol_typ[imoltyp_tors_free[i]],1))
                                                               {ierr=i;}
    }/*endfor*/
  }/*endif*/

  if(rbar_sig_free_iopt>0){

    imoltyp_rbar1_free = free_parse->imoltyp_rbar1_free;
    imoltyp_rbar2_free = free_parse->imoltyp_rbar2_free;
    imol_rbar1_free    = free_parse->imol_rbar1_free;
    imol_rbar2_free    = free_parse->imol_rbar2_free;
    ires_rbar1_free    = free_parse->ires_rbar1_free;
    ires_rbar2_free    = free_parse->ires_rbar2_free;
    nbar_bond          = free_parse->nbar_bond;

    for(i=1;i<=nbar_bond;i++){
     if(imol_rbar1_free[i]>nmol_jmol_typ[imoltyp_rbar1_free[i]]){ierr=1;}
     if(imol_rbar2_free[i]>nmol_jmol_typ[imoltyp_rbar2_free[i]]){ierr=2;}
     if(ires_rbar1_free[i]>
              MAX(nres_1mol_jmol_typ[imoltyp_rbar1_free[i]],1)){ierr=1;}
     if(ires_rbar2_free[i]>
              MAX(nres_1mol_jmol_typ[imoltyp_rbar2_free[i]],1)){ierr=2;}
    }/*endfor*/
  }/*endif*/

  if(ierr>0){
      printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      printf("Error specifing the %dth atom in a free energy def \n",ierr);
      printf("in set up file %s \n",molsetname);
      printf("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      fflush(stdout);
      exit(1);
  }/*endif*/ 

/*=======================================================================*/
/* VI) Free memory                                                       */

  cfree(&mol_ind_chk[1]);
  cfree(&ifound[1]);

/*-----------------------------------------------------------------------*/
   }/*end routine*/
Beispiel #13
0
void spline_fit(double *c0i, double *c1i, double *c2i, double *c3i, 
    double *xi, int nsplin)

  /*==========================================================================*/
{
  int i, m, n;
  int ip1, mm1, mp1;
  double c0, c1, c2, c3, divdf1, divdf3, dx,g;
  double *diag,*d;

  diag = (double *)cmalloc(nsplin*sizeof(double),"spline_fit")-1;
  d    = (double *)cmalloc(nsplin*sizeof(double),"spline_fit")-1;

  /*  1st approximate initial and final derivatives */

  n = nsplin - 1;
  c1i[1]      = (c0i[2] - c0i[1]) / (xi[2] - xi[1]);
  c1i[nsplin] = (c0i[nsplin] - c0i[n]) / (xi[nsplin] - xi[n]);
  c0 = 0.;
  c1 = 1.;
  c2 = 2.;
  c3 = 3.;
  diag[1] = c1;
  d[1] = c0;
  for (m = 2; m <= n+1; ++m) {
    mm1 = m - 1;
    d[m] = xi[m] - xi[mm1];
    diag[m] = (c0i[m] - c0i[mm1]) / d[m];
  }
  for (m = 2; m <= n; ++m) {
    mp1 = m + 1;
    mm1 = m - 1;
    c1i[m] = c3*(d[m]*diag[mp1]+d[mp1]*diag[m]);
    diag[m] = c2*(d[m]+d[mp1]);
  }
  for (m = 2; m <= n; ++m) {
    mp1 = m + 1;
    mm1 = m - 1;
    g = -d[mp1]/diag[mm1];
    diag[m] += g*d[mm1];
    c1i[m]  += g*c1i[mm1];
  }  
  for (m = n; m >= 2; --m) {
    mp1 = m + 1;
    c1i[m] = (c1i[m] - d[m] * c1i[mp1]) / diag[m];
  }


  /* CALCULATE ALL OTHER COEFFICIENTS */

  for (i = 1; i <= n; ++i) {
    ip1 = i + 1;
    dx = xi[ip1] - xi[i];
    divdf1 = (c0i[ip1] - c0i[i]) / dx;
    divdf3 = c1i[i] + c1i[ip1] - c2 * divdf1;
    c2i[i] = (divdf1 - c1i[i] - divdf3) / dx;
    c3i[i] = divdf3 / (dx * dx);
  }
  c2i[nsplin] = 0.0;
  c3i[nsplin] = 0.0;

  cfree(&d[1],"spline_fit");
  cfree(&diag[1],"spline_fit");

  /*--------------------------------------------------------------------------*/
} /* spline_fit */
Beispiel #14
0
void spline_vdv(double rmin, double rmax, 
		double *cv0, double *cdv0, 
		int nsplin, double *dr, double *dri,double sig, double eps,
		double a, double b, double c, double rm, 
                double c6, double c8, double c9, double c10, 
		double alp, double qij, int iperd,int itype, int ishift,
                double rheal, int diele_opt, double diele_rheal, double 
                diele_cut,double diele_eps)

/*==========================================================================*/ 
/*           Begin Routine                                                  */
{ /*begin routine*/
/*==========================================================================*/
/*           Local Variables                                                */

  int i,iii;
  double *r,*sw,*dsw;
  double rp,shift;

/*==========================================================================*/
/* 0) Malloc some temporary memory                                          */

  r = (double *)cmalloc(nsplin*sizeof(double))-1;
  sw = (double *)cmalloc(nsplin*sizeof(double))-1;
  dsw = (double *)cmalloc(nsplin*sizeof(double))-1;

/*==========================================================================*/
/* II) get positions at which to evaluate potential and force               */
  
  *dr = (rmax-rmin) /(double)(nsplin - 5);
  *dri = 1.0/(*dr);

  for (i = 1; i <= nsplin; ++i) {
    r[i] = (*dr) * ((double)(i-3)) + rmin;
    sw[i] = 1.0;
    dsw[i] = 0.0;  
  }/*endfor*/
  if(ishift==2){
    for (i = 1; i <= nsplin; ++i) {
      rp    = (r[i]-rmax+rheal)/rheal;
      rp    = MIN(rp,1.0);
      rp    = MAX(rp,0.0);
      sw[i] = 1.0 + rp*rp*(2.0*rp-3.0);
     dsw[i] = -6.0*(rp/rheal)*(rp-1.0)/r[i];
    }/*endfor*/
  }/*endif*/

/*==========================================================================*/
/* III) Bin the potential energy                                            */
/*       Recommended range is 1.0 to 20a0 (or cutoff)                       */

  // printf("itype = %d\n",itype); getchar();
  switch(itype){
   /* Coulomb */
    case 1: vcoul_bin(nsplin,r,cv0,cdv0,sw,dsw,qij,iperd,alp,diele_opt,
                      diele_rheal,diele_cut,diele_eps); break; 
   /* LJ      */
    case 2: vlj_bin(nsplin,r,cv0,cdv0,sw,dsw,eps,sig);  break; 
   /* Exp-6 */
    case 3: vwill_bin(nsplin,r,cv0,cdv0,sw,dsw,a,b,c6,c8,c10); break;
   /* Null potential */
    case 4: vnull_bin(nsplin,r,cv0,cdv0); break;  
   /* Exp-6 plus LJ */
    case 5: vwill_lj_bin(nsplin,r,cv0,cdv0,sw,dsw,a,b,c6,c8,c10,eps,sig);break;
   /* Aziz-Chen potential */
    case 6: vaziz_bin(nsplin,r,cv0,cdv0,sw,dsw,a,b,c,rm,c6,c8,c9,c10); break;
   /* Grimme */
    case 7: vgrimme_bin(nsplin,r,cv0,cdv0,sw,dsw,rm,c6); break;
  }/*end switch*/
/*==========================================================================*/
/* IV) Shift potential energy                                            */

  if (ishift == 1) {
    shift  = cv0[(nsplin-2)];
    for (i = 1; i <= nsplin; ++i) {
      cv0[i] -= shift;
    }/*endfor*/
  }/*endif*/

/*==========================================================================*/
/* V) Free the memory                                                       */

  cfree(&r[1]);
  cfree(&sw[1]);
  cfree(&dsw[1]);

/*--------------------------------------------------------------------------*/
 }/* end routine */ 
Beispiel #15
0
static void eblock_accept_notify_proc(Widget, XtPointer, XtPointer)
{
    int i = 0;
    char buf[256];
    int setno, graphno;
    int cx, cy, c1 = 0, c2 = 0, c3 = 0, c4 = 0; //d1,
    double *tx, *ty, *t2, *t3, *t4, *t5;

    //d1 = (int) GetChoice(eblock_type_choice_item);
    cx = (int)GetChoice(eblock_x_choice_item) - 1;
    cy = (int)GetChoice(eblock_y_choice_item);
    if (cx >= 0 && cx >= blockncols)
    {
        errwin("Column for X exceeds the number of columns in block data");
        return;
    }
    if (cy >= blockncols)
    {
        errwin("Column for Y exceeds the number of columns in block data");
        return;
    }
    switch (block_curtype)
    {
    case XY:
        break;
    case XYRT:
    case XYDX:
    case XYDY:
    case XYZ:
        c1 = (int)GetChoice(eblock_e1_choice_item);
        if (c1 >= blockncols)
        {
            errwin("Column for E1 exceeds the number of columns in block data");
            return;
        }
        break;
    case XYDXDX:
    case XYDYDY:
    case XYDXDY:
        c1 = (int)GetChoice(eblock_e1_choice_item);
        c2 = (int)GetChoice(eblock_e2_choice_item);
        if (c1 >= blockncols)
        {
            errwin("Column for E1 exceeds the number of columns in block data");
            return;
        }
        if (c2 >= blockncols)
        {
            errwin("Column for E2 exceeds the number of columns in block data");
            return;
        }
        break;
    case XYHILO:
    case XYBOX:
        c1 = (int)GetChoice(eblock_e1_choice_item);
        c2 = (int)GetChoice(eblock_e2_choice_item);
        c3 = (int)GetChoice(eblock_e3_choice_item);
        if (c1 >= blockncols)
        {
            errwin("Column for E1 exceeds the number of columns in block data");
            return;
        }
        if (c2 >= blockncols)
        {
            errwin("Column for E2 exceeds the number of columns in block data");
            return;
        }
        if (c3 >= blockncols)
        {
            errwin("Column for E3 exceeds the number of columns in block data");
            return;
        }
        break;
    case XYBOXPLOT:
        c1 = (int)GetChoice(eblock_e1_choice_item);
        c2 = (int)GetChoice(eblock_e2_choice_item);
        c3 = (int)GetChoice(eblock_e3_choice_item);
        c4 = (int)GetChoice(eblock_e4_choice_item);
        if (c1 >= blockncols)
        {
            errwin("Column for E1 exceeds the number of columns in block data");
            return;
        }
        if (c2 >= blockncols)
        {
            errwin("Column for E2 exceeds the number of columns in block data");
            return;
        }
        if (c3 >= blockncols)
        {
            errwin("Column for E3 exceeds the number of columns in block data");
            return;
        }
        if (c4 >= blockncols)
        {
            errwin("Column for E4 exceeds the number of columns in block data");
            return;
        }
    }
    setno = -1;
    graphno = (int)GetChoice(eblock_graph_choice_item) - 1;

    if (graphno == -1)
    {
        graphno = cg;
    }
    if (setno == -1)
    {
        setno = nextset(graphno);
    }
    if (setno == -1)
    {
        return;
    }
    if (g[graphno].active == OFF)
    {
        set_graph_active(graphno);
    }
    activateset(graphno, setno);
    settype(graphno, setno, block_curtype);

    tx = (double *)calloc(blocklen, sizeof(double));
    if (tx == NULL)
    {
        errwin("Can't allocate memory for X");
        return;
    }
    ty = (double *)calloc(blocklen, sizeof(double));
    if (ty == NULL)
    {
        cfree(tx);
        errwin("Can't allocate memory for Y");
        return;
    }
    for (i = 0; i < blocklen; i++)
    {
        if (cx == -1)
        {
            tx[i] = i + 1;
        }
        else
        {
            tx[i] = blockdata[cx][i];
        }
        ty[i] = blockdata[cy][i];
    }
    setcol(graphno, tx, setno, blocklen, 0);
    setcol(graphno, ty, setno, blocklen, 1);

    switch (block_curtype)
    {
    case XY:
        sprintf(buf, "Cols %d %d", cx + 1, cy + 1);
        break;
    case XYRT:
    case XYDX:
    case XYDY:
    case XYZ:
        sprintf(buf, "Cols %d %d %d", cx + 1, cy + 1, c1 + 1);
        t2 = (double *)calloc(blocklen, sizeof(double));
        for (i = 0; i < blocklen; i++)
        {
            t2[i] = blockdata[c1][i];
        }
        setcol(graphno, t2, setno, blocklen, 2);
        break;
    case XYDXDX:
    case XYDYDY:
    case XYDXDY:
        sprintf(buf, "Cols %d %d %d %d", cx + 1, cy + 1, c1 + 1, c2 + 1);
        t2 = (double *)calloc(blocklen, sizeof(double));
        t3 = (double *)calloc(blocklen, sizeof(double));
        for (i = 0; i < blocklen; i++)
        {
            t2[i] = blockdata[c1][i];
            t3[i] = blockdata[c2][i];
        }
        setcol(graphno, t2, setno, blocklen, 2);
        setcol(graphno, t3, setno, blocklen, 3);
        break;
    case XYHILO:
    case XYBOX:
        sprintf(buf, "Cols %d %d %d %d %d", cx + 1, cy + 1, c1 + 1, c2 + 1, c3 + 1);
        t2 = (double *)calloc(blocklen, sizeof(double));
        t3 = (double *)calloc(blocklen, sizeof(double));
        t4 = (double *)calloc(blocklen, sizeof(double));
        for (i = 0; i < blocklen; i++)
        {
            t2[i] = blockdata[c1][i];
            t3[i] = blockdata[c2][i];
            t4[i] = blockdata[c3][i];
        }
        setcol(graphno, t2, setno, blocklen, 2);
        setcol(graphno, t3, setno, blocklen, 3);
        setcol(graphno, t4, setno, blocklen, 4);
        break;
    case XYBOXPLOT:
        sprintf(buf, "Cols %d %d %d %d %d %d", cx + 1, cy + 1, c1 + 1, c2 + 1, c3 + 1, c4 + 1);
        t2 = (double *)calloc(blocklen, sizeof(double));
        t3 = (double *)calloc(blocklen, sizeof(double));
        t4 = (double *)calloc(blocklen, sizeof(double));
        t5 = (double *)calloc(blocklen, sizeof(double));
        for (i = 0; i < blocklen; i++)
        {
            t2[i] = blockdata[c1][i];
            t3[i] = blockdata[c2][i];
            t4[i] = blockdata[c3][i];
            t5[i] = blockdata[c4][i];
        }
        setcol(graphno, t2, setno, blocklen, 2);
        setcol(graphno, t3, setno, blocklen, 3);
        setcol(graphno, t4, setno, blocklen, 4);
        setcol(graphno, t5, setno, blocklen, 5);
        break;
    }

    setcomment(graphno, setno, buf);
    updatesetminmax(graphno, setno);
    update_status_popup(NULL, NULL, NULL);
    drawgraph();
}
Beispiel #16
0
void set_default_plotarr(plotarr *p)
{
    int i;

    if (p->len > 0)
    {
        for (i = 0; i < MAX_SET_COLS; i++)
        {
            if (p->ex[i] != NULL)
            {
                cfree(p->ex[i]);
            }
            p->ex[i] = NULL;
        }
    }
    p->active = OFF; /* active flag */
    p->type = XY; /* dataset type */
    p->deact = 0; /* deactivated set */
    p->hotlink = 0; /* hot linked set */
    p->hotfile[0] = 0; /* hot linked file name */
    p->len = 0; /* set length */
    p->missing = DATASET_MISSING; /* value for missing data */
    p->s = (char **)NULL; /* pointer to strings */
    p->xmin = p->xmax = p->ymin = p->ymax = 0.0;

    p->sym = 0; /* set plot symbol */
    p->symchar = 0; /* character for symbol */
    p->symskip = 0; /* How many symbols to skip */
    p->symfill = 0; /* Symbol fill type */
    p->symdot = 0; /* Symbol dot in center */
    p->symlines = grdefaults.lines; /* set plot sym line style */
    p->symlinew = grdefaults.linew; /* set plot sym line width */
    p->symcolor = grdefaults.color; /* color for symbol */
    p->symsize = 1.0; /* size of symbols */

    p->font = grdefaults.font; /* font for strings */
    p->format = DECIMAL; /* format for drawing values */
    p->prec = 1; /* precision for drawing values */
    p->just = LEFT; /* justification for drawing values */
    p->where = RIGHT; /* where to draw values */
    p->valsize = 1.0; /* char size for drawing values */

    p->lines = grdefaults.lines;
    p->linew = grdefaults.linew;
    p->color = grdefaults.color;
    p->lineskip = 0; /* How many points to skip when drawing lines */

    p->fill = 0; /* fill type */
    p->fillusing = COLOR; /* fill using color or pattern */
    p->fillcolor = 1; /* fill color */
    p->fillpattern = 0; /* fill pattern */

    p->errbar = -1;
    /* if type is _DX, _DY, _DXDY and errbar =
    * TRUE */
    p->errbarxy = BOTH; /* type of error bar */
    p->errbar_lines = grdefaults.lines; /* error bar line width */
    p->errbar_linew = grdefaults.linew; /* error bar line style */
    p->errbar_riser = ON; /* connecting line between error limits */
    p->errbar_riser_linew = 1;
    /* connecting line between error limits line
    * width */
    p->errbar_riser_lines = 1;
    /* connecting line between error limits line
    * style */

    p->errbarper = 1.0; /* length of error bar */
    p->hilowper = 1.0; /* length of hi-low */

    p->density_plot = 0; /* if type is XYZ then density_plot  = 1 */
    p->zmin = p->zmax = 0.0; /* min max for density plots */

    p->comments[0] = 0; /* how did this set originate */
    p->name[0] = 0; /* set name alias */

    for (i = 0; i < MAX_SET_COLS; i++)
    {
        p->emin[i] = 0.0; /* min for each column */
        p->emax[i] = 0.0; /* max for each column */
        p->imin[i] = 0; /* min loc for each column */
        p->imax[i] = 0; /* max loc for each column */
    }
    p->ep = NULL; /* EditPoints pointer */
}
Beispiel #17
0
XdmfHDF5ControllerDSM::XdmfHDF5ControllerDSM(const std::string & hdf5FilePath,
                                             const std::string & dataSetPath,
                                             const shared_ptr<const XdmfArrayType> type,
                                             const std::vector<unsigned int> & start,
                                             const std::vector<unsigned int> & stride,
                                             const std::vector<unsigned int> & dimensions,
                                             const std::vector<unsigned int> & dataspaceDimensions,
                                             MPI_Comm comm,
                                             unsigned int bufferSize,
                                             int startCoreIndex,
                                             int endCoreIndex) :
  XdmfHDF5Controller(hdf5FilePath,
                     dataSetPath,
                     type,
                     start,
                     stride,
                     dimensions,
                     dataspaceDimensions),
#ifdef XDMF_BUILD_DSM_THREADS
  mDSMBuffer(NULL),
  mDSMManager(NULL),
#endif
  mServerMode(true)

{

  int rank, size;

  MPI_Comm_size(comm, &size);
  MPI_Comm_rank(comm, &rank);

  // Negative values will be changed to maximum range
  if (startCoreIndex < 0) {
    startCoreIndex = 0;
  }
  if (endCoreIndex < 0) {
    endCoreIndex = size - 1;
  }

  // Ensure start index is less than end index
  if (startCoreIndex > endCoreIndex) {
    int tempholder = startCoreIndex;
    startCoreIndex = endCoreIndex;
    endCoreIndex = tempholder;
  }

  MPI_Comm serverComm;

  MPI_Group workers, dsmgroup, serversplit, servergroup;

  int * ServerIds = (int *)calloc((3), sizeof(int));
  unsigned int index = 0;
  for(int i=startCoreIndex ; i <= endCoreIndex ; ++i) {
    ServerIds[index++] = i;
  }

  MPI_Comm_group(comm, &serversplit);
  MPI_Group_incl(serversplit, index, ServerIds, &servergroup);
  MPI_Comm_create(comm, servergroup, &serverComm);
  MPI_Comm_group(comm, &dsmgroup);
  MPI_Group_excl(dsmgroup, index, ServerIds, &workers);
  MPI_Comm_create(comm, workers, &mWorkerComm);
  cfree(ServerIds);

  // Create the manager

  mDSMServerManager = new XdmfDSMManager();

  mDSMServerManager->SetLocalBufferSizeMBytes(bufferSize);
  mDSMServerManager->SetInterCommType(XDMF_DSM_COMM_MPI);

  if (rank >= startCoreIndex && rank <= endCoreIndex) {
    mDSMServerManager->SetMpiComm(serverComm);
    mDSMServerManager->Create();
  }
  else {
    mDSMServerManager->SetMpiComm(mWorkerComm);
    mDSMServerManager->SetIsServer(false);
    mDSMServerManager->Create(startCoreIndex, endCoreIndex);
  }

  XDMF_dsm_set_manager(mDSMServerManager);

  mDSMServerBuffer = mDSMServerManager->GetDsmBuffer();

  mDSMServerBuffer->GetComm()->DupInterComm(comm);
  mDSMServerBuffer->SetIsConnected(true);

  if (startCoreIndex < size) {
    if (rank >= startCoreIndex && rank <= endCoreIndex) {
      mDSMServerManager->GetDsmBuffer()->ReceiveInfo();
    }
    else {
      mDSMServerManager->GetDsmBuffer()->SendInfo();
    }
  }

  MPI_Barrier(comm);

  // Loop needs to be started before anything can be done to the file
  // since the service is what sets up the file

  if (rank < startCoreIndex || rank > endCoreIndex) {
    // Turn off the server designation
    mDSMServerBuffer->SetIsServer(false);
    // If this is set to false then the buffer will attempt to
    // connect to the intercomm for DSM stuff
    mDSMServerManager->SetIsServer(false);
  }
  else {
    // On cores where memory is set up, start the service loop
    // This should iterate infinitely until a value to end the loop is passed
    int returnOpCode;
    mDSMServerBuffer->BufferServiceLoop(&returnOpCode);
  }
}
Beispiel #18
0
/*
  Performs a distributed merge sort amongst processes. The data and num_items
  that are returned to the user will be different than the data buffers they
  supplied because of the nature of how the algorithm works. This
  implementation of parallel merge sort is primarily used by the parallel
  sample sort algorithm.
*/
int pmsort_a(Pmsort_Object* pmsort_object, void** data_ret, int* num_items_ret,
             int item_size, int32_t (*compare)(const void*, const void*)) {
  MPI_Comm world_comm = pmsort_object->world_comm;
  assert(world_comm != MPI_COMM_NULL);
  int32_t world_size;
  MPI_Comm_size(world_comm, &world_size);
  int32_t world_rank;
  MPI_Comm_rank(world_comm, &world_rank);

  /* Sort data to be merged */
  qsort(*data_ret, *num_items_ret, item_size, compare);

  /* Handle base case */
  if (world_size == 1) {
    return 1;
  }

  /* For convenience */
  MPI_Datatype item_type;
  MPI_Type_contiguous(item_size, MPI_BYTE, &item_type);
  MPI_Type_commit(&item_type);
  void* data = *data_ret;
  int num_items = *num_items_ret;

  /* Build the merging schedule */
  int num_merges;
  int* merge_schedule = create_merge_schedule(world_size, world_rank,
                                              &num_merges);

  /* Find the max number of items that will be received per any stage */
  int max_num_items = 0;
  MPI_Allreduce(&num_items, &max_num_items, 1, MPI_INT, MPI_MAX, world_comm);

  /* Allocate merger receive buffer and merge buffer */
  void* recv_data = cmalloc(item_size * max_num_items);
  void* merge_data = cmalloc(item_size * num_items);
  
  int i;
  void* merger_min_max = cmalloc(item_size);
  for (i = 0; i < num_merges; i++) {
    /* For non-power-of-two process counts, the merge_schedule may contain
       invalid ranks */
    if (merge_schedule[i] < world_size) {
      int send_num_items = num_items;
      int send_offset = 0;
      MPI_Status recv_status;
      int num_recv_items;

      /* Swap mins and maxs to minimize communication */
      if (world_rank < merge_schedule[i]) {
        MPI_Sendrecv(data + ((num_items - 1) * item_size),
                     (num_items == 0) ? 0 : 1, item_type,
                     merge_schedule[i], i, merger_min_max, 1, item_type,
                     merge_schedule[i], i, world_comm, &recv_status);
        MPI_Get_count(&recv_status, item_type, &num_recv_items);
        /* If sender or receiver has no elements, go to the next merger */
        if (num_items == 0 || num_recv_items == 0) {
          continue;
        }
        /* Find the first element to send to the other merger */
        send_offset = (bsearchx(merger_min_max, data, num_items,
                                item_size, compare) + 1) / 2;
        send_num_items = num_items - send_offset;
      } else {
        MPI_Sendrecv(data, (num_items == 0) ? 0 : 1, item_type,
                     merge_schedule[i], i, merger_min_max, 1, item_type,
                     merge_schedule[i], i, world_comm, &recv_status);
        MPI_Get_count(&recv_status, item_type, &num_recv_items);
        /* If sender or receiver has no elements, go to the next merger */
        if (num_items == 0 || num_recv_items == 0) {
          continue;
        }
        send_num_items = (bsearchx(merger_min_max, data,
                                   num_items, item_size, compare) + 1) / 2;
      }

      MPI_Sendrecv(data + (send_offset * item_size), send_num_items, 
                   item_type, merge_schedule[i], i, recv_data, max_num_items,
                   item_type, merge_schedule[i], i, world_comm, &recv_status);
      MPI_Get_count(&recv_status, item_type, &num_recv_items);

      /* Merge the items on each merger, either keeping the upper or lower
         part of elements */
      if (world_rank < merge_schedule[i]) {
        merge_items_forward(data, recv_data, merge_data, num_items, 
                            num_recv_items, item_size, compare);
      } else {
        merge_items_backward(data, recv_data, merge_data, num_items, 
                             num_recv_items, item_size, compare);
      }

      /* Update your data */
      void* temp = merge_data;
      merge_data = data;
      data = temp;
    }
  }
  cfree(merger_min_max);

  /* Clean up */
  cfree(merge_schedule);
  cfree(merge_data);
  cfree(recv_data);
  MPI_Type_free(&item_type);
  
  *num_items_ret = num_items;
  *data_ret = data;
}
Beispiel #19
0
void control_mol_params(MDINTEGRATE *mdintegrate, MDATOMS *mdatoms, 
    MDINTER *mdinter, GENERAL_DATA *general_data,
    MDINTRA *mdintra,CP *cp,
    CLASS_PARSE *class_parse,CP_PARSE *cp_parse,
    FREE_PARSE *free_parse,
    FILENAME_PARSE *filename_parse)

  /*==========================================================================*/
{ /*begin routine*/
  /*========================================================================*/
  /*             Local variable declarations                                */

#include "../class_defs/allclass_strip_mdatoms.h"
#include "../class_defs/allclass_strip_mdintegrate.h"
#include "../class_defs/allclass_strip_mdinter.h"
#include "../class_defs/allclass_strip_mdintra.h"
#include "../class_defs/allclass_strip_gen.h"
#include "../class_defs/allclass_strip_cp.h"

  int i,iii,jmol_typ,nmol_tot; 
  int nmol_typ,bond_free_num,bend_free_num,tors_free_num,rbar_sig_free_iopt;
  int ifirst,nline,nfun_key;
  int num_user,num_def,cp_on;
  double now_memory;
  char *fun_key;
  int nhist,nhist_bar,nhist_sig,nfree,nsurf;

  FILE *fp; 
  DICT_MOL dict_mol;                        /* Dictionaries and sizes */
  DICT_WORD *word;

  char *molsetname   = filename_parse->molsetname;
  double *text_mol;
  double *text_nhc_mol;
  int    *mol_freeze_opt;
  int    *imol_nhc_opt;
  int    *nmol_jmol_typ;
  int pi_beads       = mdatoms->mdclatoms_info.pi_beads;
  int iextend,ipress;
  iextend            = (general_data->genensopts.nvt 
      +general_data->genensopts.npt_i  
      +general_data->genensopts.npt_f
      +general_data->genensopts.nst);
  ipress             = (general_data->genensopts.npt_i
      +general_data->genensopts.npt_f);

  cp_on  =    general_data->gensimopts.cp_min 
    + general_data->gensimopts.cp_wave_min 
    + general_data->gensimopts.cp_wave_min_pimd
    + general_data->gensimopts.cp
    + general_data->gensimopts.cp_wave
    + general_data->gensimopts.cp_pimd 
    + general_data->gensimopts.cp_wave_pimd
    + general_data->gensimopts.debug_cp
    + general_data->gensimopts.debug_cp_pimd;


  /*========================================================================*/
  /* 0) Output to screen */

  PRINTF("\n");  PRINT_LINE_STAR;
  PRINTF("Reading molecular set up file %s\n",molsetname);
  PRINT_LINE_DASH;PRINTF("\n");

  /*========================================================================*/
  /* I) Set up dictionaries and malloc temporaries                          */

  ifirst = 1;

  set_molset_fun_dict(&dict_mol.fun_dict,&dict_mol.num_fun_dict);
  set_mol_dict(&dict_mol.mol_dict,&dict_mol.num_mol_dict,
      iextend,class_parse->tau_nhc_def,
      general_data->genstatepoint.t_ext,ifirst);

  set_wave_dict(&dict_mol.wave_dict,&dict_mol.num_wave_dict,cp_parse);
  set_bond_free_dict(&dict_mol.bond_free_dict,&dict_mol.num_bond_free_dict);
  set_bend_free_dict(&dict_mol.bend_free_dict,&dict_mol.num_bend_free_dict);
  set_tors_free_dict(&dict_mol.tors_free_dict,&dict_mol.num_tors_free_dict); 
  set_rbar_free_dict(&dict_mol.rbar_free_dict,&dict_mol.num_rbar_free_dict); 
  set_user_base_dict(&dict_mol.user_base_dict,&dict_mol.num_user_base_dict);   
  set_def_base_dict(&dict_mol.def_base_dict,&dict_mol.num_def_base_dict);
  set_surf_dict(&dict_mol.surface_dict,&dict_mol.num_surface_dict);
  num_user = dict_mol.num_user_base_dict;
  num_def  = dict_mol.num_def_base_dict;

  word = (DICT_WORD *)cmalloc(sizeof(DICT_WORD),"control_mol_params");
  fun_key = (char *)cmalloc(MAXWORD*sizeof(char),"control_mol_params");

  /*========================================================================*/
  /* II) Read the moleset file and count the molecule types                 */
  /*       and the free energy stuff                                        */

  nmol_typ            = 0;
  nline               = 0;
  nfun_key            = 0;
  bond_free_num       = 0;
  bend_free_num       = 0;
  tors_free_num       = 0;
  rbar_sig_free_iopt  = 0;
  nsurf               = 0;

  fp = cfopen((const char *) molsetname,"r");
  while(get_fun_key_cnt(fp,fun_key,&nline,&nfun_key,molsetname)){
    if(!strcasecmp(fun_key,"molecule_def")) {nmol_typ+=1;}
    if(!strcasecmp(fun_key,"bond_free_def")){bond_free_num+=1;}
    if(!strcasecmp(fun_key,"bend_free_def")){bend_free_num+=1;}
    if(!strcasecmp(fun_key,"tors_free_def")){tors_free_num+=1;}
    if(!strcasecmp(fun_key,"rbar_sig_free_def")){rbar_sig_free_iopt+=1;}
    if(!strcasecmp(fun_key,"surface_def")){nsurf+=1;}
  }/*endwhile*/
  fclose(fp);

  mdatom_maps->nmol_typ          = nmol_typ;
  mdintra->mdbond_free.num       = bond_free_num;
  mdintra->mdbend_free.num       = bend_free_num;
  mdintra->mdtors_free.num       = tors_free_num;
  mdintra->mdrbar_sig_free.iopt  = rbar_sig_free_iopt ;
  mdintra->mdrbar_sig_free.nfree = 0;

  if((bond_free_num+bend_free_num+tors_free_num+rbar_sig_free_iopt)>1){
    PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    PRINTF("Only one free energy definition permitted\n");
    PRINTF("in set up file %s \n",molsetname);
    PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    FFLUSH(stdout);
    EXIT(1);
  }/*endif*/

#ifdef JUNK
  int iperd          = general_data->gencell.iperd;
  if( (nsurf>0) && (iperd != 2)){
    PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    PRINTF("Surface potentials permitted ONLY in systems with\n");
    PRINTF("2D periodicity in set up file  %s \n",molsetname);
    PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
    FFLUSH(stdout);
    EXIT(1);
  }/*endif*/
#endif

  mdsurface->isurf_on = nsurf;

  //========================================================================
  // III) Malloc molecular data storage and initialize                      

  now_memory = (double)((nmol_typ)*(sizeof(int)*2))*1.e-06;
  (*tot_memory) += now_memory;

  PRINTF("Allocating molecular memory: %g Mbytes; Total memory: %g Mbytes\n",
      now_memory,(*tot_memory));

  mdatom_maps->nmol_jmol_typ  = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  mdatom_maps->mol_typ        = 
    (NAME *)cmalloc(nmol_typ*sizeof(NAME),"control_mol_params")-1;
  mdatom_maps->nres_1mol_jmol_typ  = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  mdatom_maps->jres_jmol_typ_strt  = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  class_parse->ionfo_opt         = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  class_parse->ires_bond_conv    = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  class_parse->tau_nhc_mol       = 
    (double*)cmalloc(nmol_typ*sizeof(double),"control_mol_params")-1;
  class_parse->text_nhc_mol      = 
    (double*)cmalloc(nmol_typ*sizeof(double),"control_mol_params")-1;
  class_parse->imol_nhc_opt      = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;  
  class_parse->mol_freeze_opt    = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;  
  class_parse->mol_hydrog_mass_opt = 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  class_parse->mol_hydrog_mass_val = 
    (double *)cmalloc(nmol_typ*sizeof(double),"control_mol_params")-1;
  class_parse->mol_hydrog_con_opt= 
    (int *)cmalloc(nmol_typ*sizeof(int),"control_mol_params")-1;
  filename_parse->mol_param_name = 
    (NAME *)cmalloc(nmol_typ*sizeof(NAME),"control_mol_params")-1;
  filename_parse->user_intra_name= 
    (NAME *)cmalloc(num_user*sizeof(NAME),"control_mol_params")-1;
  filename_parse->def_intra_name = 
    (NAME *)cmalloc(num_def*sizeof(NAME),"control_mol_params")-1;
  if(bond_free_num>0){
    mdintra->mdbond_free.file       = 
      (char *)cmalloc(MAXWORD*sizeof(char),"control_mol_params");
    free_parse->imoltyp_bond_free= 
      (int *) cmalloc(2*sizeof(int),"control_mol_params")-1;
    free_parse->imol_bond_free   = 
      (int *) cmalloc(2*sizeof(int),"control_mol_params")-1;
    free_parse->ires_bond_free   = 
      (int *) cmalloc(2*sizeof(int),"control_mol_params")-1;
    free_parse->iatm_bond_free   = 
      (int *) cmalloc(2*sizeof(int),"control_mol_params")-1;
  }
  if(bend_free_num>0){
    mdintra->mdbend_free.file       = 
      (char *)cmalloc(MAXWORD*sizeof(char),"control_mol_params");
    free_parse->imoltyp_bend_free= 
      (int *) cmalloc(3*sizeof(int),"control_mol_params")-1;
    free_parse->imol_bend_free   = 
      (int *) cmalloc(3*sizeof(int),"control_mol_params")-1;
    free_parse->ires_bend_free   = 
      (int *) cmalloc(3*sizeof(int),"control_mol_params")-1;
    free_parse->iatm_bend_free   = 
      (int *) cmalloc(3*sizeof(int),"control_mol_params")-1;
  }
  if(tors_free_num>0){
    mdintra->mdtors_free.file       = 
      (char *)cmalloc(MAXWORD*sizeof(char),"control_mol_params");
    free_parse->imoltyp_tors_free= 
      (int *) cmalloc(8*sizeof(int),"control_mol_params")-1;
    free_parse->imol_tors_free   = 
      (int *) cmalloc(8*sizeof(int),"control_mol_params")-1;
    free_parse->ires_tors_free   = 
      (int *) cmalloc(8*sizeof(int),"control_mol_params")-1;
    free_parse->iatm_tors_free   = 
      (int *) cmalloc(8*sizeof(int),"control_mol_params")-1;
  }

  if(rbar_sig_free_iopt>0){
    mdintra->mdrbar_sig_free.file   = 
      (char *)cmalloc(MAXWORD*sizeof(char),"control_mol_params");
  }
  mdclatoms_info->text_mol   = 
    (double*)cmalloc(nmol_typ*sizeof(double),"control_mol_params")-1;

  text_mol       = mdclatoms_info->text_mol;
  text_nhc_mol   = class_parse->text_nhc_mol;
  mol_freeze_opt = class_parse->mol_freeze_opt;
  imol_nhc_opt   = class_parse->imol_nhc_opt;

  /*========================================================================*/
  /* IV) Get molecular/CP setup information */

  control_set_mol_params(mdatom_maps,&(cp->cpopts),
      &(cp->cpcoeffs_info),cp_parse,class_parse,
      mdintra,mdsurface,
      filename_parse,free_parse,
      &dict_mol,word,
      fun_key,&nfun_key,iextend,
      general_data->genstatepoint.t_ext,
      ifirst,pi_beads);
  if(tors_free_num==1){
    tors_free_num = mdintra->mdtors_free.num; /* changed in above routine */
  }/*endif*/

  for(i=1; i<= nmol_typ; i++){
    text_mol[i] = text_nhc_mol[i];   
  }/*endfor*/

  /*========================================================================*/
  /* V) Free some memory and malloc some other                              */

  if(bond_free_num>0){
    nhist = (mdintra->mdbond_free.nhist);
    mdintra->mdbond_free.hist = 
      (double *)cmalloc(nhist*sizeof(double),"control_mol_params")-1;
  }/*endif*/

  if(bend_free_num>0){
    nhist = (mdintra->mdbend_free.nhist);
    mdintra->mdbend_free.hist = 
      (double *)cmalloc(nhist*sizeof(double),"control_mol_params")-1;
  }/*endif*/

  if(tors_free_num==1){
    nhist = (mdintra->mdtors_free.nhist);
    mdintra->mdtors_free.hist = 
      (double *)cmalloc(nhist*sizeof(double),"control_mol_params")-1;
  }/*endif*/
  if(tors_free_num==2){
    nhist = (mdintra->mdtors_free.nhist);
    mdintra->mdtors_free.hist_2d = cmall_mat(1,nhist,1,nhist,"control_mol_params");
  }/*endif*/

  if(rbar_sig_free_iopt>0){
    nhist_bar = (mdintra->mdrbar_sig_free.nhist_bar);
    nhist_sig = (mdintra->mdrbar_sig_free.nhist_sig);
    nfree     = (mdintra->mdrbar_sig_free.nfree);
    mdintra->mdrbar_sig_free.hist    = 
      cmall_mat(1,nhist_bar,1,nhist_sig,"control_mol_params");
    mdintra->mdrbar_sig_free.hist_rn = 
      cmall_mat(1,nfree,1,nhist_bar,"control_mol_params");
  }/*endif*/

  cfree(fun_key,"control_mol_params");
  cfree(word,"control_mol_params");
  cfree(&dict_mol.fun_dict[1],"control_mol_params");
  cfree(&dict_mol.mol_dict[1],"control_mol_params");
  cfree(&dict_mol.wave_dict[1],"control_mol_params");
  cfree(&dict_mol.bond_free_dict[1],"control_mol_params");
  cfree(&dict_mol.bend_free_dict[1],"control_mol_params");
  cfree(&dict_mol.tors_free_dict[1],"control_mol_params");
  cfree(&dict_mol.rbar_free_dict[1],"control_mol_params");
  cfree(&dict_mol.user_base_dict[1],"control_mol_params");
  cfree(&dict_mol.def_base_dict[1],"control_mol_params");

  for(jmol_typ=1;jmol_typ<=nmol_typ;jmol_typ++){

    if((mol_freeze_opt[jmol_typ] > 0) &&  (ipress > 0)){
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      PRINTF("No freezing allowed with NPT_I and NPT_F       \n");
      PRINTF("Ensembles                                      \n");
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      FFLUSH(stdout);
      EXIT(1);
    }/*endif*/

    if((mol_freeze_opt[jmol_typ]==1)&&(imol_nhc_opt[jmol_typ] > 0)){
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      PRINTF("Do not use thermostating when freezing the     \n");
      PRINTF("whole molecule.(Use none option)               \n");
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      FFLUSH(stdout);
      EXIT(1);
    }/*endif*/

  }/*endfor*/

  /*========================================================================*/
  /* Error check */

  nmol_tot = 0;
  nmol_jmol_typ  = mdatom_maps->nmol_jmol_typ;
  for(i=1;i<=nmol_typ;i++){nmol_tot+= nmol_jmol_typ[i];}

  if(cp_on==1 && cp->cpopts.cp_dual_grid_opt >= 1){
    if(cp_parse->cp_ecut_dual_grid > cp_parse->cp_ecut){
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");   
      PRINTF("The small dense grid cutoff is less than the large sparse");
      PRINTF("grid cutoff. This might work, but I doubut it\n");
      PRINTF("@@@@@@@@@@@@@@@@@@@@_error_@@@@@@@@@@@@@@@@@@@@\n");
      FFLUSH(stdout);
      EXIT(1);
    }
  }

  /*========================================================================*/
  /* VI) Done                                                               */

  PRINTF("The class contains %d molecule types\n",nmol_typ);
  PRINTF("\n"); 

  PRINT_LINE_DASH;
  PRINTF("Completed reading molecular set up file %s\n",molsetname);
  PRINT_LINE_STAR;
  PRINTF("\n");

  /*------------------------------------------------------------------------*/
}/*end routine*/
/*==========================================================================*/
void shake_23_rolli(GRP_BOND_CON *grp_bond_con,
              CLATOMS_INFO *clatoms_info,CLATOMS_POS *clatoms_pos,
              PTENS *ptens,double dt,double *aiter,
              BARO *baro,int ifirst,
              CLASS_COMM_FORC_PKG *class_comm_forc_pkg)


/*==========================================================================*/
/*        Begin Routine                                                     */
{/*Begin Routine*/
/*=======================================================================*/
/*         Local Variable declarations                                   */
  
#include "../typ_defs/typ_mask.h"

 double ftemp;
 double xl0[NCON_23+1];
 double rmu[NCON_23+1];
 double amat[NCON_23+1][NCON_23+1],ainv[NCON_23+1][NCON_23+1];
 double r12s,r13s;
 double dxn12,dyn12,dzn12,dxn13,dyn13,dzn13;
 double dlmax,dlmax1,dlmax2,rdet_a;
 double rmu12,rmu22,rm12;

 double dts;

 int iter,igrp,*ind1,*ind2,*ind3,jtyp;
 int iii,i,ktemp,ktemp1,ktemp2,ktemp3;
 double *xlam1,*xlam2;
 double *avec1,*avec2;
 double *rm1,*rm2,*rm3;
 double *rmm11,*rmm12,*rmm21,*rmm22;
 double *dxl1,*dxl2;
 double *dx12,*dy12,*dz12,*dx13,*dy13,*dz13;
 double *dxo12,*dyo12,*dzo12,*dxo13,*dyo13,*dzo13;
 double **x,**y,**z,**xo,**yo,**zo;
 double *dij1,*dij2;
 double *p11,*p12,*p13,*p23,*p33,*p22;

/* Local pointers */

  double *clatoms_mass         = clatoms_info->mass;
  double *clatoms_x            = clatoms_pos->x;
  double *clatoms_y            = clatoms_pos->y;
  double *clatoms_z            = clatoms_pos->z;
  double *clatoms_vx           = clatoms_pos->vx;
  double *clatoms_vy           = clatoms_pos->vy;
  double *clatoms_vz           = clatoms_pos->vz;
  double *clatoms_xold         = clatoms_info->xold;
  double *clatoms_yold         = clatoms_info->yold;
  double *clatoms_zold         = clatoms_info->zold;
  int *grp_bond_con_j1_23      = grp_bond_con->j1_23;
  int *grp_bond_con_j2_23      = grp_bond_con->j2_23;
  int *grp_bond_con_j3_23      = grp_bond_con->j3_23;
  int *grp_bond_con_jtyp_23    = grp_bond_con->jtyp_23;
  double **grp_bond_con_eq_23  = grp_bond_con->eq_23;
  double **grp_bond_con_al_23  = grp_bond_con->al_23;
  double *ptens_pvten_inc      = ptens->pvten_inc;
  double *ptens_pvten_tmp      = ptens->pvten_tmp;
  double *ptens_pvten_tmp2      = ptens->pvten_tmp_res;
  double pnorm;
  double baro_roll_scv         = baro->roll_scv;

  int ngrp,irem,igrp_off;
  int ngrp_tot                 = grp_bond_con->num_23;
  int np_forc                  = class_comm_forc_pkg->num_proc;
  int myid_forc                = class_comm_forc_pkg->myid;
  MPI_Comm comm_forc           = class_comm_forc_pkg->comm;

/*=======================================================================*/

  ngrp = (ngrp_tot);
  igrp_off = 0;

/*=======================================================================*/
/* assign local memory */
  if(ngrp > 0){
     xlam1 = dvector(1,ngrp);
     xlam2 = dvector(1,ngrp);

     avec1 = dvector(1,ngrp);
     avec2 = dvector(1,ngrp);

     rm1 = dvector(1,ngrp);
     rm2 = dvector(1,ngrp);
     rm3 = dvector(1,ngrp);

     rmm11 = dvector(1,ngrp);
     rmm12 = dvector(1,ngrp);
     rmm21 = dvector(1,ngrp);
     rmm22 = dvector(1,ngrp);

     dxl1 = dvector(1,ngrp);
     dxl2 = dvector(1,ngrp);

     dx12 = dvector(1,ngrp);
     dy12 = dvector(1,ngrp);
     dz12 = dvector(1,ngrp);

     dx13 = dvector(1,ngrp);
     dy13 = dvector(1,ngrp);
     dz13 = dvector(1,ngrp);

     dxo12 = dvector(1,ngrp);
     dyo12 = dvector(1,ngrp);
     dzo12 = dvector(1,ngrp);

     dxo13 = dvector(1,ngrp);
     dyo13 = dvector(1,ngrp);
     dzo13 = dvector(1,ngrp);

      dij1= dvector(1,ngrp);
      dij2= dvector(1,ngrp);
         x= dmatrix(1,3,1,ngrp);
         y= dmatrix(1,3,1,ngrp);
         z= dmatrix(1,3,1,ngrp);
        xo= dmatrix(1,3,1,ngrp);
        yo= dmatrix(1,3,1,ngrp);
        zo= dmatrix(1,3,1,ngrp);
       p11= dvector(1,ngrp);
       p12= dvector(1,ngrp);
       p13= dvector(1,ngrp);
       p22= dvector(1,ngrp);
       p23= dvector(1,ngrp);
       p33= dvector(1,ngrp);
      ind1 = (int *) cmalloc(ngrp*sizeof(int))-1;
      ind2 = (int *) cmalloc(ngrp*sizeof(int))-1;
      ind3 = (int *) cmalloc(ngrp*sizeof(int))-1;
  }/*endif*/


/*=======================================================================*/
/* CC */

 dts = dt*dt;
 pnorm = 2.0/dts;
 *aiter = 0.0;
 ptens_pvten_tmp[1] = 0.0;
 ptens_pvten_tmp[2] = 0.0;
 ptens_pvten_tmp[3] = 0.0;
 ptens_pvten_tmp[4] = 0.0;
 ptens_pvten_tmp[5] = 0.0;
 ptens_pvten_tmp[6] = 0.0;
 ptens_pvten_tmp[7] = 0.0;
 ptens_pvten_tmp[8] = 0.0;
 ptens_pvten_tmp[9] = 0.0;

 if(ifirst == 2){
   for(igrp=1;igrp <= ngrp; igrp++) {
     grp_bond_con_al_23[1][(igrp+igrp_off)] = 0.0;
     grp_bond_con_al_23[2][(igrp+igrp_off)] = 0.0;
   }
 }

 for(igrp=1;igrp <= ngrp; igrp++) {
    ind1[igrp] = grp_bond_con_j1_23[(igrp+igrp_off)];
    ind2[igrp] = grp_bond_con_j2_23[(igrp+igrp_off)];
    ind3[igrp] = grp_bond_con_j3_23[(igrp+igrp_off)];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind1[igrp];
    x[1][igrp] = clatoms_x[ktemp];
    y[1][igrp] = clatoms_y[ktemp];
    z[1][igrp] = clatoms_z[ktemp];
    rm1[igrp] = 1.0/clatoms_mass[ktemp];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind2[igrp];
    x[2][igrp] = clatoms_x[ktemp];
    y[2][igrp] = clatoms_y[ktemp];
    z[2][igrp] = clatoms_z[ktemp];
    rm2[igrp] = 1.0/clatoms_mass[ktemp];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind3[igrp];
    x[3][igrp] = clatoms_x[ktemp];
    y[3][igrp] = clatoms_y[ktemp];
    z[3][igrp] = clatoms_z[ktemp];
    rm3[igrp] = 1.0/clatoms_mass[ktemp];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind1[igrp];
    xo[1][igrp] = clatoms_xold[ktemp];
    yo[1][igrp] = clatoms_yold[ktemp];
    zo[1][igrp] = clatoms_zold[ktemp];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind2[igrp];
    xo[2][igrp] = clatoms_xold[ktemp];
    yo[2][igrp] = clatoms_yold[ktemp];
    zo[2][igrp] = clatoms_zold[ktemp];
}

 for(igrp=1;igrp <= ngrp; igrp++) {
    ktemp= ind3[igrp];
    xo[3][igrp] = clatoms_xold[ktemp];
    yo[3][igrp] = clatoms_yold[ktemp];
    zo[3][igrp] = clatoms_zold[ktemp];
}


 for(igrp=1;igrp <= ngrp; igrp++) {
  jtyp = grp_bond_con_jtyp_23[(igrp+igrp_off)];
  dij1[igrp] = grp_bond_con_eq_23[1][jtyp];
  dij2[igrp] = grp_bond_con_eq_23[2][jtyp];
 }/*end for*/

/* Initial Guess for multipliers */
 for(igrp=1;igrp <= ngrp; igrp++) {
    rmm11[igrp] = -(rm1[igrp]+rm2[igrp]);
    rmm12[igrp] = -rm1[igrp];
    rmm21[igrp] = -rm1[igrp];
    rmm22[igrp] = -(rm1[igrp]+rm3[igrp]);
 }

 for(igrp=1;igrp <= ngrp; igrp++) {
    dx12[igrp] = x[1][igrp]-x[2][igrp];
    dy12[igrp] = y[1][igrp]-y[2][igrp];
    dz12[igrp] = z[1][igrp]-z[2][igrp];
  }
 for(igrp=1;igrp <= ngrp; igrp++) {
    dx13[igrp] = x[1][igrp]-x[3][igrp];
    dy13[igrp] = y[1][igrp]-y[3][igrp];
    dz13[igrp] = z[1][igrp]-z[3][igrp];
  }

 for(igrp=1;igrp <= ngrp; igrp++) {
  dxo12[igrp] = (xo[1][igrp]-xo[2][igrp])*baro_roll_scv;
  dyo12[igrp] = (yo[1][igrp]-yo[2][igrp])*baro_roll_scv;
  dzo12[igrp] = (zo[1][igrp]-zo[2][igrp])*baro_roll_scv;
 }


 for(igrp=1;igrp <= ngrp; igrp++) {
    dxo13[igrp] = (xo[1][igrp]-xo[3][igrp])*baro_roll_scv;
    dyo13[igrp] = (yo[1][igrp]-yo[3][igrp])*baro_roll_scv;
    dzo13[igrp] = (zo[1][igrp]-zo[3][igrp])*baro_roll_scv;
 }
  

 for(igrp=1;igrp <= ngrp; igrp++) {
   r12s = dx12[igrp]*dx12[igrp] + dy12[igrp]*dy12[igrp]
        + dz12[igrp]*dz12[igrp];
   r13s = dx13[igrp]*dx13[igrp] + dy13[igrp]*dy13[igrp]
        + dz13[igrp]*dz13[igrp];

   avec1[igrp] = dij1[igrp]*dij1[igrp] - r12s;
   avec2[igrp] = dij2[igrp]*dij2[igrp] - r13s;
  }


 if(ifirst==2||ifirst==0){
 for(igrp=1;igrp <= ngrp; igrp++) {

   amat[1][1] = 2.0*rmm11[igrp]*(dx12[igrp]*dxo12[igrp]
              + dy12[igrp]*dyo12[igrp]
              + dz12[igrp]*dzo12[igrp]);
   amat[1][2] = 2.0*rmm12[igrp]*(dx12[igrp]*dxo13[igrp]
              + dy12[igrp]*dyo13[igrp]
              + dz12[igrp]*dzo13[igrp]);
   amat[2][1] = 2.0*rmm21[igrp]*(dx13[igrp]*dxo12[igrp]
              + dy13[igrp]*dyo12[igrp]
              + dz13[igrp]*dzo12[igrp]);
   amat[2][2] = 2.0*rmm22[igrp]*(dx13[igrp]*dxo13[igrp]
              + dy13[igrp]*dyo13[igrp]
              + dz13[igrp]*dzo13[igrp]);


   rdet_a = 1.0/(amat[1][1]*amat[2][2] - amat[1][2]*amat[2][1]);
   ainv[1][1] =  amat[2][2]*rdet_a;
   ainv[1][2] = -amat[1][2]*rdet_a;
   ainv[2][1] = -amat[2][1]*rdet_a;
   ainv[2][2] =  amat[1][1]*rdet_a;

   xlam1[igrp] = ainv[1][1]*avec1[igrp] + ainv[1][2]*avec2[igrp];
   xlam2[igrp] = ainv[2][1]*avec1[igrp] + ainv[2][2]*avec2[igrp];

 }/*end for*/ 
 }else{
  for(igrp=1;igrp <= ngrp; igrp++) {
    xlam1[igrp] = grp_bond_con_al_23[1][(igrp+igrp_off)];
    xlam2[igrp] = grp_bond_con_al_23[2][(igrp+igrp_off)];
    grp_bond_con_al_23[1][(igrp+igrp_off)] = 0.0;
    grp_bond_con_al_23[2][(igrp+igrp_off)] = 0.0;
 }/* end for */
 }/*endif*/


/* Iterative do loop for multiplier */

 if(ngrp > 0){

  iter = 0;
  do {
   ++iter;
   if(iter > grp_bond_con->max_iter) {
    printf("$$$$$$$$$$$$$$$$$$$$_WARNING_$$$$$$$$$$$$$$$$$$$$\n");
    printf("Shake not converged after %d iterations.\n",
            grp_bond_con->max_iter);
    printf("The present tolerance is %g \n",dlmax);
    printf("The desired tolerance is %g \n",grp_bond_con->tol);
    printf("$$$$$$$$$$$$$$$$$$$$_WARNING_$$$$$$$$$$$$$$$$$$$$\n");
    fflush(stdout);
    break;
   }/*endif*/
/* Get elements of matrix */
 for(igrp=1;igrp <= ngrp; igrp++) {
 
  dxn12 = 2.0*dx12[igrp]
        + rmm11[igrp]*xlam1[igrp]*dxo12[igrp]
        + rmm12[igrp]*xlam2[igrp]*dxo13[igrp];
  dyn12 = 2.0*dy12[igrp]
        + rmm11[igrp]*xlam1[igrp]*dyo12[igrp]
        + rmm12[igrp]*xlam2[igrp]*dyo13[igrp];
  dzn12 = 2.0*dz12[igrp]
        + rmm11[igrp]*xlam1[igrp]*dzo12[igrp]
        + rmm12[igrp]*xlam2[igrp]*dzo13[igrp];
  dxn13 = 2.0*dx13[igrp]
        + rmm21[igrp]*xlam1[igrp]*dxo12[igrp]
        + rmm22[igrp]*xlam2[igrp]*dxo13[igrp];
  dyn13 = 2.0*dy13[igrp]
        + rmm21[igrp]*xlam1[igrp]*dyo12[igrp]
        + rmm22[igrp]*xlam2[igrp]*dyo13[igrp];
  dzn13 = 2.0*dz13[igrp]
        + rmm21[igrp]*xlam1[igrp]*dzo12[igrp]
        + rmm22[igrp]*xlam2[igrp]*dzo13[igrp];

   amat[1][1] = rmm11[igrp]*(dxn12*dxo12[igrp]
              + dyn12*dyo12[igrp]
              + dzn12*dzo12[igrp]);
   amat[1][2] = rmm12[igrp]*(dxn12*dxo13[igrp]
              + dyn12*dyo13[igrp]
              + dzn12*dzo13[igrp]);
   amat[2][1] = rmm21[igrp]*(dxn13*dxo12[igrp]
              + dyn13*dyo12[igrp]
              + dzn13*dzo12[igrp]);
   amat[2][2] = rmm22[igrp]*(dxn13*dxo13[igrp]
              + dyn13*dyo13[igrp]
              + dzn13*dzo13[igrp]);

  rdet_a = 1.0/(amat[1][1]*amat[2][2] - amat[1][2]*amat[2][1]);
  ainv[1][1] =  amat[2][2]*rdet_a;
  ainv[1][2] = -amat[1][2]*rdet_a;
  ainv[2][1] = -amat[2][1]*rdet_a;
  ainv[2][2] =  amat[1][1]*rdet_a;

  xl0[1] = xlam1[igrp];
  xl0[2] = xlam2[igrp];

  xlam1[igrp] = ainv[1][1]*avec1[igrp] + ainv[1][2]*avec2[igrp];
  xlam2[igrp] = ainv[2][1]*avec1[igrp] + ainv[2][2]*avec2[igrp];

  dxl1[igrp] = fabs(xlam1[igrp]-xl0[1]);
  dxl2[igrp] = fabs(xlam2[igrp]-xl0[2]);
 } /* end loop over groups */

/* test for convergence */
      dlmax1 = dxl1[1];
      dlmax2 = dxl2[1];

  for(igrp=2;igrp <= ngrp; igrp++) {
     dlmax1= (dlmax1 > dxl1[igrp] ? dlmax1 : dxl1[igrp]); 
     dlmax2= (dlmax2 > dxl2[igrp] ? dlmax2 : dxl1[igrp]); 
  }
   dlmax = (dlmax1 > dlmax2 ? dlmax1:dlmax2);

  } while(dlmax > grp_bond_con->tol);
  *aiter += (double) iter;

 }/*endif for ngrp > 0*/

/* position update */

#ifndef NO_PRAGMA
#pragma IVDEP
#endif
  for(igrp=1;igrp <= ngrp; igrp++) {
   double xlam_1,xlam_2;
   double rms1,rms2,rms3;
   double dxo120,dyo120,dzo120;
   double dxo130,dyo130,dzo130;
      ktemp1 = ind1[igrp];
      ktemp2 = ind2[igrp];
      ktemp3 = ind3[igrp];

    xlam_1 = xlam1[igrp]; xlam_2 = xlam2[igrp];
    

    rms1= rm1[igrp];
    rms2= rm2[igrp];
    rms3= rm3[igrp];

    dxo120 = (xo[1][igrp]-xo[2][igrp]);
    dyo120 = (yo[1][igrp]-yo[2][igrp]);
    dzo120 = (zo[1][igrp]-zo[2][igrp]);

    dxo130 = (xo[1][igrp]-xo[3][igrp]);
    dyo130 = (yo[1][igrp]-yo[3][igrp]);
    dzo130 = (zo[1][igrp]-zo[3][igrp]);



  clatoms_x[ktemp1] -= (xlam_1*dxo120 + xlam_2*dxo130)*rms1 *baro_roll_scv;
  clatoms_y[ktemp1] -= (xlam_1*dyo120 + xlam_2*dyo130)*rms1 *baro_roll_scv;
  clatoms_z[ktemp1] -= (xlam_1*dzo120 + xlam_2*dzo130)*rms1 *baro_roll_scv;

  clatoms_x[ktemp2] += xlam_1*dxo120*rms2*baro_roll_scv;
  clatoms_y[ktemp2] += xlam_1*dyo120*rms2*baro_roll_scv;
  clatoms_z[ktemp2] += xlam_1*dzo120*rms2*baro_roll_scv;

  clatoms_x[ktemp3] += xlam_2*dxo130*rms3*baro_roll_scv;
  clatoms_y[ktemp3] += xlam_2*dyo130*rms3*baro_roll_scv;
  clatoms_z[ktemp3] += xlam_2*dzo130*rms3*baro_roll_scv;

 
/* Velocity update */

  clatoms_vx[ktemp1] -= (xlam_1*dxo120 + xlam_2*dxo130)*rms1/dt;
  clatoms_vy[ktemp1] -= (xlam_1*dyo120 + xlam_2*dyo130)*rms1/dt;
  clatoms_vz[ktemp1] -= (xlam_1*dzo120 + xlam_2*dzo130)*rms1/dt;

  clatoms_vx[ktemp2] += xlam_1*dxo120*rms2/dt;
  clatoms_vy[ktemp2] += xlam_1*dyo120*rms2/dt;
  clatoms_vz[ktemp2] += xlam_1*dzo120*rms2/dt;

  clatoms_vx[ktemp3] += xlam_2*dxo130*rms3/dt;
  clatoms_vy[ktemp3] += xlam_2*dyo130*rms3/dt;
  clatoms_vz[ktemp3] += xlam_2*dzo130*rms3/dt;



/* Pressure tensor update */
/* Compute difference vectors: unscaled old distances !!!*/

    p11[igrp] = xlam_1*dxo120*dxo120 + xlam_2*dxo130*dxo130;
    p22[igrp] = xlam_1*dyo120*dyo120 + xlam_2*dyo130*dyo130;
    p33[igrp] = xlam_1*dzo120*dzo120 + xlam_2*dzo130*dzo130;
    p12[igrp] = xlam_1*dxo120*dyo120 + xlam_2*dxo130*dyo130;
    p13[igrp] = xlam_1*dxo120*dzo120 + xlam_2*dxo130*dzo130;
    p23[igrp] = xlam_1*dyo120*dzo120 + xlam_2*dyo130*dzo130;
}/*end for*/

#ifndef NO_PRAGMA
#pragma IVDEP
#endif
  for(igrp=1;igrp <= ngrp; igrp++) {
    ptens_pvten_tmp[1] -= (p11[igrp]*pnorm); 
    ptens_pvten_tmp[2] -= (p12[igrp]*pnorm);
    ptens_pvten_tmp[3] -= (p13[igrp]*pnorm);
    ptens_pvten_tmp[4] -= (p12[igrp]*pnorm);
    ptens_pvten_tmp[5] -= (p22[igrp]*pnorm);
    ptens_pvten_tmp[6] -= (p23[igrp]*pnorm);
    ptens_pvten_tmp[7] -= (p13[igrp]*pnorm);
    ptens_pvten_tmp[8] -= (p23[igrp]*pnorm);
    ptens_pvten_tmp[9] -= (p33[igrp]*pnorm);
 }/*end for*/

/* Save multiplier */
  for(igrp=1;igrp <= ngrp; igrp++) {
    grp_bond_con_al_23[1][(igrp+igrp_off)] += xlam1[igrp];
    grp_bond_con_al_23[2][(igrp+igrp_off)] += xlam2[igrp];
 } /* end for igrp */

 
/*=======================================================================*/
/*  IV)Allreduce pvten_tmp     */

  if(np_forc > 1 ){
   for(i=1;i<=9;i++){
    ptens_pvten_tmp2[i] = ptens_pvten_tmp[i];
   }/*endfor*/
   Allreduce(&(ptens_pvten_tmp2[1]), &(ptens_pvten_tmp[1]),9,MPI_DOUBLE,
                   MPI_SUM,0,comm_forc);
  }/*endif*/

  ptens_pvten_inc[1] += ptens_pvten_tmp[1];
  ptens_pvten_inc[2] += ptens_pvten_tmp[2];
  ptens_pvten_inc[3] += ptens_pvten_tmp[3];
  ptens_pvten_inc[4] += ptens_pvten_tmp[4];
  ptens_pvten_inc[5] += ptens_pvten_tmp[5];
  ptens_pvten_inc[6] += ptens_pvten_tmp[6];
  ptens_pvten_inc[7] += ptens_pvten_tmp[7];
  ptens_pvten_inc[8] += ptens_pvten_tmp[8];
  ptens_pvten_inc[9] += ptens_pvten_tmp[9];


 if(ifirst == 0){
  ftemp   = (ptens_pvten_tmp[1]+ptens_pvten_tmp[5]+ptens_pvten_tmp[9]);
  baro->f_lnv_p += ftemp;
  baro->v_lnv   += 0.5*ftemp*(baro->roll_scg)*dt/(baro->mass_lnv);
 }

/* free locally assigned memory */
 if(ngrp > 0){
     free_dvector(xlam1,1,ngrp);
     free_dvector(xlam2,1,ngrp);

     free_dvector(avec1,1,ngrp);
     free_dvector(avec2,1,ngrp);

     free_dvector(rm1,1,ngrp);
     free_dvector(rm2,1,ngrp);
     free_dvector(rm3,1,ngrp);

     free_dvector(rmm11,1,ngrp);
     free_dvector(rmm12,1,ngrp);
     free_dvector(rmm21,1,ngrp);
     free_dvector(rmm22,1,ngrp);

     free_dvector(dxl1,1,ngrp);
     free_dvector(dxl2,1,ngrp);

     free_dvector(dx12,1,ngrp);
     free_dvector(dy12,1,ngrp);
     free_dvector(dz12,1,ngrp);

     free_dvector(dx13,1,ngrp);
     free_dvector(dy13,1,ngrp);
     free_dvector(dz13,1,ngrp);

     free_dvector(dxo12,1,ngrp);
     free_dvector(dyo12,1,ngrp);
     free_dvector(dzo12,1,ngrp);

     free_dvector(dxo13,1,ngrp);
     free_dvector(dyo13,1,ngrp);
     free_dvector(dzo13,1,ngrp);

    free_dvector(dij1,1,ngrp);
    free_dvector(dij2,1,ngrp);

    free_dmatrix(x,1,3,1,ngrp);
    free_dmatrix(y,1,3,1,ngrp);
    free_dmatrix(z,1,3,1,ngrp);

    free_dmatrix(xo,1,3,1,ngrp);
    free_dmatrix(yo,1,3,1,ngrp);
    free_dmatrix(zo,1,3,1,ngrp);

    free_dvector(p11,1,ngrp);
    free_dvector(p12,1,ngrp);
    free_dvector(p13,1,ngrp);
    free_dvector(p22,1,ngrp);
    free_dvector(p23,1,ngrp);
    free_dvector(p33,1,ngrp);

    cfree(&(ind1[1]));
    cfree(&(ind2[1]));
    cfree(&(ind3[1]));
 }/*endif*/

/*=======================================================================*/
} /* end routine */
Beispiel #21
0
/*
  Compute cxx on atm to compare against L2, invpsd, fractal.
*/
static void test_cxx(){
    rand_t rstat;
    int seed=4;
    double r0=0.2;
    double dx=1./4;
    long N=16;
    long nx=N;
    long ny=N;
    long nframe=40960;
    seed_rand(&rstat, seed);
    {
	dmat *cxx=dnew(N*N,N*N);
	map_t *atm=mapnew(nx+1, ny+1, dx, dx,NULL);
	for(long i=0; i<nframe; i++){
	    info("%ld of %ld\n", i, nframe);
	    for(long j=0; j<(nx+1)*(ny+1); j++){
		atm->p[j]=randn(&rstat);
	    }
	    fractal_do((dmat*)atm, dx, r0, L0, ninit);
	    dmat *sec=dsub((dmat*)atm, 0, nx, 0, ny);
	    dmat *atmvec=dref_reshape(sec, nx*ny, 1);
	    dmm(&cxx,1, atmvec,atmvec,"nt",1);
	    dfree(atmvec);
	    dfree(sec);
	}
	dscale(cxx, 1./nframe);
	writebin(cxx, "cxx_fractal");
	dfree(cxx);
	mapfree(atm);
    }
    {
	dmat *cxx=dnew(N*N,N*N);
	dmat *spect=turbpsd(nx, ny, dx, r0, 100, 0, 0.5);
	spect->p[0]=spect->p[1];
	cmat *atm=cnew(nx, ny);
	//cfft2plan(atm, -1);
	dmat *atmr=dnew(nx*ny,1);
	dmat *atmi=dnew(nx*ny,1);
	for(long ii=0; ii<nframe; ii+=2){
	    info("%ld of %ld\n", ii, nframe);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atm->p[i]=COMPLEX(randn(&rstat), randn(&rstat))*spect->p[i];
	    }
	    cfft2(atm, -1);
	    for(long i=0; i<atm->nx*atm->ny; i++){
		atmr->p[i]=creal(atm->p[i]);
		atmi->p[i]=cimag(atm->p[i]);
	    }
	    dmm(&cxx,1, atmr,atmr,"nt",1);
	    dmm(&cxx,1, atmi,atmi,"nt",1);
	}
	dscale(cxx, 1./nframe);
	writebin(cxx, "cxx_fft");
	dfree(cxx);
	dfree(atmr);
	dfree(atmi);
	cfree(atm);
    }
    loc_t *loc=mksqloc_auto(16,16,1./4,1./4);
    locwrite(loc,"loc");
    dmat *B=stfun_kolmogorov(loc, r0);
    writebin(B, "B_theory");
}
Beispiel #22
0
/* <dirdata_ren>:
 * Rename a file.  Because entries in 'filelist' will point to the original
 * block, we do not simply allocate a new block, but re-use the old one.
 * This requires that we re-link the list.
 */
void	dirdata_ren (FILENT *znew, FILENT *zold)
{
	FLINK	*pnew = 0,
		*pold = 0;
	int	found = dirdata_find (znew, &pnew);

	if (!memcmp(znew, zold, sizeof(FILENT)))
		return;		/* don't waste my time !! */

	/*
	 * If the "new" name is in the list already, then this is probably
	 * (if no bug!) because the caller marked the file deleted.  To safely
	 * dispose of this, we must move it also in the list by making its
	 * version number non-conflicting with other entries.
	 */
	if (found > 0)
	{
	FLINK	*old,
		*now	= pnew->file_next;

	    /*
	     * De-link the "new" entry from the list, saving pointer-before.
	     */
	    if (pnew == filelink)
	    	old = filelink = pnew->file_next;
	    else
	    {
		for (old = filelink; old->file_next != pnew; old = old->file_next);
		old->file_next = pnew->file_next;
	    }

	    /*
	     * If the block is referenced by more than the current level, find
	     * a new insertion point (with a negative version code to make it
	     * transparent to other data).
	     */
	    if (pnew->file_refs != nameheap_ref())
	    {
	    FILENT	*z	= &(pnew->fk);
	    int		tvers	= -1;

		now = old->file_next;	/* => after de-linked "new" data */
		while (now)
		{
		    if (!(SAMEP(fpath_) && SAMEP(fname) && SAMEP(ftype)))
			break;
		    if (tvers >= now->fk.fvers) tvers = now->fk.fvers - 1;
		    old = now;
		    now = now->file_next;
		}
		pnew->fk.fvers = tvers;
		if (old == filelink)
		{
		    pnew->file_next = filelink;
		    filelink = pnew;
		}
		else
		{
		    pnew->file_next = old->file_next;
		    old->file_next  = pnew;
		}
	    }
	    else	/* simply de-allocate the entry	*/
		cfree (pnew);
	}

	/*
	 * Now, we know that the "new" name does not appear in the list.  We
	 * can re-link the entry in which we have the "old" filename stored
	 * (if it is in the list).
	 *
	 * From the code above, we now have no instance of 'znew' in the list.
	 */
	if ((found = dirdata_find (zold, &pold)) > 0)
	{
	FLINK	*now = filelink;

	    if (now == pold)	/* de-link at beginning */
		filelink = now->file_next;
	    else
	    {
		while (now->file_next != pold)
		    now = now->file_next;
		now->file_next = pold->file_next;
	    }
	    pold->fk = *znew;
	    pnew = nullS(FLINK);
	    if ((found = dirdata_find (znew, &pnew)) < 0)
	    {
		pold->file_next = filelink;
		filelink = pold;
	    }
	    else
	    {
		pold->file_next = pnew->file_next;
		pnew->file_next = pold;
	    }
	    pold->fk = *znew;
	}
	else
	{
	    pold = 0;
	    dirdata_one (znew, &pold);
	}

	/*
	 * Ensure that any strings and pathnames to which we refer have at least
	 * the same scope as the object which we have just renamed:
	 */
	dirpath_add  (pold->file_refs, pold->fk.fpath_);
	nameheap_add (pold->file_refs, pold->fk.fname);
	nameheap_add (pold->file_refs, pold->fk.ftype);
}
Beispiel #23
0
static int test_random(size_t maxsize, int n)
{
	uint32_t *r;
	int i, numrand = 1000, loops=7;
	void **p;

	srandom(0);
	r = calloc(sizeof(uint32_t), numrand);
	for (i=0;i<numrand;i++) {
		r[i] = random() % maxsize;
	}

	p = calloc(sizeof(void*), n);

	for (i=0;i<n;i++) {
		p[i] = malloc(r[i%numrand]);
		assert(p[i] != NULL);
	}
	
	while (loops--) {
		for (i=0;i<n;i++) {
			switch (r[(loops*i)%numrand]%5) {
			case 0:
				free(p[i]);
				p[i] = NULL;
				break;
			case 1:
				p[i] = realloc(p[i], r[(i*3)%numrand]);
				assert(p[i] != NULL || r[(i*3)%numrand] == 0);
				break;
			case 2:
				free(p[i]);
				p[i] = malloc(r[(i*5)%numrand]);
				assert(p[i] != NULL);
				break;
			case 3:
				cfree(p[i]);
				p[i] = calloc(i%4, r[(i*5)%numrand]);
				assert(p[i] != NULL);
				break;
			case 4:
				free(p[i]);
				if (random() % 100 == 0) {
					int boundary = (1<<r[(i*7)%numrand]%3)*4096;
					int ret = posix_memalign(&p[i], 
								 boundary,
								 r[(i*7)%numrand]);
					assert(ret==0);
				} else {
					p[i] = memalign((1<<(i%5)), r[(i*7)%numrand]);
				}
				assert(p[i] != NULL);
				break;
			}
		}
	}
	for (i=0;i<n;i++) {
		if (p[i] != NULL) free(p[i]);
	}

	return 0;	
}
void cp_transpose_bck_prim_dvr(double *c,int *icoef_form,double *c_temp,
                               int nstate,int nstate_max,int ncoef,
                               int nstate_proc,int nstate_proc_max,
                               int nstate_proc_min,
                               int nstate_ncoef_proc_max,
                               int nstate_ncoef_proc,
                               int nkf1,int nkf2,int nkf3,
                               int num_proc,int myid,MPI_Comm comm)

/*======================================================================*/
/*                Begin Routine */
{   /*begin routine */

/*======================================================================*/
/*               Local variable declarations                            */

#include "../typ_defs/typ_mask.h"

  int nfull,i,j;
  int idv,irm;
  int irems,iremc,irem,ig,is,ioff;
  int ioff_c,iproc,iii;
  int sendcounts,recvcounts;
  int icount;
  int *ioffv,*inum;

/*========================================================================*/
/*              Incoming variable declarations                            */
/*                                                                        */
/* nstate            = Total number of states                             */
/* nstate_proc       = number of states on this processor                 */
/* nstate_proc_max   = maximum number of states on any processor          */
/* ncoef             = Total number of coefficients in a state            */
/* nstate_ncoef_proc = Number of coefficients in a state on this processor*/
/*                     in the transposed data                             */
/* nstate_ncoef_proc_max = Maximum number of coefficients in a state on   */
/*                          any processesor in the transposed data        */
/* nstate_max        = nstate_proc_max*num_proc                           */
/* c                 = nstate_proc x ncoef array of coefficients          */
/* c_temp            = transposed data stored as nstate x ncoef_proc_max  */
/* ct_temp           = scratch space to help make transposed data         */
/* nscr_size         = size of scratch nstate_ncoef_proc_max*nstate_max   */
/*========================================================================*/
/* 0) Check the forms */

  if((*icoef_form) !=1){
    printf("@@@@@@@@@@@@@@@@@@@@_ERROR_@@@@@@@@@@@@@@@@@@@@\n");
    printf("The coefficients must be in transposed form\n");
    printf("on state processor %d in cp_transpose_bck_prim \n",myid);
    printf("@@@@@@@@@@@@@@@@@@@@_ERROR_@@@@@@@@@@@@@@@@@@@@\n");
    fflush(stdout);exit(1);
  }/*endif*/

  *icoef_form = 0;

/*========================================================================*/
/*========================================================================*/
/* I) Internal rearrangement of coeff data                                */

  irems = (nstate % num_proc);
  iremc = ((nkf2*nkf3)% num_proc);
  irem  = MAX(irems,iremc);

  ioffv = (int *) cmalloc(num_proc*sizeof(int))-1;
  inum  = (int *) cmalloc(num_proc*sizeof(int))-1;

  if((irems != 0)||(iremc != 0)){

    ioffv[1] = 0;
    for(i=1; i<= irems; i++){
      ioffv[i+1] = ioffv[i] + nstate_proc_max*nstate_ncoef_proc;
      inum[i]    = nstate_proc_max*nstate_ncoef_proc;
    }
    for(i=irems+1; i < num_proc; i++){
      ioffv[i+1] = ioffv[i] + nstate_proc_min*nstate_ncoef_proc;
      inum[i]    = nstate_proc_min*nstate_ncoef_proc;
    }
    inum[num_proc] = nstate_proc_min*nstate_ncoef_proc;

/* 1) copy data into temp array */

    for(i=1;i <= (num_proc*nstate_proc_max*nstate_ncoef_proc_max);i++){ 
      c_temp[i] = 0.00;
    }

    for(i=1; i<= num_proc; i++){
      ioff = (i-1)*nstate_proc_max*nstate_ncoef_proc_max;
      for(j=1; j <= inum[i]; j++){
        c_temp[(ioff+j)] = c[(ioffv[i]+j)];
      }
    }

/* 2) copy back into c     */

    nfull = nstate_ncoef_proc_max*nstate_max;
    for(ig=1;ig<=nfull;ig++){c[ig] = c_temp[ig];}

  }/*endif: remainder */

/*======================================================================*/
/* II) Send the transformed position data                               */

  sendcounts = nstate_ncoef_proc_max*nstate_proc_max;
  recvcounts = nstate_ncoef_proc_max*nstate_proc_max;

  Alltoall(&c[1],sendcounts,MPI_DOUBLE,&c_temp[1],recvcounts,
                MPI_DOUBLE,comm);

/*=======================================================================*/
/* III) Extract the transformed position data                            */

  idv   = (nkf2*nkf3)/num_proc;
  irm   = (nkf2*nkf3)%num_proc;

  for(i = 0; i < num_proc; i++){
    inum[i+1] = ( i < irm ? (idv+1)*nkf1 : idv*nkf1);
  }

  for(i=1;i<=nstate_ncoef_proc_max*nstate_max;i++){c[i]=0.0;}

  for(is=1; is <= nstate_proc; is++){
    icount = 0;
    ioff_c = (is-1)*ncoef;
    for(iproc=1;iproc<=num_proc;iproc++){
      ioff = (is-1)*inum[iproc]
           + (iproc-1)*nstate_proc_max*nstate_ncoef_proc_max;
      for(i=1;i<= inum[iproc];i++){
        icount++;
        c[ioff_c+icount] = c_temp[ioff+i];
      }/*endfor*/
    }/*endfor*/
  }

  cfree(&ioffv[1]);
  cfree(&inum[1]);

/*========================================================================*/
}/*end routine*/
  void build_communicate_groups(COMMUNICATE *communicate,int cp_on)

/*==========================================================================*/
/*             Begin routine                                                */
    {/*begin routine */
/*==========================================================================*/
#include "../typ_defs/typ_mask.h"

   int myid           = communicate->myid;
   int np_states      = communicate->np_states;
   int np_beads       = communicate->np_beads;
   int np             = communicate->np;
   int np_forc        = communicate->np_forc;
   int np_forc_src = communicate->np_forc_src;
   int np_forc_trg = communicate->np_forc_trg;

   int i,ii,loop,iii,ntemp,idiv,irem,icase,numcomm_bead;
   int *ranks;

   MPI_Comm world;
   MPI_Comm comm_forc;
   MPI_Group excl_group,temp;

/*=======================================================================*/
/* 0) Mallocs and Dups                                                   */

   numcomm_bead = np/np_beads;           /* number of bead communicators */
   if(numcomm_bead==0){numcomm_bead=1;}

   ranks = (int *) cmalloc(MAXPROCS*sizeof(int));

   Comm_dup(communicate->world,&(world));
   Barrier(world);

/*=======================================================================*/
/* I) Get path_integral or Bead level communicators                      */
/*     Bead communciators are OUTER communicators                        */
/*     Split world into forc  and bead pieces if cp is off               */
/*     Split world into state and bead pieces if cp is on                */
/*     Comm_beads_forc is a copy of Comm_beads                           */

   if(cp_on==1){icase=1;}
   if(cp_on==0){icase=2;}

   switch(icase){

     case 1:
        communicate->comm_beads = 
             build_grp_comm_outer(np,np_beads,np_states,myid,
                                &(communicate->myid_bead),ranks,world);
     break;

     case 2:
        communicate->comm_beads = 
             build_grp_comm_outer(np,np_beads,np_forc,myid,
                                &(communicate->myid_bead),ranks,world);
     break;

   }/*switch*/

   Comm_dup(communicate->comm_beads,&(communicate->comm_beads_forc));
   communicate->myid_bead_forc = communicate->myid_bead;

/*=======================================================================*/
/* II) Get state and force level communicators                           */
/*     State and Force comms are INNER communicators                     */
/*     CP is off : np = np_forc*np_bead                                  */

  if((cp_on==1)&&(np_forc==1))        {icase=1;}
  if((cp_on==1)&&(np_forc==np_states)){icase=2;}
  if((cp_on==0))                      {icase=3;}

  switch(icase){

  /*======================================================================*/
  /* CP IS ON : Np_forc = 1 */

   case 1:
 
     /*------------------------------------------------------*/
     /* i) The force level communicator is only proc 0       */

      ranks[0] = myid;
      Comm_group(world,&excl_group);
      Group_incl(excl_group,np_forc,ranks,&temp);
      Comm_create(world,temp,&communicate->comm_forc);
      Comm_dup(communicate->comm_forc,&(communicate->comm_forc_source));
      Comm_dup(communicate->comm_forc,&(communicate->comm_forc_target));
      communicate->myid_forc        = 0;
      communicate->myid_forc_source = 0;
      communicate->myid_forc_target = 0;
      Group_free(&excl_group);

     /*------------------------------------------------------*/
     /* ii) The state level communicator is an INNER         */
      communicate->comm_states =
           build_grp_comm_inner(np,np_beads,np_states,myid,
                              &(communicate->myid_state),ranks,world);

     /*------------------------------------------------*/
     /* iii) The myid_bead_prime and myid_bead store   */
     /*      the id of this proc in the comm_bead, if  */
     /*      it is the FIRST bead level communicator.  */
     /*      In subsequent comm_beads,myid_bead is out */
     /*      of range and myid_bead_prime=myid_state.  */
     /*      myid_bead_forc ALWAYS has carries         */
     /*      the rank of this proc in the bead comm    */
     /*      to which it is associated                 */

      communicate->myid_bead_prime = communicate->myid_bead;
      if(communicate->myid_state!=0){
        communicate->myid_bead       = communicate->np_beads;
      }/*endif*/

     break;

  /*======================================================================*/
   case 2:

     /*------------------------------------------------------*/
     /* i) The state level communicator is an INNER          */

      communicate->comm_states =
           build_grp_comm_inner(np,np_beads,np_states,myid,
                              &(communicate->myid_state),ranks,world);

  
     /*------------------------------------------------------*/
     /* ii) The forc level communicator is an INNER = state  */

       communicate->myid_forc = communicate->myid_state;
       Comm_dup(communicate->comm_states,&(communicate->comm_forc));
       Comm_dup(communicate->comm_states,&(comm_forc));

     /*------------------------------------------------*/
     /* iii) Split the force level communicator        */
     /*     Targets are OUTER and Sources are INNER    */

      communicate->comm_forc_target =
          build_grp_comm_outer(np_forc,np_forc_trg,np_forc_src,
                   communicate->myid_forc,&(communicate->myid_forc_target),
                   ranks,comm_forc);
      communicate->comm_forc_source =
          build_grp_comm_inner(np_forc,np_forc_trg,np_forc_src,
                   communicate->myid_forc,&(communicate->myid_forc_source),
                   ranks,comm_forc);
  
     /*------------------------------------------------*/
     /* iii) The myid_bead_prime and myid_bead store   */
     /*      the id of this proc in the comm_bead, if  */
     /*      it is the FIRST bead level communicator.  */
     /*      In subsequent comm_beads,myid_bead is out */
     /*      of range and myid_bead_prime=myid_state.  */
     /*      myid_bead_forc ALWAYS has carries         */
     /*      the rank of this proc in the bead comm    */
     /*      to which it is associated                 */

      communicate->myid_bead_prime = communicate->myid_bead;
      if(communicate->myid_state!=0){
        communicate->myid_bead       = communicate->np_beads;
      }/*endif*/

     break;

  /*======================================================================*/
   case 3: /* CP is off : force level only */

     /*------------------------------------------------*/
     /* i) The state communicator is only proc 0       */

      ranks[0] = myid;
      Comm_group(world,&excl_group);
      Group_incl(excl_group,np_states,ranks,&temp);
      Comm_create(world,temp,&communicate->comm_states);
      communicate->myid_state = 0;
      Group_free(&excl_group);

     /*------------------------------------------------*/
     /* ii) The force level communicator is an INNER   */

      communicate->comm_forc =
           build_grp_comm_inner(np,np_beads,np_forc,myid,
                              &(communicate->myid_forc),ranks,world);
      Comm_dup(communicate->comm_forc,&(comm_forc));

     /*------------------------------------------------*/
     /* iii) Split the force level communicator        */
     /*     Targets are OUTER and Sources are INNER    */

      communicate->comm_forc_target =
          build_grp_comm_outer(np_forc,np_forc_trg,np_forc_src,
                   communicate->myid_forc,&(communicate->myid_forc_target),
                   ranks,comm_forc);
      communicate->comm_forc_source =
          build_grp_comm_inner(np_forc,np_forc_trg,np_forc_src,
                   communicate->myid_forc,&(communicate->myid_forc_source),
                   ranks,comm_forc);

     /*------------------------------------------------*/
     /* iv) The myid_bead_prime and myid_bead store    */
     /*      the id of this proc in the comm_bead, if  */
     /*      it is the FIRST bead level communicator.  */
     /*      In subsequent comm_beads,myid_bead is out */
     /*      of range and myid_bead_prime=myid_forc.   */
     /*      myid_bead_forc ALWAYS has carries         */
     /*      the rank of this proc in the bead comm    */
     /*      to which it is associated                 */

      communicate->myid_bead_prime = communicate->myid_bead;
      if(communicate->myid_forc!=0){
        communicate->myid_bead       = communicate->np_beads;
      }/*endif*/

   break;

 }/*end switch*/

/*------------------------------------------------------------------------*/
/*  Free the memory                                                       */

      cfree(&ranks[0]);

/*------------------------------------------------------------------------*/
   } /*end routine*/ 
int main(int argc, char *argv[])
{    
    /* definitions */
    int nocells;           /* number of cells */
    int nonets;            /* number of nets */
    int nopins;            /* number of pins */
    int noparts;           /* number of partitions */
    int totsize;           /* total net weight of the partition */
    int totcellsize;       /* total cell weight of the partition */
    int cutsize;           /* cutsize of the partition */
    int max_gain;          /* max gain of a cell */
    int max_density;       /* max density of a cell */
    int max_cweight;       /* max cell weight */
    int max_nweight;       /* max net weight */
    int bucketsize;        /* max size of a bucket array */
    int msize;             /* index to mcells */

    if (argc < 5) {
        printf("\nUsage: %s InputFileName NoParts InCount OutCount [Seed]\n", argv[0]);
	printf("\t#cells moved per phase = incount * nocells / 4\n");
	printf("\t\tUse 1, 2, 3, or 4 for incount.\n");
	printf("\t#cells moved per pass = nocells if outcount = 1,\n");
	printf("\t#cells moved per pass = nocells * noparts if outcount = 2, and\n");
	printf("\t#cells moved per pass = nocells * noparts * noparts if outcount = 3.\n");
        exit(1);
    }  /* if */

    char fname[STR_SIZE];
    sprintf(fname, "%s", argv[1]);

    noparts = atoi(argv[2]);

    int incount = atoi(argv[3]);
    int outcount = atoi(argv[4]);

    long seed;
    if (argc > 5) {
        seed = (long) atoi(argv[5]);
    } else {
        seed = (long) -1;
    }
    seed = randomize((long)  seed);
    printf("SEED = %ld fname = %s\n", seed, fname);

    read_graph_size(fname, &nocells, &nonets);
    nopins = 2 * nonets;

    /* determine what in- & out-count imply */
    int max_moved_cells = incount * nocells / 4;
    switch (outcount) {
    case 1 : outcount = nocells; break;
    case 2 : outcount = nocells * noparts; break;
    case 3 : outcount = nocells * noparts * noparts; break;
    default : break;
    }
    /* max_noiter = outcount / max_moved_cells;*/ /* do that many iterations */
    int max_noiter = outcount;

    /* alloc memory for all data structures */
    cells_t *cells = (cells_t *) calloc(nocells, sizeof(cells_t));
    assert(cells != NULL);
    cells_info_t *cells_info = (cells_info_t *) calloc(nocells, sizeof(cells_info_t));
    assert(cells_info != NULL);
    for (int i = 0; i < nocells; i++) {
        cells_info[i].mgain = (int *) calloc(noparts, sizeof(int));
        cells_info[i].partb_ptr = (bnode_ptr_t *) calloc(noparts - 1, sizeof(bnode_ptr_t));
        cells_info[i].partb_gain_inx = (int *) calloc(noparts - 1, sizeof(int));
    }

    nets_t *nets = (nets_t *) calloc(nonets, sizeof(nets_t));
    assert(nets != NULL);

    /* cells of nets */
    corn_t *cnets = (corn_t *) calloc(nopins, sizeof(corn_t));
    assert(cnets != NULL);

    /* partition buckets */
    partb_t partb[noparts][noparts - 1];  
    parts_info_t parts_info[noparts]; 

    /* population (w/ one individual!) */
    ind_t pop[MAX_POP];             
    for (int i = 0; i < MAX_POP; i++) {
        pop[i].chrom = (allele *) calloc(nocells, sizeof(allele));
        pop[i].parts = (parts_t *) calloc(noparts, sizeof(parts_t));
    }

    /* selected cell */
    selected_cell_t scell[1];     

    /* moved cells */
    mcells_t *mcells = (mcells_t *) calloc(2 * max_noiter, sizeof(mcells_t));
    assert(mcells != NULL);

    /* temp chrom */
    allele *tchrom = (allele *) calloc(nocells, sizeof(allele));
    assert(tchrom != NULL);
  
    read_graph(fname, nocells, nonets, noparts, &totsize, &totcellsize,
               &max_density, &max_cweight, &max_nweight,
               cells, nets, cnets);

    max_gain = max_density * max_nweight;
    bucketsize = 2 * max_gain + 1;

    /* alloc memory (statically if possible) */
    for (int i = 0; i < noparts; i++) {
        for (int j = 0; j < noparts - 1; ++j) {
            partb[i][j].bnode_ptr = (bnode_ptr_t *) calloc(bucketsize, sizeof(bnode_ptr_t));
        }
    }

    create_partition(nocells, noparts, totcellsize, 
                     cells, &pop[0]);

#ifdef DEBUG
    printf("Initial : Part_no min_size curr_size max_size\n");
    for (int i = 0; i < noparts; i++) {
        printf("II %d %d %d %d\n", i, pop[0].parts[i].pmin_size,
               pop[0].parts[i].pcurr_size, pop[0].parts[i].pmax_size);
    }
#endif

    init_buckets(noparts, bucketsize, partb);
    cutsize = find_cut_size(nonets, totsize, nets, &pop[0]);

#ifdef DEBUG
    printf("Totalsize = %d Initial cutsize = %d\n", totsize, cutsize);
#endif

    int gain_sum;
    int glob_inx = 0;
    int pass_no = 0;
    do {

        copy_partition(noparts, parts_info, &pop[0]);

        for (int i = 0; i < nocells; i++) {
            tchrom[i] = pop[0].chrom[i];
        }

        msize = 0;

        int noiter = 0;
        while (noiter < max_noiter) {

            compute_gains(nocells, noparts, tchrom, 
                          cells, nets, cnets, cells_info);

            create_buckets(nocells, noparts, max_gain, tchrom, partb, cells_info);

            /* max_moved_cells = nocells / 2; */
            int nlocked = 0;
            do {

                int move_possible = select_cell(noparts, scell, parts_info, cells, 
                                                partb, cells_info);

                delete_partb_nodes_of_cell(noparts, scell[0].mov_cell_no, 
                                           scell[0].from_part, partb, cells_info);

                /* lock cell */
                cells_info[scell[0].mov_cell_no].locked = True;
                if (move_possible == True) {
                    move_cell(mcells, msize, scell, tchrom);  
                    msize++;
                    update_gains(noparts, max_gain, scell, tchrom,
                                 cells, nets, cnets,
                                 partb, cells_info);
                }   /* if */
                nlocked++;

                noiter++;
            } while ((nlocked < max_moved_cells) && (noiter < max_noiter)); 

            free_nodes(noparts, bucketsize, partb);

        }   /* while */

        int max_mcells_inx;
        gain_sum = find_move_set(mcells, msize, &max_mcells_inx);

#ifdef DEBUG
        printf("gain_sum=%d max_mcells_inx=%d msize = %d\n",
               gain_sum, max_mcells_inx, msize);
#endif
        if (gain_sum > 0) {
            int cut_gain = move_cells(False, mcells, max_mcells_inx, cutsize, &glob_inx, 
                                      &pop[0], cells);
            cutsize -= cut_gain;
        }   /* if */
        pass_no++;

#ifdef DEBUG
        printf("pass_no = %d Final cutsize = %d Check cutsize = %d\n", pass_no,
               cutsize, find_cut_size(nonets, totsize, nets, &pop[0]));
#endif

    } while ((gain_sum > 0) && (cutsize > 0));

    printf("pass_no = %d Final cutsize = %d Check cutsize = %d\n", pass_no,
           cutsize, find_cut_size(nonets, totsize, nets, &pop[0]));

    free_nodes(noparts, bucketsize, partb);

#ifdef DEBUG
    printf("Final : Part_no min_size curr_size max_size\n");
    for (int i = 0; i < noparts; i++) {
        printf("FF %d %d %d %d\n", i, pop[0].parts[i].pmin_size,
               pop[0].parts[i].pcurr_size, pop[0].parts[i].pmax_size);
    }
#endif

    /* free memory for all data structures */
    cfree(cells);
    for (int i = 0; i < nocells; i++) {
        cfree(cells_info[i].mgain);
        cfree(cells_info[i].partb_ptr);
        cfree(cells_info[i].partb_gain_inx);
    }
    cfree(cells_info);

    cfree(nets);

    cfree(cnets);

    for (int i = 0; i < noparts; i++) {
        for (int j = 0; j < noparts - 1; ++j) {
            cfree(partb[i][j].bnode_ptr);
        }
    }

    for (int i = 0; i < MAX_POP; i++) {
        cfree(pop[i].chrom);
        cfree(pop[i].parts);
    }

    cfree(mcells);

    cfree(tchrom);

    return (0);
}   /* main-plm */
Beispiel #27
0
/*
 * Free the dynamically-allocated strings in a `struct printer'.
 * Idempotent.
 */
void
free_printer(struct printer *pp)
{
	enum lpd_filters filt;
#define	cfree(x)	do { if (x) free(x); } while(0)
	cfree(pp->printer);
	cfree(pp->acct_file);
	for (filt = 0; filt < LPF_COUNT; filt++)
		cfree(pp->filters[filt]);
	cfree(pp->form_feed);
	cfree(pp->log_file);
	cfree(pp->lock_file);
	cfree(pp->lp);
	cfree(pp->restrict_grp);
	cfree(pp->remote_host);
	cfree(pp->remote_queue);
	cfree(pp->spool_dir);
	cfree(pp->stat_recv);
	cfree(pp->stat_send);
	cfree(pp->status_file);
	cfree(pp->trailer);
	cfree(pp->mode_set);

	init_printer(pp);
}
Beispiel #28
0
dclgen()
{
register ptr p, q;
ptr q1;
chainp *y, z;
register struct stentry *s;
struct stentry **hp;
int first;
int i, j;
extern char *types[];
char *sp;

/*   print procedure statement and argument list */

for(p = prevcomments ; p ; p = p->nextp)
	{
	sp = p->datap;
	fprintf(codefile, "%s\n", sp+1);
	cfree(sp);
	}
frchain(&prevcomments);

if(tailor.procheader)
	fprintf(codefile, "%s\n", tailor.procheader);

if(procname)
	{
	p2str("      ");
	if(procname->vtype==TYSUBR || procname->vtype==TYUNDEFINED)
		p2key(FSUBROUTINE);
	else	{
		p2str(types[procname->vtype]);
		p2key(FFUNCTION);
		}

	p2str(procname->sthead->namep);
	}
else if(procclass == PRBLOCK)
	{
	p2stmt(0);
	p2key(FBLOCKDATA);
	}
else	{
	p2str("c  main program");
	if(tailor.ftnsys == CRAY)
		{
		p2stmt(0);
		p2key(FPROGRAM);
		}
	}

if(thisargs)
	{
	p2str( "(" );
	first = 1;

	for(p = thisargs ; p ; p = p->nextp)
		if( (q=p->datap)->vextbase)
			{
			if(first) first = 0;
			else p2str(", ");
			p2str(ftnames[q->vextbase]);
			}
		else	for(i=0 ; i<NFTNTYPES ; ++i)
				if(j = q->vbase[i])
					{
					if(first) first = 0;
					else p2str( ", " );
					p2str(ftnames[j]);
					}
	p2str( ")" );
	}

/* first put out declarations of variables that are used as
   adjustable dimensions
*/

y = 0;
z = & y;
for(hp = hashtab ; hp<hashend; ++hp)
	if( *hp && (q = (*hp)->varp) )
		if(q->tag==TNAME && q->vadjdim && q!=procname)
			z = z->nextp = mkchain(q,CHNULL);

dclchain(y, NOCOMMON);
frchain(&y);

/* then declare the rest of the arguments */
z = & y;
for(p = thisargs ; p ; p = p->nextp)
	if(p->datap->vadjdim == 0)
		z = z->nextp = mkchain(p->datap,CHNULL);
dclchain(y, NOCOMMON);
frchain(&y);
frchain(&thisargs);


/* now put out declarations for common blocks */
for(p = commonlist ; p ; p = p->nextp)
	prcomm(p->datap);

TEST fprintf(diagfile, "\nend of common declarations");
z = &y;

/* next the other variables that are in the symbol table */

for(hp = hashtab ; hp<hashend ; ++hp)
	if( *hp && (q = (*hp)->varp) )
		if(q->tag==TNAME && q->vadjdim==0 && q->vclass!=CLCOMMON &&
		    q->vclass!=CLARG && q!=procname &&
		    (tailor.dclintrinsics || q->vproc!=PROCINTRINSIC) )
			z = z->nextp = mkchain(q,CHNULL);

dclchain(y, NOCOMMON);
frchain(&y);

TEST fprintf(diagfile, "\nend of symbol table, start of gonelist");

/* now declare variables that are no longer in the symbol table */

dclchain(gonelist, NOCOMMON);

TEST fprintf(diagfile, "\nbeginning of hidlist");
dclchain(hidlist, NOCOMMON);

dclchain(tempvarlist, NOCOMMON);


/* finally put out equivalence statements that are generated 
   because of structure and character variables
*/
for(p = genequivs; p ; p = p->nextp)
	{
	q = p->datap;
	p2stmt(0);
	first = 1;
	p2key(FEQUIVALENCE);
	p2str( "(" );
	for(i=0; i<NFTNTYPES; ++i)
		if(q->vbase[i])
			{
			if(first) first = 0;
			else p2str( ", " );
			p2str(ftnames[ q->vbase[i] ]);
			p2str( "(1" );
			if(q1 = q->vdim)
				for(q1 = q1->datap; q1 ; q1 = q1->nextp)
					p2str( ",1" );
			p2str( ")" );
			}
	p2str( ")" );
	}
frchain(&genequivs);
}
Beispiel #29
0
int
closedir(DIR * dirp)
{
    cfree(dirp);
    return 0;
}
Beispiel #30
0
/*traduit un wildchar*/
int traduce(char *wildchar, char *dir, char **tab, int *i, int n){
	struct dirent *curdir;
	char *substr;
	int begin = 0;
	int not = 0;
	DIR *rep;
	char *token = cmalloc((strlen(wildchar) + 1) * sizeof(char));
	char *s = cmalloc((strlen(wildchar ) + 1) * sizeof(char));
	int l = strlen(wildchar);
	char *memtoken = token;
	char *mems = s;
	char *sauv = malloc(sizeof(char) * (l + 1));
	strncpy(sauv, wildchar, l + 1);
	
	rep = opendir(dir);
	if (rep == NULL) {
		perror("Ne peut ouvrir le répertoire\n");
	} else {
		//printf("wildchar = %s\n", wildchar);
		switch (*wildchar) {
		case '*':/*deux cas sont traité: l'étoile seule et l'étoile suivie d'un texte*/
			if (l > 1)
			     sauv++; /*on saute le char * */
			while ((curdir = readdir(rep))) {
				if (l > 1) {
				     /*l'étoile est suivie d'un texte, il faut chercher les correspondances*/
				     substr = strstr(curdir->d_name, sauv);
				     while (substr != NULL){
					  /*il faut que le texte derière l'étoile se trouve à la fin du nom de fichier*/
					  if ( (substr + strlen(sauv)) == (curdir->d_name + strlen(curdir->d_name))){
					       insert(tab, curdir->d_name, dir, i, n);
					  }
					  substr = strstr(++substr, sauv);
				     } 
				     
				} else { /*Si l'étoile est seule on insère tout*/
				     insert(tab, curdir->d_name, dir, i, n);
				}
			}
			break;
		case '?':
			break;
		case '!':
			if (l > 1)
				wildchar++;
			not = 1;
		default:/*pour les expressions de type [aaa,b,ccc]*/
		     /*on détecte si on a la containte d'être au début*/
		     if (*wildchar == '^'){
			  wildchar++;
			  begin = 1;
		     }
		     strcpy(s, wildchar);
		     token = strtok(s, ",");
		     while(token != NULL) {
			  l = strlen(token);
			  while ((curdir = readdir(rep))) {
			       /*on cherche si le token correspond à une sous chaine du nom de fichier*/
			       substr = strstr(curdir->d_name, token);
			       if ( substr != NULL) {
				    if (not == 0){
					 /*si la contrainte begin était présente, il faut en plus que le token corresponde au début du fichier*/
					 if (begin == 1){
					      (substr == curdir->d_name) ? insert(tab, curdir->d_name, dir, i, n) : 0;
					 } else {
					      insert(tab, curdir->d_name, dir, i, n);
					 }
				    } else { /*not == 1 on cherche donc tous les noms de fichier ne commençant pas par l'expression*/
					 if (begin == 1)
					      (substr == curdir->d_name) ? 0 : insert(tab, curdir->d_name, dir, i, n);
				    }
			       } else {
				    /*cas ou pas de sous chaine n'est trouvée, il faut insérer que si on avait une négation*/
				    if (not == 1)
					 insert(tab, curdir->d_name, dir, i, n);
			       }
			  }
			  token = strtok(NULL, ",");
			  closedir(rep);
			  rep = opendir(dir);
		     }
		     break;
		}
		closedir(rep);
	}
	cfree(memtoken);
	cfree(mems);
	return 0;
}