void init_molinfo(t_molinfo *mol)
{
    mol->nrexcl     = 0;
    mol->excl_set   = FALSE;
    mol->bProcessed = FALSE;
    init_plist(mol->plist);
    init_block(&mol->cgs);
    init_block(&mol->mols);
    init_blocka(&mol->excls);
    init_atom(&mol->atoms);
}
示例#2
0
int main(int argc, char *argv[]){
  plist_info plist;
  int        snapshot;
  char       filename_in[256];
  char       filename_out[256];

  SID_init(&argc,&argv,NULL,NULL);

  /**********************/
  /* Parse command line */
  /**********************/
  if(argc!=2){
    fprintf(stderr,"\n syntax: %s gadget_file\n",argv[0]);
    fprintf(stderr," ------\n\n");
    return(ERROR_SYNTAX);
  }
  else{
    strcpy(filename_in, argv[1]);
    snapshot=atoi(argv[2]);
    strcpy(filename_out,argv[3]);
    strcat(filename_out,".csv");
  }

  SID_log("Converting GADGET file to .csv...",SID_LOG_OPEN|SID_LOG_TIMER,filename_in,filename_out);

  /****************************************/
  /* Read GADGET file into data structure */
  /****************************************/
  init_plist(&plist,NULL,GADGET_LENGTH,GADGET_MASS,GADGET_VELOCITY);
  SID_log("Reading GADGET file {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_in);
  read_gadget_binary(filename_in,snapshot,&plist,READ_GADGET_DEFAULT);
  SID_log("Done.",SID_LOG_CLOSE);

  /********************/
  /* Write ascii file */
  /********************/
  SID_log("Writing .csv file {%s}...",SID_LOG_OPEN|SID_LOG_TIMER,filename_out);
  write_gadget_csv(filename_out,&plist);
  SID_log("Done.",SID_LOG_CLOSE);

  /************/
  /* Clean-up */
  /************/
  free_plist(&plist);

  SID_log("Done.",SID_LOG_CLOSE);

  return(ERROR_NONE);
}
示例#3
0
/****************************** scanimage ************************************
PROTO   void scanimage(picstruct *field, picstruct *dfield, picstruct *ffield,
        picstruct *wfield, picstruct *dwfield)
PURPOSE Scan of the large pixmap(s). Main loop and heart of the program.
INPUT   Measurement field pointer,
        Detection field pointer,
        Flag field pointer,
        Measurement weight-map field pointer,
        Detection weight-map field pointer,
OUTPUT  -.
NOTES   -.
AUTHOR  E. Bertin (IAP)
VERSION 21/12/2011
 ***/
void	scanimage(picstruct *field, picstruct *dfield, picstruct **pffield,
		int nffield, picstruct *wfield, picstruct *dwfield)

  {
   static infostruct	curpixinfo, *info, *store,
			initinfo, freeinfo, *victim;
   picstruct		*ffield;
   checkstruct		*check;
   objliststruct       	objlist;
   objstruct		*cleanobj;
   pliststruct		*pixel, *pixt;
   picstruct		*cfield, *cdwfield;

   char			*marker, newmarker, *blankpad, *bpt,*bpt0;
   int			co, i,j, flag, luflag,pstop, xl,xl2,yl, cn,
			nposize, stacksize, w, h, blankh, maxpixnb,
			varthreshflag, ontotal;
   short	       	trunflag;
   PIXTYPE		thresh, relthresh, cdnewsymbol, cdwthresh,wthresh,
			*scan,*dscan,*cdscan,*dwscan,*dwscanp,*dwscann,
			*cdwscan,*cdwscanp,*cdwscann,*wscand,
			*scant, *wscan,*wscann,*wscanp;
   FLAGTYPE		*pfscan[MAXFLAG];
   status		cs, ps, *psstack;
   int			*start, *end, ymax;

/* Avoid gcc -Wall warnings */
  scan = dscan = cdscan = cdwscan = cdwscann = cdwscanp
	= dwscan = dwscann = dwscanp
	= wscan = wscann = wscanp = NULL;
  victim = NULL;			/* Avoid gcc -Wall warnings */
  blankh = 0;				/* Avoid gcc -Wall warnings */
/*----- Beginning of the main loop: Initialisations  */
  thecat.ntotal = thecat.ndetect = 0;

/* cfield is the detection field in any case */
  cfield = dfield? dfield:field;

/* cdwfield is the detection weight-field if available */
  cdwfield = dwfield? dwfield:(prefs.dweight_flag?wfield:NULL);
  cdwthresh = cdwfield ? cdwfield->weight_thresh : 0.0;
  if (cdwthresh>BIG*WTHRESH_CONVFAC);
    cdwthresh = BIG*WTHRESH_CONVFAC;
  wthresh = wfield? wfield->weight_thresh : 0.0;

/* If WEIGHTing and no absolute thresholding, activate threshold scaling */
  varthreshflag = (cdwfield && prefs.thresh_type[0]!=THRESH_ABSOLUTE);
  relthresh = varthreshflag ? prefs.dthresh[0] : 0.0;/* To avoid gcc warnings*/
  w = cfield->width;
  h = cfield->height;
  objlist.dthresh = cfield->dthresh;
  objlist.thresh = field->thresh;
  cfield->yblank = 1;
  field->y = field->stripy = 0;
  field->ymin = field->stripylim = 0;
  field->stripysclim = 0;
  if (dfield)
    {
    dfield->y = dfield->stripy = 0;
    dfield->ymin = dfield->stripylim = 0;
    dfield->stripysclim = 0;
    }
  if (nffield)
    for (i=0; i<nffield; i++)
      {
      ffield = pffield[i];
      ffield->y = ffield->stripy = 0;
      ffield->ymin = ffield->stripylim = 0;
      ffield->stripysclim = 0;
      }
  if (wfield)
    {
    wfield->y = wfield->stripy = 0;
    wfield->ymin = wfield->stripylim = 0;
    wfield->stripysclim = 0;
    }
  if (dwfield)
    {
    dwfield->y = dwfield->stripy = 0;
    dwfield->ymin = dwfield->stripylim = 0;
    dwfield->stripysclim = 0;
    }

/*Allocate memory for buffers */
  stacksize = w+1;
  QMALLOC(info, infostruct, stacksize);
  QCALLOC(store, infostruct, stacksize);
  QMALLOC(marker, char, stacksize);
  QMALLOC(dumscan, PIXTYPE, stacksize);
  QMALLOC(psstack, status, stacksize);
  QCALLOC(start, int, stacksize);
  QMALLOC(end, int, stacksize);
  blankpad = bpt = NULL;
  lutzalloc(w,h);
  allocparcelout();

/* Some initializations */

  thresh = objlist.dthresh;
  initinfo.pixnb = 0;
  initinfo.flag = 0;
  initinfo.firstpix = initinfo.lastpix = -1;

  for (xl=0; xl<stacksize; xl++)
    {
    marker[xl]  = 0 ;
    dumscan[xl] = -BIG ;
    }

  co = pstop = 0;
  objlist.nobj = 1;
  curpixinfo.pixnb = 1;

/* Init cleaning procedure */
  initclean();

/*----- Allocate memory for the pixel list */
  init_plist();

  if (!(pixel = objlist.plist = malloc(nposize=prefs.mem_pixstack*plistsize)))
    error(EXIT_FAILURE, "Not enough memory to store the pixel stack:\n",
        "           Try to decrease MEMORY_PIXSTACK");

/*----- at the beginning, "free" object fills the whole pixel list */
  freeinfo.firstpix = 0;
  freeinfo.lastpix = nposize-plistsize;
  pixt = pixel;
  for (i=plistsize; i<nposize; i += plistsize, pixt += plistsize)
    PLIST(pixt, nextpix) = i;
  PLIST(pixt, nextpix) = -1;

/* Allocate memory for other buffers */
  if (prefs.filter_flag)
    {
    QMALLOC(cdscan, PIXTYPE, stacksize);
    if (cdwfield)
      {
      QCALLOC(cdwscan, PIXTYPE, stacksize);
      if (PLISTEXIST(wflag))
        {
        QCALLOC(cdwscanp, PIXTYPE, stacksize);
        QCALLOC(cdwscann, PIXTYPE, stacksize);
        }
      }
/*-- One needs a buffer to protect filtering if source-blanking applies */
    if (prefs.blank_flag)
      {
      blankh = thefilter->convh/2+1;
      QMALLOC(blankpad, char, w*blankh);
      cfield->yblank -= blankh;
      if (dfield)
        field->yblank = cfield->yblank;
      bpt = blankpad;
      }
    }

/*----- Here we go */
  for (yl=0; yl<=h;)
    {
    ps = COMPLETE;
    cs = NONOBJECT;
    if (yl==h)
      {
/*---- Need an empty line for Lutz' algorithm to end gracely */
      if (prefs.filter_flag)
        {
        free(cdscan);
        if (cdwfield)
          {
          if (PLISTEXIST(wflag))
            {
            free(cdwscanp);
            free(cdwscann);
            cdwscanp = cdwscan;
            }
          else
            free(cdwscan);
          }
        }
      cdwscan = cdwscann = cdscan = dumscan;
      }
    else
      {
      if (nffield)
        for (i=0; i<nffield; i++)
          {
          ffield = pffield[i];
          pfscan[i] = (ffield->stripy==ffield->stripysclim)?
		  (FLAGTYPE *)loadstrip(ffield, (picstruct *)NULL)
		: &ffield->fstrip[ffield->stripy*ffield->width];
          }
      if (wfield)
        {
/*------ Copy the previous weight line to track bad pixel limits */
        wscan = (wfield->stripy==wfield->stripysclim)?
		  (PIXTYPE *)loadstrip(wfield, (picstruct *)NULL)
		: &wfield->strip[wfield->stripy*wfield->width];
        if (PLISTEXIST(wflag))
          {
          if (yl>0)
            wscanp = &wfield->strip[((yl-1)%wfield->stripheight)*wfield->width];
          if (yl<h-1)
            wscann = &wfield->strip[((yl+1)%wfield->stripheight)*wfield->width];
          }
        }
      scan = (field->stripy==field->stripysclim)?
		  (PIXTYPE *)loadstrip(field, wfield)
		: &field->strip[field->stripy*field->width];
      if (dwfield)
        {
        dwscan = (dwfield->stripy==dwfield->stripysclim)?
		  (PIXTYPE *)loadstrip(dwfield,
				dfield?(picstruct *)NULL:dwfield)
		: &dwfield->strip[dwfield->stripy*dwfield->width];
        if (PLISTEXIST(wflag))
          {
          if (yl>0)
            dwscanp = &dwfield->strip[((yl-1)%dwfield->stripheight)
			*dwfield->width];
          if (yl<h-1)
            dwscann = &dwfield->strip[((yl+1)%dwfield->stripheight)
			*dwfield->width];
          }
        }
      else
        {
        dwscan = wscan;
        if (PLISTEXIST(wflag))
          {
          dwscanp = wscanp;
          dwscann = wscann;
          }
        }
      if (dfield)
        dscan = (dfield->stripy==dfield->stripysclim)?
		  (PIXTYPE *)loadstrip(dfield, dwfield)
		: &dfield->strip[dfield->stripy*dfield->width];
      else
        dscan = scan;

      if (prefs.filter_flag)
        {
        filter(cfield, cdscan, cfield->y);
        if (cdwfield)
          {
          if (PLISTEXIST(wflag))
            {
            if (yl==0)
              filter(cdwfield, cdwscann, yl);
            wscand = cdwscanp;
            cdwscanp = cdwscan;
            cdwscan = cdwscann;
            cdwscann = wscand;
            if (yl < h-1)
              filter(cdwfield, cdwscann, yl + 1);
            }
          else
            filter(cdwfield, cdwscan, yl);
          }
        }
      else
        {
        cdscan = dscan;
        cdwscan = dwscan;
        if (PLISTEXIST(wflag))
          {
          cdwscanp = dwscanp;
          cdwscann = dwscann;
          }
        }

      if ((check=prefs.check[CHECK_FILTERED]))
        writecheck(check, cdscan, w);
      }

    trunflag = (yl==0 || yl==h-1)? OBJ_TRUNC:0;

    for (xl=0; xl<=w; xl++)
      {
      if (xl == w)
        cdnewsymbol = -BIG;
      else
        cdnewsymbol = cdscan[xl];

      newmarker = marker[xl];
      marker[xl] = 0;

      curpixinfo.flag = trunflag;
      if (varthreshflag)
        thresh = relthresh*sqrt((xl==w || yl==h)? 0.0:cdwscan[xl]);
      luflag = cdnewsymbol > thresh?1:0;

      if (luflag)
        {
        if (xl==0 || xl==w-1)
          curpixinfo.flag |= OBJ_TRUNC;
        pixt = pixel + (cn=freeinfo.firstpix);
        freeinfo.firstpix = PLIST(pixt, nextpix);

/*------- Running out of pixels, the largest object becomes a "victim" ------*/

        if (freeinfo.firstpix==freeinfo.lastpix)
          {
          sprintf(gstr, "%d,%d", xl+1, yl+1);
          warning("Pixel stack overflow at position ", gstr);
          maxpixnb = 0;
          for (i=0; i<=w; i++)
            if (store[i].pixnb>maxpixnb)
              if (marker[i]=='S' || (newmarker=='S' && i==xl))
                {
                flag = 0;
                if (i<xl)
                  for (j=0; j<=co; j++)
                    flag |= (start[j]==i);
                if (!flag)
                  maxpixnb = (victim = &store[i])->pixnb;
                }
          for (j=1; j<=co; j++)
            if (info[j].pixnb>maxpixnb)
              maxpixnb = (victim = &info[j])->pixnb;

          if (!maxpixnb)
            error(EXIT_FAILURE, "*Fatal Error*: something is badly bugged in ",
		"scanimage()!");
          if (maxpixnb <= 1)
            error(EXIT_FAILURE, "Pixel stack overflow in ", "scanimage()");
          freeinfo.firstpix = PLIST(pixel+victim->firstpix, nextpix);
          PLIST(pixel+victim->lastpix, nextpix) = freeinfo.lastpix;
          PLIST(pixel+(victim->lastpix=victim->firstpix), nextpix) = -1;
          victim->pixnb = 1;
          victim->flag |= OBJ_OVERFLOW;
          }

/*---------------------------------------------------------------------------*/
        curpixinfo.lastpix = curpixinfo.firstpix = cn;
        PLIST(pixt, nextpix) = -1;
        PLIST(pixt, x) = xl;
        PLIST(pixt, y) = yl;
        PLIST(pixt, value) = scan[xl];
        if (PLISTEXIST(dvalue))
          PLISTPIX(pixt, dvalue) = dscan[xl];
        if (PLISTEXIST(cdvalue))
          PLISTPIX(pixt, cdvalue) = cdnewsymbol;
        if (PLISTEXIST(flag))
          for (i=0; i<nffield; i++)
            PLISTFLAG(pixt, flag[i]) = pfscan[i][xl];
/*--------------------- Detect pixels with a low weight ---------------------*/
        if (PLISTEXIST(wflag) && wscan)
          {
	  PLISTFLAG(pixt, wflag) = 0;
          if (wscan[xl] >= wthresh)
            PLISTFLAG(pixt, wflag) |= OBJ_LOWWEIGHT;
          if (cdwscan[xl] >= cdwthresh)
            PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;

          if (yl>0)
            {
            if (cdwscanp[xl] >= cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            if (xl>0 && cdwscanp[xl-1]>=cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            if (xl<w-1 && cdwscanp[xl+1]>=cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            }
          if (xl>0 && cdwscan[xl-1]>=cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
          if (xl<w-1 && cdwscan[xl+1]>=cdwthresh)
            PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
          if (yl<h-1)
            {
            if (cdwscann[xl] >= cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            if (xl>0 && cdwscann[xl-1]>=cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            if (xl<w-1 && cdwscann[xl+1]>=cdwthresh)
              PLISTFLAG(pixt, wflag) |= OBJ_LOWDWEIGHT;
            }
          }
        if (PLISTEXIST(dthresh))
          PLISTPIX(pixt, dthresh) = thresh;
        if (PLISTEXIST(var))
          PLISTPIX(pixt, var) = wscan[xl];

        if (cs != OBJECT)
/*------------------------------- Start Segment -----------------------------*/

          {
          cs = OBJECT;
          if (ps == OBJECT)
            {
            if (start[co] == UNKNOWN)
              {
              marker[xl] = 'S';
              start[co] = xl;
              }
            else
              marker[xl] = 's';
            }
          else
            {
            psstack[pstop++] = ps;
            marker[xl] = 'S';
            start[++co] = xl;
            ps = COMPLETE;
            info[co] = initinfo;
            }
          }

/*---------------------------------------------------------------------------*/
        }

      if (newmarker)

/*---------------------------- Process New Marker ---------------------------*/

        {
        if (newmarker == 'S')
          {
          psstack[pstop++] = ps;
          if (cs == NONOBJECT)
            {
            psstack[pstop++] = COMPLETE;
            info[++co] = store[xl];
            start[co] = UNKNOWN;
            }
          else
            update (&info[co],&store[xl], pixel);
          ps = OBJECT;
          }
        else if (newmarker == 's')
          {
          if ((cs == OBJECT) && (ps == COMPLETE))
            {
            pstop--;
            xl2 = start[co];
            update (&info[co-1],&info[co], pixel);
            if (start[--co] == UNKNOWN)
              start[co] = xl2;
            else
              marker[xl2] = 's';
            }
          ps = OBJECT;
          }
        else if (newmarker == 'f')
          ps = INCOMPLETE;
        else if (newmarker == 'F')
          {
          ps = psstack[--pstop];
          if ((cs == NONOBJECT) && (ps == COMPLETE))
            {
            if (start[co] == UNKNOWN)
              {
              if ((int)info[co].pixnb >= prefs.ext_minarea)
                {
                sortit(field, dfield, wfield, cdwfield, &info[co], &objlist,
		       cdwscan, wscan);
                }
/* ------------------------------------ free the chain-list */

              PLIST(pixel+info[co].lastpix, nextpix) = freeinfo.firstpix;
              freeinfo.firstpix = info[co].firstpix;
              }
            else
              {
              marker[end[co]] = 'F';
              store[start[co]] = info[co];
              }
            co--;
            ps = psstack[--pstop];
            }
          }
        }
/*---------------------------------------------------------------------------*/

      if (luflag)
        update (&info[co],&curpixinfo, pixel);
      else
        {
        if (cs == OBJECT)
/*-------------------------------- End Segment ------------------------------*/
          {
          cs = NONOBJECT;
          if (ps != COMPLETE)
            {
            marker[xl] = 'f';
            end[co] = xl;
            }
          else
            {
            ps = psstack[--pstop];
            marker[xl] = 'F';
            store[start[co]] = info[co];
            co--;
            }
          }
        }

      if (prefs.blank_flag && xl<w)
        {
        if (prefs.filter_flag)
	  *(bpt++) = (luflag)?1:0;
        else if (luflag)
          dscan[xl] = -BIG;
        if (dfield && luflag)
          scan[xl] = -BIG;
        }
/*--------------------- End of the loop over the x's -----------------------*/
      }

/* Detected pixel removal at the end of each line */
    if (prefs.blank_flag && yl<h)
      {
      if (prefs.filter_flag)
        {
        bpt = bpt0 = blankpad + w*((yl+1)%blankh);
        if (cfield->yblank >= 0)
          {
          scant = &PIX(cfield, 0, cfield->yblank);
          for (i=w; i--; scant++)
            if (*(bpt++))
              *scant = -BIG;
          if (dfield)
            {
            bpt = bpt0;
            scant = &PIX(field, 0, cfield->yblank);
            for (i=w; i--; scant++)
              if (*(bpt++))
                *scant = -BIG;
            }
          bpt = bpt0;
          }
        }
      cfield->yblank++;
      if (dfield)
        field->yblank = cfield->yblank;
      }

/*-- Prepare markers for the next line */
    yl++;
    field->stripy = (field->y=yl)%field->stripheight;
    if (dfield)
      dfield->stripy = (dfield->y=yl)%dfield->stripheight;
    if (nffield)
      for (i=0; i<nffield; i++)
        {
        ffield = pffield[i];
        ffield->stripy = (ffield->y=yl)%ffield->stripheight;
        }
    if (wfield)
      wfield->stripy = (wfield->y=yl)%wfield->stripheight;
    if (dwfield)
      dwfield->stripy = (dwfield->y=yl)%dwfield->stripheight;

/*-- Remove objects close to the ymin limit if ymin is ready to increase */
    if (cfield->stripy==cfield->stripysclim)
      {
      cleanobj = cleanobjlist->obj+cleanobjlist->nobj-1;
      ontotal = 0;
      for (i=cleanobjlist->nobj; i--; cleanobj--)
        {
        if (cleanobj->ycmin <= cfield->ymin)
          {
/*-------- Warn if there is a possibility for any aperture to be truncated */
          if ((ymax=cleanobj->ycmax) > cfield->ymax)
            {
            sprintf(gstr, "Object at position %.0f,%.0f ",
		cleanobj->mx+1, cleanobj->my+1);
            QWARNING(gstr, "may have some apertures truncated:\n"
		"          You might want to increase MEMORY_BUFSIZE");
            }
          else if (ymax>cfield->yblank && prefs.blank_flag)
            {
            sprintf(gstr, "Object at position %.0f,%.0f ",
		cleanobj->mx+1, cleanobj->my+1);
            QWARNING(gstr, "may have some unBLANKed neighbours:\n"
		"          You might want to increase MEMORY_PIXSTACK");
            }
          if ((prefs.prof_flag && !(thecat.ntotal%10)
		&& thecat.ntotal != ontotal)
		|| !(thecat.ntotal%400))
            NPRINTF(OUTPUT, "\33[1M> Line:%5d  "
		"Objects: %8d detected / %8d sextracted\n\33[1A",
		yl>h? h:yl, thecat.ndetect, thecat.ntotal);
          ontotal = thecat.ntotal;
          endobject(field, dfield, wfield, cdwfield, i, cleanobjlist);
          subcleanobj(i);
          cleanobj = cleanobjlist->obj+i;	/* realloc in subcleanobj() */
          }
        }
      }

    if ((prefs.prof_flag && !(thecat.ntotal%10)) || !(yl%25))
      NPRINTF(OUTPUT, "\33[1M> Line:%5d  "
		"Objects: %8d detected / %8d sextracted\n\33[1A",
	yl>h?h:yl, thecat.ndetect, thecat.ntotal);
/*--------------------- End of the loop over the y's -----------------------*/
    }

/* Removal or the remaining pixels */
  if (prefs.blank_flag && prefs.filter_flag && (cfield->yblank >= 0))
    for (j=blankh-1; j--; yl++)
      {
      bpt = bpt0 = blankpad + w*(yl%blankh);
      scant = &PIX(cfield, 0, cfield->yblank);
      for (i=w; i--; scant++)
        if (*(bpt++))
          *scant = -BIG;
      if (dfield)
        {
        bpt = bpt0;
        scant = &PIX(field, 0, cfield->yblank);
        for (i=w; i--; scant++)
          if (*(bpt++))
            *scant = -BIG;
        }
      cfield->yblank++;
      if (dfield)
        field->yblank = cfield->yblank;
      }

/* Now that all "detected" pixels have been removed, analyse detections */
  ontotal = 0;
  for (j=cleanobjlist->nobj; j--;)
    {
    if ((prefs.prof_flag && !(thecat.ntotal%10) && thecat.ntotal != ontotal)
		|| !(thecat.ntotal%400))
      NPRINTF(OUTPUT, "\33[1M> Line:%5d  "
		"Objects: %8d detected / %8d sextracted\n\33[1A",
	h, thecat.ndetect, thecat.ntotal);
    ontotal = thecat.ntotal;
    endobject(field, dfield, wfield, cdwfield, 0, cleanobjlist);
    subcleanobj(0);
    }

  endclean();

/*Free memory */
  if (prefs.filter_flag && cdwfield && PLISTEXIST(wflag))
    free(cdwscanp);
  freeparcelout();
  free(pixel); pixel = NULL;
  lutzfree();
  free(info); info = NULL;
  free(store); store = NULL;
  free(marker); marker = NULL;
  free(dumscan); dumscan = NULL;
  free(psstack); psstack = NULL;
  free(start); start = NULL;
  free(end); end = NULL;
  if (prefs.blank_flag && prefs.filter_flag)
    free(blankpad); blankpad = NULL;

  return;
  }
示例#4
0
int gmx_x2top(int argc, char *argv[])
{
    const char        *desc[] = {
        "[THISMODULE] generates a primitive topology from a coordinate file.",
        "The program assumes all hydrogens are present when defining",
        "the hybridization from the atom name and the number of bonds.",
        "The program can also make an [TT].rtp[tt] entry, which you can then add",
        "to the [TT].rtp[tt] database.[PAR]",
        "When [TT]-param[tt] is set, equilibrium distances and angles",
        "and force constants will be printed in the topology for all",
        "interactions. The equilibrium distances and angles are taken",
        "from the input coordinates, the force constant are set with",
        "command line options.",
        "The force fields somewhat supported currently are:[PAR]",
        "G53a5  GROMOS96 53a5 Forcefield (official distribution)[PAR]",
        "oplsaa OPLS-AA/L all-atom force field (2001 aminoacid dihedrals)[PAR]",
        "The corresponding data files can be found in the library directory",
        "with name [TT]atomname2type.n2t[tt]. Check Chapter 5 of the manual for more",
        "information about file formats. By default, the force field selection",
        "is interactive, but you can use the [TT]-ff[tt] option to specify",
        "one of the short names above on the command line instead. In that",
        "case [THISMODULE] just looks for the corresponding file.[PAR]",
    };
    const char        *bugs[] = {
        "The atom type selection is primitive. Virtually no chemical knowledge is used",
        "Periodic boundary conditions screw up the bonding",
        "No improper dihedrals are generated",
        "The atoms to atomtype translation table is incomplete ([TT]atomname2type.n2t[tt] file in the data directory). Please extend it and send the results back to the GROMACS crew."
    };
    FILE              *fp;
    t_params           plist[F_NRE];
    t_excls           *excls;
    t_atoms           *atoms; /* list with all atoms */
    gpp_atomtype_t     atype;
    t_nextnb           nnb;
    t_nm2type         *nm2t;
    t_mols             mymol;
    int                nnm;
    char               title[STRLEN], forcefield[32], ffdir[STRLEN];
    rvec              *x; /* coordinates? */
    int               *nbonds, *cgnr;
    int                bts[] = { 1, 1, 1, 2 };
    matrix             box;    /* box length matrix */
    int                natoms; /* number of atoms in one molecule  */
    int                nres;   /* number of molecules? */
    int                i, j, k, l, m, ndih;
    int                epbc;
    gmx_bool           bRTP, bTOP, bOPLS;
    t_symtab           symtab;
    real               cutoff, qtot, mtot;
    char               n2t[STRLEN];
    output_env_t       oenv;

    t_filenm           fnm[] = {
        { efSTX, "-f", "conf", ffREAD  },
        { efTOP, "-o", "out",  ffOPTWR },
        { efRTP, "-r", "out",  ffOPTWR }
    };
#define NFILE asize(fnm)
    static real        scale = 1.1, kb = 4e5, kt = 400, kp = 5;
    static t_restp     rtp_header_settings;
    static gmx_bool    bRemoveDihedralIfWithImproper = FALSE;
    static gmx_bool    bGenerateHH14Interactions     = TRUE;
    static gmx_bool    bKeepAllGeneratedDihedrals    = FALSE;
    static int         nrexcl                        = 3;
    static gmx_bool    bParam                        = TRUE, bRound = TRUE;
    static gmx_bool    bPairs                        = TRUE, bPBC = TRUE;
    static gmx_bool    bUsePDBcharge                 = FALSE, bVerbose = FALSE;
    static const char *molnm                         = "ICE";
    static const char *ff                            = "oplsaa";
    t_pargs            pa[]                          = {
        { "-ff",     FALSE, etSTR, {&ff},
          "Force field for your simulation. Type \"select\" for interactive selection." },
        { "-v",      FALSE, etBOOL, {&bVerbose},
          "Generate verbose output in the top file." },
        { "-nexcl", FALSE, etINT,  {&nrexcl},
          "Number of exclusions" },
        { "-H14",    FALSE, etBOOL, {&bGenerateHH14Interactions},
          "Use 3rd neighbour interactions for hydrogen atoms" },
        { "-alldih", FALSE, etBOOL, {&bKeepAllGeneratedDihedrals},
          "Generate all proper dihedrals" },
        { "-remdih", FALSE, etBOOL, {&bRemoveDihedralIfWithImproper},
          "Remove dihedrals on the same bond as an improper" },
        { "-pairs",  FALSE, etBOOL, {&bPairs},
          "Output 1-4 interactions (pairs) in topology file" },
        { "-name",   FALSE, etSTR,  {&molnm},
          "Name of your molecule" },
        { "-pbc",    FALSE, etBOOL, {&bPBC},
          "Use periodic boundary conditions." },
        { "-pdbq",  FALSE, etBOOL, {&bUsePDBcharge},
          "Use the B-factor supplied in a [TT].pdb[tt] file for the atomic charges" },
        { "-param", FALSE, etBOOL, {&bParam},
          "Print parameters in the output" },
        { "-round",  FALSE, etBOOL, {&bRound},
          "Round off measured values" },
        { "-kb",    FALSE, etREAL, {&kb},
          "Bonded force constant (kJ/mol/nm^2)" },
        { "-kt",    FALSE, etREAL, {&kt},
          "Angle force constant (kJ/mol/rad^2)" },
        { "-kp",    FALSE, etREAL, {&kp},
          "Dihedral angle force constant (kJ/mol/rad^2)" }
    };

    if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa,
                           asize(desc), desc, asize(bugs), bugs, &oenv))
    {
        return 0;
    }
    bRTP = opt2bSet("-r", NFILE, fnm);
    bTOP = opt2bSet("-o", NFILE, fnm);
    /* C89 requirements mean that these struct members cannot be used in
     * the declaration of pa. So some temporary variables are needed. */
    rtp_header_settings.bRemoveDihedralIfWithImproper = bRemoveDihedralIfWithImproper;
    rtp_header_settings.bGenerateHH14Interactions     = bGenerateHH14Interactions;
    rtp_header_settings.bKeepAllGeneratedDihedrals    = bKeepAllGeneratedDihedrals;
    rtp_header_settings.nrexcl = nrexcl;

    if (!bRTP && !bTOP)
    {
        gmx_fatal(FARGS, "Specify at least one output file");
    }

    /* Force field selection, interactive or direct */
    choose_ff(strcmp(ff, "select") == 0 ? NULL : ff,
              forcefield, sizeof(forcefield),
              ffdir, sizeof(ffdir));

    bOPLS = (strcmp(forcefield, "oplsaa") == 0);


    mymol.name = strdup(molnm);
    mymol.nr   = 1;

    /* Init parameter lists */
    init_plist(plist);

    /* Read coordinates */
    get_stx_coordnum(opt2fn("-f", NFILE, fnm), &natoms);
    snew(atoms, 1);

    /* make space for all the atoms */
    init_t_atoms(atoms, natoms, TRUE);
    snew(x, natoms);

    read_stx_conf(opt2fn("-f", NFILE, fnm), title, atoms, x, NULL, &epbc, box);

    sprintf(n2t, "%s", ffdir);
    nm2t = rd_nm2type(n2t, &nnm);
    if (nnm == 0)
    {
        gmx_fatal(FARGS, "No or incorrect atomname2type.n2t file found (looking for %s)",
                  n2t);
    }
    else
    {
        printf("There are %d name to type translations in file %s\n", nnm, n2t);
    }
    if (debug)
    {
        dump_nm2type(debug, nnm, nm2t);
    }
    printf("Generating bonds from distances...\n");
    snew(nbonds, atoms->nr);
    mk_bonds(nnm, nm2t, atoms, x, &(plist[F_BONDS]), nbonds, bPBC, box);

    open_symtab(&symtab);
    atype = set_atom_type(&symtab, atoms, &(plist[F_BONDS]), nbonds, nnm, nm2t);

    /* Make Angles and Dihedrals */
    snew(excls, atoms->nr);
    printf("Generating angles and dihedrals from bonds...\n");
    init_nnb(&nnb, atoms->nr, 4);
    gen_nnb(&nnb, plist);
    print_nnb(&nnb, "NNB");
    gen_pad(&nnb, atoms, &rtp_header_settings, plist, excls, NULL, TRUE);
    done_nnb(&nnb);

    if (!bPairs)
    {
        plist[F_LJ14].nr = 0;
    }
    fprintf(stderr,
            "There are %4d %s dihedrals, %4d impropers, %4d angles\n"
            "          %4d pairs,     %4d bonds and  %4d atoms\n",
            plist[F_PDIHS].nr,
            bOPLS ? "Ryckaert-Bellemans" : "proper",
            plist[F_IDIHS].nr, plist[F_ANGLES].nr,
            plist[F_LJ14].nr, plist[F_BONDS].nr, atoms->nr);

    calc_angles_dihs(&plist[F_ANGLES], &plist[F_PDIHS], x, bPBC, box);

    set_force_const(plist, kb, kt, kp, bRound, bParam);

    cgnr = set_cgnr(atoms, bUsePDBcharge, &qtot, &mtot);
    printf("Total charge is %g, total mass is %g\n", qtot, mtot);
    if (bOPLS)
    {
        bts[2] = 3;
        bts[3] = 1;
    }

    if (bTOP)
    {
        fp = ftp2FILE(efTOP, NFILE, fnm, "w");
        print_top_header(fp, ftp2fn(efTOP, NFILE, fnm), TRUE, ffdir, 1.0);

        write_top(fp, NULL, mymol.name, atoms, FALSE, bts, plist, excls, atype,
                  cgnr, rtp_header_settings.nrexcl);
        print_top_mols(fp, mymol.name, ffdir, NULL, 0, NULL, 1, &mymol);

        ffclose(fp);
    }
    if (bRTP)
    {
        print_rtp(ftp2fn(efRTP, NFILE, fnm), "Generated by x2top",
                  atoms, plist, atype, cgnr);
    }

    if (debug)
    {
        dump_hybridization(debug, atoms, nbonds);
    }
    close_symtab(&symtab);
    free(mymol.name);

    printf("\nWARNING: topologies generated by %s can not be trusted at face value.\n",
           ShortProgram());
    printf("         Please verify atomtypes and charges by comparison to other\n");
    printf("         topologies.\n");

    return 0;
}
示例#5
0
void pdb2top(FILE *top_file, char *posre_fn, char *molname,
             t_atoms *atoms, rvec **x, gpp_atomtype_t atype, t_symtab *tab,
             int nrtp, t_restp rtp[],
             t_restp *restp, t_hackblock *hb,
             int nterpairs,t_hackblock **ntdb, t_hackblock **ctdb,
             gmx_bool bAllowMissing,
             gmx_bool bVsites, gmx_bool bVsiteAromatics,
             const char *ff, const char *ffdir,
             real mHmult,
             int nssbonds, t_ssbond *ssbonds,
             real long_bond_dist, real short_bond_dist,
             gmx_bool bDeuterate, gmx_bool bChargeGroups, gmx_bool bCmap,
             gmx_bool bRenumRes,gmx_bool bRTPresname)
{
    /*
  t_hackblock *hb;
  t_restp  *restp;
    */
  t_params plist[F_NRE];
  t_excls  *excls;
  t_nextnb nnb;
  int      *cgnr;
  int      *vsite_type;
  int      i,nmissat;
  int      bts[ebtsNR];
  
  init_plist(plist);

  if (debug) {
    print_resall(debug, atoms->nres, restp, atype);
    dump_hb(debug, atoms->nres, hb);
  }
  
  /* Make bonds */
  at2bonds(&(plist[F_BONDS]), hb, 
           atoms->nr, atoms->atom, atoms->atomname, atoms->nres, *x, 
           long_bond_dist, short_bond_dist, bAllowMissing);
  
  /* specbonds: disulphide bonds & heme-his */
  do_ssbonds(&(plist[F_BONDS]),
	     atoms->nr, atoms->atom, atoms->atomname, nssbonds, ssbonds,
	     bAllowMissing);
  
  nmissat = name2type(atoms, &cgnr, atype, restp);
  if (nmissat) {
    if (bAllowMissing)
      fprintf(stderr,"There were %d missing atoms in molecule %s\n",
	      nmissat,molname);
    else
      gmx_fatal(FARGS,"There were %d missing atoms in molecule %s, if you want to use this incomplete topology anyhow, use the option -missing",
		  nmissat,molname);
  }
  
  /* Cleanup bonds (sort and rm doubles) */ 
  clean_bonds(&(plist[F_BONDS]));
  
  snew(vsite_type,atoms->nr);
  for(i=0; i<atoms->nr; i++)
    vsite_type[i]=NOTSET;
  if (bVsites) {
    /* determine which atoms will be vsites and add dummy masses 
       also renumber atom numbers in plist[0..F_NRE]! */
    do_vsites(nrtp, rtp, atype, atoms, tab, x, plist, 
              &vsite_type, &cgnr, mHmult, bVsiteAromatics, ffdir);
  }
  
  /* Make Angles and Dihedrals */
  fprintf(stderr,"Generating angles, dihedrals and pairs...\n");
  snew(excls,atoms->nr);
  init_nnb(&nnb,atoms->nr,4);
  gen_nnb(&nnb,plist);
  print_nnb(&nnb,"NNB");
  gen_pad(&nnb,atoms,restp[0].nrexcl,restp[0].HH14,
          plist,excls,hb,restp[0].bAlldih,restp[0].bRemoveDih,
          bAllowMissing);
  done_nnb(&nnb);
  
    /* Make CMAP */
    if (TRUE == bCmap)
    {
		gen_cmap(&(plist[F_CMAP]), restp, atoms->nr, atoms->atom, atoms->atomname, atoms->nres);
        if (plist[F_CMAP].nr > 0)
        {
            fprintf(stderr, "There are %4d cmap torsion pairs\n",
                    plist[F_CMAP].nr);
        }
    }

  /* set mass of all remaining hydrogen atoms */
  if (mHmult != 1.0)
    do_h_mass(&(plist[F_BONDS]),vsite_type,atoms,mHmult,bDeuterate);
  sfree(vsite_type);
  
  /* Cleanup bonds (sort and rm doubles) */ 
  /* clean_bonds(&(plist[F_BONDS]));*/
   
  fprintf(stderr,
	  "There are %4d dihedrals, %4d impropers, %4d angles\n"
	  "          %4d pairs,     %4d bonds and  %4d virtual sites\n",
	  plist[F_PDIHS].nr, plist[F_IDIHS].nr, plist[F_ANGLES].nr,
	  plist[F_LJ14].nr, plist[F_BONDS].nr,
	  plist[F_VSITE2].nr +
	  plist[F_VSITE3].nr +
	  plist[F_VSITE3FD].nr +
	  plist[F_VSITE3FAD].nr +
	  plist[F_VSITE3OUT].nr +
      plist[F_VSITE4FD].nr +
      plist[F_VSITE4FDN].nr );
  
  print_sums(atoms, FALSE);
  
  if (FALSE == bChargeGroups)
  {
	  scrub_charge_groups(cgnr, atoms->nr);
  }

    if (bRenumRes)
    {
        for(i=0; i<atoms->nres; i++) 
        {
            atoms->resinfo[i].nr = i + 1;
            atoms->resinfo[i].ic = ' ';
        }
    }
	
  if (top_file) {
    fprintf(stderr,"Writing topology\n");
    /* We can copy the bonded types from the first restp,
     * since the types have to be identical for all residues in one molecule.
     */
    for(i=0; i<ebtsNR; i++) {
        bts[i] = restp[0].rb[i].type;
    }
    write_top(top_file, posre_fn, molname,
              atoms, bRTPresname, 
              bts, plist, excls, atype, cgnr, restp[0].nrexcl);
  }
  
  /* cleaning up */
  free_t_hackblock(atoms->nres, &hb);
  free_t_restp(atoms->nres, &restp);
    
  /* we should clean up hb and restp here, but that is a *L*O*T* of work! */
  sfree(cgnr);
  for (i=0; i<F_NRE; i++)
    sfree(plist[i].param);
  for (i=0; i<atoms->nr; i++)
    sfree(excls[i].e);
  sfree(excls);
}
示例#6
0
int main(int argc, char *argv[]) {
    plist_info            plist;
    char                  filename_root[256];
    char                  filename_log[256];
    char                  filename_number[256];
    char                  filename_in_halos[256];
    char                  filename_out_groups[256];
    char                  filename_out_groups_A[256];
    char                  filename_out_groups_B[256];
    char                  filename_out_groups_C[256];
    char                  filename_out_subgroups[256];
    char                  filename_out_subgroups_A[256];
    char                  filename_out_subgroups_B[256];
    char                  filename_out_hierarchy[256];
    char                  filename_out_hierarchy_A[256];
    char                  filename_out_hierarchy_B[256];
    char                  filename_out_particles[256];
    char                  i_match_txt[5];
    int                   n_groups_AHF;
    int                   n_groups;
    int                   n_subgroups;
    int                   n_subgroups_matched;
    int                   n_subgroups_group;
    size_t                n_particles;
    size_t                n_particles_in_groups;
    size_t                n_particles_in_subgroups;
    size_t                n_particles_AHF_not_used;
    int                   n_particles_temp;
    int *                 n_p_1 = NULL;
    int                   flag_continue;
    int                   flag_long_ids;
    int                   i_match;
    int                   match_id_next;
    int *                 match_id         = NULL;
    int *                 match_id_initial = NULL;
    FILE *                fp               = NULL;
    FILE *                fp_in_halos      = NULL;
    FILE *                fp_out           = NULL;
    int                   n_match;
    int *                 id_2                   = NULL;
    size_t *              particle_ids_AHF       = NULL;
    size_t *              particle_ids_AHF_index = NULL;
    size_t                id_largest;
    int                   id_byte_size;
    size_t *              group_particles = NULL;
    int                   group_id;
    int                   subgroup_id;
    int                   i_group;
    int                   j_group;
    int                   k_group;
    size_t                n_particles_AHF;
    int *                 subgroup_size   = NULL;
    int *                 hierarchy_level = NULL;
    int *                 hierarchy_match = NULL;
    int                   subgroup_size_max;
    int *                 subgroup_size_list       = NULL;
    int *                 subgroup_index_list      = NULL;
    size_t *              subgroup_size_list_index = NULL;
    int *                 group_offsets            = NULL;
    size_t                group_index;
    int *                 group_size        = NULL;
    int *                 group_size_AHF    = NULL;
    int *                 group_offsets_AHF = NULL;
    int                   max_subgroup_size;
    int                   i_subgroup;
    int                   j_subgroup;
    int                   n_subgroups_group_max;
    size_t *              group_size_index = NULL;
    size_t *              match_id_index   = NULL;
    size_t                subgroup_index;
    int                   group_offset;
    int                   subgroup_offset;
    int                   group_count;
    size_t *              group_particles_index = NULL;
    size_t *              subgroup_particles    = NULL;
    int *                 particle_group        = NULL;
    size_t *              particle_group_index  = NULL;
    size_t                i_particle;
    size_t                j_particle;
    size_t                k_particle;
    int                   i_file;
    int                   i_file_start;
    int                   i_file_stop;
    size_t *              match_index = NULL;
    int                   flag_match_subgroups;
    FILE *                fp_log             = NULL;
    FILE *                fp_in              = NULL;
    FILE *                fp_out_particles   = NULL;
    FILE *                fp_out_groups      = NULL;
    FILE *                fp_out_groups_A    = NULL;
    FILE *                fp_out_groups_B    = NULL;
    FILE *                fp_out_groups_C    = NULL;
    FILE *                fp_out_subgroups_A = NULL;
    FILE *                fp_out_subgroups_B = NULL;
    FILE *                fp_out_hierarchy_A = NULL;
    FILE *                fp_out_hierarchy_B = NULL;
    FILE *                fp_test            = NULL;
    int                   substructure_level;
    int                   substructure_level_max;
    halo_properties_info *properties      = NULL;
    void *                particle_buffer = NULL;
    int                   flag_found;

    SID_Init(&argc, &argv, NULL);

    strcpy(filename_root, argv[1]);
    i_file_start = atoi(argv[2]);
    i_file_stop  = atoi(argv[3]);

    SID_log("Converting files #%d->#%d from AHF to subfind format...", SID_LOG_OPEN | SID_LOG_TIMER, i_file_start, i_file_stop);

    sprintf(filename_log, "%s_%dto%d.convert_AHF_log", filename_root, i_file_start, i_file_stop);

    // Loop over all files
    for(i_file = i_file_start; i_file <= i_file_stop; i_file++) {
        SID_log("Processing file #%d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file);

        // Read catalogs
        if(i_file < 10)
            sprintf(filename_number, "00%1d", i_file);
        else if(i_file < 100)
            sprintf(filename_number, "0%2d", i_file);
        else
            sprintf(filename_number, "%3d", i_file);

        // Read AHF group file
        init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);
        read_groups_AHF(filename_root, i_file, READ_GROUPS_ALL, &plist, filename_number);
        n_groups_AHF = ((int *)ADaPS_fetch(plist.data, "n_groups_%s", filename_number))[0];

        n_groups                 = 0;
        n_subgroups              = 0;
        n_subgroups_matched      = 0;
        n_subgroups_group        = 0;
        n_particles              = 0;
        n_particles_in_groups    = 0;
        n_particles_in_subgroups = 0;
        n_particles_AHF_not_used = 0;
        n_subgroups_group_max    = 0;

        if(n_groups_AHF > 0) {
            n_particles_AHF   = (size_t)((size_t *)ADaPS_fetch(plist.data, "n_particles_%s", filename_number))[0];
            group_size_AHF    = (int *)ADaPS_fetch(plist.data, "n_particles_group_%s", filename_number);
            group_offsets_AHF = (int *)ADaPS_fetch(plist.data, "particle_offset_group_%s", filename_number);
            particle_ids_AHF  = (size_t *)ADaPS_fetch(plist.data, "particle_ids_%s", filename_number);

            // Find largest id so we know what size to write the ids with
            for(i_particle = 0, id_largest = 0; i_particle < n_particles_AHF; i_particle++)
                id_largest = GBP_MAX(id_largest, particle_ids_AHF[i_particle]);
            if(id_largest > INT_MAX) {
                flag_long_ids = GBP_TRUE;
                id_byte_size  = sizeof(size_t);
            } else {
                flag_long_ids = GBP_FALSE;
                id_byte_size  = sizeof(int);
            }

            // Match AHF groups against themselves to find substructure
            match_halos(&plist, NULL, i_file, NULL, 0, &plist, NULL, i_file, NULL, 0, "substructure", MATCH_SUBSTRUCTURE, MATCH_SCORE_RANK_INDEX);
            match_id_initial = (int *)ADaPS_fetch(plist.data, "match_substructure");
            hierarchy_match  = match_id_initial; // Fore readability

            // Assign sub-...-sub-structures to parent (ie. top-level) halos
            SID_log("Assigning substructures to groups...", SID_LOG_OPEN);
            group_size      = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            subgroup_size   = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            hierarchy_level = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            particle_group  = (int *)SID_malloc(sizeof(int) * n_particles_AHF);
            for(i_group = 0, i_particle = 0; i_group < n_groups_AHF; i_group++) {
                group_size[i_group]    = 0;
                subgroup_size[i_group] = 0;
                for(j_particle = 0; j_particle < group_size_AHF[i_group]; i_particle++, j_particle++)
                    particle_group[i_particle] = i_group;
            }
            match_id = (int *)SID_malloc(sizeof(int) * n_groups_AHF);
            for(i_group = 0, substructure_level_max = 0; i_group < n_groups_AHF; i_group++) {
                substructure_level = 0;
                match_id_next      = match_id_initial[i_group];
                match_id[i_group]  = match_id_next;
                while(match_id_next >= 0) {
                    substructure_level++;
                    match_id[i_group] = match_id_next; // Tie subgroups to their top-level group
                    match_id_next     = match_id_initial[match_id_next];
                }
                if(match_id[i_group] < 0)
                    match_id[i_group] = i_group; // Unmatched halos should be matched to themselves
                hierarchy_level[i_group] = substructure_level;
                substructure_level_max   = GBP_MAX(substructure_level, substructure_level_max);
            }
            // needed? ADaPS_store(&(plist.data),(void *)(match_id),"match_substructure",ADaPS_DEFAULT);
            SID_log("Done.", SID_LOG_CLOSE);

            // Make sure the deepest substructures are given particle ownership
            SID_log("Assigning particles to subgroups...", SID_LOG_OPEN);
            merge_sort(
                (void *)particle_ids_AHF, (size_t)n_particles_AHF, &particle_ids_AHF_index, SID_SIZE_T, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);
            for(i_particle = 0, n_particles_AHF_not_used = 0; i_particle < n_particles_AHF; i_particle += k_particle) {
                // Count the number of times this particle id is used
                j_particle = i_particle;
                while(particle_ids_AHF[particle_ids_AHF_index[j_particle]] == particle_ids_AHF[particle_ids_AHF_index[i_particle]] &&
                      j_particle < (n_particles_AHF - 2))
                    j_particle++;
                if(particle_ids_AHF[particle_ids_AHF_index[j_particle]] == particle_ids_AHF[particle_ids_AHF_index[i_particle]])
                    j_particle++;
                k_particle = j_particle - i_particle;
                // Find the deepest substructure using this particle id...
                i_group = particle_group[particle_ids_AHF_index[i_particle]];
                for(j_particle = 1; j_particle < k_particle; j_particle++) {
                    j_group = particle_group[particle_ids_AHF_index[i_particle + j_particle]];
                    if(group_size_AHF[j_group] < group_size_AHF[i_group])
                        i_group = j_group;
                }
                // ... and set particle's group to a dummy value if this particle instance is not from the deepest group
                for(j_particle = 0, flag_found = GBP_FALSE; j_particle < k_particle; j_particle++) {
                    if(particle_group[particle_ids_AHF_index[i_particle + j_particle]] != i_group || flag_found) {
                        particle_group[particle_ids_AHF_index[i_particle + j_particle]] = -1;
                        n_particles_AHF_not_used++;
                    } else
                        flag_found = GBP_TRUE;
                }
            }
            SID_free((void **)&particle_ids_AHF_index);
            SID_log("Done.", SID_LOG_CLOSE);

            // Generate subgroup_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size[i_group] = 0;
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0)
                    subgroup_size[i_group]++;
            }

            // Get rid of groups that are too small
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0) {
                    if(subgroup_size[i_group] < 20) {
                        n_particles_AHF_not_used++;
                        particle_group[i_particle] = -1;
                    }
                }
            }

            // Regenerate subgroup_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size[i_group] = 0;
            for(i_particle = 0; i_particle < n_particles_AHF; i_particle++) {
                i_group = particle_group[i_particle];
                if(i_group >= 0)
                    subgroup_size[i_group]++;
            }

            // Find the largest subgroup's size
            for(i_group = 0, n_subgroups = 0, subgroup_size_max = 0; i_group < n_groups_AHF; i_group++)
                subgroup_size_max = GBP_MAX(subgroup_size[i_group], subgroup_size_max);

            // Generate group_size array
            for(i_group = 0; i_group < n_groups_AHF; i_group++)
                group_size[match_id[i_group]] += subgroup_size[i_group]; // update group size

            // Sort groups in order of size
            merge_sort((void *)group_size, (size_t)n_groups_AHF, &group_size_index, SID_INT, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);
            merge_sort((void *)match_id, (size_t)n_groups_AHF, &match_id_index, SID_INT, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);

            // Count groups, subgroups, etc.
            SID_log("Counting groups & subgroups...", SID_LOG_OPEN);
            for(i_group = 0, n_groups = 0, n_subgroups = 0; i_group < n_groups_AHF; i_group++) {
                group_index = group_size_index[n_groups_AHF - i_group - 1];

                // Find start of subgroup list for this group
                j_group = find_index_int(match_id, group_index, n_groups_AHF, match_id_index);
                while(group_index > match_id[match_id_index[j_group]] && j_group < (n_groups_AHF - 2))
                    j_group++;
                if(group_index > match_id[match_id_index[j_group]])
                    j_group++;

                // Count subgroups
                n_subgroups_group = 0;
                while(match_id[match_id_index[j_group]] == group_index && j_group < (n_groups_AHF - 2)) {
                    if(subgroup_size[match_id_index[j_group]] > 0)
                        n_subgroups_group++;
                    j_group++;
                }
                if(match_id[match_id_index[j_group]] == group_index) {
                    if(subgroup_size[match_id_index[j_group]] > 0)
                        n_subgroups_group++;
                    j_group++;
                }
                n_subgroups += n_subgroups_group;

                // Largest number of subgroups
                n_subgroups_group_max = GBP_MAX(n_subgroups_group_max, n_subgroups_group);

                // Count groups
                if(n_subgroups_group > 0)
                    n_groups++;
            }
            SID_log("Done.", SID_LOG_CLOSE);
        }

        // Find largest subgroup and count the number of particles in groups
        for(i_group = 0, max_subgroup_size = 0, n_particles_in_groups = 0; i_group < n_groups_AHF; i_group++) {
            max_subgroup_size = GBP_MAX(max_subgroup_size, subgroup_size[i_group]);
            if(subgroup_size[i_group] > 0)
                n_particles_in_groups += (size_t)subgroup_size[i_group];
        }

        // Write some statistics
        SID_log("Substructure statistics:", SID_LOG_OPEN);
        SID_log("Number of groups                 =%d", SID_LOG_COMMENT, n_groups);
        SID_log("Number of subgroups              =%d", SID_LOG_COMMENT, n_subgroups);
        SID_log("Max number of subgroups per group=%d", SID_LOG_COMMENT, n_subgroups_group_max);
        SID_log("Largest subgroup                 =%d particles", SID_LOG_COMMENT, subgroup_size_max);
        SID_log("Depth of substructure heirarchy  =%d levels", SID_LOG_COMMENT, substructure_level_max);
        SID_log("Number of AHF particles used     =%lld", SID_LOG_COMMENT, n_particles_in_groups);
        SID_log("Number of AHF particles NOT used =%lld", SID_LOG_COMMENT, n_particles_AHF_not_used);
        SID_log("", SID_LOG_CLOSE | SID_LOG_NOPRINT);

        // Open files
        SID_set_verbosity(SID_SET_VERBOSITY_RELATIVE, 0);
        SID_log("Writing %d groups, %d subgroups and %lld particles to files...",
                SID_LOG_OPEN | SID_LOG_TIMER,
                n_groups,
                n_subgroups,
                n_particles_in_groups);
        sprintf(filename_out_groups, "%s_%s.catalog_groups", filename_root, filename_number);
        sprintf(filename_out_groups_A, "%s_%s.catalog_groups_A", filename_root, filename_number);
        sprintf(filename_out_groups_B, "%s_%s.catalog_groups_B", filename_root, filename_number);
        sprintf(filename_out_groups_C, "%s_%s.catalog_groups_C", filename_root, filename_number);
        sprintf(filename_out_subgroups, "%s_%s.catalog_subgroups", filename_root, filename_number);
        sprintf(filename_out_subgroups_A, "%s_%s.catalog_subgroups_A", filename_root, filename_number);
        sprintf(filename_out_subgroups_B, "%s_%s.catalog_subgroups_B", filename_root, filename_number);
        sprintf(filename_out_hierarchy, "%s_%s.catalog_hierarchy", filename_root, filename_number);
        sprintf(filename_out_hierarchy_A, "%s_%s.catalog_hierarchy_A", filename_root, filename_number);
        sprintf(filename_out_hierarchy_B, "%s_%s.catalog_hierarchy_B", filename_root, filename_number);
        sprintf(filename_out_particles, "%s_%s.catalog_particles", filename_root, filename_number);
        fp_out_groups_A    = fopen(filename_out_groups_A, "w");
        fp_out_groups_B    = fopen(filename_out_groups_B, "w");
        fp_out_groups_C    = fopen(filename_out_groups_C, "w");
        fp_out_subgroups_A = fopen(filename_out_subgroups_A, "w");
        fp_out_subgroups_B = fopen(filename_out_subgroups_B, "w");
        fp_out_hierarchy_A = fopen(filename_out_hierarchy_A, "w");
        fp_out_hierarchy_B = fopen(filename_out_hierarchy_B, "w");
        fp_out_particles   = fopen(filename_out_particles, "w");

        // Write headers
        fwrite(&n_groups, sizeof(int), 1, fp_out_groups_A);
        fwrite(&n_subgroups, sizeof(int), 1, fp_out_subgroups_A);
        fwrite(&n_subgroups, sizeof(int), 1, fp_out_hierarchy_A);
        fwrite(&id_byte_size, sizeof(int), 1, fp_out_particles);
        switch(flag_long_ids) {
            case GBP_TRUE:
                fwrite(&n_particles_in_groups, sizeof(size_t), 1, fp_out_particles);
                break;
            default:
                n_particles_temp = (int)n_particles_in_groups;
                fwrite(&n_particles_temp, sizeof(int), 1, fp_out_particles);
                break;
        }

        // Write files; group and subgroup files in parts (to be concatinated together later)
        subgroup_size_list  = (int *)SID_malloc(sizeof(int) * n_subgroups_group_max);
        subgroup_index_list = (int *)SID_malloc(sizeof(int) * n_subgroups_group_max);
        particle_buffer     = (void *)SID_malloc(id_byte_size * subgroup_size_max);
        subgroup_offset     = 0;
        group_offset        = 0;

        for(i_group = n_groups_AHF - 1; i_group >= n_groups_AHF - n_groups; i_group--) {
            group_index = group_size_index[i_group];

            // Find start of subgroup list for this group
            i_subgroup = find_index_int(match_id, group_index, n_groups_AHF, match_id_index);
            while(group_index > match_id[match_id_index[i_subgroup]] && i_subgroup < (n_groups_AHF - 2))
                i_subgroup++;
            if(group_index > match_id[match_id_index[i_subgroup]])
                i_subgroup++;

            // Create a list of subgroups for this group and sort it by size
            n_subgroups_group = 0;
            subgroup_index    = match_id_index[i_subgroup];
            while(match_id[subgroup_index] == group_index && i_subgroup < (n_groups_AHF - 2)) {
                if(subgroup_size[subgroup_index] > 0) {
                    subgroup_size_list[n_subgroups_group]  = subgroup_size[subgroup_index];
                    subgroup_index_list[n_subgroups_group] = (int)subgroup_index;
                    n_subgroups_group++;
                }
                i_subgroup++;
                subgroup_index = match_id_index[i_subgroup];
            }
            if(match_id[subgroup_index] == group_index) {
                if(subgroup_size[subgroup_index] > 0) {
                    subgroup_size_list[n_subgroups_group]  = subgroup_size[subgroup_index];
                    subgroup_index_list[n_subgroups_group] = (int)subgroup_index;
                    n_subgroups_group++;
                }
                i_subgroup++;
                subgroup_index = match_id_index[i_subgroup];
            }
            merge_sort((void *)subgroup_size_list,
                       (size_t)n_subgroups_group,
                       &subgroup_size_list_index,
                       SID_INT,
                       SORT_COMPUTE_INDEX,
                       SORT_COMPUTE_NOT_INPLACE);

            // Perform writes for subgroups and particle lists
            for(i_subgroup = 0, i_particle = 0; i_subgroup < n_subgroups_group; i_subgroup++) {
                j_subgroup = subgroup_index_list[subgroup_size_list_index[n_subgroups_group - i_subgroup - 1]];
                // ... subgroups ...
                fwrite(&(subgroup_size[j_subgroup]), sizeof(int), 1, fp_out_subgroups_A);
                fwrite(&(subgroup_offset), sizeof(int), 1, fp_out_subgroups_B);
                fwrite(&(hierarchy_match[j_subgroup]), sizeof(int), 1, fp_out_hierarchy_A);
                fwrite(&(hierarchy_level[j_subgroup]), sizeof(int), 1, fp_out_hierarchy_B);
                subgroup_offset += subgroup_size[j_subgroup];
                // ... and particles
                for(j_particle = group_offsets_AHF[j_subgroup], k_particle = 0, i_particle = 0; k_particle < group_size_AHF[j_subgroup];
                    j_particle++, k_particle++) {
                    if(particle_group[j_particle] == j_subgroup) {
                        switch(flag_long_ids) {
                            case GBP_TRUE:
                                ((size_t *)particle_buffer)[i_particle++] = (size_t)(particle_ids_AHF[j_particle]);
                                break;
                            default:
                                ((int *)particle_buffer)[i_particle++] = (int)(particle_ids_AHF[j_particle]);
                                break;
                        }
                    }
                }
                if(i_particle == subgroup_size[j_subgroup])
                    fwrite(particle_buffer, id_byte_size, i_particle, fp_out_particles);
                else
                    SID_exit_error("Subgroup size mismatch!", SID_ERROR_LOGIC);
            }

            SID_free((void **)&subgroup_size_list_index);

            // Perform writes for groups
            fwrite(&(group_size[group_index]), sizeof(int), 1, fp_out_groups_A);
            fwrite(&group_offset, sizeof(int), 1, fp_out_groups_B);
            fwrite(&n_subgroups_group, sizeof(int), 1, fp_out_groups_C);
            group_offset += group_size[group_index];
        }
        SID_free((void **)&subgroup_size_list);
        SID_free((void **)&subgroup_index_list);
        SID_free((void **)&particle_buffer);

        fclose(fp_out_groups_A);
        fclose(fp_out_groups_B);
        fclose(fp_out_groups_C);
        fclose(fp_out_subgroups_A);
        fclose(fp_out_subgroups_B);
        fclose(fp_out_hierarchy_A);
        fclose(fp_out_hierarchy_B);
        fclose(fp_out_particles);

        // Concatinate group and subgroup temp files into final files
        SID_cat_files(filename_out_groups, SID_CAT_CLEAN, 3, filename_out_groups_A, filename_out_groups_B, filename_out_groups_C);

        SID_cat_files(filename_out_subgroups, SID_CAT_CLEAN, 2, filename_out_subgroups_A, filename_out_subgroups_B);

        SID_cat_files(filename_out_hierarchy, SID_CAT_CLEAN, 2, filename_out_hierarchy_A, filename_out_hierarchy_B);

        // Clean-up
        SID_free((void **)&subgroup_size);
        SID_free((void **)&hierarchy_level);
        SID_free((void **)&group_size);
        SID_free((void **)&group_size_index);
        SID_free((void **)&match_id_index);
        free_plist(&plist);
        SID_set_verbosity(SID_SET_VERBOSITY_DEFAULT);
        SID_log("Done.", SID_LOG_CLOSE);

        // Write log file
        SID_log("Writing to log file...", SID_LOG_OPEN);
        // Write a header for the log file
        if(i_file == i_file_start) {
            fp_log = fopen(filename_log, "w");
            fprintf(fp_log, "# (1):  filenumber\n");
            fprintf(fp_log, "# (2):  n_groups_AHF\n");
            fprintf(fp_log, "# (3):  n_particles_AHF\n");
            fprintf(fp_log, "# (4):  n_groups\n");
            fprintf(fp_log, "# (5):  n_subgroups\n");
            fprintf(fp_log, "# (6):  max number of subgroups per group\n");
            fprintf(fp_log, "# (7):  largest subgroup\n");
            fprintf(fp_log, "# (8):  depth of substructure heirarchy\n");
            fprintf(fp_log, "# (9):  number of AHF particles used\n");
            fprintf(fp_log, "# (10): number of AHF particles NOT used\n");
        } else
            fp_log = fopen(filename_log, "a");
        fprintf(fp_log,
                "%4d %9d %12zd %9d %9d %9d %9d %9d %12zd %12zd\n",
                i_file,
                n_groups_AHF,
                n_particles_AHF,
                n_groups,
                n_subgroups,
                n_subgroups_group_max,
                subgroup_size_max,
                substructure_level_max,
                n_particles_in_groups,
                n_particles_AHF_not_used);
        fclose(fp_log);

        SID_log("Done.", SID_LOG_CLOSE);

        SID_log("Done.", SID_LOG_CLOSE);
    }

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
示例#7
0
int main(int argc, char *argv[]) {
    SID_Init(&argc, &argv, NULL);

    // Parse command line
    select_gadget_volume_params_info select_gadget_volume_params;
    int                              snapshot;
    int                              n_files_out;
    int                              select_mode;
    char                             filename_in_root[SID_MAX_FILENAME_LENGTH];
    char                             filename_out_root[SID_MAX_FILENAME_LENGTH];
    GBPREAL                          cen_select[3];
    GBPREAL                          select_size;
    strcpy(filename_in_root, argv[1]);
    snapshot                           = atoi(argv[2]);
    select_gadget_volume_params.cen[0] = (GBPREAL)atof(argv[3]);
    select_gadget_volume_params.cen[1] = (GBPREAL)atof(argv[4]);
    select_gadget_volume_params.cen[2] = (GBPREAL)atof(argv[5]);
    select_gadget_volume_params.size   = (GBPREAL)atof(argv[6]);
    strcpy(filename_out_root, argv[7]);
    n_files_out = atoi(argv[8]);
    select_mode = atoi(argv[9]);

    // Check that the selection mode is valid and set function pointer
    int (*select_function)(
        gadget_read_info * fp_gadget, void *params, size_t i_particle, size_t i_particle_type, int i_type, GBPREAL *pos, GBPREAL *vel, size_t ID_i);
    if(select_mode == 1)
        select_function = select_gadget_cube;
    else if(select_mode == 2) {
        select_function                   = select_gadget_sphere;
        select_gadget_volume_params.size2 = pow(select_gadget_volume_params.size, 2.);
    } else
        SID_exit_error("Invalid selection mode (%d) given.", SID_ERROR_SYNTAX, select_mode);

    SID_log("Excising volume from Gadget binary file {%s;snapshot=%d}...", SID_LOG_OPEN | SID_LOG_TIMER, filename_in_root, snapshot);

    // Initialize the plist data structure
    plist_info plist;
    select_gadget_volume_params.plist = &plist;
    init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);

    // Read the header and determine the input file-format
    gadget_read_info   fp_gadget;
    int                flag_filefound = init_gadget_read(filename_in_root, snapshot, &fp_gadget);
    int                flag_multifile = fp_gadget.flag_multifile;
    int                flag_file_type = fp_gadget.flag_file_type;
    gadget_header_info header         = fp_gadget.header;
    if(!flag_filefound)
        SID_exit_error("File not found.", SID_ERROR_LOGIC);
    select_gadget_volume_params.box_size = fp_gadget.header.box_size;

    // Count the particles
    size_t n_particles_type_local[N_GADGET_TYPE];
    size_t n_particles_type[N_GADGET_TYPE];
    int    flag_long_IDs;
    process_gadget_file("Counting particles in selection...",
                        filename_in_root,
                        snapshot,
                        select_function,
                        process_gadget_file_fctn_null,
                        &select_gadget_volume_params,
                        n_particles_type_local,
                        n_particles_type,
                        &flag_long_IDs,
                        PROCESS_GADGET_BINARY_DEFAULT);

    // Allocate RAM for the particles
    allocate_gadget_particles(&plist, n_particles_type_local, n_particles_type, flag_long_IDs);

    // Read the particles
    process_gadget_file("Performing read/select/write...",
                        filename_in_root,
                        snapshot,
                        select_function,
                        store_gadget_particles,
                        &select_gadget_volume_params,
                        NULL,
                        NULL,
                        &flag_long_IDs,
                        PROCESS_GADGET_BINARY_DEFAULT);

    // Write the snapshot
    char filename_out[SID_MAX_FILENAME_LENGTH];
    sprintf(filename_out, "%s_%03d", filename_out_root, snapshot);
    write_gadget_binary_new(&plist, filename_out, n_files_out, WRITE_GADGET_BINARY_DEFAULT);

    // Clean-up
    free_plist(&plist);

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
示例#8
0
int main(int argc, char *argv[]) {
    int        snapshot;
    char       filename_out[256];
    char       filename_smooth[256];
    char       filename_snapshot[256];
    char *     species_name;
    double     h_Hubble;
    plist_info plist;
    size_t     i_particle;
    int        i_species;
    int        j_species;
    int        i_rank;
    size_t     n_particles;
    GBPREAL *  x_array;
    GBPREAL *  y_array;
    GBPREAL *  z_array;
    GBPREAL *  r_smooth_array;
    GBPREAL *  rho_array;
    GBPREAL *  sigma_v_array;
    FILE *     fp_out;

    SID_Init(&argc, &argv, NULL);

    strcpy(filename_snapshot, argv[1]);
    snapshot = atoi(argv[2]);
    strcpy(filename_smooth, argv[3]);
    strcpy(filename_out, argv[4]);

    SID_log("Creating ascii file {%s} from smmoth files {%s} and snapshot {%s}...",
            SID_LOG_OPEN | SID_LOG_TIMER,
            filename_out,
            filename_smooth,
            filename_snapshot);

    // Read snapshot files
    init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);
    read_gadget_binary(filename_snapshot, snapshot, &plist, READ_GADGET_DEFAULT);
    read_smooth(&plist, filename_smooth, 0, SMOOTH_DEFAULT);
    h_Hubble = ((double *)ADaPS_fetch(plist.data, "h_Hubble"))[0];

    // Loop over each species
    for(i_species = 0, j_species = 0; i_species < N_GADGET_TYPE; i_species++) {
        species_name = plist.species[i_species];
        if(ADaPS_exist(plist.data, "n_all_%s", species_name))
            n_particles = ((size_t *)ADaPS_fetch(plist.data, "n_all_%s", species_name))[0];
        else
            n_particles = 0;
        // If at least one rank has particles for this species ...
        if(n_particles > 0) {
            SID_log("Writting %s particles...", SID_LOG_OPEN, species_name);
            // ... then fetch arrays ...
            n_particles = ((size_t *)ADaPS_fetch(plist.data, "n_%s", species_name))[0];
            x_array     = (GBPREAL *)ADaPS_fetch(plist.data, "x_%s", species_name);
            y_array     = (GBPREAL *)ADaPS_fetch(plist.data, "y_%s", species_name);
            z_array     = (GBPREAL *)ADaPS_fetch(plist.data, "z_%s", species_name);
            if(ADaPS_exist(plist.data, "r_smooth_%s", species_name))
                r_smooth_array = (GBPREAL *)ADaPS_fetch(plist.data, "r_smooth_%s", species_name);
            else
                r_smooth_array = NULL;
            if(ADaPS_exist(plist.data, "rho_%s", species_name))
                rho_array = (GBPREAL *)ADaPS_fetch(plist.data, "rho_%s", species_name);
            else
                rho_array = NULL;
            if(ADaPS_exist(plist.data, "sigma_v_%s", species_name))
                sigma_v_array = (GBPREAL *)ADaPS_fetch(plist.data, "sigma_v_%s", species_name);
            else
                sigma_v_array = NULL;

            // ... and write this species' particles
            for(i_rank = 0; i_rank < SID.n_proc; i_rank++) {
                if(SID.My_rank == i_rank) {
                    if(j_species == 0 && i_rank == 0)
                        fp_out = fopen(filename_out, "w");
                    else
                        fp_out = fopen(filename_out, "a");
                    for(i_particle = 0; i_particle < n_particles; i_particle++) {
                        fprintf(fp_out,
                                "%2d %11.4le %11.4le %11.4le",
                                i_species,
                                (double)x_array[i_particle] * h_Hubble / M_PER_MPC,
                                (double)y_array[i_particle] * h_Hubble / M_PER_MPC,
                                (double)z_array[i_particle] * h_Hubble / M_PER_MPC);
                        if(r_smooth_array != NULL)
                            fprintf(fp_out, " %10.4le", (double)r_smooth_array[i_particle] * h_Hubble / M_PER_MPC);
                        if(rho_array != NULL)
                            fprintf(fp_out, " %10.4le", (double)rho_array[i_particle] / (M_SOL * pow(h_Hubble / M_PER_MPC, 3.)));
                        if(sigma_v_array != NULL)
                            fprintf(fp_out, " %10.4le", (double)sigma_v_array[i_particle] * 1e-3);
                        fprintf(fp_out, "\n");
                    }
                    fclose(fp_out);
                }
                SID_Barrier(SID_COMM_WORLD);
            }
            j_species++;
            SID_log("Done.", SID_LOG_CLOSE);
        }
    }

    // Clean-up
    free_plist(&plist);
    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
示例#9
0
int main (int argc, char *argv[])
{
  static const char *desc[] = {
    "The gromacs preprocessor",
    "reads a molecular topology file, checks the validity of the",
    "file, expands the topology from a molecular description to an atomic",
    "description. The topology file contains information about",
    "molecule types and the number of molecules, the preprocessor",
    "copies each molecule as needed. ",
    "There is no limitation on the number of molecule types. ",
    "Bonds and bond-angles can be converted into constraints, separately",
    "for hydrogens and heavy atoms.",
    "Then a coordinate file is read and velocities can be generated",
    "from a Maxwellian distribution if requested.",
    "grompp also reads parameters for the mdrun ",
    "(eg. number of MD steps, time step, cut-off), and others such as",
    "NEMD parameters, which are corrected so that the net acceleration",
    "is zero.",
    "Eventually a binary file is produced that can serve as the sole input",
    "file for the MD program.[PAR]",
    
    "grompp uses the atom names from the topology file. The atom names",
    "in the coordinate file (option [TT]-c[tt]) are only read to generate",
    "warnings when they do not match the atom names in the topology.",
    "Note that the atom names are irrelevant for the simulation as",
    "only the atom types are used for generating interaction parameters.[PAR]",

    "grompp calls a preprocessor to resolve includes, macros ",
    "etcetera. By default we use the cpp in your path. To specify a "
    "different macro-preprocessor (e.g. m4) or alternative location",

    "you can put a line in your parameter file specifying the path",
    "to that program. Specifying [TT]-pp[tt] will get the pre-processed",
    "topology file written out.[PAR]",
    
    "If your system does not have a c-preprocessor, you can still",
    "use grompp, but you do not have access to the features ",
    "from the cpp. Command line options to the c-preprocessor can be given",
    "in the [TT].mdp[tt] file. See your local manual (man cpp).[PAR]",
    
    "When using position restraints a file with restraint coordinates",
    "can be supplied with [TT]-r[tt], otherwise restraining will be done",
    "with respect to the conformation from the [TT]-c[tt] option.",
    "For free energy calculation the the coordinates for the B topology",
    "can be supplied with [TT]-rb[tt], otherwise they will be equal to",
    "those of the A topology.[PAR]",
    
    "Starting coordinates can be read from trajectory with [TT]-t[tt].",
    "The last frame with coordinates and velocities will be read,",
    "unless the [TT]-time[tt] option is used.",
    "Note that these velocities will not be used when [TT]gen_vel = yes[tt]",
    "in your [TT].mdp[tt] file. An energy file can be supplied with",
    "[TT]-e[tt] to have exact restarts when using pressure and/or",
    "Nose-Hoover temperature coupling. For an exact restart do not forget",
    "to turn off velocity generation and turn on unconstrained starting",
    "when constraints are present in the system.",
    "If you want to continue a crashed run, it is",
    "easier to use [TT]tpbconv[tt].[PAR]",

    "Using the [TT]-morse[tt] option grompp can convert the harmonic bonds",
    "in your topology to morse potentials. This makes it possible to break",
    "bonds. For this option to work you need an extra file in your $GMXLIB",
    "with dissociation energy. Use the -debug option to get more information",
    "on the workings of this option (look for MORSE in the grompp.log file",
    "using less or something like that).[PAR]",
    
    "By default all bonded interactions which have constant energy due to",
    "virtual site constructions will be removed. If this constant energy is",
    "not zero, this will result in a shift in the total energy. All bonded",
    "interactions can be kept by turning off [TT]-rmvsbds[tt]. Additionally,",
    "all constraints for distances which will be constant anyway because",
    "of virtual site constructions will be removed. If any constraints remain",
    "which involve virtual sites, a fatal error will result.[PAR]"
    
    "To verify your run input file, please make notice of all warnings",
    "on the screen, and correct where necessary. Do also look at the contents",
    "of the [TT]mdout.mdp[tt] file, this contains comment lines, as well as",
    "the input that [TT]grompp[tt] has read. If in doubt you can start grompp",
    "with the [TT]-debug[tt] option which will give you more information",
    "in a file called grompp.log (along with real debug info). Finally, you",
    "can see the contents of the run input file with the [TT]gmxdump[tt]",
    "program."
  };
  t_gromppopts *opts;
  gmx_mtop_t   *sys;
  int          nmi;
  t_molinfo    *mi;
  gpp_atomtype_t atype;
  t_inputrec   *ir;
  int          natoms,nvsite,comb,mt;
  t_params     *plist;
  t_state      state;
  matrix       box;
  real         max_spacing,fudgeQQ;
  double       reppow;
  char         fn[STRLEN],fnB[STRLEN],*mdparin;
  int          nerror,ntype;
  bool         bNeedVel,bGenVel;
  bool         have_radius,have_vol,have_surftens,have_gb_radius,have_S_hct;
  bool         have_atomnumber;
  int		   n12,n13,n14;
  t_params     *gb_plist = NULL;
  gmx_genborn_t *born = NULL;

  t_filenm fnm[] = {
    { efMDP, NULL,  NULL,        ffOPTRD },
    { efMDP, "-po", "mdout",     ffWRITE },
    { efSTX, "-c",  NULL,        ffREAD  },
    { efSTX, "-r",  NULL,        ffOPTRD },
    { efSTX, "-rb", NULL,        ffOPTRD },
    { efNDX, NULL,  NULL,        ffOPTRD },
    { efTOP, NULL,  NULL,        ffREAD  },
    { efTOP, "-pp", "processed", ffOPTWR },
    { efTPX, "-o",  NULL,        ffWRITE },
    { efTRN, "-t",  NULL,        ffOPTRD },
    { efEDR, "-e",  NULL,        ffOPTRD }
  };
#define NFILE asize(fnm)

  /* Command line options */
  static bool bVerbose=TRUE,bRenum=TRUE;
  static bool bRmVSBds=TRUE,bZero=FALSE;
  static int  i,maxwarn=0;
  static real fr_time=-1;
  t_pargs pa[] = {
    { "-v",       FALSE, etBOOL, {&bVerbose},
      "Be loud and noisy" },
    { "-time",    FALSE, etREAL, {&fr_time},
      "Take frame at or first after this time." },
    { "-rmvsbds",FALSE, etBOOL, {&bRmVSBds},
      "Remove constant bonded interactions with virtual sites" },
    { "-maxwarn", FALSE, etINT,  {&maxwarn},
      "Number of allowed warnings during input processing" },
    { "-zero",    FALSE, etBOOL, {&bZero},
      "Set parameters for bonded interactions without defaults to zero instead of generating an error" },
    { "-renum",   FALSE, etBOOL, {&bRenum},
      "Renumber atomtypes and minimize number of atomtypes" }
  };
  
  CopyRight(stdout,argv[0]);
  
  /* Initiate some variables */
  nerror=0;
  snew(ir,1);
  snew(opts,1);
  init_ir(ir,opts);
  
  /* Parse the command line */
  parse_common_args(&argc,argv,0,NFILE,fnm,asize(pa),pa,
		    asize(desc),desc,0,NULL);
  
  init_warning(maxwarn);
  
  /* PARAMETER file processing */
  mdparin = opt2fn("-f",NFILE,fnm);
  set_warning_line(mdparin,-1);    
  get_ir(mdparin,opt2fn("-po",NFILE,fnm),ir,opts,&nerror);
  
  if (bVerbose) 
    fprintf(stderr,"checking input for internal consistency...\n");
  check_ir(mdparin,ir,opts,&nerror);

  if (ir->ld_seed == -1) {
    ir->ld_seed = make_seed();
    fprintf(stderr,"Setting the LD random seed to %d\n",ir->ld_seed);
  }

  bNeedVel = EI_STATE_VELOCITY(ir->eI);
  bGenVel  = (bNeedVel && opts->bGenVel);

  snew(plist,F_NRE);
  init_plist(plist);
  snew(sys,1);
  atype = init_atomtype();
  if (debug)
    pr_symtab(debug,0,"Just opened",&sys->symtab);
    
  strcpy(fn,ftp2fn(efTOP,NFILE,fnm));
  if (!gmx_fexist(fn)) 
    gmx_fatal(FARGS,"%s does not exist",fn);
  new_status(fn,opt2fn_null("-pp",NFILE,fnm),opt2fn("-c",NFILE,fnm),
	     opts,ir,bZero,bGenVel,bVerbose,&state,
	     atype,sys,&nmi,&mi,plist,&comb,&reppow,&fudgeQQ,
	     opts->bMorse,
	     &nerror);
  
  if (debug)
    pr_symtab(debug,0,"After new_status",&sys->symtab);
  
  if (count_constraints(sys,mi) && (ir->eConstrAlg == econtSHAKE)) {
    if (ir->eI == eiCG || ir->eI == eiLBFGS) {
      fprintf(stderr,
	      "ERROR: Can not do %s with %s, use %s\n",
	      EI(ir->eI),econstr_names[econtSHAKE],econstr_names[econtLINCS]);
      nerror++;
    }
    if (ir->bPeriodicMols) {
      fprintf(stderr,
	      "ERROR: can not do periodic molecules with %s, use %s\n",
	      econstr_names[econtSHAKE],econstr_names[econtLINCS]);
      nerror++;
    }
  }

  /* If we are doing GBSA, check that we got the parameters we need                                                            
   * This checking is to see if there are GBSA paratmeters for all                                                             
   * atoms in the force field. To go around this for testing purposes                                                          
   * comment out the nerror++ counter temporarliy                                                                              
   */
  have_radius=have_vol=have_surftens=have_gb_radius=have_S_hct=TRUE;
  for(i=0;i<get_atomtype_ntypes(atype);i++) {
    have_radius=have_radius       && (get_atomtype_radius(i,atype) > 0);
    have_vol=have_vol             && (get_atomtype_vol(i,atype) > 0);
    have_surftens=have_surftens   && (get_atomtype_surftens(i,atype) > 0);
    have_gb_radius=have_gb_radius && (get_atomtype_gb_radius(i,atype) > 0);
    have_S_hct=have_S_hct         && (get_atomtype_S_hct(i,atype) > 0);
  }
  if(!have_radius && ir->implicit_solvent==eisGBSA) {
    fprintf(stderr,"Can't do GB electrostatics; the forcefield is missing values for\n"
	    "atomtype radii, or they might be zero\n.");
    /* nerror++; */
  }
  /*
  if(!have_surftens && ir->implicit_solvent!=eisNO) {
    fprintf(stderr,"Can't do implicit solvent; the forcefield is missing values\n"
	    " for atomtype surface tension\n.");
    nerror++;                                                                                                                
  }
  */
  
  /* If we are doing QM/MM, check that we got the atom numbers */
  have_atomnumber = TRUE;
  for (i=0; i<get_atomtype_ntypes(atype); i++) {
    have_atomnumber = have_atomnumber && (get_atomtype_atomnumber(i,atype) >= 0);
  }
  if (!have_atomnumber && ir->bQMMM)
  {
    fprintf(stderr,"\n"
            "It appears as if you are trying to run a QM/MM calculation, but the force\n"
            "field you are using does not contain atom numbers fields. This is an\n"
            "optional field (introduced in Gromacs 3.3) for general runs, but mandatory\n"
            "for QM/MM. The good news is that it is easy to add - put the atom number as\n"
            "an integer just before the mass column in ffXXXnb.itp.\n"
            "NB: United atoms have the same atom numbers as normal ones.\n\n"); 
    nerror++;
  }

  if (nerror) {
    print_warn_num(FALSE);
    
    gmx_fatal(FARGS,"There were %d error(s) processing your input",nerror);
  }
  if (opt2bSet("-r",NFILE,fnm))
    sprintf(fn,"%s",opt2fn("-r",NFILE,fnm));
  else
    sprintf(fn,"%s",opt2fn("-c",NFILE,fnm));
  if (opt2bSet("-rb",NFILE,fnm))
    sprintf(fnB,"%s",opt2fn("-rb",NFILE,fnm));
  else
    strcpy(fnB,fn);

  if (nint_ftype(sys,mi,F_POSRES) > 0) {
    if (bVerbose) {
      fprintf(stderr,"Reading position restraint coords from %s",fn);
      if (strcmp(fn,fnB) == 0) {
	fprintf(stderr,"\n");
      } else {
	fprintf(stderr," and %s\n",fnB);
	if (ir->efep != efepNO && ir->n_flambda > 0) {
	  fprintf(stderr,"ERROR: can not change the position restraint reference coordinates with lambda togther with foreign lambda calculation.\n");
	  nerror++;
	}
      }
    }
    gen_posres(sys,mi,fn,fnB,
	       ir->refcoord_scaling,ir->ePBC,
	       ir->posres_com,ir->posres_comB);
  }
		
  nvsite = 0;
  /* set parameters for virtual site construction (not for vsiten) */
  for(mt=0; mt<sys->nmoltype; mt++) {
    nvsite +=
      set_vsites(bVerbose, &sys->moltype[mt].atoms, atype, mi[mt].plist);
  }
  /* now throw away all obsolete bonds, angles and dihedrals: */
  /* note: constraints are ALWAYS removed */
  if (nvsite) {
    for(mt=0; mt<sys->nmoltype; mt++) {
      clean_vsite_bondeds(mi[mt].plist,sys->moltype[mt].atoms.nr,bRmVSBds);
    }
  }
  
	/* If we are using CMAP, setup the pre-interpolation grid */
	if(plist->ncmap>0)
	{
		init_cmap_grid(&sys->cmap_grid, plist->nc, plist->grid_spacing);
		setup_cmap(plist->grid_spacing, plist->nc, plist->cmap,&sys->cmap_grid);
	}
	
  set_wall_atomtype(atype,opts,ir);
  if (bRenum) {
    renum_atype(plist, sys, ir->wall_atomtype, atype, bVerbose);
    ntype = get_atomtype_ntypes(atype);
  }
  
	/* PELA: Copy the atomtype data to the topology atomtype list */
	copy_atomtype_atomtypes(atype,&(sys->atomtypes));

	if (debug)
    pr_symtab(debug,0,"After renum_atype",&sys->symtab);

  if (bVerbose) 
    fprintf(stderr,"converting bonded parameters...\n");
	
  ntype = get_atomtype_ntypes(atype);
  convert_params(ntype, plist, mi, comb, reppow, fudgeQQ, sys);
  	
	if(ir->implicit_solvent)
	{
		printf("Constructing Generalized Born topology...\n");

		/* Check for -normvsbds switch to grompp, necessary for gb together with vsites */
		if(bRmVSBds && nvsite)
		{
			fprintf(stderr, "ERROR: Must use -normvsbds switch to grompp when doing Generalized Born\n"
					"together with virtual sites\n");
			nerror++;
		}
		
		if (nerror)
		{
			print_warn_num(FALSE);
			gmx_fatal(FARGS,"There were %d error(s) processing your input",nerror);
		}
		
		generate_gb_topology(sys,mi);
	}
	
  if (debug)
    pr_symtab(debug,0,"After convert_params",&sys->symtab);

  /* set ptype to VSite for virtual sites */
  for(mt=0; mt<sys->nmoltype; mt++) {
    set_vsites_ptype(FALSE,&sys->moltype[mt]);
  }
  if (debug) {
    pr_symtab(debug,0,"After virtual sites",&sys->symtab);
  }
  /* Check velocity for virtual sites and shells */
  if (bGenVel) {
    check_vel(sys,state.v);
  }
    
  /* check masses */
  check_mol(sys);
  
  for(i=0; i<sys->nmoltype; i++) {
    check_cg_sizes(ftp2fn(efTOP,NFILE,fnm),&sys->moltype[i].cgs);
  }

  check_warning_error(FARGS);
	
  if (bVerbose) 
    fprintf(stderr,"initialising group options...\n");
  do_index(mdparin,ftp2fn_null(efNDX,NFILE,fnm),
	   sys,bVerbose,ir,
	   bGenVel ? state.v : NULL);
	
  /* Init the temperature coupling state */
  init_gtc_state(&state,ir->opts.ngtc);

  if (bVerbose)
    fprintf(stderr,"Checking consistency between energy and charge groups...\n");
  check_eg_vs_cg(sys);
  
  if (debug)
    pr_symtab(debug,0,"After index",&sys->symtab);
  triple_check(mdparin,ir,sys,&nerror);
  close_symtab(&sys->symtab);
  if (debug)
    pr_symtab(debug,0,"After close",&sys->symtab);

  /* make exclusions between QM atoms */
  if (ir->bQMMM) {
    generate_qmexcl(sys,ir);
  }

  if (ftp2bSet(efTRN,NFILE,fnm)) {
    if (bVerbose)
      fprintf(stderr,"getting data from old trajectory ...\n");
    cont_status(ftp2fn(efTRN,NFILE,fnm),ftp2fn_null(efEDR,NFILE,fnm),
		bNeedVel,bGenVel,fr_time,ir,&state,sys);
  }

  if (ir->ePBC==epbcXY && ir->nwall!=2)
    clear_rvec(state.box[ZZ]);
  
  if (EEL_FULL(ir->coulombtype)) {
    /* Calculate the optimal grid dimensions */
    copy_mat(state.box,box);
    if (ir->ePBC==epbcXY && ir->nwall==2)
      svmul(ir->wall_ewald_zfac,box[ZZ],box[ZZ]);
    max_spacing = calc_grid(stdout,box,opts->fourierspacing,
			    &(ir->nkx),&(ir->nky),&(ir->nkz),1);
    if ((ir->coulombtype == eelPPPM) && (max_spacing > 0.1)) {
      set_warning_line(mdparin,-1);
      sprintf(warn_buf,"Grid spacing larger then 0.1 while using PPPM.");
      warning_note(NULL);
    }
  }

  if (ir->ePull != epullNO)
    set_pull_init(ir,sys,state.x,state.box,opts->pull_start);

  /*  reset_multinr(sys); */
  
  if (EEL_PME(ir->coulombtype)) {
    float ratio = pme_load_estimate(sys,ir,state.box);
    fprintf(stderr,"Estimate for the relative computational load of the PME mesh part: %.2f\n",ratio);
    if (ratio > 0.5)
      warning_note("The optimal PME mesh load for parallel simulations is below 0.5\n"
		   "and for highly parallel simulations between 0.25 and 0.33,\n"
		   "for higher performance, increase the cut-off and the PME grid spacing");
  }

  {
    double cio = compute_io(ir,sys->natoms,&sys->groups,F_NRE,1);
    sprintf(warn_buf,"This run will generate roughly %.0f Mb of data",cio);
    if (cio > 2000) {
      set_warning_line(mdparin,-1);
      warning_note(NULL);
    } else {
      printf("%s\n",warn_buf);
    }
  }
	
  if (bVerbose) 
    fprintf(stderr,"writing run input file...\n");

  print_warn_num(TRUE);
  state.lambda = ir->init_lambda;
  write_tpx_state(ftp2fn(efTPX,NFILE,fnm),ir,&state,sys);
  
  thanx(stderr);
  
  return 0;
}
示例#10
0
int main(int argc, char *argv[]) {
    int    i, j, i_x, i_y, i_z;
    int    n_2D_total;
    char   species_name[256];
    double h_Hubble;
    double Omega_Lambda;
    double Omega_M;
    double Omega_b;
    double f_gas;
    double Omega_k;
    double sigma_8;
    double n_spec;
    double redshift;
    int    i_rank;
    int    i_grouping;
    int    i_grouping_start;
    int    i_grouping_stop;
    char   filename_in[SID_MAX_FILENAME_LENGTH];
    char   filename_cosmology[SID_MAX_FILENAME_LENGTH];
    char   filename_in_root[SID_MAX_FILENAME_LENGTH];
    char   filename_in_model[SID_MAX_FILENAME_LENGTH];
    char   filename_out_root[SID_MAX_FILENAME_LENGTH];
    char   grouping_name[6];
    char   filename_TF[256];
    char   n_string[64];
    int    n[3];
    double x_in, y_in, z_in, vx_in, vy_in, vz_in;
    double box_size;
    double L[3];
    size_t n_all;
    FILE * fp_in;
    double M_min, M_max, M_med;
    double V_min, V_max, V_med;
    char * line        = NULL;
    size_t line_length = 0;
    int    i_bin, j_bin;
    int    i_file, n_files;
    int    n_1D, n_2D;
    int    grid_size;
    double k_min_1D;
    double dk_1D;
    double k_max_1D;
    double k_min_2D;
    double dk_2D;
    double k_max_2D;

    // Initialization -- MPI etc.
    SID_Init(&argc, &argv, NULL);
    if(argc != 8)
        SID_exit_error("Incorrect syntax.", SID_ERROR_SYNTAX);

    // Parse arguments
    strcpy(filename_in_root, argv[1]);
    strcpy(filename_out_root, argv[2]);
    redshift = (double)atof(argv[3]);
    strcpy(filename_cosmology, argv[4]);
    grid_size        = (int)atoi(argv[5]);
    box_size         = (double)atof(argv[6]);
    i_grouping_start = (int)atoi(argv[7]);
    i_grouping_stop  = (int)atoi(argv[8]);

    // Sanity check
    int n_groupings;
    n_groupings = i_grouping_stop - i_grouping_start + 1;
    if(n_groupings < 1)
        SID_exit_error("No groupings have been selected (you chose start=%d, stop=%d).", SID_ERROR_LOGIC,
                       i_grouping_start, i_grouping_stop);

    SID_log("Producing power spectra for halo grouping(s)...", SID_LOG_OPEN | SID_LOG_TIMER);

    // Set the k ranges
    double k_Nyq;
    k_Nyq    = (TWO_PI * (double)grid_size / box_size) / 2.;
    k_min_1D = 0.02;
    dk_1D    = 0.02;
    k_max_1D = dk_1D * (float)((int)(k_Nyq / dk_1D));
    k_min_2D = 0.0;
    dk_2D    = 0.02;
    k_max_2D = dk_2D * (float)((int)(k_Nyq / dk_2D));

    // Initialize the objects structure
    plist_info plist;
    init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);

    // Initialize the power spectrum
    pspec_info pspec;
    init_pspec(
        &pspec, filename_cosmology, NULL, MAP2GRID_DIST_DWT20, redshift, box_size, grid_size, k_min_1D, k_max_1D, dk_1D, k_min_2D, k_max_2D, dk_2D);

    // Process each grouping in turn
    for(i_grouping = i_grouping_start; i_grouping <= i_grouping_stop; i_grouping++) {
        SID_log("Processing grouping #%03d...", SID_LOG_OPEN | SID_LOG_TIMER, i_grouping);

        // Loop over ithe real-space and 3 redshift-space frames
        int i_run;
        for(i_run = 0; i_run < 4; i_run++) {
            // Read catalog
            switch(i_run) {
                case 0:
                    SID_log("Processing real-space ...", SID_LOG_OPEN | SID_LOG_TIMER);
                    read_groupings(filename_in_root, i_grouping, &plist, READ_GROUPING_DEFAULT, &(pspec.FFT.slab));
                    break;
                case 1:
                    SID_log("Processing v_x redshift space...", SID_LOG_OPEN | SID_LOG_TIMER);
                    read_groupings(filename_in_root,
                                   i_grouping,
                                   &plist,
                                   READ_GROUPING_DEFAULT | READ_GROUPING_ADD_VX,
                                   &(pspec.FFT.slab),
                                   box_size,
                                   redshift,
                                   pspec.cosmo);
                    break;
                case 2:
                    SID_log("Processing v_y redshift space...", SID_LOG_OPEN | SID_LOG_TIMER);
                    read_groupings(filename_in_root,
                                   i_grouping,
                                   &plist,
                                   READ_GROUPING_DEFAULT | READ_GROUPING_ADD_VY,
                                   &(pspec.FFT.slab),
                                   box_size,
                                   redshift,
                                   pspec.cosmo);
                    break;
                case 3:
                    SID_log("Processing v_z redsift space...", SID_LOG_OPEN | SID_LOG_TIMER);
                    read_groupings(filename_in_root,
                                   i_grouping,
                                   &plist,
                                   READ_GROUPING_DEFAULT | READ_GROUPING_ADD_VZ,
                                   &(pspec.FFT.slab),
                                   box_size,
                                   redshift,
                                   pspec.cosmo);
                    break;
            }

            // Compute power spectrum
            compute_pspec(&plist, "halos", &pspec, i_run);

            SID_log("Done.", SID_LOG_CLOSE);
        } // Loop over 4 P(k)'s

        // Now that all 4 runs are done, let's write the results
        char filename_out_root_grouping[SID_MAX_FILENAME_LENGTH];
        sprintf(filename_out_root_grouping, "%s_grouping_%03d", filename_out_root, i_grouping);
        write_pspec(&pspec, filename_out_root_grouping, &plist, "halos");

        SID_log("Done.", SID_LOG_CLOSE);
    } // Loop over groupings

    // Clean-up
    free_pspec(&pspec);

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
示例#11
0
int main(int argc, char *argv[]){
  int     n_species;
  int     n_load;
  int     n_used;
  int     flag_used[N_GADGET_TYPE];
  char    species_name[256];
  double  h_Hubble;
  double  n_spec;
  double  redshift;
  int     i_species;
  char    n_string[64];
  int             n[3];
  double          L[3];
  FILE           *fp_1D;
  FILE           *fp_2D;
  cosmo_info     *cosmo;
  field_info     *field[N_GADGET_TYPE];
  field_info     *field_norm[N_GADGET_TYPE];
  plist_info      plist_header;
  plist_info      plist;
  FILE           *fp;
  int     i_temp;
  int     n_temp;
  double *k_temp;
  double *kmin_temp;
  double *kmax_temp;
  double *P_temp;
  size_t *n_mode_temp;
  double *sigma_P_temp;
  double *shot_noise_temp;
  double *dP_temp;
  int     snapshot_number;
  int     i_compute;
  int     distribution_scheme;
  double  k_min_1D;
  double  k_max_1D;
  double  k_min_2D;
  double  k_max_2D;
  int     n_k_1D;
  int     n_k_2D;
  double *k_1D;
  double *P_k_1D;
  double *dP_k_1D;
  int    *n_modes_1D;
  double *P_k_2D;
  double *dP_k_2D;
  int    *n_modes_2D;
  int     n_groups=1;
  double  dk_1D;
  double  dk_2D;
  char   *grid_identifier;

  // Initialization -- MPI etc.
  SID_init(&argc,&argv,NULL,NULL);

  // Parse arguments
  int grid_size;
  char filename_in_root[MAX_FILENAME_LENGTH];
  char filename_out_root[MAX_FILENAME_LENGTH];
  strcpy(filename_in_root,  argv[1]);
  snapshot_number=(int)atoi(argv[2]);
  strcpy(filename_out_root, argv[3]);
  grid_size      =(int)atoi(argv[4]);
  if(!strcmp(argv[5],"ngp") || !strcmp(argv[5],"NGP"))
     distribution_scheme=MAP2GRID_DIST_NGP;
  else if(!strcmp(argv[5],"cic") || !strcmp(argv[5],"CIC"))
     distribution_scheme=MAP2GRID_DIST_CIC;
  else if(!strcmp(argv[5],"tsc") || !strcmp(argv[5],"TSC"))
     distribution_scheme=MAP2GRID_DIST_TSC;
  else if(!strcmp(argv[5],"d12") || !strcmp(argv[5],"D12"))
     distribution_scheme=MAP2GRID_DIST_DWT12;
  else if(!strcmp(argv[5],"d20") || !strcmp(argv[5],"D20"))
     distribution_scheme=MAP2GRID_DIST_DWT20;
  else
     SID_trap_error("Invalid distribution scheme {%s} specified.",ERROR_SYNTAX,argv[5]);

  SID_log("Smoothing Gadget file {%s;snapshot=#%d} to a %dx%dx%d grid with %s kernel...",SID_LOG_OPEN|SID_LOG_TIMER,
          filename_in_root,snapshot_number,grid_size,grid_size,grid_size,argv[5]);

  // Initialization -- fetch header info
  SID_log("Reading Gadget header...",SID_LOG_OPEN);
  gadget_read_info   fp_gadget;
  int                flag_filefound=init_gadget_read(filename_in_root,snapshot_number,&fp_gadget);
  int                flag_multifile=fp_gadget.flag_multifile;
  int                flag_file_type=fp_gadget.flag_file_type;
  gadget_header_info header        =fp_gadget.header;
  double             box_size      =(double)(header.box_size);
  size_t            *n_all         =(size_t *)SID_calloc(sizeof(size_t)*N_GADGET_TYPE);
  size_t             n_total;
  if(flag_filefound){
     if(SID.I_am_Master){
        FILE *fp_in;
        char  filename[MAX_FILENAME_LENGTH];
        int   block_length_open;
        int   block_length_close;
        set_gadget_filename(&fp_gadget,0,filename);
        fp_in=fopen(filename,"r");
        fread_verify(&block_length_open, sizeof(int),1,fp_in);
        fread_verify(&header,            sizeof(gadget_header_info),1,fp_in);
        fread_verify(&block_length_close,sizeof(int),1,fp_in);
        fclose(fp_in);
        if(block_length_open!=block_length_close)
           SID_trap_error("Block lengths don't match (ie. %d!=%d).",ERROR_LOGIC,block_length_open,block_length_close);
     }
     SID_Bcast(&header,sizeof(gadget_header_info),MASTER_RANK,SID.COMM_WORLD);
     redshift=header.redshift;
     h_Hubble=header.h_Hubble;
     box_size=header.box_size;
     if(SID.n_proc>1)
        n_load=1;
     else
        n_load=header.n_files;
     for(i_species=0,n_total=0,n_used=0;i_species<N_GADGET_TYPE;i_species++){
        n_all[i_species]=(size_t)header.n_all_lo_word[i_species]+((size_t)header.n_all_hi_word[i_species])<<32;
        n_total+=n_all[i_species];
        if(n_all[i_species]>0){
           n_used++;
           flag_used[i_species]=TRUE;
        }
        else
           flag_used[i_species]=FALSE;
     }

     // Initialize cosmology
     double box_size        =((double *)ADaPS_fetch(plist.data,"box_size"))[0];
     double h_Hubble        =((double *)ADaPS_fetch(plist.data,"h_Hubble"))[0];
     double redshift        =((double *)ADaPS_fetch(plist.data,"redshift"))[0];
     double expansion_factor=((double *)ADaPS_fetch(plist.data,"expansion_factor"))[0];
     double Omega_M         =((double *)ADaPS_fetch(plist.data,"Omega_M"))[0];
     double Omega_Lambda    =((double *)ADaPS_fetch(plist.data,"Omega_Lambda"))[0];
     double Omega_k         =1.-Omega_Lambda-Omega_M;
     double Omega_b=0.; // not needed, so doesn't matter
     double f_gas  =Omega_b/Omega_M;
     double sigma_8=0.; // not needed, so doesn't matter
     double n_spec =0.; // not needed, so doesn't matter
     char   cosmo_name[16];
     sprintf(cosmo_name,"Gadget file's");
     init_cosmo(&cosmo,
                cosmo_name,
                Omega_Lambda,
                Omega_M,
                Omega_k,
                Omega_b,
                f_gas,
                h_Hubble,
                sigma_8,
                n_spec);
  }
  SID_log("Done.",SID_LOG_CLOSE);

  grid_identifier=(char *)SID_calloc(GRID_IDENTIFIER_SIZE*sizeof(char));

  // Only process if there are >0 particles present
  if(n_used>0){

     // Loop over ithe real-space and 3 redshift-space frames
     int i_write;
     int i_run;
     int n_run;
     int n_grids_total; 
     n_grids_total=4; // For now, hard-wire real-space density and velocity grids only
     n_run=1;         // For now, hard-wire real-space calculation only
     for(i_run=0,i_write=0;i_run<n_run;i_run++){

        // Read catalog
        int  n_grid;
        char i_run_identifier[8];
        switch(i_run){
        case 0:
           SID_log("Processing real-space ...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"r");
           n_grid=4;
           break;
        case 1:
           SID_log("Processing v_x redshift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"x");
           n_grid=1;
           break;
        case 2:
           SID_log("Processing v_y redshift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"y");
           n_grid=1;
           break;
        case 3:
           SID_log("Processing v_z redsift space...",SID_LOG_OPEN|SID_LOG_TIMER);
           sprintf(i_run_identifier,"z");
           n_grid=1;
           break;
        }

        // For each i_run case, loop over the fields we want to produce
        int i_grid;
        for(i_grid=0;i_grid<n_grid;i_grid++){

           char i_grid_identifier[8];
           switch(i_grid){
           case 0:
              SID_log("Processing density grid ...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"rho");
              break;
           case 1:
              SID_log("Processing v_x velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_x");
              break;
           case 2:
              SID_log("Processing v_y velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_y");
              break;
           case 3:
              SID_log("Processing v_z velocity grid...",SID_LOG_OPEN|SID_LOG_TIMER);
              sprintf(i_grid_identifier,"v_z");
              break;
           }

           // Initialize the field that will hold the grid
           int        n[]={grid_size,grid_size,grid_size};
           double     L[]={box_size, box_size, box_size};
           int        i_init;
           for(i_species=0;i_species<N_GADGET_TYPE;i_species++){
              if(flag_used[i_species]){
                 field[i_species]     =(field_info *)SID_malloc(sizeof(field_info));
                 field_norm[i_species]=(field_info *)SID_malloc(sizeof(field_info));
                 init_field(3,n,L,field[i_species]);
                 init_field(3,n,L,field_norm[i_species]);
                 i_init=i_species;
              }
              else{
                 field[i_species]     =NULL;
                 field_norm[i_species]=NULL;
              }
           }

           // Loop over all the files that this rank will read
           int i_load;
           for(i_load=0;i_load<n_load;i_load++){
              if(n_load>1)
                 SID_log("Processing file No. %d of %d...",SID_LOG_OPEN|SID_LOG_TIMER,i_load+1,n_load);

              // Initialization -- read gadget file
              GBPREAL mass_array[N_GADGET_TYPE];
              init_plist(&plist,&((field[i_init])->slab),GADGET_LENGTH,GADGET_MASS,GADGET_VELOCITY);
              char filename_root[MAX_FILENAME_LENGTH];
              read_gadget_binary_local(filename_in_root,
                                       snapshot_number,
                                       i_run,
                                       i_load,
                                       n_load,
                                       mass_array,
                                       &(field[i_init]->slab),
                                       cosmo,
                                       &plist);

              // Generate power spectra
              for(i_species=0;i_species<plist.n_species;i_species++){

                 // Determine how many particles of species i_species there are
                 if(n_all[i_species]>0){
                    // Fetch the needed information
                    size_t   n_particles;
                    size_t   n_particles_local;
                    int      flag_alloc_m;
                    GBPREAL *x_particles_local;
                    GBPREAL *y_particles_local;
                    GBPREAL *z_particles_local;
                    GBPREAL *vx_particles_local;
                    GBPREAL *vy_particles_local;
                    GBPREAL *vz_particles_local;
                    GBPREAL *m_particles_local;
                    GBPREAL *v_particles_local;
                    GBPREAL *w_particles_local;
                    n_particles      =((size_t  *)ADaPS_fetch(plist.data,"n_all_%s",plist.species[i_species]))[0];
                    n_particles_local=((size_t  *)ADaPS_fetch(plist.data,"n_%s",    plist.species[i_species]))[0];
                    x_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"x_%s",    plist.species[i_species]);
                    y_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"y_%s",    plist.species[i_species]);
                    z_particles_local= (GBPREAL *)ADaPS_fetch(plist.data,"z_%s",    plist.species[i_species]);
                    vx_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vx_%s",   plist.species[i_species]);
                    vy_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vy_%s",   plist.species[i_species]);
                    vz_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"vz_%s",   plist.species[i_species]);
                    if(ADaPS_exist(plist.data,"M_%s",plist.species[i_species])){
                       flag_alloc_m=FALSE;
                       m_particles_local=(GBPREAL *)ADaPS_fetch(plist.data,"M_%s",plist.species[i_species]);
                    }
                    else{
                       flag_alloc_m=TRUE;
                       m_particles_local=(GBPREAL *)SID_malloc(n_particles_local*sizeof(GBPREAL));
                       int i_particle;
                       for(i_particle=0;i_particle<n_particles_local;i_particle++)
                          m_particles_local[i_particle]=mass_array[i_species];
                    }

                    // Decide the map_to_grid() mode
                    int mode;
                    if(n_load==1)
                       mode=MAP2GRID_MODE_DEFAULT;
                    else if(i_load==0 || n_load==1)
                       mode=MAP2GRID_MODE_DEFAULT|MAP2GRID_MODE_NONORM;
                    else if(i_load==(n_load-1))
                       mode=MAP2GRID_MODE_NOCLEAN;
                    else
                       mode=MAP2GRID_MODE_NOCLEAN|MAP2GRID_MODE_NONORM;

                    // Set the array that will weight the grid
                    field_info *field_i;
                    field_info *field_norm_i;
                    double factor;
                    switch(i_grid){
                    case 0:
                       v_particles_local=m_particles_local;
                       w_particles_local=NULL;
                       field_i          =field[i_species];
                       field_norm_i     =NULL;
                       mode|=MAP2GRID_MODE_APPLYFACTOR;
                       factor=pow((double)grid_size/box_size,3.);
                       break;
                    case 1:
                       v_particles_local=vx_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    case 2:
                       v_particles_local=vy_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    case 3:
                       v_particles_local=vz_particles_local;
                       w_particles_local=m_particles_local;
                       field_i          =field[i_species];
                       field_norm_i     =field_norm[i_species];
                       factor=1.;
                       break;
                    }

                    // Generate grid
                    map_to_grid(n_particles_local,
                                x_particles_local,
                                y_particles_local,
                                z_particles_local,
                                v_particles_local,
                                w_particles_local,
                                cosmo,
                                redshift,
                                distribution_scheme,
                                factor,
                                field_i,
                                field_norm_i,
                                mode);
                    if(flag_alloc_m)
                       SID_free(SID_FARG m_particles_local);
                 }
              }

              // Clean-up
              free_plist(&plist);
              if(n_load>1)
                 SID_log("Done.",SID_LOG_CLOSE);
           } // loop over i_load
           
           // Write results to disk
           char filename_out_species[MAX_FILENAME_LENGTH];
           init_plist(&plist,NULL,GADGET_LENGTH,GADGET_MASS,GADGET_VELOCITY);
           for(i_species=0;i_species<plist.n_species;i_species++){
              if(flag_used[i_species]){
                 sprintf(grid_identifier,"%s_%s_%s",i_grid_identifier,i_run_identifier,plist.species[i_species]);
                 sprintf(filename_out_species,"%s_%s",filename_out_root,plist.species[i_species]);
                 write_grid(field[i_species],
                            filename_out_species,
                            i_write,
                            n_grids_total,
                            distribution_scheme,
                            grid_identifier,
                            header.box_size);
                 free_field(field[i_species]);
                 free_field(field_norm[i_species]);
                 SID_free(SID_FARG field[i_species]);
                 SID_free(SID_FARG field_norm[i_species]);
                 i_write++;
              }
           }

           // Clean-up
           free_plist(&plist);
           SID_log("Done.",SID_LOG_CLOSE);

        } // loop over i_grid

        SID_log("Done.",SID_LOG_CLOSE);
     } // loop over i_run
  } // if n_used>0 

  // Clean-up
  free_cosmo(&cosmo);
  SID_free(SID_FARG grid_identifier);
  SID_free(SID_FARG n_all);

  SID_log("Done.",SID_LOG_CLOSE);

  SID_exit(ERROR_NONE);
}
示例#12
0
int main(int argc, char *argv[]) {
    SID_Init(&argc, &argv, NULL);

    // Parse command line
    select_gadget_ids_params_info params;
    int                           snapshot;
    int                           halo_index;
    int                           halo_type;
    int                           n_files_out;
    int                           select_mode;
    char                          filename_SSimPL_root[SID_MAX_FILENAME_LENGTH];
    char                          filename_halo_version[SID_MAX_FILENAME_LENGTH];
    char                          filename_in_root[SID_MAX_FILENAME_LENGTH];
    char                          filename_out_root[SID_MAX_FILENAME_LENGTH];
    GBPREAL                       cen_select[3];
    GBPREAL                       select_size;
    strcpy(filename_SSimPL_root, argv[1]);
    strcpy(filename_halo_version, argv[2]);
    snapshot   = atoi(argv[3]);
    halo_index = atoi(argv[4]);
    halo_type  = atoi(argv[5]);
    strcpy(filename_out_root, argv[6]);
    n_files_out = atoi(argv[7]);

    SID_log("Writing halo particles to ascii file {%s;snapshot=%d;halo_index=%d}...",
            SID_LOG_OPEN | SID_LOG_TIMER,
            filename_SSimPL_root,
            snapshot,
            halo_index);

    // Initialize the plist data structure
    plist_info plist;
    params.plist = &plist;
    init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);

    // Read the halo ID list.  Generate sort indicies and copy the
    //    list to a duplicate array.  Make sure this is the one added
    //    to params.  Pass this to write_gadget_ascii below, so that
    //    the particles get written in the same order that they are
    //    in the halo catalog.

    char filename_halos[SID_MAX_FILENAME_LENGTH];
    if(halo_type == 0)
        sprintf(filename_halos, "%s/halos/%s_%03d.catalog_groups", filename_SSimPL_root, filename_halo_version, snapshot);
    else
        sprintf(filename_halos, "%s/halos/%s_%03d.catalog_subgroups", filename_SSimPL_root, filename_halo_version, snapshot);
    FILE * fp_groups = fopen(filename_halos, "r");
    int    n_groups;
    int    offset_size;
    int    halo_length;
    size_t halo_offset;
    SID_fread_verify(&n_groups, sizeof(int), 1, fp_groups);
    SID_fread_verify(&offset_size, sizeof(int), 1, fp_groups);
    fseeko(fp_groups, (off_t)(2 * sizeof(int) + halo_index * sizeof(int)), SEEK_SET);
    SID_fread_verify(&halo_length, sizeof(int), 1, fp_groups);
    fseeko(fp_groups, (off_t)(2 * sizeof(int) + n_groups * sizeof(int) + halo_index * offset_size), SEEK_SET);
    if(offset_size == sizeof(int)) {
        int halo_offset_i;
        SID_fread_verify(&halo_offset_i, offset_size, 1, fp_groups);
        halo_offset = (size_t)halo_offset_i;
    } else
        SID_fread_verify(&halo_offset, offset_size, 1, fp_groups);
    fclose(fp_groups);

    char filename_ids[SID_MAX_FILENAME_LENGTH];
    sprintf(filename_ids, "%s/halos/%s_%03d.catalog_particles", filename_SSimPL_root, filename_halo_version, snapshot);
    FILE * fp_ids = fopen(filename_ids, "r");
    int    id_byte_size;
    size_t n_ids;
    SID_fread_verify(&id_byte_size, sizeof(int), 1, fp_ids);
    SID_log("%d %d-byte IDs to be read (offset=%d)", SID_LOG_COMMENT, halo_length, id_byte_size, halo_offset);
    if(id_byte_size == sizeof(int)) {
        int n_ids_i;
        SID_fread_verify(&n_ids_i, sizeof(int), 1, fp_ids);
        n_ids = (size_t)n_ids_i;
    } else
        SID_fread_verify(&n_ids, sizeof(size_t), 1, fp_ids);
    fseeko(fp_ids, (off_t)(sizeof(int) + id_byte_size + halo_offset * id_byte_size), SEEK_SET);
    params.n_ids             = halo_length;
    params.id_list           = (size_t *)SID_malloc(sizeof(size_t) * halo_length);
    size_t *id_list_unsorted = (size_t *)SID_malloc(sizeof(size_t) * halo_length);
    int     flag_long_ids    = GBP_TRUE;
    if(id_byte_size == sizeof(int)) {
        flag_long_ids  = GBP_FALSE;
        int *id_list_i = (int *)SID_malloc(sizeof(int) * halo_length);
        SID_fread_verify(id_list_i, id_byte_size, halo_length, fp_ids);
        for(int i_p = 0; i_p < halo_length; i_p++)
            id_list_unsorted[i_p] = (size_t)id_list_i[i_p];
        SID_free(SID_FARG id_list_i);
    } else
        SID_fread_verify(id_list_unsorted, id_byte_size, halo_length, fp_ids);
    fclose(fp_ids);
    memcpy(params.id_list, id_list_unsorted, sizeof(size_t) * halo_length);
    merge_sort(params.id_list, halo_length, NULL, SID_SIZE_T, SORT_INPLACE_ONLY, SORT_COMPUTE_INPLACE);

    // Count the particles
    size_t n_particles_type_local[N_GADGET_TYPE];
    size_t n_particles_type[N_GADGET_TYPE];
    int    flag_long_IDs;
    sprintf(filename_in_root, "%s/snapshots/snapshot", filename_SSimPL_root);
    process_gadget_file("Counting particles in selection...",
                        filename_in_root,
                        snapshot,
                        select_gadget_all,
                        process_gadget_file_fctn_null,
                        &params,
                        n_particles_type_local,
                        n_particles_type,
                        &flag_long_IDs,
                        PROCESS_GADGET_BINARY_DEFAULT);

    // Allocate RAM for the particles
    allocate_gadget_particles(&plist, n_particles_type_local, n_particles_type, flag_long_IDs);

    // Read the particles
    process_gadget_file("Performing read...",
                        filename_in_root,
                        snapshot,
                        select_gadget_all,
                        store_gadget_particles,
                        &params,
                        NULL,
                        NULL,
                        &flag_long_IDs,
                        PROCESS_GADGET_BINARY_DEFAULT);

    // Write the snapshot
    if(SID.I_am_Master) {
        char filename_out[SID_MAX_FILENAME_LENGTH];
        sprintf(filename_out, "%s_%03d_%08d.ascii", filename_out_root, snapshot, halo_index);
        FILE *fp = fopen(filename_out, "w");
        fprintf(fp, "#Columns:\n");
        fprintf(fp, "#  1) Gadget particle type\n");
        fprintf(fp, "#  2) x   [Mpc/h]\n");
        fprintf(fp, "#  3) y   [Mpc/h]\n");
        fprintf(fp, "#  4) z   [Mpc/h]\n");
        fprintf(fp, "#  5) v_x [km/s]\n");
        fprintf(fp, "#  6) v_y [km/s]\n");
        fprintf(fp, "#  7) v_z [km/s]\n");
        fprintf(fp, "#  8) id\n");
        int      i_species  = GADGET_TYPE_DARK;
        size_t   n_p        = ((size_t *)ADaPS_fetch(plist.data, "n_%s", plist.species[i_species]))[0];
        GBPREAL *x          = (GBPREAL *)ADaPS_fetch(plist.data, "x_%s", plist.species[i_species]);
        GBPREAL *y          = (GBPREAL *)ADaPS_fetch(plist.data, "y_%s", plist.species[i_species]);
        GBPREAL *z          = (GBPREAL *)ADaPS_fetch(plist.data, "z_%s", plist.species[i_species]);
        GBPREAL *vx         = (GBPREAL *)ADaPS_fetch(plist.data, "vx_%s", plist.species[i_species]);
        GBPREAL *vy         = (GBPREAL *)ADaPS_fetch(plist.data, "vy_%s", plist.species[i_species]);
        GBPREAL *vz         = (GBPREAL *)ADaPS_fetch(plist.data, "vz_%s", plist.species[i_species]);
        size_t * id         = (size_t *)ADaPS_fetch(plist.data, "id_%s", plist.species[i_species]);
        size_t * id_indices = NULL;
        SID_log("Sorting IDs...", SID_LOG_OPEN);
        merge_sort(id, n_p, &id_indices, SID_SIZE_T, SORT_COMPUTE_INDEX, SORT_COMPUTE_NOT_INPLACE);
        SID_log("Done.", SID_LOG_CLOSE);
        SID_log("Writing particles...", SID_LOG_OPEN);
        pcounter_info pcounter;
        SID_Init_pcounter(&pcounter, halo_length, 10);
        int n_unfound = 0;
        for(int i_p = 0; i_p < halo_length; i_p++) {
            size_t k_p = id_indices[find_index(id, id_list_unsorted[i_p], n_p, id_indices)];
            if(id[k_p] != id_list_unsorted[i_p])
                n_unfound++;
            else
                fprintf(fp,
                        "%1d %11.4e %11.4e %11.4e %11.4e %11.4e %11.4e %7zd\n",
                        i_species,
                        (double)(x[k_p]),
                        (double)(y[k_p]),
                        (double)(z[k_p]),
                        (double)(vx[k_p]),
                        (double)(vy[k_p]),
                        (double)(vz[k_p]),
                        id[k_p]);
            SID_check_pcounter(&pcounter, i_p);
        }
        fclose(fp);
        if(n_unfound != 0)
            SID_log("(%d unfound)...", SID_LOG_CONTINUE, n_unfound);
        SID_log("Done.", SID_LOG_CLOSE);
        SID_free(SID_FARG id_indices);
    }

    // Clean-up
    SID_free(SID_FARG id_list_unsorted);
    SID_free(SID_FARG params.id_list);
    free_plist(&plist);

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}
示例#13
0
//! This function is documented in the header file
void nbnxn_gpu_init(gmx_nbnxn_ocl_t          **p_nb,
                    const gmx_device_info_t   *deviceInfo,
                    const interaction_const_t *ic,
                    const NbnxnListParameters *listParams,
                    const nbnxn_atomdata_t    *nbat,
                    int                        rank,
                    gmx_bool                   bLocalAndNonlocal)
{
    gmx_nbnxn_ocl_t            *nb;
    cl_int                      cl_error;
    cl_command_queue_properties queue_properties;

    assert(ic);

    if (p_nb == nullptr)
    {
        return;
    }

    snew(nb, 1);
    snew(nb->atdat, 1);
    snew(nb->nbparam, 1);
    snew(nb->plist[eintLocal], 1);
    if (bLocalAndNonlocal)
    {
        snew(nb->plist[eintNonlocal], 1);
    }

    nb->bUseTwoStreams = static_cast<cl_bool>(bLocalAndNonlocal);

    nb->timers = new cl_timers_t();
    snew(nb->timings, 1);

    /* set device info, just point it to the right GPU among the detected ones */
    nb->dev_info = deviceInfo;
    snew(nb->dev_rundata, 1);

    /* init nbst */
    pmalloc(reinterpret_cast<void**>(&nb->nbst.e_lj), sizeof(*nb->nbst.e_lj));
    pmalloc(reinterpret_cast<void**>(&nb->nbst.e_el), sizeof(*nb->nbst.e_el));
    pmalloc(reinterpret_cast<void**>(&nb->nbst.fshift), SHIFTS * sizeof(*nb->nbst.fshift));

    init_plist(nb->plist[eintLocal]);

    /* OpenCL timing disabled if GMX_DISABLE_GPU_TIMING is defined. */
    nb->bDoTime = static_cast<cl_bool>(getenv("GMX_DISABLE_GPU_TIMING") == nullptr);

    /* Create queues only after bDoTime has been initialized */
    if (nb->bDoTime)
    {
        queue_properties = CL_QUEUE_PROFILING_ENABLE;
    }
    else
    {
        queue_properties = 0;
    }

    nbnxn_gpu_create_context(nb->dev_rundata, nb->dev_info, rank);

    /* local/non-local GPU streams */
    nb->stream[eintLocal] = clCreateCommandQueue(nb->dev_rundata->context, nb->dev_info->ocl_gpu_id.ocl_device_id, queue_properties, &cl_error);
    if (CL_SUCCESS != cl_error)
    {
        gmx_fatal(FARGS, "On rank %d failed to create context for GPU #%s: OpenCL error %d",
                  rank,
                  nb->dev_info->device_name,
                  cl_error);
    }

    if (nb->bUseTwoStreams)
    {
        init_plist(nb->plist[eintNonlocal]);

        nb->stream[eintNonlocal] = clCreateCommandQueue(nb->dev_rundata->context, nb->dev_info->ocl_gpu_id.ocl_device_id, queue_properties, &cl_error);
        if (CL_SUCCESS != cl_error)
        {
            gmx_fatal(FARGS, "On rank %d failed to create context for GPU #%s: OpenCL error %d",
                      rank,
                      nb->dev_info->device_name,
                      cl_error);
        }
    }

    if (nb->bDoTime)
    {
        init_timers(nb->timers, nb->bUseTwoStreams == CL_TRUE);
        init_timings(nb->timings);
    }

    nbnxn_ocl_init_const(nb, ic, listParams, nbat);

    /* Enable LJ param manual prefetch for AMD or Intel or if we request through env. var.
     * TODO: decide about NVIDIA
     */
    nb->bPrefetchLjParam =
        (getenv("GMX_OCL_DISABLE_I_PREFETCH") == nullptr) &&
        ((nb->dev_info->vendor_e == OCL_VENDOR_AMD) || (nb->dev_info->vendor_e == OCL_VENDOR_INTEL)
         || (getenv("GMX_OCL_ENABLE_I_PREFETCH") != nullptr));

    /* NOTE: in CUDA we pick L1 cache configuration for the nbnxn kernels here,
     * but sadly this is not supported in OpenCL (yet?). Consider adding it if
     * it becomes supported.
     */
    nbnxn_gpu_compile_kernels(nb);
    nbnxn_gpu_init_kernels(nb);

    /* clear energy and shift force outputs */
    nbnxn_ocl_clear_e_fshift(nb);

    *p_nb = nb;

    if (debug)
    {
        fprintf(debug, "Initialized OpenCL data structures.\n");
    }
}
示例#14
0
int main(int argc, char *argv[]) {
    SID_Init(&argc, &argv, NULL);

    // Fetch user inputs
    char   filename_halos_root[256];
    char   filename_catalog_root[256];
    char   filename_PHKs_root[256];
    double box_size;
    double dx;
    int    i_file_lo_in;
    int    i_file_hi_in;
    int    i_file_skip;
    strcpy(filename_halos_root, argv[1]);
    strcpy(filename_catalog_root, argv[2]);
    strcpy(filename_PHKs_root, argv[3]);
    box_size     = atof(argv[4]);
    dx           = atof(argv[5]);
    i_file_lo_in = atoi(argv[6]);
    i_file_hi_in = atoi(argv[7]);
    i_file_skip  = atoi(argv[8]);

    int i_file_lo;
    int i_file_hi;
    if(i_file_lo_in < i_file_hi_in) {
        i_file_lo = i_file_lo_in;
        i_file_hi = i_file_hi_in;
    } else {
        i_file_lo = i_file_hi_in;
        i_file_hi = i_file_lo_in;
    }

    SID_log("Generating group PH keys for files #%d->#%d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file_lo, i_file_hi);
    for(int i_file = i_file_lo; i_file <= i_file_hi; i_file += i_file_skip) {
        SID_log("Processing file #%03d...", SID_LOG_OPEN | SID_LOG_TIMER, i_file);
        SID_set_verbosity(SID_SET_VERBOSITY_RELATIVE, 0);

        // Read group info from the halo catalogs
        plist_info plist;
        int *      PHK_group       = NULL;
        size_t *   PHK_group_index = NULL;
        char *     filename_number = (char *)SID_malloc(sizeof(char) * 10);
        init_plist(&plist, NULL, GADGET_LENGTH, GADGET_MASS, GADGET_VELOCITY);
        sprintf(filename_number, "%03d", i_file);
        ADaPS_store(&(plist.data), (void *)filename_number, "read_catalog", ADaPS_DEFAULT);
        read_groups(filename_halos_root, i_file, READ_GROUPS_ALL | READ_GROUPS_MBP_IDS_ONLY, &plist, filename_number);
        int n_groups_all = ((int *)ADaPS_fetch(plist.data, "n_groups_all_%s", filename_number))[0];
        int n_groups     = ((int *)ADaPS_fetch(plist.data, "n_groups_%s", filename_number))[0];

        // If there's any groups to analyze ...
        int *  n_particles_groups     = NULL;
        size_t n_particles_cumulative = 0;
        int    n_bits                 = 0; // Default value if there are no groups
        if(n_groups > 0) {
            // Fetch the halo sizes
            n_particles_groups = (int *)ADaPS_fetch(plist.data, "n_particles_group_%s", filename_number);

            // Read MBP data from halo catalogs
            SID_log("Reading most-bound-particle positions...", SID_LOG_OPEN);
            halo_properties_info group_properties;
            fp_catalog_info      fp_group_properties;
            double *             x_array = (double *)SID_malloc(sizeof(double) * n_groups);
            double *             y_array = (double *)SID_malloc(sizeof(double) * n_groups);
            double *             z_array = (double *)SID_malloc(sizeof(double) * n_groups);
            fopen_catalog(filename_catalog_root, i_file, READ_CATALOG_GROUPS | READ_CATALOG_PROPERTIES, &fp_group_properties);
            if(fp_group_properties.n_halos_total != n_groups)
                SID_exit_error("Halo counts in group files and catalogs don't match (ie. %d!=%d)", SID_ERROR_LOGIC,
                               fp_group_properties.n_halos_total, n_groups);
            for(int i_group = 0; i_group < n_groups; i_group++) {
                fread_catalog_file(&fp_group_properties, NULL, NULL, &group_properties, NULL, i_group);
                x_array[i_group] = group_properties.position_MBP[0];
                y_array[i_group] = group_properties.position_MBP[1];
                z_array[i_group] = group_properties.position_MBP[2];
                // Enforce periodic BCs
                if(x_array[i_group] < 0.)
                    x_array[i_group] += box_size;
                if(x_array[i_group] >= box_size)
                    x_array[i_group] -= box_size;
                if(y_array[i_group] < 0.)
                    y_array[i_group] += box_size;
                if(y_array[i_group] >= box_size)
                    y_array[i_group] -= box_size;
                if(z_array[i_group] < 0.)
                    z_array[i_group] += box_size;
                if(z_array[i_group] >= box_size)
                    z_array[i_group] -= box_size;
            }
            fclose_catalog(&fp_group_properties);
            SID_log("Done.", SID_LOG_CLOSE);

            // Determine the number of bits to use for the PHKs
            for(n_bits = N_BITS_MIN; (box_size / pow(2., (double)(n_bits + 1))) > dx && n_bits <= 20;)
                n_bits++;

            // Compute PHKs
            SID_log("Computing PHKs (using %d bits per dimension)...", SID_LOG_OPEN, n_bits);
            PHK_group = (int *)SID_malloc(sizeof(int) * n_groups);
            for(int i_group = 0; i_group < n_groups; i_group++) {
                // Compute the key for this group
                PHK_group[i_group] = compute_PHK_from_Cartesian(
                    n_bits, 3, (double)x_array[i_group] / box_size, (double)y_array[i_group] / box_size, (double)z_array[i_group] / box_size);
            }
            SID_free(SID_FARG x_array);
            SID_free(SID_FARG y_array);
            SID_free(SID_FARG z_array);
            SID_log("Done.", SID_LOG_CLOSE);

            // Sort PHKs
            SID_log("Sorting PHKs...", SID_LOG_OPEN);
            merge_sort((void *)PHK_group, n_groups, &PHK_group_index, SID_INT, SORT_COMPUTE_INDEX, GBP_FALSE);
            SID_log("Done.", SID_LOG_CLOSE);

            // Count the number of particles
            for(int i_group = 0; i_group < n_groups; i_group++)
                n_particles_cumulative += n_particles_groups[PHK_group_index[i_group]];
        }

        // Write results
        SID_log("Writing results for %d groups...", SID_LOG_OPEN, n_groups);
        char filename_output_properties[256];
        sprintf(filename_output_properties, "%s_%s.catalog_PHKs", filename_PHKs_root, filename_number);
        FILE *fp_PHKs = fopen(filename_output_properties, "w");
        fwrite(&n_groups, sizeof(int), 1, fp_PHKs);
        fwrite(&n_bits, sizeof(int), 1, fp_PHKs);
        fwrite(&n_particles_cumulative, sizeof(size_t), 1, fp_PHKs);
        n_particles_cumulative = 0;
        for(int i_group = 0; i_group < n_groups; i_group++) {
            int index_temp = (int)PHK_group_index[i_group];
            n_particles_cumulative += n_particles_groups[index_temp];
            fwrite(&(PHK_group[index_temp]), sizeof(int), 1, fp_PHKs);
            fwrite(&index_temp, sizeof(int), 1, fp_PHKs);
            fwrite(&n_particles_cumulative, sizeof(size_t), 1, fp_PHKs);
        }
        fclose(fp_PHKs);
        SID_log("Done.", SID_LOG_CLOSE);

        // Clean-up
        free_plist(&plist);
        if(n_groups > 0) {
            SID_free(SID_FARG PHK_group);
            SID_free(SID_FARG PHK_group_index);
        }

        SID_set_verbosity(SID_SET_VERBOSITY_DEFAULT);
        SID_log("Done.", SID_LOG_CLOSE);
    }

    SID_log("Done.", SID_LOG_CLOSE);
    SID_Finalize();
}