Beispiel #1
0
/*! \brief High level ACF routine. */
void do_four_core(unsigned long mode, int nfour, int nf2, int nframes,
                  real c1[], real csum[], real ctmp[])
{
    real   *cfour;
    char    buf[32];
    real    fac;
    int     j, m, m1;

    snew(cfour, nfour);

    if (MODE(eacNormal))
    {
        /********************************************
         *  N O R M A L
         ********************************************/
        low_do_four_core(nfour, nf2, c1, csum, enNorm);
    }
    else if (MODE(eacCos))
    {
        /***************************************************
         * C O S I N E
         ***************************************************/
        /* Copy the data to temp array. Since we need it twice
         * we can't overwrite original.
         */
        for (j = 0; (j < nf2); j++)
        {
            ctmp[j] = c1[j];
        }

        /* Cosine term of AC function */
        low_do_four_core(nfour, nf2, ctmp, cfour, enCos);
        for (j = 0; (j < nf2); j++)
        {
            c1[j]  = cfour[j];
        }

        /* Sine term of AC function */
        low_do_four_core(nfour, nf2, ctmp, cfour, enSin);
        for (j = 0; (j < nf2); j++)
        {
            c1[j]  += cfour[j];
            csum[j] = c1[j];
        }
    }
    else if (MODE(eacP2))
    {
        /***************************************************
         * Legendre polynomials
         ***************************************************/
        /* First normalize the vectors */
        norm_and_scale_vectors(nframes, c1, 1.0);

        /* For P2 thingies we have to do six FFT based correls
         * First for XX^2, then for YY^2, then for ZZ^2
         * Then we have to do XY, YZ and XZ (counting these twice)
         * After that we sum them and normalise
         * P2(x) = (3 * cos^2 (x) - 1)/2
         * for unit vectors u and v we compute the cosine as the inner product
         * cos(u,v) = uX vX + uY vY + uZ vZ
         *
         *        oo
         *        /
         * C(t) = |  (3 cos^2(u(t'),u(t'+t)) - 1)/2 dt'
         *        /
         *        0
         *
         * For ACF we need:
         * P2(u(0),u(t)) = [3 * (uX(0) uX(t) +
         *                       uY(0) uY(t) +
         *                       uZ(0) uZ(t))^2 - 1]/2
         *               = [3 * ((uX(0) uX(t))^2 +
         *                       (uY(0) uY(t))^2 +
         *                       (uZ(0) uZ(t))^2 +
         *                 2(uX(0) uY(0) uX(t) uY(t)) +
         *                 2(uX(0) uZ(0) uX(t) uZ(t)) +
         *                 2(uY(0) uZ(0) uY(t) uZ(t))) - 1]/2
         *
         *               = [(3/2) * (<uX^2> + <uY^2> + <uZ^2> +
         *                         2<uXuY> + 2<uXuZ> + 2<uYuZ>) - 0.5]
         *
         */

        /* Because of normalization the number of -0.5 to subtract
         * depends on the number of data points!
         */
        for (j = 0; (j < nf2); j++)
        {
            csum[j]  = -0.5*(nf2-j);
        }

        /***** DIAGONAL ELEMENTS ************/
        for (m = 0; (m < DIM); m++)
        {
            /* Copy the vector data in a linear array */
            for (j = 0; (j < nf2); j++)
            {
                ctmp[j]  = gmx::square(c1[DIM*j+m]);
            }
            if (debug)
            {
                sprintf(buf, "c1diag%d.xvg", m);
                dump_tmp(buf, nf2, ctmp);
            }

            low_do_four_core(nfour, nf2, ctmp, cfour, enNorm);

            if (debug)
            {
                sprintf(buf, "c1dfout%d.xvg", m);
                dump_tmp(buf, nf2, cfour);
            }
            fac = 1.5;
            for (j = 0; (j < nf2); j++)
            {
                csum[j] += fac*(cfour[j]);
            }
        }
        /******* OFF-DIAGONAL ELEMENTS **********/
        for (m = 0; (m < DIM); m++)
        {
            /* Copy the vector data in a linear array */
            m1 = (m+1) % DIM;
            for (j = 0; (j < nf2); j++)
            {
                ctmp[j] = c1[DIM*j+m]*c1[DIM*j+m1];
            }

            if (debug)
            {
                sprintf(buf, "c1off%d.xvg", m);
                dump_tmp(buf, nf2, ctmp);
            }
            low_do_four_core(nfour, nf2, ctmp, cfour, enNorm);
            if (debug)
            {
                sprintf(buf, "c1ofout%d.xvg", m);
                dump_tmp(buf, nf2, cfour);
            }
            fac = 3.0;
            for (j = 0; (j < nf2); j++)
            {
                csum[j] += fac*cfour[j];
            }
        }
    }
    else if (MODE(eacP1) || MODE(eacVector))
    {
        /***************************************************
         * V E C T O R & P1
         ***************************************************/
        if (MODE(eacP1))
        {
            /* First normalize the vectors */
            norm_and_scale_vectors(nframes, c1, 1.0);
        }

        /* For vector thingies we have to do three FFT based correls
         * First for XX, then for YY, then for ZZ
         * After that we sum them and normalise
         */
        for (j = 0; (j < nf2); j++)
        {
            csum[j] = 0.0;
        }
        for (m = 0; (m < DIM); m++)
        {
            /* Copy the vector data in a linear array */
            for (j = 0; (j < nf2); j++)
            {
                ctmp[j] = c1[DIM*j+m];
            }
            low_do_four_core(nfour, nf2, ctmp, cfour, enNorm);
            for (j = 0; (j < nf2); j++)
            {
                csum[j] += cfour[j];
            }
        }
    }
    else
    {
        gmx_fatal(FARGS, "\nUnknown mode in do_autocorr (%d)", mode);
    }

    sfree(cfour);
    for (j = 0; (j < nf2); j++)
    {
        c1[j] = csum[j]/(real)(nframes-j);
    }
}
Beispiel #2
0
static void free_params(game_params *params)
{
    sfree(params);
}
Beispiel #3
0
static void free_ui(game_ui *ui)
{
    if (ui->sel)
        sfree(ui->sel);
    sfree(ui);
}
Beispiel #4
0
static void make_shake_sblock_pd(struct gmx_constr *constr,
				 t_idef *idef,t_mdatoms *md)
{
  int  i,j,m,ncons;
  int  bstart,bnr;
  t_blocka    sblocks;
  t_sortblock *sb;
  t_iatom     *iatom;
  atom_id     *inv_sblock;

  ncons = idef->il[F_CONSTR].nr/3;

  init_blocka(&sblocks);
  gen_sblocks(NULL,md->start,md->start+md->homenr,idef,&sblocks,FALSE);
  
  /*
    bstart=(idef->nodeid > 0) ? blocks->multinr[idef->nodeid-1] : 0;
    nblocks=blocks->multinr[idef->nodeid] - bstart;
  */
  bstart  = 0;
  constr->nblocks = sblocks.nr;
  if (debug) 
    fprintf(debug,"ncons: %d, bstart: %d, nblocks: %d\n",
	    ncons,bstart,constr->nblocks);
  
  /* Calculate block number for each atom */
  inv_sblock = make_invblocka(&sblocks,md->nr);
  
  done_blocka(&sblocks);
  
  /* Store the block number in temp array and
   * sort the constraints in order of the sblock number 
   * and the atom numbers, really sorting a segment of the array!
   */
#ifdef DEBUGIDEF 
  pr_idef(fplog,0,"Before Sort",idef);
#endif
  iatom=idef->il[F_CONSTR].iatoms;
  snew(sb,ncons);
  for(i=0; (i<ncons); i++,iatom+=3) {
    for(m=0; (m<3); m++)
      sb[i].iatom[m] = iatom[m];
    sb[i].blocknr = inv_sblock[iatom[1]];
  }
  
  /* Now sort the blocks */
  if (debug) {
    pr_sortblock(debug,"Before sorting",ncons,sb);
    fprintf(debug,"Going to sort constraints\n");
  }
  
  qsort(sb,ncons,(size_t)sizeof(*sb),pcomp);
  
  if (debug) {
    fprintf(debug,"I used %d calls to pcomp\n",pcount);
    pr_sortblock(debug,"After sorting",ncons,sb);
  }
  
  iatom=idef->il[F_CONSTR].iatoms;
  for(i=0; (i<ncons); i++,iatom+=3) 
    for(m=0; (m<3); m++)
      iatom[m]=sb[i].iatom[m];
#ifdef DEBUGIDEF
  pr_idef(fplog,0,"After Sort",idef);
#endif
  
  j=0;
  snew(constr->sblock,constr->nblocks+1);
  bnr=-2;
  for(i=0; (i<ncons); i++) {
    if (sb[i].blocknr != bnr) {
      bnr=sb[i].blocknr;
      constr->sblock[j++]=3*i;
    }
  }
  /* Last block... */
  constr->sblock[j++] = 3*ncons;
  
  if (j != (constr->nblocks+1)) {
    fprintf(stderr,"bstart: %d\n",bstart);
    fprintf(stderr,"j: %d, nblocks: %d, ncons: %d\n",
	    j,constr->nblocks,ncons);
    for(i=0; (i<ncons); i++)
      fprintf(stderr,"i: %5d  sb[i].blocknr: %5u\n",i,sb[i].blocknr);
    for(j=0; (j<=constr->nblocks); j++)
      fprintf(stderr,"sblock[%3d]=%5d\n",j,(int)constr->sblock[j]);
    gmx_fatal(FARGS,"DEATH HORROR: "
	      "sblocks does not match idef->il[F_CONSTR]");
  }
  sfree(sb);
  sfree(inv_sblock);
}
Beispiel #5
0
void analyse_ss(const char *outfile, t_matrix *mat, const char *ss_string,
                const output_env_t oenv)
{
    FILE        *fp;
    t_mapping   *map;
    int          f, r, *count, *total, ss_count, total_count;
    size_t       s;
    const char** leg;

    map = mat->map;
    snew(count, mat->nmap);
    snew(total, mat->nmap);
    snew(leg, mat->nmap+1);
    leg[0] = "Structure";
    for (s = 0; s < (size_t)mat->nmap; s++)
    {
        leg[s+1] = gmx_strdup(map[s].desc);
    }

    fp = xvgropen(outfile, "Secondary Structure",
                  output_env_get_xvgr_tlabel(oenv), "Number of Residues", oenv);
    if (output_env_get_print_xvgr_codes(oenv))
    {
        fprintf(fp, "@ subtitle \"Structure = ");
    }
    for (s = 0; s < strlen(ss_string); s++)
    {
        if (s > 0)
        {
            fprintf(fp, " + ");
        }
        for (f = 0; f < mat->nmap; f++)
        {
            if (ss_string[s] == map[f].code.c1)
            {
                fprintf(fp, "%s", map[f].desc);
            }
        }
    }
    fprintf(fp, "\"\n");
    xvgr_legend(fp, mat->nmap+1, leg, oenv);

    total_count = 0;
    for (s = 0; s < (size_t)mat->nmap; s++)
    {
        total[s] = 0;
    }
    for (f = 0; f < mat->nx; f++)
    {
        ss_count = 0;
        for (s = 0; s < (size_t)mat->nmap; s++)
        {
            count[s] = 0;
        }
        for (r = 0; r < mat->ny; r++)
        {
            count[mat->matrix[f][r]]++;
            total[mat->matrix[f][r]]++;
        }
        for (s = 0; s < (size_t)mat->nmap; s++)
        {
            if (strchr(ss_string, map[s].code.c1))
            {
                ss_count    += count[s];
                total_count += count[s];
            }
        }
        fprintf(fp, "%8g %5d", mat->axis_x[f], ss_count);
        for (s = 0; s < (size_t)mat->nmap; s++)
        {
            fprintf(fp, " %5d", count[s]);
        }
        fprintf(fp, "\n");
    }
    /* now print column totals */
    fprintf(fp, "%-8s %5d", "# Totals", total_count);
    for (s = 0; s < (size_t)mat->nmap; s++)
    {
        fprintf(fp, " %5d", total[s]);
    }
    fprintf(fp, "\n");

    /* now print percentages */
    fprintf(fp, "%-8s %5.2f", "# SS %", total_count / (real) (mat->nx * mat->ny));
    for (s = 0; s < (size_t)mat->nmap; s++)
    {
        fprintf(fp, " %5.2f", total[s] / (real) (mat->nx * mat->ny));
    }
    fprintf(fp, "\n");

    gmx_ffclose(fp);
    sfree(leg);
    sfree(count);
}
static void sort_molecule(t_atoms **atoms_solvt, rvec *x, rvec *v, real *r)
{
    int         atnr, i, j, moltp = 0, nrmoltypes, resi_o, resi_n, resnr;
    t_moltypes *moltypes;
    t_atoms    *atoms, *newatoms;
    rvec       *newx, *newv = NULL;
    real       *newr;

    fprintf(stderr, "Sorting configuration\n");

    atoms = *atoms_solvt;

    /* copy each residue from *atoms to a molecule in *molecule */
    moltypes   = NULL;
    nrmoltypes = 0;
    for (i = 0; i < atoms->nr; i++)
    {
        if ( (i == 0) || (atoms->atom[i].resind != atoms->atom[i-1].resind) )
        {
            /* see if this was a molecule type we haven't had yet: */
            moltp = NOTSET;
            for (j = 0; (j < nrmoltypes) && (moltp == NOTSET); j++)
            {
                if (strcmp(*(atoms->resinfo[atoms->atom[i].resind].name),
                           moltypes[j].name) == 0)
                {
                    moltp = j;
                }
            }
            if (moltp == NOTSET)
            {
                moltp = nrmoltypes;
                nrmoltypes++;
                srenew(moltypes, nrmoltypes);
                moltypes[moltp].name = *(atoms->resinfo[atoms->atom[i].resind].name);
                atnr                 = 0;
                while ((i+atnr < atoms->nr) &&
                       (atoms->atom[i].resind == atoms->atom[i+atnr].resind))
                {
                    atnr++;
                }
                moltypes[moltp].natoms = atnr;
                moltypes[moltp].nmol   = 0;
            }
            moltypes[moltp].nmol++;
        }
    }

    fprintf(stderr, "Found %d%s molecule type%s:\n",
            nrmoltypes, nrmoltypes == 1 ? "" : " different", nrmoltypes == 1 ? "" : "s");
    for (j = 0; j < nrmoltypes; j++)
    {
        if (j == 0)
        {
            moltypes[j].res0 = 0;
        }
        else
        {
            moltypes[j].res0 = moltypes[j-1].res0+moltypes[j-1].nmol;
        }
        fprintf(stderr, "%7s (%4d atoms): %5d residues\n",
                moltypes[j].name, moltypes[j].natoms, moltypes[j].nmol);
    }

    /* if we have only 1 moleculetype, we don't have to sort */
    if (nrmoltypes > 1)
    {
        /* find out which molecules should go where: */
        moltypes[0].i = moltypes[0].i0 = 0;
        for (j = 1; j < nrmoltypes; j++)
        {
            moltypes[j].i      =
                moltypes[j].i0 =
                    moltypes[j-1].i0+moltypes[j-1].natoms*moltypes[j-1].nmol;
        }

        /* now put them there: */
        snew(newatoms, 1);
        init_t_atoms(newatoms, atoms->nr, FALSE);
        newatoms->nres = atoms->nres;
        snew(newatoms->resinfo, atoms->nres);
        snew(newx, atoms->nr);
        if (v)
        {
            snew(newv, atoms->nr);
        }
        snew(newr, atoms->nr);

        resi_n = 0;
        resnr  = 1;
        j      = 0;
        for (moltp = 0; moltp < nrmoltypes; moltp++)
        {
            i = 0;
            while (i < atoms->nr)
            {
                resi_o = atoms->atom[i].resind;
                if (strcmp(*atoms->resinfo[resi_o].name, moltypes[moltp].name) == 0)
                {
                    /* Copy the residue info */
                    newatoms->resinfo[resi_n]    = atoms->resinfo[resi_o];
                    newatoms->resinfo[resi_n].nr = resnr;
                    /* Copy the atom info */
                    do
                    {
                        newatoms->atom[j]        = atoms->atom[i];
                        newatoms->atomname[j]    = atoms->atomname[i];
                        newatoms->atom[j].resind = resi_n;
                        copy_rvec(x[i], newx[j]);
                        if (v != NULL)
                        {
                            copy_rvec(v[i], newv[j]);
                        }
                        newr[j] = r[i];
                        i++;
                        j++;
                    }
                    while (i < atoms->nr && atoms->atom[i].resind == resi_o);
                    /* Increase the new residue counters */
                    resi_n++;
                    resnr++;
                }
                else
                {
                    /* Skip this residue */
                    do
                    {
                        i++;
                    }
                    while (i < atoms->nr && atoms->atom[i].resind == resi_o);
                }
            }
        }

        /* put them back into the original arrays and throw away temporary arrays */
        sfree(atoms->atomname);
        sfree(atoms->resinfo);
        sfree(atoms->atom);
        sfree(atoms);
        *atoms_solvt = newatoms;
        for (i = 0; i < (*atoms_solvt)->nr; i++)
        {
            copy_rvec(newx[i], x[i]);
            if (v)
            {
                copy_rvec(newv[i], v[i]);
            }
            r[i] = newr[i];
        }
        sfree(newx);
        if (v)
        {
            sfree(newv);
        }
        sfree(newr);
    }
    sfree(moltypes);
}
Beispiel #7
0
int gmx_genion(int argc, char *argv[])
{
    const char        *desc[] = {
        "[THISMODULE] randomly replaces solvent molecules with monoatomic ions.",
        "The group of solvent molecules should be continuous and all molecules",
        "should have the same number of atoms.",
        "The user should add the ion molecules to the topology file or use",
        "the [TT]-p[tt] option to automatically modify the topology.[PAR]",
        "The ion molecule type, residue and atom names in all force fields",
        "are the capitalized element names without sign. This molecule name",
        "should be given with [TT]-pname[tt] or [TT]-nname[tt], and the",
        "[TT][molecules][tt] section of your topology updated accordingly,",
        "either by hand or with [TT]-p[tt]. Do not use an atom name instead!",
        "[PAR]Ions which can have multiple charge states get the multiplicity",
        "added, without sign, for the uncommon states only.[PAR]",
        "For larger ions, e.g. sulfate we recommended using [gmx-insert-molecules]."
    };
    const char        *bugs[] = {
        "If you specify a salt concentration existing ions are not taken into "
        "account. In effect you therefore specify the amount of salt to be added.",
    };
    static int         p_num    = 0, n_num = 0, p_q = 1, n_q = -1;
    static const char *p_name   = "NA", *n_name = "CL";
    static real        rmin     = 0.6, conc = 0;
    static int         seed     = 1993;
    static gmx_bool    bNeutral = FALSE;
    static t_pargs     pa[]     = {
        { "-np",    FALSE, etINT,  {&p_num}, "Number of positive ions"       },
        { "-pname", FALSE, etSTR,  {&p_name}, "Name of the positive ion"      },
        { "-pq",    FALSE, etINT,  {&p_q},   "Charge of the positive ion"    },
        { "-nn",    FALSE, etINT,  {&n_num}, "Number of negative ions"       },
        { "-nname", FALSE, etSTR,  {&n_name}, "Name of the negative ion"      },
        { "-nq",    FALSE, etINT,  {&n_q},   "Charge of the negative ion"    },
        { "-rmin",  FALSE, etREAL, {&rmin},  "Minimum distance between ions" },
        { "-seed",  FALSE, etINT,  {&seed},  "Seed for random number generator" },
        { "-conc",  FALSE, etREAL, {&conc},
          "Specify salt concentration (mol/liter). This will add sufficient ions to reach up to the specified concentration as computed from the volume of the cell in the input [REF].tpr[ref] file. Overrides the [TT]-np[tt] and [TT]-nn[tt] options." },
        { "-neutral", FALSE, etBOOL, {&bNeutral}, "This option will add enough ions to neutralize the system. These ions are added on top of those specified with [TT]-np[tt]/[TT]-nn[tt] or [TT]-conc[tt]. "}
    };
    t_topology         top;
    rvec              *x, *v;
    real               vol, qtot;
    matrix             box;
    t_atoms            atoms;
    t_pbc              pbc;
    int               *repl, ePBC;
    atom_id           *index;
    char              *grpname;
    gmx_bool          *bSet;
    int                i, nw, nwa, nsa, nsalt, iqtot;
    gmx_output_env_t  *oenv;
    gmx_rng_t          rng;
    t_filenm           fnm[] = {
        { efTPR, NULL,  NULL,      ffREAD  },
        { efNDX, NULL,  NULL,      ffOPTRD },
        { efSTO, "-o",  NULL,      ffWRITE },
        { efTOP, "-p",  "topol",   ffOPTRW }
    };
#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa,
                           asize(desc), desc, asize(bugs), bugs, &oenv))
    {
        return 0;
    }

    /* Check input for something sensible */
    if ((p_num < 0) || (n_num < 0))
    {
        gmx_fatal(FARGS, "Negative number of ions to add?");
    }

    if (conc > 0 && (p_num > 0 || n_num > 0))
    {
        fprintf(stderr, "WARNING: -conc specified, overriding -nn and -np.\n");
    }

    /* Read atom positions and charges */
    read_tps_conf(ftp2fn(efTPR, NFILE, fnm), &top, &ePBC, &x, &v, box, FALSE);
    atoms = top.atoms;

    /* Compute total charge */
    qtot = 0;
    for (i = 0; (i < atoms.nr); i++)
    {
        qtot += atoms.atom[i].q;
    }
    iqtot = std::round(qtot);


    if (conc > 0)
    {
        /* Compute number of ions to be added */
        vol   = det(box);
        nsalt = std::round(conc*vol*AVOGADRO/1e24);
        p_num = abs(nsalt*n_q);
        n_num = abs(nsalt*p_q);
    }
    if (bNeutral)
    {
        int qdelta = p_num*p_q + n_num*n_q + iqtot;

        /* Check if the system is neutralizable
         * is (qdelta == p_q*p_num + n_q*n_num) solvable for p_num and n_num? */
        int gcd = gmx_greatest_common_divisor(n_q, p_q);
        if ((qdelta % gcd) != 0)
        {
            gmx_fatal(FARGS, "Can't neutralize this system using -nq %d and"
                      " -pq %d.\n", n_q, p_q);
        }

        while (qdelta != 0)
        {
            while (qdelta < 0)
            {
                p_num++;
                qdelta += p_q;
            }
            while (qdelta > 0)
            {
                n_num++;
                qdelta += n_q;
            }
        }
    }

    if ((p_num == 0) && (n_num == 0))
    {
        fprintf(stderr, "No ions to add, will just copy input configuration.\n");
    }
    else
    {
        printf("Will try to add %d %s ions and %d %s ions.\n",
               p_num, p_name, n_num, n_name);
        printf("Select a continuous group of solvent molecules\n");
        get_index(&atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, &nwa, &index, &grpname);
        for (i = 1; i < nwa; i++)
        {
            if (index[i] != index[i-1]+1)
            {
                gmx_fatal(FARGS, "The solvent group %s is not continuous: "
                          "index[%d]=%d, index[%d]=%d",
                          grpname, i, index[i-1]+1, i+1, index[i]+1);
            }
        }
        nsa = 1;
        while ((nsa < nwa) &&
               (atoms.atom[index[nsa]].resind ==
                atoms.atom[index[nsa-1]].resind))
        {
            nsa++;
        }
        if (nwa % nsa)
        {
            gmx_fatal(FARGS, "Your solvent group size (%d) is not a multiple of %d",
                      nwa, nsa);
        }
        nw = nwa/nsa;
        fprintf(stderr, "Number of (%d-atomic) solvent molecules: %d\n", nsa, nw);
        if (p_num+n_num > nw)
        {
            gmx_fatal(FARGS, "Not enough solvent for adding ions");
        }

        if (opt2bSet("-p", NFILE, fnm))
        {
            update_topol(opt2fn("-p", NFILE, fnm), p_num, n_num, p_name, n_name, grpname);
        }

        snew(bSet, nw);
        snew(repl, nw);

        snew(v, atoms.nr);
        snew(atoms.pdbinfo, atoms.nr);

        set_pbc(&pbc, ePBC, box);

        if (seed == 0)
        {
            rng = gmx_rng_init(gmx_rng_make_seed());
        }
        else
        {
            rng = gmx_rng_init(seed);
        }
        /* Now loop over the ions that have to be placed */
        while (p_num-- > 0)
        {
            insert_ion(nsa, &nw, bSet, repl, index, x, &pbc,
                       1, p_q, p_name, &atoms, rmin, rng);
        }
        while (n_num-- > 0)
        {
            insert_ion(nsa, &nw, bSet, repl, index, x, &pbc,
                       -1, n_q, n_name, &atoms, rmin, rng);
        }
        gmx_rng_destroy(rng);
        fprintf(stderr, "\n");

        if (nw)
        {
            sort_ions(nsa, nw, repl, index, &atoms, x, p_name, n_name);
        }

        sfree(atoms.pdbinfo);
        atoms.pdbinfo = NULL;
    }
    write_sto_conf(ftp2fn(efSTO, NFILE, fnm), *top.name, &atoms, x, NULL, ePBC, box);

    return 0;
}
Beispiel #8
0
static int statsd_network_init(struct pollfd **ret_fds, /* {{{ */
                               size_t *ret_fds_num) {
  struct pollfd *fds = NULL;
  size_t fds_num = 0;

  struct addrinfo *ai_list;
  int status;

  char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
  char const *service =
      (conf_service != NULL) ? conf_service : STATSD_DEFAULT_SERVICE;

  struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
                              .ai_flags = AI_PASSIVE | AI_ADDRCONFIG,
                              .ai_socktype = SOCK_DGRAM};

  status = getaddrinfo(node, service, &ai_hints, &ai_list);
  if (status != 0) {
    ERROR("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s", node,
          service, gai_strerror(status));
    return status;
  }

  for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
       ai_ptr = ai_ptr->ai_next) {
    int fd;
    struct pollfd *tmp;

    char str_node[NI_MAXHOST];
    char str_service[NI_MAXSERV];

    fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
    if (fd < 0) {
      ERROR("statsd plugin: socket(2) failed: %s", STRERRNO);
      continue;
    }

    /* allow multiple sockets to use the same PORT number */
    int yes = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
      ERROR("statsd plugin: setsockopt (reuseaddr): %s", STRERRNO);
      close(fd);
      continue;
    }

    getnameinfo(ai_ptr->ai_addr, ai_ptr->ai_addrlen, str_node, sizeof(str_node),
                str_service, sizeof(str_service),
                NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
    DEBUG("statsd plugin: Trying to bind to [%s]:%s ...", str_node,
          str_service);

    status = bind(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
    if (status != 0) {
      ERROR("statsd plugin: bind(2) to [%s]:%s failed: %s", str_node,
            str_service, STRERRNO);
      close(fd);
      continue;
    }

    tmp = realloc(fds, sizeof(*fds) * (fds_num + 1));
    if (tmp == NULL) {
      ERROR("statsd plugin: realloc failed.");
      close(fd);
      continue;
    }
    fds = tmp;
    tmp = fds + fds_num;
    fds_num++;

    memset(tmp, 0, sizeof(*tmp));
    tmp->fd = fd;
    tmp->events = POLLIN | POLLPRI;
    INFO("statsd plugin: Listening on [%s]:%s.", str_node, str_service);
  }

  freeaddrinfo(ai_list);

  if (fds_num == 0) {
    ERROR("statsd plugin: Unable to create listening socket for [%s]:%s.",
          (node != NULL) ? node : "::", service);
    return ENOENT;
  }

  *ret_fds = fds;
  *ret_fds_num = fds_num;
  return 0;
} /* }}} int statsd_network_init */

static void *statsd_network_thread(void *args) /* {{{ */
{
  struct pollfd *fds = NULL;
  size_t fds_num = 0;
  int status;

  status = statsd_network_init(&fds, &fds_num);
  if (status != 0) {
    ERROR("statsd plugin: Unable to open listening sockets.");
    pthread_exit((void *)0);
  }

  while (!network_thread_shutdown) {
    status = poll(fds, (nfds_t)fds_num, /* timeout = */ -1);
    if (status < 0) {

      if ((errno == EINTR) || (errno == EAGAIN))
        continue;

      ERROR("statsd plugin: poll(2) failed: %s", STRERRNO);
      break;
    }

    for (size_t i = 0; i < fds_num; i++) {
      if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
        continue;

      statsd_network_read(fds[i].fd);
      fds[i].revents = 0;
    }
  } /* while (!network_thread_shutdown) */

  /* Clean up */
  for (size_t i = 0; i < fds_num; i++)
    close(fds[i].fd);
  sfree(fds);

  return (void *)0;
} /* }}} void *statsd_network_thread */

static int statsd_config_timer_percentile(oconfig_item_t *ci) /* {{{ */
{
  double percent = NAN;
  double *tmp;
  int status;

  status = cf_util_get_double(ci, &percent);
  if (status != 0)
    return status;

  if ((percent <= 0.0) || (percent >= 100)) {
    ERROR("statsd plugin: The value for \"%s\" must be between 0 and 100, "
          "exclusively.",
          ci->key);
    return ERANGE;
  }

  tmp =
      realloc(conf_timer_percentile,
              sizeof(*conf_timer_percentile) * (conf_timer_percentile_num + 1));
  if (tmp == NULL) {
    ERROR("statsd plugin: realloc failed.");
    return ENOMEM;
  }
  conf_timer_percentile = tmp;
  conf_timer_percentile[conf_timer_percentile_num] = percent;
  conf_timer_percentile_num++;

  return 0;
} /* }}} int statsd_config_timer_percentile */
Beispiel #9
0
int gmx_traj(int argc, char *argv[])
{
    const char     *desc[] = {
        "[THISMODULE] plots coordinates, velocities, forces and/or the box.",
        "With [TT]-com[tt] the coordinates, velocities and forces are",
        "calculated for the center of mass of each group.",
        "When [TT]-mol[tt] is set, the numbers in the index file are",
        "interpreted as molecule numbers and the same procedure as with",
        "[TT]-com[tt] is used for each molecule.[PAR]",
        "Option [TT]-ot[tt] plots the temperature of each group,",
        "provided velocities are present in the trajectory file.",
        "No corrections are made for constrained degrees of freedom!",
        "This implies [TT]-com[tt].[PAR]",
        "Options [TT]-ekt[tt] and [TT]-ekr[tt] plot the translational and",
        "rotational kinetic energy of each group,",
        "provided velocities are present in the trajectory file.",
        "This implies [TT]-com[tt].[PAR]",
        "Options [TT]-cv[tt] and [TT]-cf[tt] write the average velocities",
        "and average forces as temperature factors to a [TT].pdb[tt] file with",
        "the average coordinates or the coordinates at [TT]-ctime[tt].",
        "The temperature factors are scaled such that the maximum is 10.",
        "The scaling can be changed with the option [TT]-scale[tt].",
        "To get the velocities or forces of one",
        "frame set both [TT]-b[tt] and [TT]-e[tt] to the time of",
        "desired frame. When averaging over frames you might need to use",
        "the [TT]-nojump[tt] option to obtain the correct average coordinates.",
        "If you select either of these option the average force and velocity",
        "for each atom are written to an [TT].xvg[tt] file as well",
        "(specified with [TT]-av[tt] or [TT]-af[tt]).[PAR]",
        "Option [TT]-vd[tt] computes a velocity distribution, i.e. the",
        "norm of the vector is plotted. In addition in the same graph",
        "the kinetic energy distribution is given."
    };
    static gmx_bool bMol    = FALSE, bCom = FALSE, bPBC = TRUE, bNoJump = FALSE;
    static gmx_bool bX      = TRUE, bY = TRUE, bZ = TRUE, bNorm = FALSE, bFP = FALSE;
    static int      ngroups = 1;
    static real     ctime   = -1, scale = 0, binwidth = 1;
    t_pargs         pa[]    = {
        { "-com", FALSE, etBOOL, {&bCom},
          "Plot data for the com of each group" },
        { "-pbc", FALSE, etBOOL, {&bPBC},
          "Make molecules whole for COM" },
        { "-mol", FALSE, etBOOL, {&bMol},
          "Index contains molecule numbers iso atom numbers" },
        { "-nojump", FALSE, etBOOL, {&bNoJump},
          "Remove jumps of atoms across the box" },
        { "-x", FALSE, etBOOL, {&bX},
          "Plot X-component" },
        { "-y", FALSE, etBOOL, {&bY},
          "Plot Y-component" },
        { "-z", FALSE, etBOOL, {&bZ},
          "Plot Z-component" },
        { "-ng",       FALSE, etINT, {&ngroups},
          "Number of groups to consider" },
        { "-len", FALSE, etBOOL, {&bNorm},
          "Plot vector length" },
        { "-fp", FALSE, etBOOL, {&bFP},
          "Full precision output" },
        { "-bin", FALSE, etREAL, {&binwidth},
          "Binwidth for velocity histogram (nm/ps)" },
        { "-ctime", FALSE, etREAL, {&ctime},
          "Use frame at this time for x in [TT]-cv[tt] and [TT]-cf[tt] instead of the average x" },
        { "-scale", FALSE, etREAL, {&scale},
          "Scale factor for [TT].pdb[tt] output, 0 is autoscale" }
    };
    FILE           *outx   = NULL, *outv = NULL, *outf = NULL, *outb = NULL, *outt = NULL;
    FILE           *outekt = NULL, *outekr = NULL;
    t_topology      top;
    int             ePBC;
    real           *mass, time;
    char            title[STRLEN];
    const char     *indexfn;
    t_trxframe      fr, frout;
    int             flags, nvhisto = 0, *vhisto = NULL;
    rvec           *xtop, *xp = NULL;
    rvec           *sumx = NULL, *sumv = NULL, *sumf = NULL;
    matrix          topbox;
    t_trxstatus    *status;
    t_trxstatus    *status_out = NULL;
    gmx_rmpbc_t     gpbc       = NULL;
    int             i, j, n;
    int             nr_xfr, nr_vfr, nr_ffr;
    char          **grpname;
    int            *isize0, *isize;
    atom_id       **index0, **index;
    atom_id        *atndx;
    t_block        *mols;
    gmx_bool        bTop, bOX, bOXT, bOV, bOF, bOB, bOT, bEKT, bEKR, bCV, bCF;
    gmx_bool        bDim[4], bDum[4], bVD;
    char           *sffmt, sffmt6[1024];
    const char     *box_leg[6] = { "XX", "YY", "ZZ", "YX", "ZX", "ZY" };
    output_env_t    oenv;

    t_filenm        fnm[] = {
        { efTRX, "-f", NULL, ffREAD },
        { efTPS, NULL, NULL, ffREAD },
        { efNDX, NULL, NULL, ffOPTRD },
        { efXVG, "-ox", "coord.xvg", ffOPTWR },
        { efTRX, "-oxt", "coord.xtc", ffOPTWR },
        { efXVG, "-ov", "veloc.xvg", ffOPTWR },
        { efXVG, "-of", "force.xvg", ffOPTWR },
        { efXVG, "-ob", "box.xvg",   ffOPTWR },
        { efXVG, "-ot", "temp.xvg",  ffOPTWR },
        { efXVG, "-ekt", "ektrans.xvg", ffOPTWR },
        { efXVG, "-ekr", "ekrot.xvg", ffOPTWR },
        { efXVG, "-vd", "veldist.xvg", ffOPTWR },
        { efPDB, "-cv", "veloc.pdb", ffOPTWR },
        { efPDB, "-cf", "force.pdb", ffOPTWR },
        { efXVG, "-av", "all_veloc.xvg", ffOPTWR },
        { efXVG, "-af", "all_force.xvg", ffOPTWR }
    };
#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv,
                           PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW | PCA_BE_NICE,
                           NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }

    if (bMol)
    {
        fprintf(stderr, "Interpreting indexfile entries as molecules.\n"
                "Using center of mass.\n");
    }

    bOX  = opt2bSet("-ox", NFILE, fnm);
    bOXT = opt2bSet("-oxt", NFILE, fnm);
    bOV  = opt2bSet("-ov", NFILE, fnm);
    bOF  = opt2bSet("-of", NFILE, fnm);
    bOB  = opt2bSet("-ob", NFILE, fnm);
    bOT  = opt2bSet("-ot", NFILE, fnm);
    bEKT = opt2bSet("-ekt", NFILE, fnm);
    bEKR = opt2bSet("-ekr", NFILE, fnm);
    bCV  = opt2bSet("-cv", NFILE, fnm) || opt2bSet("-av", NFILE, fnm);
    bCF  = opt2bSet("-cf", NFILE, fnm) || opt2bSet("-af", NFILE, fnm);
    bVD  = opt2bSet("-vd", NFILE, fnm) || opt2parg_bSet("-bin", asize(pa), pa);
    if (bMol || bOT || bEKT || bEKR)
    {
        bCom = TRUE;
    }

    bDim[XX]  = bX;
    bDim[YY]  = bY;
    bDim[ZZ]  = bZ;
    bDim[DIM] = bNorm;

    if (bFP)
    {
        sffmt = "\t" gmx_real_fullprecision_pfmt;
    }
    else
    {
        sffmt = "\t%g";
    }
    sprintf(sffmt6, "%s%s%s%s%s%s", sffmt, sffmt, sffmt, sffmt, sffmt, sffmt);

    bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm), title, &top, &ePBC,
                         &xtop, NULL, topbox,
                         bCom && (bOX || bOXT || bOV || bOT || bEKT || bEKR));
    sfree(xtop);
    if ((bMol || bCV || bCF) && !bTop)
    {
        gmx_fatal(FARGS, "Need a run input file for option -mol, -cv or -cf");
    }

    if (bMol)
    {
        indexfn = ftp2fn(efNDX, NFILE, fnm);
    }
    else
    {
        indexfn = ftp2fn_null(efNDX, NFILE, fnm);
    }

    if (!(bCom && !bMol))
    {
        ngroups = 1;
    }
    snew(grpname, ngroups);
    snew(isize0, ngroups);
    snew(index0, ngroups);
    get_index(&(top.atoms), indexfn, ngroups, isize0, index0, grpname);

    if (bMol)
    {
        mols    = &(top.mols);
        atndx   = mols->index;
        ngroups = isize0[0];
        snew(isize, ngroups);
        snew(index, ngroups);
        for (i = 0; i < ngroups; i++)
        {
            if (index0[0][i] < 0 || index0[0][i] >= mols->nr)
            {
                gmx_fatal(FARGS, "Molecule index (%d) is out of range (%d-%d)",
                          index0[0][i]+1, 1, mols->nr);
            }
            isize[i] = atndx[index0[0][i]+1] - atndx[index0[0][i]];
            snew(index[i], isize[i]);
            for (j = 0; j < isize[i]; j++)
            {
                index[i][j] = atndx[index0[0][i]] + j;
            }
        }
    }
    else
    {
        isize = isize0;
        index = index0;
    }
    if (bCom)
    {
        snew(mass, top.atoms.nr);
        for (i = 0; i < top.atoms.nr; i++)
        {
            mass[i] = top.atoms.atom[i].m;
        }
    }
    else
    {
        mass = NULL;
    }

    flags = 0;
    if (bOX)
    {
        flags = flags | TRX_READ_X;
        outx  = xvgropen(opt2fn("-ox", NFILE, fnm),
                         bCom ? "Center of mass" : "Coordinate",
                         output_env_get_xvgr_tlabel(oenv), "Coordinate (nm)", oenv);
        make_legend(outx, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOXT)
    {
        flags      = flags | TRX_READ_X;
        status_out = open_trx(opt2fn("-oxt", NFILE, fnm), "w");
    }
    if (bOV)
    {
        flags = flags | TRX_READ_V;
        outv  = xvgropen(opt2fn("-ov", NFILE, fnm),
                         bCom ? "Center of mass velocity" : "Velocity",
                         output_env_get_xvgr_tlabel(oenv), "Velocity (nm/ps)", oenv);
        make_legend(outv, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOF)
    {
        flags = flags | TRX_READ_F;
        outf  = xvgropen(opt2fn("-of", NFILE, fnm), "Force",
                         output_env_get_xvgr_tlabel(oenv), "Force (kJ mol\\S-1\\N nm\\S-1\\N)",
                         oenv);
        make_legend(outf, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOB)
    {
        outb = xvgropen(opt2fn("-ob", NFILE, fnm), "Box vector elements",
                        output_env_get_xvgr_tlabel(oenv), "(nm)", oenv);

        xvgr_legend(outb, 6, box_leg, oenv);
    }
    if (bOT)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_V;
        outt      = xvgropen(opt2fn("-ot", NFILE, fnm), "Temperature",
                             output_env_get_xvgr_tlabel(oenv), "(K)", oenv);
        make_legend(outt, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bEKT)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_V;
        outekt    = xvgropen(opt2fn("-ekt", NFILE, fnm), "Center of mass translation",
                             output_env_get_xvgr_tlabel(oenv), "Energy (kJ mol\\S-1\\N)", oenv);
        make_legend(outekt, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bEKR)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_X | TRX_READ_V;
        outekr    = xvgropen(opt2fn("-ekr", NFILE, fnm), "Center of mass rotation",
                             output_env_get_xvgr_tlabel(oenv), "Energy (kJ mol\\S-1\\N)", oenv);
        make_legend(outekr, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bVD)
    {
        flags = flags | TRX_READ_V;
    }
    if (bCV)
    {
        flags = flags | TRX_READ_X | TRX_READ_V;
    }
    if (bCF)
    {
        flags = flags | TRX_READ_X | TRX_READ_F;
    }
    if ((flags == 0) && !bOB)
    {
        fprintf(stderr, "Please select one or more output file options\n");
        exit(0);
    }

    read_first_frame(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &fr, flags);

    if (bCV || bCF)
    {
        snew(sumx, fr.natoms);
    }
    if (bCV)
    {
        snew(sumv, fr.natoms);
    }
    if (bCF)
    {
        snew(sumf, fr.natoms);
    }
    nr_xfr = 0;
    nr_vfr = 0;
    nr_ffr = 0;

    if (bCom && bPBC)
    {
        gpbc = gmx_rmpbc_init(&top.idef, ePBC, fr.natoms);
    }

    do
    {
        time = output_env_conv_time(oenv, fr.time);

        if (fr.bX && bNoJump && fr.bBox)
        {
            if (xp)
            {
                remove_jump(fr.box, fr.natoms, xp, fr.x);
            }
            else
            {
                snew(xp, fr.natoms);
            }
            for (i = 0; i < fr.natoms; i++)
            {
                copy_rvec(fr.x[i], xp[i]);
            }
        }

        if (fr.bX && bCom && bPBC)
        {
            gmx_rmpbc_trxfr(gpbc, &fr);
        }

        if (bVD && fr.bV)
        {
            update_histo(isize[0], index[0], fr.v, &nvhisto, &vhisto, binwidth);
        }

        if (bOX && fr.bX)
        {
            print_data(outx, time, fr.x, mass, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOXT && fr.bX)
        {
            frout = fr;
            if (!frout.bAtoms)
            {
                frout.atoms  = &top.atoms;
                frout.bAtoms = TRUE;
            }
            write_trx_x(status_out, &frout, mass, bCom, ngroups, isize, index);
        }
        if (bOV && fr.bV)
        {
            print_data(outv, time, fr.v, mass, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOF && fr.bF)
        {
            print_data(outf, time, fr.f, NULL, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOB && fr.bBox)
        {
            fprintf(outb, "\t%g", fr.time);
            fprintf(outb, sffmt6,
                    fr.box[XX][XX], fr.box[YY][YY], fr.box[ZZ][ZZ],
                    fr.box[YY][XX], fr.box[ZZ][XX], fr.box[ZZ][YY]);
            fprintf(outb, "\n");
        }
        if (bOT && fr.bV)
        {
            fprintf(outt, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outt, sffmt, temp(fr.v, mass, isize[i], index[i]));
            }
            fprintf(outt, "\n");
        }
        if (bEKT && fr.bV)
        {
            fprintf(outekt, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outekt, sffmt, ektrans(fr.v, mass, isize[i], index[i]));
            }
            fprintf(outekt, "\n");
        }
        if (bEKR && fr.bX && fr.bV)
        {
            fprintf(outekr, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outekr, sffmt, ekrot(fr.x, fr.v, mass, isize[i], index[i]));
            }
            fprintf(outekr, "\n");
        }
        if ((bCV || bCF) && fr.bX &&
            (ctime < 0 || (fr.time >= ctime*0.999999 &&
                           fr.time <= ctime*1.000001)))
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumx[i], fr.x[i]);
            }
            nr_xfr++;
        }
        if (bCV && fr.bV)
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumv[i], fr.v[i]);
            }
            nr_vfr++;
        }
        if (bCF && fr.bF)
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumf[i], fr.f[i]);
            }
            nr_ffr++;
        }

    }
    while (read_next_frame(oenv, status, &fr));

    if (gpbc != NULL)
    {
        gmx_rmpbc_done(gpbc);
    }

    /* clean up a bit */
    close_trj(status);

    if (bOX)
    {
        ffclose(outx);
    }
    if (bOXT)
    {
        close_trx(status_out);
    }
    if (bOV)
    {
        ffclose(outv);
    }
    if (bOF)
    {
        ffclose(outf);
    }
    if (bOB)
    {
        ffclose(outb);
    }
    if (bOT)
    {
        ffclose(outt);
    }
    if (bEKT)
    {
        ffclose(outekt);
    }
    if (bEKR)
    {
        ffclose(outekr);
    }

    if (bVD)
    {
        print_histo(opt2fn("-vd", NFILE, fnm), nvhisto, vhisto, binwidth, oenv);
    }

    if (bCV || bCF)
    {
        if (nr_xfr > 1)
        {
            if (ePBC != epbcNONE && !bNoJump)
            {
                fprintf(stderr, "\nWARNING: More than one frame was used for option -cv or -cf\n"
                        "If atoms jump across the box you should use the -nojump or -ctime option\n\n");
            }
            for (i = 0; i < isize[0]; i++)
            {
                svmul(1.0/nr_xfr, sumx[index[0][i]], sumx[index[0][i]]);
            }
        }
        else if (nr_xfr == 0)
        {
            fprintf(stderr, "\nWARNING: No coordinate frames found for option -cv or -cf\n\n");
        }
    }
    if (bCV)
    {
        write_pdb_bfac(opt2fn("-cv", NFILE, fnm),
                       opt2fn("-av", NFILE, fnm), "average velocity", &(top.atoms),
                       ePBC, topbox, isize[0], index[0], nr_xfr, sumx,
                       nr_vfr, sumv, bDim, scale, oenv);
    }
    if (bCF)
    {
        write_pdb_bfac(opt2fn("-cf", NFILE, fnm),
                       opt2fn("-af", NFILE, fnm), "average force", &(top.atoms),
                       ePBC, topbox, isize[0], index[0], nr_xfr, sumx,
                       nr_ffr, sumf, bDim, scale, oenv);
    }

    /* view it */
    view_all(oenv, NFILE, fnm);

    return 0;
}
Beispiel #10
0
/*
 * Helper function to parse a comma-separated list of strings into
 * a preference list array of values. Any missing values are added
 * to the end and duplicates are weeded.
 * XXX: assumes vals in 'mapping' are small +ve integers
 */
static void gprefs(void *sesskey, char *name, char *def,
		   const struct keyvalwhere *mapping, int nvals,
		   Conf *conf, int primary)
{
    char *commalist;
    char *p, *q;
    int i, j, n, v, pos;
    unsigned long seen = 0;	       /* bitmap for weeding dups etc */

    /*
     * Fetch the string which we'll parse as a comma-separated list.
     */
    commalist = gpps_raw(sesskey, name, def);

    /*
     * Go through that list and convert it into values.
     */
    n = 0;
    p = commalist;
    while (1) {
        while (*p && *p == ',') p++;
        if (!*p)
            break;                     /* no more words */

        q = p;
        while (*p && *p != ',') p++;
        if (*p) *p++ = '\0';

        v = key2val(mapping, nvals, q);
        if (v != -1 && !(seen & (1 << v))) {
	    seen |= (1 << v);
            conf_set_int_int(conf, primary, n, v);
            n++;
	}
    }

    sfree(commalist);

    /*
     * Now go through 'mapping' and add values that weren't mentioned
     * in the list we fetched. We may have to loop over it multiple
     * times so that we add values before other values whose default
     * positions depend on them.
     */
    while (n < nvals) {
        for (i = 0; i < nvals; i++) {
	    assert(mapping[i].v < 32);

	    if (!(seen & (1 << mapping[i].v))) {
                /*
                 * This element needs adding. But can we add it yet?
                 */
                if (mapping[i].vrel != -1 && !(seen & (1 << mapping[i].vrel)))
                    continue;          /* nope */

                /*
                 * OK, we can work out where to add this element, so
                 * do so.
                 */
                if (mapping[i].vrel == -1) {
                    pos = (mapping[i].where < 0 ? n : 0);
                } else {
                    for (j = 0; j < n; j++)
                        if (conf_get_int_int(conf, primary, j) ==
                            mapping[i].vrel)
                            break;
                    assert(j < n);     /* implied by (seen & (1<<vrel)) */
                    pos = (mapping[i].where < 0 ? j : j+1);
                }

                /*
                 * And add it.
                 */
                for (j = n-1; j >= pos; j--)
                    conf_set_int_int(conf, primary, j+1,
                                     conf_get_int_int(conf, primary, j));
                conf_set_int_int(conf, primary, pos, mapping[i].v);
                n++;
            }
        }
    }
}
Beispiel #11
0
void load_open_settings(void *sesskey, Conf *conf)
{
    int i;
    char *prot;

    conf_set_int(conf, CONF_ssh_subsys, 0);   /* FIXME: load this properly */
    conf_set_str(conf, CONF_remote_cmd, "");
    conf_set_str(conf, CONF_remote_cmd2, "");
    conf_set_str(conf, CONF_ssh_nc_host, "");

    gpps(sesskey, "HostName", "", conf, CONF_host);
    gppfile(sesskey, "LogFileName", conf, CONF_logfilename);
    gppi(sesskey, "LogType", 0, conf, CONF_logtype);
    gppi(sesskey, "LogFileClash", LGXF_ASK, conf, CONF_logxfovr);
    gppi(sesskey, "LogFlush", 1, conf, CONF_logflush);
    gppi(sesskey, "SSHLogOmitPasswords", 1, conf, CONF_logomitpass);
    gppi(sesskey, "SSHLogOmitData", 0, conf, CONF_logomitdata);

    prot = gpps_raw(sesskey, "Protocol", "default");
    conf_set_int(conf, CONF_protocol, default_protocol);
    conf_set_int(conf, CONF_port, default_port);
    {
	const Backend *b = backend_from_name(prot);
	if (b) {
	    conf_set_int(conf, CONF_protocol, b->protocol);
	    gppi(sesskey, "PortNumber", default_port, conf, CONF_port);
	}
    }
    sfree(prot);

    /* Address family selection */
    gppi(sesskey, "AddressFamily", ADDRTYPE_UNSPEC, conf, CONF_addressfamily);

    /* The CloseOnExit numbers are arranged in a different order from
     * the standard FORCE_ON / FORCE_OFF / AUTO. */
    i = gppi_raw(sesskey, "CloseOnExit", 1); conf_set_int(conf, CONF_close_on_exit, (i+1)%3);
    gppi(sesskey, "WarnOnClose", 1, conf, CONF_warn_on_close);
    {
	/* This is two values for backward compatibility with 0.50/0.51 */
	int pingmin, pingsec;
	pingmin = gppi_raw(sesskey, "PingInterval", 0);
	pingsec = gppi_raw(sesskey, "PingIntervalSecs", 0);
	conf_set_int(conf, CONF_ping_interval, pingmin * 60 + pingsec);
    }
    gppi(sesskey, "TCPNoDelay", 1, conf, CONF_tcp_nodelay);
    gppi(sesskey, "TCPKeepalives", 0, conf, CONF_tcp_keepalives);
    gpps(sesskey, "TerminalType", "xterm", conf, CONF_termtype);
    gpps(sesskey, "TerminalSpeed", "38400,38400", conf, CONF_termspeed);
    if (!gppmap(sesskey, "TerminalModes", conf, CONF_ttymodes)) {
	/* This hardcodes a big set of defaults in any new saved
	 * sessions. Let's hope we don't change our mind. */
	for (i = 0; ttymodes[i]; i++)
	    conf_set_str_str(conf, CONF_ttymodes, ttymodes[i], "A");
    }

    /* proxy settings */
    gpps(sesskey, "ProxyExcludeList", "", conf, CONF_proxy_exclude_list);
    i = gppi_raw(sesskey, "ProxyDNS", 1); conf_set_int(conf, CONF_proxy_dns, (i+1)%3);
    gppi(sesskey, "ProxyLocalhost", 0, conf, CONF_even_proxy_localhost);
    gppi(sesskey, "ProxyMethod", -1, conf, CONF_proxy_type);
    if (conf_get_int(conf, CONF_proxy_type) == -1) {
        int i;
        i = gppi_raw(sesskey, "ProxyType", 0);
        if (i == 0)
            conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
        else if (i == 1)
            conf_set_int(conf, CONF_proxy_type, PROXY_HTTP);
        else if (i == 3)
            conf_set_int(conf, CONF_proxy_type, PROXY_TELNET);
        else if (i == 4)
            conf_set_int(conf, CONF_proxy_type, PROXY_CMD);
        else {
            i = gppi_raw(sesskey, "ProxySOCKSVersion", 5);
            if (i == 5)
                conf_set_int(conf, CONF_proxy_type, PROXY_SOCKS5);
            else
                conf_set_int(conf, CONF_proxy_type, PROXY_SOCKS4);
        }
    }
    gpps(sesskey, "ProxyHost", "proxy", conf, CONF_proxy_host);
    gppi(sesskey, "ProxyPort", 80, conf, CONF_proxy_port);
    gpps(sesskey, "ProxyUsername", "", conf, CONF_proxy_username);
    gpps(sesskey, "ProxyPassword", "", conf, CONF_proxy_password);
    gpps(sesskey, "ProxyTelnetCommand", "connect %host %port\\n",
	 conf, CONF_proxy_telnet_command);
    gppmap(sesskey, "Environment", conf, CONF_environmt);
    gpps(sesskey, "UserName", "", conf, CONF_username);
    gpps(sesskey, "Password", "", conf, CONF_password);
    gppi(sesskey, "UserNameFromEnvironment", 0, conf, CONF_username_from_env);
    gpps(sesskey, "LocalUserName", "", conf, CONF_localusername);
    gppi(sesskey, "NoPTY", 0, conf, CONF_nopty);
    gppi(sesskey, "Compression", 0, conf, CONF_compression);
    gppi(sesskey, "TryAgent", 1, conf, CONF_tryagent);
    gppi(sesskey, "AgentFwd", 0, conf, CONF_agentfwd);
    gppi(sesskey, "ChangeUsername", 0, conf, CONF_change_username);
    gppi(sesskey, "GssapiFwd", 0, conf, CONF_gssapifwd);
    gprefs(sesskey, "Cipher", "\0",
	   ciphernames, CIPHER_MAX, conf, CONF_ssh_cipherlist);
    {
	/* Backward-compatibility: we used to have an option to
	 * disable gex under the "bugs" panel after one report of
	 * a server which offered it then choked, but we never got
	 * a server version string or any other reports. */
	char *default_kexes;
	i = 2 - gppi_raw(sesskey, "BugDHGEx2", 0);
	if (i == FORCE_ON)
	    default_kexes = "dh-group14-sha1,dh-group1-sha1,rsa,WARN,dh-gex-sha1";
	else
	    default_kexes = "dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN";
	gprefs(sesskey, "KEX", default_kexes,
	       kexnames, KEX_MAX, conf, CONF_ssh_kexlist);
    }
    gppi(sesskey, "RekeyTime", 60, conf, CONF_ssh_rekey_time);
    gpps(sesskey, "RekeyBytes", "1G", conf, CONF_ssh_rekey_data);
    /* SSH-2 only by default */
    gppi(sesskey, "SshProt", 3, conf, CONF_sshprot);
    gpps(sesskey, "LogHost", "", conf, CONF_loghost);
    gppi(sesskey, "SSH2DES", 0, conf, CONF_ssh2_des_cbc);
    gppi(sesskey, "SshNoAuth", 0, conf, CONF_ssh_no_userauth);
    gppi(sesskey, "SshBanner", 1, conf, CONF_ssh_show_banner);
    gppi(sesskey, "AuthTIS", 0, conf, CONF_try_tis_auth);
    gppi(sesskey, "AuthKI", 1, conf, CONF_try_ki_auth);
    gppi(sesskey, "AuthGSSAPI", 1, conf, CONF_try_gssapi_auth);
#ifndef NO_GSSAPI
    gprefs(sesskey, "GSSLibs", "\0",
	   gsslibkeywords, ngsslibs, conf, CONF_ssh_gsslist);
    gppfile(sesskey, "GSSCustom", conf, CONF_ssh_gss_custom);
#endif
    gppi(sesskey, "SshNoShell", 0, conf, CONF_ssh_no_shell);
    gppfile(sesskey, "PublicKeyFile", conf, CONF_keyfile);
    gpps(sesskey, "RemoteCommand", "", conf, CONF_remote_cmd);
    gppi(sesskey, "RFCEnviron", 0, conf, CONF_rfc_environ);
    gppi(sesskey, "PassiveTelnet", 0, conf, CONF_passive_telnet);
    gppi(sesskey, "BackspaceIsDelete", 1, conf, CONF_bksp_is_delete);
    gppi(sesskey, "RXVTHomeEnd", 0, conf, CONF_rxvt_homeend);
    gppi(sesskey, "LinuxFunctionKeys", 0, conf, CONF_funky_type);
    gppi(sesskey, "NoApplicationKeys", 0, conf, CONF_no_applic_k);
    gppi(sesskey, "NoApplicationCursors", 0, conf, CONF_no_applic_c);
    gppi(sesskey, "NoMouseReporting", 0, conf, CONF_no_mouse_rep);
    gppi(sesskey, "NoRemoteResize", 0, conf, CONF_no_remote_resize);
    gppi(sesskey, "NoAltScreen", 0, conf, CONF_no_alt_screen);
    gppi(sesskey, "NoRemoteWinTitle", 0, conf, CONF_no_remote_wintitle);
    {
	/* Backward compatibility */
	int no_remote_qtitle = gppi_raw(sesskey, "NoRemoteQTitle", 1);
	/* We deliberately interpret the old setting of "no response" as
	 * "empty string". This changes the behaviour, but hopefully for
	 * the better; the user can always recover the old behaviour. */
	gppi(sesskey, "RemoteQTitleAction",
	     no_remote_qtitle ? TITLE_EMPTY : TITLE_REAL,
	     conf, CONF_remote_qtitle_action);
    }
    gppi(sesskey, "NoDBackspace", 0, conf, CONF_no_dbackspace);
    gppi(sesskey, "NoRemoteCharset", 0, conf, CONF_no_remote_charset);
    gppi(sesskey, "ApplicationCursorKeys", 0, conf, CONF_app_cursor);
    gppi(sesskey, "ApplicationKeypad", 0, conf, CONF_app_keypad);
    gppi(sesskey, "NetHackKeypad", 0, conf, CONF_nethack_keypad);
    gppi(sesskey, "AltF4", 1, conf, CONF_alt_f4);
    gppi(sesskey, "AltSpace", 0, conf, CONF_alt_space);
    gppi(sesskey, "AltOnly", 0, conf, CONF_alt_only);
    gppi(sesskey, "ComposeKey", 0, conf, CONF_compose_key);
    gppi(sesskey, "CtrlAltKeys", 1, conf, CONF_ctrlaltkeys);
    gppi(sesskey, "TelnetKey", 0, conf, CONF_telnet_keyboard);
    gppi(sesskey, "TelnetRet", 1, conf, CONF_telnet_newline);
    gppi(sesskey, "LocalEcho", AUTO, conf, CONF_localecho);
    gppi(sesskey, "LocalEdit", AUTO, conf, CONF_localedit);
    gpps(sesskey, "Answerback", "PuTTY", conf, CONF_answerback);
    gppi(sesskey, "AlwaysOnTop", 0, conf, CONF_alwaysontop);
    gppi(sesskey, "FullScreenOnAltEnter", 0, conf, CONF_fullscreenonaltenter);
    gppi(sesskey, "HideMousePtr", 0, conf, CONF_hide_mouseptr);
    gppi(sesskey, "SunkenEdge", 0, conf, CONF_sunken_edge);
    gppi(sesskey, "WindowBorder", 1, conf, CONF_window_border);
    gppi(sesskey, "CurType", 0, conf, CONF_cursor_type);
    gppi(sesskey, "BlinkCur", 0, conf, CONF_blink_cur);
    /* pedantic compiler tells me I can't use conf, CONF_beep as an int * :-) */
    gppi(sesskey, "Beep", 1, conf, CONF_beep);
    gppi(sesskey, "BeepInd", 0, conf, CONF_beep_ind);
    gppfile(sesskey, "BellWaveFile", conf, CONF_bell_wavefile);
    gppi(sesskey, "BellOverload", 1, conf, CONF_bellovl);
    gppi(sesskey, "BellOverloadN", 5, conf, CONF_bellovl_n);
    i = gppi_raw(sesskey, "BellOverloadT", 2*TICKSPERSEC
#ifdef PUTTY_UNIX_H
				   *1000
#endif
				   );
    conf_set_int(conf, CONF_bellovl_t, i
#ifdef PUTTY_UNIX_H
		 / 1000
#endif
		 );
    i = gppi_raw(sesskey, "BellOverloadS", 5*TICKSPERSEC
#ifdef PUTTY_UNIX_H
				   *1000
#endif
				   );
    conf_set_int(conf, CONF_bellovl_s, i
#ifdef PUTTY_UNIX_H
		 / 1000
#endif
		 );
    gppi(sesskey, "ScrollbackLines", 2000, conf, CONF_savelines);
    gppi(sesskey, "DECOriginMode", 0, conf, CONF_dec_om);
    gppi(sesskey, "AutoWrapMode", 1, conf, CONF_wrap_mode);
    gppi(sesskey, "LFImpliesCR", 0, conf, CONF_lfhascr);
    gppi(sesskey, "CRImpliesLF", 0, conf, CONF_crhaslf);
    gppi(sesskey, "DisableArabicShaping", 0, conf, CONF_arabicshaping);
    gppi(sesskey, "DisableBidi", 0, conf, CONF_bidi);
    gppi(sesskey, "WinNameAlways", 1, conf, CONF_win_name_always);
    gpps(sesskey, "WinTitle", "", conf, CONF_wintitle);
    gppi(sesskey, "TermWidth", 80, conf, CONF_width);
    gppi(sesskey, "TermHeight", 24, conf, CONF_height);
    gppfont(sesskey, "Font", conf, CONF_font);
    gppi(sesskey, "FontQuality", FQ_DEFAULT, conf, CONF_font_quality);
    gppi(sesskey, "FontVTMode", VT_UNICODE, conf, CONF_vtmode);
    gppi(sesskey, "UseSystemColours", 0, conf, CONF_system_colour);
    gppi(sesskey, "TryPalette", 0, conf, CONF_try_palette);
    gppi(sesskey, "ANSIColour", 1, conf, CONF_ansi_colour);
    gppi(sesskey, "Xterm256Colour", 1, conf, CONF_xterm_256_colour);
    i = gppi_raw(sesskey, "BoldAsColour", 1); conf_set_int(conf, CONF_bold_style, i+1);

    for (i = 0; i < 22; i++) {
	static const char *const defaults[] = {
	    "187,187,187", "255,255,255", "0,0,0", "85,85,85", "0,0,0",
	    "0,255,0", "0,0,0", "85,85,85", "187,0,0", "255,85,85",
	    "0,187,0", "85,255,85", "187,187,0", "255,255,85", "0,0,187",
	    "85,85,255", "187,0,187", "255,85,255", "0,187,187",
	    "85,255,255", "187,187,187", "255,255,255"
	};
	char buf[20], *buf2;
	int c0, c1, c2;
	sprintf(buf, "Colour%d", i);
	buf2 = gpps_raw(sesskey, buf, defaults[i]);
	if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) {
	    conf_set_int_int(conf, CONF_colours, i*3+0, c0);
	    conf_set_int_int(conf, CONF_colours, i*3+1, c1);
	    conf_set_int_int(conf, CONF_colours, i*3+2, c2);
	}
	sfree(buf2);
    }
    gppi(sesskey, "RawCNP", 0, conf, CONF_rawcnp);
    gppi(sesskey, "PasteRTF", 0, conf, CONF_rtf_paste);
    gppi(sesskey, "MouseIsXterm", 0, conf, CONF_mouse_is_xterm);
    gppi(sesskey, "RectSelect", 0, conf, CONF_rect_select);
    gppi(sesskey, "MouseOverride", 1, conf, CONF_mouse_override);
    for (i = 0; i < 256; i += 32) {
	static const char *const defaults[] = {
	    "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
	    "0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1",
	    "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2",
	    "1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1",
	    "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
	    "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
	    "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2",
	    "2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2"
	};
	char buf[20], *buf2, *p;
	int j;
	sprintf(buf, "Wordness%d", i);
	buf2 = gpps_raw(sesskey, buf, defaults[i / 32]);
	p = buf2;
	for (j = i; j < i + 32; j++) {
	    char *q = p;
	    while (*p && *p != ',')
		p++;
	    if (*p == ',')
		*p++ = '\0';
	    conf_set_int_int(conf, CONF_wordness, j, atoi(q));
	}
	sfree(buf2);
    }
    /*
     * The empty default for LineCodePage will be converted later
     * into a plausible default for the locale.
     */
    gpps(sesskey, "LineCodePage", "EUC-JP", conf, CONF_line_codepage);
    /* No compatibility with the old iso2022 patch */
    gppi(sesskey, "CJKAmbigWide", 0, conf, CONF_cjk_ambig_wide);
    gppi(sesskey, "UTF8Override", 1, conf, CONF_utf8_override);
    gpps(sesskey, "Printer", "", conf, CONF_printer);
    gppi(sesskey, "CapsLockCyr", 0, conf, CONF_xlat_capslockcyr);
    gppi(sesskey, "ScrollBar", 1, conf, CONF_scrollbar);
    gppi(sesskey, "ScrollBarFullScreen", 0, conf, CONF_scrollbar_in_fullscreen);
    gppi(sesskey, "ScrollOnKey", 0, conf, CONF_scroll_on_key);
    gppi(sesskey, "ScrollOnDisp", 1, conf, CONF_scroll_on_disp);
    gppi(sesskey, "EraseToScrollback", 1, conf, CONF_erase_to_scrollback);
    gppi(sesskey, "LockSize", 0, conf, CONF_resize_action);
    gppi(sesskey, "BCE", 1, conf, CONF_bce);
    gppi(sesskey, "BlinkText", 0, conf, CONF_blinktext);
    gppi(sesskey, "X11Forward", 0, conf, CONF_x11_forward);
    gpps(sesskey, "X11Display", "", conf, CONF_x11_display);
    gppi(sesskey, "X11AuthType", X11_MIT, conf, CONF_x11_auth);
    gppfile(sesskey, "X11AuthFile", conf, CONF_xauthfile);

    gppi(sesskey, "LocalPortAcceptAll", 0, conf, CONF_lport_acceptall);
    gppi(sesskey, "RemotePortAcceptAll", 0, conf, CONF_rport_acceptall);
    gppmap(sesskey, "PortForwardings", conf, CONF_portfwd);
    i = gppi_raw(sesskey, "BugIgnore1", 0); conf_set_int(conf, CONF_sshbug_ignore1, 2-i);
    i = gppi_raw(sesskey, "BugPlainPW1", 0); conf_set_int(conf, CONF_sshbug_plainpw1, 2-i);
    i = gppi_raw(sesskey, "BugRSA1", 0); conf_set_int(conf, CONF_sshbug_rsa1, 2-i);
    i = gppi_raw(sesskey, "BugIgnore2", 0); conf_set_int(conf, CONF_sshbug_ignore2, 2-i);
    {
	int i;
	i = gppi_raw(sesskey, "BugHMAC2", 0); conf_set_int(conf, CONF_sshbug_hmac2, 2-i);
	if (2-i == AUTO) {
	    i = gppi_raw(sesskey, "BuggyMAC", 0);
	    if (i == 1)
		conf_set_int(conf, CONF_sshbug_hmac2, FORCE_ON);
	}
    }
    i = gppi_raw(sesskey, "BugDeriveKey2", 0); conf_set_int(conf, CONF_sshbug_derivekey2, 2-i);
    i = gppi_raw(sesskey, "BugRSAPad2", 0); conf_set_int(conf, CONF_sshbug_rsapad2, 2-i);
    i = gppi_raw(sesskey, "BugPKSessID2", 0); conf_set_int(conf, CONF_sshbug_pksessid2, 2-i);
    i = gppi_raw(sesskey, "BugRekey2", 0); conf_set_int(conf, CONF_sshbug_rekey2, 2-i);
    i = gppi_raw(sesskey, "BugMaxPkt2", 0); conf_set_int(conf, CONF_sshbug_maxpkt2, 2-i);
    i = gppi_raw(sesskey, "BugOldGex2", 0); conf_set_int(conf, CONF_sshbug_oldgex2, 2-i);
    i = gppi_raw(sesskey, "BugWinadj", 0); conf_set_int(conf, CONF_sshbug_winadj, 2-i);
    i = gppi_raw(sesskey, "BugChanReq", 0); conf_set_int(conf, CONF_sshbug_chanreq, 2-i);
    conf_set_int(conf, CONF_ssh_simple, FALSE);
    gppi(sesskey, "StampUtmp", 1, conf, CONF_stamp_utmp);
    gppi(sesskey, "LoginShell", 1, conf, CONF_login_shell);
    gppi(sesskey, "ScrollbarOnLeft", 0, conf, CONF_scrollbar_on_left);
    gppi(sesskey, "ShadowBold", 0, conf, CONF_shadowbold);
    gppfont(sesskey, "BoldFont", conf, CONF_boldfont);
    gppfont(sesskey, "WideFont", conf, CONF_widefont);
    gppfont(sesskey, "WideBoldFont", conf, CONF_wideboldfont);
    gppi(sesskey, "ShadowBoldOffset", 1, conf, CONF_shadowboldoffset);
    gpps(sesskey, "SerialLine", "", conf, CONF_serline);
    gppi(sesskey, "SerialSpeed", 9600, conf, CONF_serspeed);
    gppi(sesskey, "SerialDataBits", 8, conf, CONF_serdatabits);
    gppi(sesskey, "SerialStopHalfbits", 2, conf, CONF_serstopbits);
    gppi(sesskey, "SerialParity", SER_PAR_NONE, conf, CONF_serparity);
    gppi(sesskey, "SerialFlowControl", SER_FLOW_XONXOFF, conf, CONF_serflow);
    gpps(sesskey, "WindowClass", "", conf, CONF_winclass);
    gppi(sesskey, "ConnectionSharing", 0, conf, CONF_ssh_connection_sharing);
    gppi(sesskey, "ConnectionSharingUpstream", 1, conf, CONF_ssh_connection_sharing_upstream);
    gppi(sesskey, "ConnectionSharingDownstream", 1, conf, CONF_ssh_connection_sharing_downstream);
    gppmap(sesskey, "SSHManualHostKeys", conf, CONF_ssh_manual_hostkeys);
}
Beispiel #12
0
/*
 * Write a set of name/value pairs in the above format, or just the
 * names if include_values is FALSE.
 */
static void wmap(void *handle, char const *outkey, Conf *conf, int primary,
                 int include_values)
{
    char *buf, *p, *q, *key, *realkey, *val;
    int len;

    len = 1;			       /* allow for NUL */

    for (val = conf_get_str_strs(conf, primary, NULL, &key);
	 val != NULL;
	 val = conf_get_str_strs(conf, primary, key, &key))
	len += 2 + 2 * (strlen(key) + strlen(val));   /* allow for escaping */

    buf = snewn(len, char);
    p = buf;

    for (val = conf_get_str_strs(conf, primary, NULL, &key);
	 val != NULL;
	 val = conf_get_str_strs(conf, primary, key, &key)) {

        if (primary == CONF_portfwd && !strcmp(val, "D")) {
            /*
             * Backwards-compatibility hack, as above: translate from
             * the sensible internal representation of dynamic
             * forwardings (key "L<port>", value "D") to the
             * conceptually incoherent legacy storage format (key
             * "D<port>", value empty).
             */
            char *L;

            realkey = key;             /* restore it at end of loop */
            val = "";
            key = dupstr(key);
            L = strchr(key, 'L');
            if (L) *L = 'D';
        } else {
            realkey = NULL;
        }

	if (p != buf)
	    *p++ = ',';
	for (q = key; *q; q++) {
	    if (*q == '=' || *q == ',' || *q == '\\')
		*p++ = '\\';
	    *p++ = *q;
	}
        if (include_values) {
            *p++ = '=';
            for (q = val; *q; q++) {
                if (*q == '=' || *q == ',' || *q == '\\')
                    *p++ = '\\';
                *p++ = *q;
            }
        }

        if (realkey) {
            free(key);
            key = realkey;
        }
    }
    *p = '\0';
    write_setting_s(handle, outkey, buf);
    sfree(buf);
}
Beispiel #13
0
/*
 * Read a set of name-value pairs in the format we occasionally use:
 *   NAME\tVALUE\0NAME\tVALUE\0\0 in memory
 *   NAME=VALUE,NAME=VALUE, in storage
 * If there's no "=VALUE" (e.g. just NAME,NAME,NAME) then those keys
 * are mapped to the empty string.
 */
static int gppmap(void *handle, char *name, Conf *conf, int primary)
{
    char *buf, *p, *q, *key, *val;

    /*
     * Start by clearing any existing subkeys of this key from conf.
     */
    while ((key = conf_get_str_nthstrkey(conf, primary, 0)) != NULL)
        conf_del_str_str(conf, primary, key);

    /*
     * Now read a serialised list from the settings and unmarshal it
     * into its components.
     */
    buf = gpps_raw(handle, name, NULL);
    if (!buf)
	return FALSE;

    p = buf;
    while (*p) {
	q = buf;
	val = NULL;
	while (*p && *p != ',') {
	    int c = *p++;
	    if (c == '=')
		c = '\0';
	    if (c == '\\')
		c = *p++;
	    *q++ = c;
	    if (!c)
		val = q;
	}
	if (*p == ',')
	    p++;
	if (!val)
	    val = q;
	*q = '\0';

        if (primary == CONF_portfwd && strchr(buf, 'D') != NULL) {
            /*
             * Backwards-compatibility hack: dynamic forwardings are
             * indexed in the data store as a third type letter in the
             * key, 'D' alongside 'L' and 'R' - but really, they
             * should be filed under 'L' with a special _value_,
             * because local and dynamic forwardings both involve
             * _listening_ on a local port, and are hence mutually
             * exclusive on the same port number. So here we translate
             * the legacy storage format into the sensible internal
             * form, by finding the D and turning it into a L.
             */
            char *newkey = dupstr(buf);
            *strchr(newkey, 'D') = 'L';
            conf_set_str_str(conf, primary, newkey, "D");
            sfree(newkey);
        } else {
            conf_set_str_str(conf, primary, buf, val);
        }
    }
    sfree(buf);

    return TRUE;
}
Beispiel #14
0
void low_do_autocorr(const char *fn, const gmx_output_env_t *oenv, const char *title,
                     int nframes, int nitem, int nout, real **c1,
                     real dt, unsigned long mode, int nrestart,
                     gmx_bool bAver, gmx_bool bNormalize,
                     gmx_bool bVerbose, real tbeginfit, real tendfit,
                     int eFitFn)
{
    FILE       *fp, *gp = NULL;
    int         i, k, nfour;
    real       *csum;
    real       *ctmp, *fit;
    real        c0, sum, Ct2av, Ctav;
    gmx_bool    bFour = acf.bFour;

    /* Check flags and parameters */
    nout = get_acfnout();
    if (nout == -1)
    {
        nout = acf.nout = (nframes+1)/2;
    }
    else if (nout > nframes)
    {
        nout = nframes;
    }

    if (MODE(eacCos) && MODE(eacVector))
    {
        gmx_fatal(FARGS, "Incompatible options bCos && bVector (%s, %d)",
                  __FILE__, __LINE__);
    }
    if ((MODE(eacP3) || MODE(eacRcross)) && bFour)
    {
        if (bVerbose)
        {
            fprintf(stderr, "Can't combine mode %lu with FFT, turning off FFT\n", mode);
        }
        bFour = FALSE;
    }
    if (MODE(eacNormal) && MODE(eacVector))
    {
        gmx_fatal(FARGS, "Incompatible mode bits: normal and vector (or Legendre)");
    }

    /* Print flags and parameters */
    if (bVerbose)
    {
        printf("Will calculate %s of %d thingies for %d frames\n",
               title ? title : "autocorrelation", nitem, nframes);
        printf("bAver = %s, bFour = %s bNormalize= %s\n",
               gmx::boolToString(bAver), gmx::boolToString(bFour),
               gmx::boolToString(bNormalize));
        printf("mode = %lu, dt = %g, nrestart = %d\n", mode, dt, nrestart);
    }
    if (bFour)
    {
        c0 = std::log(static_cast<double>(nframes))/std::log(2.0);
        k  = static_cast<int>(c0);
        if (k < c0)
        {
            k++;
        }
        k++;
        nfour = 1<<k;
        if (debug)
        {
            fprintf(debug, "Using FFT to calculate %s, #points for FFT = %d\n",
                    title, nfour);
        }

        /* Allocate temp arrays */
        snew(csum, nfour);
        snew(ctmp, nfour);
    }
    else
    {
        nfour = 0; /* To keep the compiler happy */
        snew(csum, nframes);
        snew(ctmp, nframes);
    }

    /* Loop over items (e.g. molecules or dihedrals)
     * In this loop the actual correlation functions are computed, but without
     * normalizing them.
     */
    for (int i = 0; i < nitem; i++)
    {
        if (bVerbose && (((i % 100) == 0) || (i == nitem-1)))
        {
            fprintf(stderr, "\rThingie %d", i+1);
        }

        if (bFour)
        {
            do_four_core(mode, nfour, nframes, nframes, c1[i], csum, ctmp);
        }
        else
        {
            do_ac_core(nframes, nout, ctmp, c1[i], nrestart, mode);
        }
    }
    if (bVerbose)
    {
        fprintf(stderr, "\n");
    }
    sfree(ctmp);
    sfree(csum);

    if (fn)
    {
        snew(fit, nout);
        fp = xvgropen(fn, title, "Time (ps)", "C(t)", oenv);
    }
    else
    {
        fit = NULL;
        fp  = NULL;
    }
    if (bAver)
    {
        if (nitem > 1)
        {
            average_acf(bVerbose, nframes, nitem, c1);
        }

        if (bNormalize)
        {
            normalize_acf(nout, c1[0]);
        }

        if (eFitFn != effnNONE)
        {
            fit_acf(nout, eFitFn, oenv, fn != NULL, tbeginfit, tendfit, dt, c1[0], fit);
            sum = print_and_integrate(fp, nout, dt, c1[0], fit, 1);
        }
        else
        {
            sum = print_and_integrate(fp, nout, dt, c1[0], NULL, 1);
        }
        if (bVerbose)
        {
            printf("Correlation time (integral over corrfn): %g (ps)\n", sum);
        }
    }
    else
    {
        /* Not averaging. Normalize individual ACFs */
        Ctav = Ct2av = 0;
        if (debug)
        {
            gp = xvgropen("ct-distr.xvg", "Correlation times", "item", "time (ps)", oenv);
        }
        for (i = 0; i < nitem; i++)
        {
            if (bNormalize)
            {
                normalize_acf(nout, c1[i]);
            }
            if (eFitFn != effnNONE)
            {
                fit_acf(nout, eFitFn, oenv, fn != NULL, tbeginfit, tendfit, dt, c1[i], fit);
                sum = print_and_integrate(fp, nout, dt, c1[i], fit, 1);
            }
            else
            {
                sum = print_and_integrate(fp, nout, dt, c1[i], NULL, 1);
                if (debug)
                {
                    fprintf(debug,
                            "CORRelation time (integral over corrfn %d): %g (ps)\n",
                            i, sum);
                }
            }
            Ctav  += sum;
            Ct2av += sum*sum;
            if (debug)
            {
                fprintf(gp, "%5d  %.3f\n", i, sum);
            }
        }
        if (debug)
        {
            xvgrclose(gp);
        }
        if (nitem > 1)
        {
            Ctav  /= nitem;
            Ct2av /= nitem;
            printf("Average correlation time %.3f Std. Dev. %.3f Error %.3f (ps)\n",
                   Ctav, std::sqrt((Ct2av - gmx::square(Ctav))),
                   std::sqrt((Ct2av - gmx::square(Ctav))/(nitem-1)));
        }
    }
    if (fp)
    {
        xvgrclose(fp);
    }
    sfree(fit);
}
static void add_solv(const char *fn, t_atoms *atoms, rvec **x, rvec **v, real **exclusionDistances,
                     int ePBC, matrix box,
                     gmx_atomprop_t aps,
                     real defaultDistance, real scaleFactor, int *atoms_added,
                     int *residues_added, real rshell, int max_sol,
                     const output_env_t oenv)
{
    int      i, nmol;
    ivec     n_box;
    char     filename[STRLEN];
    char     title_solvt[STRLEN];
    t_atoms *atoms_solvt;
    rvec    *x_solvt, *v_solvt = NULL;
    real    *exclusionDistances_solvt;
    int      ePBC_solvt;
    matrix   box_solvt;
    int      onr, onres;
    char    *lfn;

    lfn = gmxlibfn(fn);
    strncpy(filename, lfn, STRLEN);
    sfree(lfn);
    {
        int natoms;
        get_stx_coordnum(filename, &natoms);
        if (0 == natoms)
        {
            gmx_fatal(FARGS, "No solvent in %s, please check your input\n", filename);
        }
        snew(atoms_solvt, 1);
        init_t_atoms(atoms_solvt, natoms, FALSE);
    }
    snew(x_solvt, atoms_solvt->nr);
    if (v)
    {
        snew(v_solvt, atoms_solvt->nr);
    }
    snew(exclusionDistances_solvt, atoms_solvt->nr);
    snew(atoms_solvt->resinfo, atoms_solvt->nr);
    snew(atoms_solvt->atomname, atoms_solvt->nr);
    snew(atoms_solvt->atom, atoms_solvt->nr);
    atoms_solvt->pdbinfo = NULL;
    fprintf(stderr, "Reading solvent configuration%s\n",
            v_solvt ? " and velocities" : "");
    read_stx_conf(filename, title_solvt, atoms_solvt, x_solvt, v_solvt,
                  &ePBC_solvt, box_solvt);
    fprintf(stderr, "\"%s\"\n", title_solvt);
    fprintf(stderr, "solvent configuration contains %d atoms in %d residues\n",
            atoms_solvt->nr, atoms_solvt->nres);
    fprintf(stderr, "\n");

    /* apply pbc for solvent configuration for whole molecules */
    rm_res_pbc(atoms_solvt, x_solvt, box_solvt);

    /* initialise distance arrays for solvent configuration */
    exclusionDistances_solvt = makeExclusionDistances(atoms_solvt, aps, defaultDistance, scaleFactor);

    /* calculate the box multiplication factors n_box[0...DIM] */
    nmol = 1;
    for (i = 0; (i < DIM); i++)
    {
        n_box[i] = 1;
        while (n_box[i]*box_solvt[i][i] < box[i][i])
        {
            n_box[i]++;
        }
        nmol *= n_box[i];
    }
    fprintf(stderr, "Will generate new solvent configuration of %dx%dx%d boxes\n",
            n_box[XX], n_box[YY], n_box[ZZ]);

    /* realloc atoms_solvt for the new solvent configuration */
    srenew(atoms_solvt->resinfo, atoms_solvt->nres*nmol);
    srenew(atoms_solvt->atomname, atoms_solvt->nr*nmol);
    srenew(atoms_solvt->atom, atoms_solvt->nr*nmol);
    srenew(x_solvt, atoms_solvt->nr*nmol);
    if (v_solvt)
    {
        srenew(v_solvt, atoms_solvt->nr*nmol);
    }
    srenew(exclusionDistances_solvt, atoms_solvt->nr*nmol);

    /* generate a new solvent configuration */
    make_new_conformation(atoms_solvt, x_solvt, v_solvt, exclusionDistances_solvt, box_solvt, n_box);

#ifdef DEBUG
    print_stat(x_solvt, atoms_solvt->nr, box_solvt);
#endif

#ifdef DEBUG
    print_stat(x_solvt, atoms_solvt->nr, box_solvt);
#endif
    /* Sort the solvent mixture, not the protein... */
    sort_molecule(&atoms_solvt, x_solvt, v_solvt, exclusionDistances_solvt);

    /* add the two configurations */
    onr   = atoms->nr;
    onres = atoms->nres;
    add_conf(atoms, x, v, exclusionDistances, TRUE, ePBC, box, FALSE,
             atoms_solvt, x_solvt, v_solvt, exclusionDistances_solvt, TRUE, rshell, max_sol, oenv);
    *atoms_added    = atoms->nr-onr;
    *residues_added = atoms->nres-onres;

    sfree(x_solvt);
    sfree(exclusionDistances_solvt);
    done_atom(atoms_solvt);
    sfree(atoms_solvt);

    fprintf(stderr, "Generated solvent containing %d atoms in %d residues\n",
            *atoms_added, *residues_added);
}
Beispiel #16
0
int gmx_covar(int argc, char *argv[])
{
    const char     *desc[] = {
        "[THISMODULE] calculates and diagonalizes the (mass-weighted)",
        "covariance matrix.",
        "All structures are fitted to the structure in the structure file.",
        "When this is not a run input file periodicity will not be taken into",
        "account. When the fit and analysis groups are identical and the analysis",
        "is non mass-weighted, the fit will also be non mass-weighted.",
        "[PAR]",
        "The eigenvectors are written to a trajectory file ([TT]-v[tt]).",
        "When the same atoms are used for the fit and the covariance analysis,",
        "the reference structure for the fit is written first with t=-1.",
        "The average (or reference when [TT]-ref[tt] is used) structure is",
        "written with t=0, the eigenvectors",
        "are written as frames with the eigenvector number as timestamp.",
        "[PAR]",
        "The eigenvectors can be analyzed with [gmx-anaeig].",
        "[PAR]",
        "Option [TT]-ascii[tt] writes the whole covariance matrix to",
        "an ASCII file. The order of the elements is: x1x1, x1y1, x1z1, x1x2, ...",
        "[PAR]",
        "Option [TT]-xpm[tt] writes the whole covariance matrix to an [REF].xpm[ref] file.",
        "[PAR]",
        "Option [TT]-xpma[tt] writes the atomic covariance matrix to an [REF].xpm[ref] file,",
        "i.e. for each atom pair the sum of the xx, yy and zz covariances is",
        "written.",
        "[PAR]",
        "Note that the diagonalization of a matrix requires memory and time",
        "that will increase at least as fast as than the square of the number",
        "of atoms involved. It is easy to run out of memory, in which",
        "case this tool will probably exit with a 'Segmentation fault'. You",
        "should consider carefully whether a reduced set of atoms will meet",
        "your needs for lower costs."
    };
    static gmx_bool bFit = TRUE, bRef = FALSE, bM = FALSE, bPBC = TRUE;
    static int      end  = -1;
    t_pargs         pa[] = {
        { "-fit",  FALSE, etBOOL, {&bFit},
          "Fit to a reference structure"},
        { "-ref",  FALSE, etBOOL, {&bRef},
          "Use the deviation from the conformation in the structure file instead of from the average" },
        { "-mwa",  FALSE, etBOOL, {&bM},
          "Mass-weighted covariance analysis"},
        { "-last",  FALSE, etINT, {&end},
          "Last eigenvector to write away (-1 is till the last)" },
        { "-pbc",  FALSE,  etBOOL, {&bPBC},
          "Apply corrections for periodic boundary conditions" }
    };
    FILE           *out = NULL; /* initialization makes all compilers happy */
    t_trxstatus    *status;
    t_trxstatus    *trjout;
    t_topology      top;
    int             ePBC;
    t_atoms        *atoms;
    rvec           *x, *xread, *xref, *xav, *xproj;
    matrix          box, zerobox;
    real           *sqrtm, *mat, *eigenvalues, sum, trace, inv_nframes;
    real            t, tstart, tend, **mat2;
    real            xj, *w_rls = NULL;
    real            min, max, *axis;
    int             ntopatoms, step;
    int             natoms, nat, count, nframes0, nframes, nlevels;
    gmx_int64_t     ndim, i, j, k, l;
    int             WriteXref;
    const char     *fitfile, *trxfile, *ndxfile;
    const char     *eigvalfile, *eigvecfile, *averfile, *logfile;
    const char     *asciifile, *xpmfile, *xpmafile;
    char            str[STRLEN], *fitname, *ananame, *pcwd;
    int             d, dj, nfit;
    atom_id        *index, *ifit;
    gmx_bool        bDiffMass1, bDiffMass2;
    char            timebuf[STRLEN];
    t_rgb           rlo, rmi, rhi;
    real           *eigenvectors;
    output_env_t    oenv;
    gmx_rmpbc_t     gpbc = NULL;

    t_filenm        fnm[] = {
        { efTRX, "-f",  NULL, ffREAD },
        { efTPS, NULL,  NULL, ffREAD },
        { efNDX, NULL,  NULL, ffOPTRD },
        { efXVG, NULL,  "eigenval", ffWRITE },
        { efTRN, "-v",  "eigenvec", ffWRITE },
        { efSTO, "-av", "average.pdb", ffWRITE },
        { efLOG, NULL,  "covar", ffWRITE },
        { efDAT, "-ascii", "covar", ffOPTWR },
        { efXPM, "-xpm", "covar", ffOPTWR },
        { efXPM, "-xpma", "covara", ffOPTWR }
    };
#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT,
                           NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }

    clear_mat(zerobox);

    fitfile    = ftp2fn(efTPS, NFILE, fnm);
    trxfile    = ftp2fn(efTRX, NFILE, fnm);
    ndxfile    = ftp2fn_null(efNDX, NFILE, fnm);
    eigvalfile = ftp2fn(efXVG, NFILE, fnm);
    eigvecfile = ftp2fn(efTRN, NFILE, fnm);
    averfile   = ftp2fn(efSTO, NFILE, fnm);
    logfile    = ftp2fn(efLOG, NFILE, fnm);
    asciifile  = opt2fn_null("-ascii", NFILE, fnm);
    xpmfile    = opt2fn_null("-xpm", NFILE, fnm);
    xpmafile   = opt2fn_null("-xpma", NFILE, fnm);

    read_tps_conf(fitfile, str, &top, &ePBC, &xref, NULL, box, TRUE);
    atoms = &top.atoms;

    if (bFit)
    {
        printf("\nChoose a group for the least squares fit\n");
        get_index(atoms, ndxfile, 1, &nfit, &ifit, &fitname);
        if (nfit < 3)
        {
            gmx_fatal(FARGS, "Need >= 3 points to fit!\n");
        }
    }
    else
    {
        nfit = 0;
    }
    printf("\nChoose a group for the covariance analysis\n");
    get_index(atoms, ndxfile, 1, &natoms, &index, &ananame);

    bDiffMass1 = FALSE;
    if (bFit)
    {
        snew(w_rls, atoms->nr);
        for (i = 0; (i < nfit); i++)
        {
            w_rls[ifit[i]] = atoms->atom[ifit[i]].m;
            if (i)
            {
                bDiffMass1 = bDiffMass1 || (w_rls[ifit[i]] != w_rls[ifit[i-1]]);
            }
        }
    }
    bDiffMass2 = FALSE;
    snew(sqrtm, natoms);
    for (i = 0; (i < natoms); i++)
    {
        if (bM)
        {
            sqrtm[i] = sqrt(atoms->atom[index[i]].m);
            if (i)
            {
                bDiffMass2 = bDiffMass2 || (sqrtm[i] != sqrtm[i-1]);
            }
        }
        else
        {
            sqrtm[i] = 1.0;
        }
    }

    if (bFit && bDiffMass1 && !bDiffMass2)
    {
        bDiffMass1 = natoms != nfit;
        i          = 0;
        for (i = 0; (i < natoms) && !bDiffMass1; i++)
        {
            bDiffMass1 = index[i] != ifit[i];
        }
        if (!bDiffMass1)
        {
            fprintf(stderr, "\n"
                    "Note: the fit and analysis group are identical,\n"
                    "      while the fit is mass weighted and the analysis is not.\n"
                    "      Making the fit non mass weighted.\n\n");
            for (i = 0; (i < nfit); i++)
            {
                w_rls[ifit[i]] = 1.0;
            }
        }
    }

    /* Prepare reference frame */
    if (bPBC)
    {
        gpbc = gmx_rmpbc_init(&top.idef, ePBC, atoms->nr);
        gmx_rmpbc(gpbc, atoms->nr, box, xref);
    }
    if (bFit)
    {
        reset_x(nfit, ifit, atoms->nr, NULL, xref, w_rls);
    }

    snew(x, natoms);
    snew(xav, natoms);
    ndim = natoms*DIM;
    if (sqrt(GMX_INT64_MAX) < ndim)
    {
        gmx_fatal(FARGS, "Number of degrees of freedoms to large for matrix.\n");
    }
    snew(mat, ndim*ndim);

    fprintf(stderr, "Calculating the average structure ...\n");
    nframes0 = 0;
    nat      = read_first_x(oenv, &status, trxfile, &t, &xread, box);
    if (nat != atoms->nr)
    {
        fprintf(stderr, "\nWARNING: number of atoms in tpx (%d) and trajectory (%d) do not match\n", natoms, nat);
    }
    do
    {
        nframes0++;
        /* calculate x: a fitted struture of the selected atoms */
        if (bPBC)
        {
            gmx_rmpbc(gpbc, nat, box, xread);
        }
        if (bFit)
        {
            reset_x(nfit, ifit, nat, NULL, xread, w_rls);
            do_fit(nat, w_rls, xref, xread);
        }
        for (i = 0; i < natoms; i++)
        {
            rvec_inc(xav[i], xread[index[i]]);
        }
    }
    while (read_next_x(oenv, status, &t, xread, box));
    close_trj(status);

    inv_nframes = 1.0/nframes0;
    for (i = 0; i < natoms; i++)
    {
        for (d = 0; d < DIM; d++)
        {
            xav[i][d]         *= inv_nframes;
            xread[index[i]][d] = xav[i][d];
        }
    }
    write_sto_conf_indexed(opt2fn("-av", NFILE, fnm), "Average structure",
                           atoms, xread, NULL, epbcNONE, zerobox, natoms, index);
    sfree(xread);

    fprintf(stderr, "Constructing covariance matrix (%dx%d) ...\n", (int)ndim, (int)ndim);
    nframes = 0;
    nat     = read_first_x(oenv, &status, trxfile, &t, &xread, box);
    tstart  = t;
    do
    {
        nframes++;
        tend = t;
        /* calculate x: a (fitted) structure of the selected atoms */
        if (bPBC)
        {
            gmx_rmpbc(gpbc, nat, box, xread);
        }
        if (bFit)
        {
            reset_x(nfit, ifit, nat, NULL, xread, w_rls);
            do_fit(nat, w_rls, xref, xread);
        }
        if (bRef)
        {
            for (i = 0; i < natoms; i++)
            {
                rvec_sub(xread[index[i]], xref[index[i]], x[i]);
            }
        }
        else
        {
            for (i = 0; i < natoms; i++)
            {
                rvec_sub(xread[index[i]], xav[i], x[i]);
            }
        }

        for (j = 0; j < natoms; j++)
        {
            for (dj = 0; dj < DIM; dj++)
            {
                k  = ndim*(DIM*j+dj);
                xj = x[j][dj];
                for (i = j; i < natoms; i++)
                {
                    l = k+DIM*i;
                    for (d = 0; d < DIM; d++)
                    {
                        mat[l+d] += x[i][d]*xj;
                    }
                }
            }
        }
    }
    while (read_next_x(oenv, status, &t, xread, box) &&
           (bRef || nframes < nframes0));
    close_trj(status);
    gmx_rmpbc_done(gpbc);

    fprintf(stderr, "Read %d frames\n", nframes);

    if (bRef)
    {
        /* copy the reference structure to the ouput array x */
        snew(xproj, natoms);
        for (i = 0; i < natoms; i++)
        {
            copy_rvec(xref[index[i]], xproj[i]);
        }
    }
    else
    {
        xproj = xav;
    }

    /* correct the covariance matrix for the mass */
    inv_nframes = 1.0/nframes;
    for (j = 0; j < natoms; j++)
    {
        for (dj = 0; dj < DIM; dj++)
        {
            for (i = j; i < natoms; i++)
            {
                k = ndim*(DIM*j+dj)+DIM*i;
                for (d = 0; d < DIM; d++)
                {
                    mat[k+d] = mat[k+d]*inv_nframes*sqrtm[i]*sqrtm[j];
                }
            }
        }
    }

    /* symmetrize the matrix */
    for (j = 0; j < ndim; j++)
    {
        for (i = j; i < ndim; i++)
        {
            mat[ndim*i+j] = mat[ndim*j+i];
        }
    }

    trace = 0;
    for (i = 0; i < ndim; i++)
    {
        trace += mat[i*ndim+i];
    }
    fprintf(stderr, "\nTrace of the covariance matrix: %g (%snm^2)\n",
            trace, bM ? "u " : "");

    if (asciifile)
    {
        out = gmx_ffopen(asciifile, "w");
        for (j = 0; j < ndim; j++)
        {
            for (i = 0; i < ndim; i += 3)
            {
                fprintf(out, "%g %g %g\n",
                        mat[ndim*j+i], mat[ndim*j+i+1], mat[ndim*j+i+2]);
            }
        }
        gmx_ffclose(out);
    }

    if (xpmfile)
    {
        min = 0;
        max = 0;
        snew(mat2, ndim);
        for (j = 0; j < ndim; j++)
        {
            mat2[j] = &(mat[ndim*j]);
            for (i = 0; i <= j; i++)
            {
                if (mat2[j][i] < min)
                {
                    min = mat2[j][i];
                }
                if (mat2[j][j] > max)
                {
                    max = mat2[j][i];
                }
            }
        }
        snew(axis, ndim);
        for (i = 0; i < ndim; i++)
        {
            axis[i] = i+1;
        }
        rlo.r   = 0; rlo.g = 0; rlo.b = 1;
        rmi.r   = 1; rmi.g = 1; rmi.b = 1;
        rhi.r   = 1; rhi.g = 0; rhi.b = 0;
        out     = gmx_ffopen(xpmfile, "w");
        nlevels = 80;
        write_xpm3(out, 0, "Covariance", bM ? "u nm^2" : "nm^2",
                   "dim", "dim", ndim, ndim, axis, axis,
                   mat2, min, 0.0, max, rlo, rmi, rhi, &nlevels);
        gmx_ffclose(out);
        sfree(axis);
        sfree(mat2);
    }

    if (xpmafile)
    {
        min = 0;
        max = 0;
        snew(mat2, ndim/DIM);
        for (i = 0; i < ndim/DIM; i++)
        {
            snew(mat2[i], ndim/DIM);
        }
        for (j = 0; j < ndim/DIM; j++)
        {
            for (i = 0; i <= j; i++)
            {
                mat2[j][i] = 0;
                for (d = 0; d < DIM; d++)
                {
                    mat2[j][i] += mat[ndim*(DIM*j+d)+DIM*i+d];
                }
                if (mat2[j][i] < min)
                {
                    min = mat2[j][i];
                }
                if (mat2[j][j] > max)
                {
                    max = mat2[j][i];
                }
                mat2[i][j] = mat2[j][i];
            }
        }
        snew(axis, ndim/DIM);
        for (i = 0; i < ndim/DIM; i++)
        {
            axis[i] = i+1;
        }
        rlo.r   = 0; rlo.g = 0; rlo.b = 1;
        rmi.r   = 1; rmi.g = 1; rmi.b = 1;
        rhi.r   = 1; rhi.g = 0; rhi.b = 0;
        out     = gmx_ffopen(xpmafile, "w");
        nlevels = 80;
        write_xpm3(out, 0, "Covariance", bM ? "u nm^2" : "nm^2",
                   "atom", "atom", ndim/DIM, ndim/DIM, axis, axis,
                   mat2, min, 0.0, max, rlo, rmi, rhi, &nlevels);
        gmx_ffclose(out);
        sfree(axis);
        for (i = 0; i < ndim/DIM; i++)
        {
            sfree(mat2[i]);
        }
        sfree(mat2);
    }


    /* call diagonalization routine */

    snew(eigenvalues, ndim);
    snew(eigenvectors, ndim*ndim);

    memcpy(eigenvectors, mat, ndim*ndim*sizeof(real));
    fprintf(stderr, "\nDiagonalizing ...\n");
    fflush(stderr);
    eigensolver(eigenvectors, ndim, 0, ndim, eigenvalues, mat);
    sfree(eigenvectors);

    /* now write the output */

    sum = 0;
    for (i = 0; i < ndim; i++)
    {
        sum += eigenvalues[i];
    }
    fprintf(stderr, "\nSum of the eigenvalues: %g (%snm^2)\n",
            sum, bM ? "u " : "");
    if (fabs(trace-sum) > 0.01*trace)
    {
        fprintf(stderr, "\nWARNING: eigenvalue sum deviates from the trace of the covariance matrix\n");
    }

    /* Set 'end', the maximum eigenvector and -value index used for output */
    if (end == -1)
    {
        if (nframes-1 < ndim)
        {
            end = nframes-1;
            fprintf(out, "WARNING: there are fewer frames in your trajectory than there are\n");
            fprintf(out, "degrees of freedom in your system. Only generating the first\n");
            fprintf(out, "%d out of %d eigenvectors and eigenvalues.\n", end, (int)ndim);
        }
        else
        {
            end = ndim;
        }
    }

    fprintf(stderr, "\nWriting eigenvalues to %s\n", eigvalfile);

    sprintf(str, "(%snm\\S2\\N)", bM ? "u " : "");
    out = xvgropen(eigvalfile,
                   "Eigenvalues of the covariance matrix",
                   "Eigenvector index", str, oenv);
    for (i = 0; (i < end); i++)
    {
        fprintf (out, "%10d %g\n", (int)i+1, eigenvalues[ndim-1-i]);
    }
    xvgrclose(out);

    if (bFit)
    {
        /* misuse lambda: 0/1 mass weighted analysis no/yes */
        if (nfit == natoms)
        {
            WriteXref = eWXR_YES;
            for (i = 0; i < nfit; i++)
            {
                copy_rvec(xref[ifit[i]], x[i]);
            }
        }
        else
        {
            WriteXref = eWXR_NO;
        }
    }
    else
    {
        /* misuse lambda: -1 for no fit */
        WriteXref = eWXR_NOFIT;
    }

    write_eigenvectors(eigvecfile, natoms, mat, TRUE, 1, end,
                       WriteXref, x, bDiffMass1, xproj, bM, eigenvalues);

    out = gmx_ffopen(logfile, "w");

    gmx_format_current_time(timebuf, STRLEN);
    fprintf(out, "Covariance analysis log, written %s\n", timebuf);

    fprintf(out, "Program: %s\n", argv[0]);
    gmx_getcwd(str, STRLEN);

    fprintf(out, "Working directory: %s\n\n", str);

    fprintf(out, "Read %d frames from %s (time %g to %g %s)\n", nframes, trxfile,
            output_env_conv_time(oenv, tstart), output_env_conv_time(oenv, tend), output_env_get_time_unit(oenv));
    if (bFit)
    {
        fprintf(out, "Read reference structure for fit from %s\n", fitfile);
    }
    if (ndxfile)
    {
        fprintf(out, "Read index groups from %s\n", ndxfile);
    }
    fprintf(out, "\n");

    fprintf(out, "Analysis group is '%s' (%d atoms)\n", ananame, natoms);
    if (bFit)
    {
        fprintf(out, "Fit group is '%s' (%d atoms)\n", fitname, nfit);
    }
    else
    {
        fprintf(out, "No fit was used\n");
    }
    fprintf(out, "Analysis is %smass weighted\n", bDiffMass2 ? "" : "non-");
    if (bFit)
    {
        fprintf(out, "Fit is %smass weighted\n", bDiffMass1 ? "" : "non-");
    }
    fprintf(out, "Diagonalized the %dx%d covariance matrix\n", (int)ndim, (int)ndim);
    fprintf(out, "Trace of the covariance matrix before diagonalizing: %g\n",
            trace);
    fprintf(out, "Trace of the covariance matrix after diagonalizing: %g\n\n",
            sum);

    fprintf(out, "Wrote %d eigenvalues to %s\n", (int)end, eigvalfile);
    if (WriteXref == eWXR_YES)
    {
        fprintf(out, "Wrote reference structure to %s\n", eigvecfile);
    }
    fprintf(out, "Wrote average structure to %s and %s\n", averfile, eigvecfile);
    fprintf(out, "Wrote eigenvectors %d to %d to %s\n", 1, end, eigvecfile);

    gmx_ffclose(out);

    fprintf(stderr, "Wrote the log to %s\n", logfile);

    return 0;
}
int gmx_solvate(int argc, char *argv[])
{
    const char *desc[] = {
        "[THISMODULE] can do one of 2 things:[PAR]",

        "1) Generate a box of solvent. Specify [TT]-cs[tt] and [TT]-box[tt].",
        "Or specify [TT]-cs[tt] and [TT]-cp[tt] with a structure file with",
        "a box, but without atoms.[PAR]",

        "2) Solvate a solute configuration, e.g. a protein, in a bath of solvent ",
        "molecules. Specify [TT]-cp[tt] (solute) and [TT]-cs[tt] (solvent). ",
        "The box specified in the solute coordinate file ([TT]-cp[tt]) is used,",
        "unless [TT]-box[tt] is set.",
        "If you want the solute to be centered in the box,",
        "the program [gmx-editconf] has sophisticated options",
        "to change the box dimensions and center the solute.",
        "Solvent molecules are removed from the box where the ",
        "distance between any atom of the solute molecule(s) and any atom of ",
        "the solvent molecule is less than the sum of the scaled van der Waals",
        "radii of both atoms. A database ([TT]vdwradii.dat[tt]) of van der",
        "Waals radii is read by the program, and the resulting radii scaled",
        "by [TT]-scale[tt]. If radii are not found in the database, those"
        "atoms are assigned the (pre-scaled) distance [TT]-radius[tt].[PAR]",

        "The default solvent is Simple Point Charge water (SPC), with coordinates ",
        "from [TT]$GMXLIB/spc216.gro[tt]. These coordinates can also be used",
        "for other 3-site water models, since a short equibilibration will remove",
        "the small differences between the models.",
        "Other solvents are also supported, as well as mixed solvents. The",
        "only restriction to solvent types is that a solvent molecule consists",
        "of exactly one residue. The residue information in the coordinate",
        "files is used, and should therefore be more or less consistent.",
        "In practice this means that two subsequent solvent molecules in the ",
        "solvent coordinate file should have different residue number.",
        "The box of solute is built by stacking the coordinates read from",
        "the coordinate file. This means that these coordinates should be ",
        "equlibrated in periodic boundary conditions to ensure a good",
        "alignment of molecules on the stacking interfaces.",
        "The [TT]-maxsol[tt] option simply adds only the first [TT]-maxsol[tt]",
        "solvent molecules and leaves out the rest that would have fitted",
        "into the box. This can create a void that can cause problems later.",
        "Choose your volume wisely.[PAR]",

        "The program can optionally rotate the solute molecule to align the",
        "longest molecule axis along a box edge. This way the amount of solvent",
        "molecules necessary is reduced.",
        "It should be kept in mind that this only works for",
        "short simulations, as e.g. an alpha-helical peptide in solution can ",
        "rotate over 90 degrees, within 500 ps. In general it is therefore ",
        "better to make a more or less cubic box.[PAR]",

        "Setting [TT]-shell[tt] larger than zero will place a layer of water of",
        "the specified thickness (nm) around the solute. Hint: it is a good",
        "idea to put the protein in the center of a box first (using [gmx-editconf]).",
        "[PAR]",

        "Finally, [THISMODULE] will optionally remove lines from your topology file in ",
        "which a number of solvent molecules is already added, and adds a ",
        "line with the total number of solvent molecules in your coordinate file."
    };

    const char *bugs[] = {
        "Molecules must be whole in the initial configurations.",
    };

    /* parameter data */
    gmx_bool       bProt, bBox;
    const char    *conf_prot, *confout;
    real          *exclusionDistances = NULL;
    gmx_atomprop_t aps;

    /* protein configuration data */
    char    *title = NULL;
    t_atoms *atoms;
    rvec    *x    = NULL, *v = NULL;
    int      ePBC = -1;
    matrix   box;

    /* other data types */
    int      atoms_added, residues_added;

    t_filenm fnm[] = {
        { efSTX, "-cp", "protein", ffOPTRD },
        { efSTX, "-cs", "spc216",  ffLIBRD},
        { efSTO, NULL,  NULL,      ffWRITE},
        { efTOP, NULL,  NULL,      ffOPTRW},
    };
#define NFILE asize(fnm)

    static real     defaultDistance = 0.105, r_shell = 0, scaleFactor = 0.57;
    static rvec     new_box         = {0.0, 0.0, 0.0};
    static gmx_bool bReadV          = FALSE;
    static int      max_sol         = 0;
    output_env_t    oenv;
    t_pargs         pa[]              = {
        { "-box",    FALSE, etRVEC, {new_box},
          "Box size (in nm)" },
        { "-radius",   FALSE, etREAL, {&defaultDistance},
          "Default van der Waals distance"},
        { "-scale", FALSE, etREAL, {&scaleFactor},
          "Scale factor to multiply Van der Waals radii from the database in share/gromacs/top/vdwradii.dat. The default value of 0.57 yields density close to 1000 g/l for proteins in water." },
        { "-shell",  FALSE, etREAL, {&r_shell},
          "Thickness of optional water layer around solute" },
        { "-maxsol", FALSE, etINT,  {&max_sol},
          "Maximum number of solvent molecules to add if they fit in the box. If zero (default) this is ignored" },
        { "-vel",    FALSE, etBOOL, {&bReadV},
          "Keep velocities from input solute and solvent" },
    };

    if (!parse_common_args(&argc, argv, PCA_BE_NICE, NFILE, fnm, asize(pa), pa,
                           asize(desc), desc, asize(bugs), bugs, &oenv))
    {
        return 0;
    }

    const char *solventFileName = opt2fn("-cs", NFILE, fnm);
    bProt     = opt2bSet("-cp", NFILE, fnm);
    bBox      = opt2parg_bSet("-box", asize(pa), pa);

    /* check input */
    if (!bProt && !bBox)
    {
        gmx_fatal(FARGS, "When no solute (-cp) is specified, "
                  "a box size (-box) must be specified");
    }

    aps = gmx_atomprop_init();

    snew(atoms, 1);
    init_t_atoms(atoms, 0, FALSE);
    if (bProt)
    {
        /* Generate a solute configuration */
        conf_prot = opt2fn("-cp", NFILE, fnm);
        title     = readConformation(conf_prot, atoms, &x,
                                     bReadV ? &v : NULL, &ePBC, box);
        exclusionDistances = makeExclusionDistances(atoms, aps, defaultDistance, scaleFactor);

        if (bReadV && !v)
        {
            fprintf(stderr, "Note: no velocities found\n");
        }
        if (atoms->nr == 0)
        {
            fprintf(stderr, "Note: no atoms in %s\n", conf_prot);
            bProt = FALSE;
        }
    }
    if (bBox)
    {
        ePBC = epbcXYZ;
        clear_mat(box);
        box[XX][XX] = new_box[XX];
        box[YY][YY] = new_box[YY];
        box[ZZ][ZZ] = new_box[ZZ];
    }
    if (det(box) == 0)
    {
        gmx_fatal(FARGS, "Undefined solute box.\nCreate one with gmx editconf "
                  "or give explicit -box command line option");
    }

    add_solv(solventFileName, atoms, &x, v ? &v : NULL, &exclusionDistances, ePBC, box,
             aps, defaultDistance, scaleFactor, &atoms_added, &residues_added, r_shell, max_sol,
             oenv);

    /* write new configuration 1 to file confout */
    confout = ftp2fn(efSTO, NFILE, fnm);
    fprintf(stderr, "Writing generated configuration to %s\n", confout);
    if (bProt)
    {
        write_sto_conf(confout, title, atoms, x, v, ePBC, box);
        /* print box sizes and box type to stderr */
        fprintf(stderr, "%s\n", title);
    }
    else
    {
        write_sto_conf(confout, "Generated by gmx solvate", atoms, x, v, ePBC, box);
    }

    /* print size of generated configuration */
    fprintf(stderr, "\nOutput configuration contains %d atoms in %d residues\n",
            atoms->nr, atoms->nres);
    update_top(atoms, box, NFILE, fnm, aps);

    gmx_atomprop_destroy(aps);
    sfree(exclusionDistances);
    sfree(x);
    sfree(v);
    done_atom(atoms);
    sfree(atoms);

    return 0;
}
Beispiel #18
0
/* Read a whole line from the file. 
   The line may have arbitrary length and continuation lines ending
   with '\' are heeded.
   The function will return a pointer to a buffer or NULL if an
   error occured or eof occurs while no characters have been read.
   The function will set the global variable lineno.
*/
static char *vtf_getline(VTFFILE file) {
  static char *buffer = NULL;
  static int buffer_size = 0;
  char *s;   /* pointer to the place where the line will be read to */
  int bytes_left;              /* the number of bytes that are left */
  int l;

  if (buffer == NULL) {
    buffer_size = 255;
    buffer = malloc(buffer_size);
    /* TODO: error handling */
  }

  /* Point s to the beginning of buffer. */
  s = buffer;
  bytes_left = buffer_size;

  if (feof(file)) {
    sfree(buffer);
    buffer = NULL;
    return NULL;
  }
  do {
    /* read a line */
    if (fgets(s, bytes_left, file) == NULL) {
      sfree(buffer);
      buffer = NULL;
      return NULL;
    }

    vtf_lineno++;

    /* if we reached eof, finish */
    if (feof(file)) break;

    /* pos of the last char */
    l = strlen(s) - 1;
    if (l >= 0 && ( s[l] == '\n' || s[l] == '\r')) {
      l--;
      /* remove all line endings */
      while (l >= 0 && (s[l] == '\n' || s[l] == '\r')) l--;
      /* overwrite the first line ending char */
      s[l+1] = '\0';
      /* check the previous char, whether it is '\' */
      if (l >= 0 && s[l] == '\\') {
        /* last char before is continuation char */
        /* position s to the continuation char */
        bytes_left -= l+1;
        s += l+1;
      } else 
        /* otherwise, the line is complete */
        break;
    } else {
      /* last char is not a newline */
      /* enlarge the buffer */
      buffer_size += 255;
      buffer = realloc(buffer, buffer_size);
      /* TODO: error handling */
      /* reposition s */
      l = strlen(buffer);
      s = buffer + l;
      bytes_left += buffer_size - l;
      vtf_lineno--;
    }
  } while (1);

  /* now check the whole string */
  s = buffer;
  
  /* skip all leading whitespace */
  while (isspace(s[0])) s++;

  /* ignore comment lines */
  if (s[0] == '#') return vtf_getline(file);

  l = strlen(s);

  /* handle empty lines */
  if (l == 0) {
    if (feof(file)) {
      sfree(buffer);
      buffer = NULL;
      return NULL;
    }
    else return vtf_getline(file);
  }

  return s;
}
Beispiel #19
0
void sort_ions(int nsa, int nw, int repl[], atom_id index[],
               t_atoms *atoms, rvec x[],
               const char *p_name, const char *n_name)
{
    int    i, j, k, r, np, nn, starta, startr, npi, nni;
    rvec  *xt;
    char **pptr = NULL, **nptr = NULL, **paptr = NULL, **naptr = NULL;

    snew(xt, atoms->nr);

    /* Put all the solvent in front and count the added ions */
    np = 0;
    nn = 0;
    j  = index[0];
    for (i = 0; i < nw; i++)
    {
        r = repl[i];
        if (r == 0)
        {
            for (k = 0; k < nsa; k++)
            {
                copy_rvec(x[index[nsa*i+k]], xt[j++]);
            }
        }
        else if (r > 0)
        {
            np++;
        }
        else if (r < 0)
        {
            nn++;
        }
    }

    if (np+nn > 0)
    {
        /* Put the positive and negative ions at the end */
        starta = index[nsa*(nw - np - nn)];
        startr = atoms->atom[starta].resind;

        if (np)
        {
            snew(pptr, 1);
            pptr[0] = gmx_strdup(p_name);
            snew(paptr, 1);
            paptr[0] = aname(p_name);
        }
        if (nn)
        {
            snew(nptr, 1);
            nptr[0] = gmx_strdup(n_name);
            snew(naptr, 1);
            naptr[0] = aname(n_name);
        }
        npi = 0;
        nni = 0;
        for (i = 0; i < nw; i++)
        {
            r = repl[i];
            if (r > 0)
            {
                j = starta+npi;
                k = startr+npi;
                copy_rvec(x[index[nsa*i]], xt[j]);
                atoms->atomname[j]     = paptr;
                atoms->atom[j].resind  = k;
                atoms->resinfo[k].name = pptr;
                npi++;
            }
            else if (r < 0)
            {
                j = starta+np+nni;
                k = startr+np+nni;
                copy_rvec(x[index[nsa*i]], xt[j]);
                atoms->atomname[j]     = naptr;
                atoms->atom[j].resind  = k;
                atoms->resinfo[k].name = nptr;
                nni++;
            }
        }
        for (i = index[nsa*nw-1]+1; i < atoms->nr; i++)
        {
            j                  = i-(nsa-1)*(np+nn);
            atoms->atomname[j] = atoms->atomname[i];
            atoms->atom[j]     = atoms->atom[i];
            copy_rvec(x[i], xt[j]);
        }
        atoms->nr -= (nsa-1)*(np+nn);

        /* Copy the new positions back */
        for (i = index[0]; i < atoms->nr; i++)
        {
            copy_rvec(xt[i], x[i]);
        }
        sfree(xt);
    }
}
Beispiel #20
0
/* Parse the aid specifier.
   Return an integer list of the aids that need to be modifed. The
   list is terminated by -1. If the list is NULL, an error occured. If
   the list is empty (i.e. it only contains -1), the default atom is
   to be modified.
 */
static int *vtf_parse_aid_specifier(char *s, vtf_data *d) {
  int n;
  unsigned int aid, from, to, offset;
  unsigned int size = 0;
  int *aid_list = NULL;

  if (s[0] == 'd') {
    /* DEFAULT */
    /* if the specifier is "default", just leave the list empty! */
#ifdef DEBUG
    printf("%s", "\tdefine default atom\n");
#endif
  } else {
    /* otherwise parse the aid specifier */
    while (1) {
      from = d->natoms;

      if (sscanf(s, " %u:%u%n", &from, &to, &n) == 2) {
        /* RANGE */
        if (from > to) { 
          vtf_error("bad range specifier (from > to):", s); 
          sfree(aid_list);
          return NULL;
        }
        vtf_create_atoms_as_needed(to, d);
        /* add the range to the aid list */
        offset = size;
        size += to-from+1;
        aid_list = realloc(aid_list, size*sizeof(int));
        for (aid = from; aid <= to; aid++) {
          aid_list[offset] = aid;
          offset++;
        }

      } else if (sscanf(s, " %u%n", &to, &n) == 1) {
        /* SINGLE AID */
        vtf_create_atoms_as_needed(to, d);
        /* add the aid to the aid_list */
        size += 1;
        aid_list = realloc(aid_list, size*sizeof(int));
        aid_list[size - 1] = to;

      } else {
        /* ERROR */
        vtf_error("bad aid specifier", s);
        sfree(aid_list);
        return NULL;
      }

      /* advance s */
      s += n;

      /* if there is no more to parse, break */
      if (s[0] == '\0') break;

      /* otherwise the next char should be a ',' */
      if (s[0] != ',') {
        vtf_error("bad aid specifier", s);
        sfree(aid_list);
        return NULL;
      }
      /* skip the ',' */
      s++;
    };
  }

  /* Terminate the list with -1 */
  aid_list = realloc(aid_list, (size+1)*sizeof(int));
  aid_list[size] = -1;
  return aid_list;
}
gmx_shellfc_t init_shell_flexcon(FILE *fplog,
				 gmx_mtop_t *mtop,int nflexcon,
				 rvec *x)
{
  struct gmx_shellfc *shfc;
  t_shell     *shell;
  int         *shell_index=NULL,*at2cg;
  t_atom      *atom;
  int         n[eptNR],ns,nshell,nsi;
  int         i,j,nmol,type,mb,mt,a_offset,cg,mol,ftype,nra;
  real        qS,alpha;
  int         aS,aN=0; /* Shell and nucleus */
  int         bondtypes[] = { F_BONDS, F_HARMONIC, F_CUBICBONDS, F_POLARIZATION, F_WATER_POL };
#define NBT asize(bondtypes)
  t_iatom     *ia;
  gmx_mtop_atomloop_block_t aloopb;
  gmx_mtop_atomloop_all_t aloop;
  gmx_ffparams_t *ffparams;
  gmx_molblock_t *molb;
  gmx_moltype_t *molt;
  t_block     *cgs;

  /* Count number of shells, and find their indices */
  for(i=0; (i<eptNR); i++) {
    n[i] = 0;
  }

  aloopb = gmx_mtop_atomloop_block_init(mtop);
  while (gmx_mtop_atomloop_block_next(aloopb,&atom,&nmol)) {
    n[atom->ptype] += nmol;
  }

  if (fplog) {
    /* Print the number of each particle type */  
    for(i=0; (i<eptNR); i++) {
      if (n[i] != 0) {
	fprintf(fplog,"There are: %d %ss\n",n[i],ptype_str[i]);
      }
    }
  }

  nshell = n[eptShell];
  
  if (nshell == 0 && nflexcon == 0) {
    return NULL;
  }

  snew(shfc,1);
  shfc->nflexcon = nflexcon;

  if (nshell == 0) {
    return shfc;
  }

  /* We have shells: fill the shell data structure */

  /* Global system sized array, this should be avoided */
  snew(shell_index,mtop->natoms);

  aloop = gmx_mtop_atomloop_all_init(mtop);
  nshell = 0;
  while (gmx_mtop_atomloop_all_next(aloop,&i,&atom)) {
    if (atom->ptype == eptShell) {
      shell_index[i] = nshell++;
    }
  }

  snew(shell,nshell);
  
  /* Initiate the shell structures */    
  for(i=0; (i<nshell); i++) {
    shell[i].shell = NO_ATID;
    shell[i].nnucl = 0;
    shell[i].nucl1 = NO_ATID;
    shell[i].nucl2 = NO_ATID;
    shell[i].nucl3 = NO_ATID;
    /* shell[i].bInterCG=FALSE; */
    shell[i].k_1   = 0;
    shell[i].k     = 0;
  }

  ffparams = &mtop->ffparams;

  /* Now fill the structures */
  shfc->bInterCG = FALSE;
  ns = 0;
  a_offset = 0;
  for(mb=0; mb<mtop->nmolblock; mb++) {
    molb = &mtop->molblock[mb];
    molt = &mtop->moltype[molb->type];

    cgs = &molt->cgs;
    snew(at2cg,molt->atoms.nr);
    for(cg=0; cg<cgs->nr; cg++) {
      for(i=cgs->index[cg]; i<cgs->index[cg+1]; i++) {
	at2cg[i] = cg;
      }
    }

    atom = molt->atoms.atom;
    for(mol=0; mol<molb->nmol; mol++) {
      for(j=0; (j<NBT); j++) {
	ia = molt->ilist[bondtypes[j]].iatoms;
	for(i=0; (i<molt->ilist[bondtypes[j]].nr); ) {
	  type  = ia[0];
	  ftype = ffparams->functype[type];
	  nra   = interaction_function[ftype].nratoms;
	  
	  /* Check whether we have a bond with a shell */
	  aS = NO_ATID;
	  
	  switch (bondtypes[j]) {
	  case F_BONDS:
	  case F_HARMONIC:
	  case F_CUBICBONDS:
	  case F_POLARIZATION:
	    if (atom[ia[1]].ptype == eptShell) {
	      aS = ia[1];
	      aN = ia[2];
	    }
	    else if (atom[ia[2]].ptype == eptShell) {
	      aS = ia[2];
	      aN = ia[1];
	    }
	    break;
	  case F_WATER_POL:
	    aN    = ia[4];  /* Dummy */
	    aS    = ia[5];  /* Shell */
	    break;
	  default:
	    gmx_fatal(FARGS,"Death Horror: %s, %d",__FILE__,__LINE__);
	  }
	  
	  if (aS != NO_ATID) {	  
	    qS = atom[aS].q;
	    
	    /* Check whether one of the particles is a shell... */
	    nsi = shell_index[a_offset+aS];
	    if ((nsi < 0) || (nsi >= nshell))
	      gmx_fatal(FARGS,"nsi is %d should be within 0 - %d. aS = %d",
			nsi,nshell,aS);
	    if (shell[nsi].shell == NO_ATID) {
	      shell[nsi].shell = a_offset + aS;
	      ns ++;
	    }
	    else if (shell[nsi].shell != a_offset+aS)
	      gmx_fatal(FARGS,"Weird stuff in %s, %d",__FILE__,__LINE__);
	    
	    if      (shell[nsi].nucl1 == NO_ATID) {
	      shell[nsi].nucl1 = a_offset + aN;
	    } else if (shell[nsi].nucl2 == NO_ATID) {
	      shell[nsi].nucl2 = a_offset + aN;
	    } else if (shell[nsi].nucl3 == NO_ATID) {
	      shell[nsi].nucl3 = a_offset + aN;
	    } else {
	      if (fplog)
		pr_shell(fplog,ns,shell);
	      gmx_fatal(FARGS,"Can not handle more than three bonds per shell\n");
	    }
	    if (at2cg[aS] != at2cg[aN]) {
	      /* shell[nsi].bInterCG = TRUE; */
	      shfc->bInterCG = TRUE;
	    }
	    
	    switch (bondtypes[j]) {
	    case F_BONDS:
	    case F_HARMONIC:
	      shell[nsi].k    += ffparams->iparams[type].harmonic.krA;
	      break;
	    case F_CUBICBONDS:
	      shell[nsi].k    += ffparams->iparams[type].cubic.kb;
	      break;
	    case F_POLARIZATION:
	      if (qS != atom[aS].qB)
		gmx_fatal(FARGS,"polarize can not be used with qA != qB");
	      shell[nsi].k    += sqr(qS)*ONE_4PI_EPS0/
		ffparams->iparams[type].polarize.alpha;
	      break;
	    case F_WATER_POL:
	      if (qS != atom[aS].qB)
		gmx_fatal(FARGS,"water_pol can not be used with qA != qB");
	      alpha          = (ffparams->iparams[type].wpol.al_x+
				ffparams->iparams[type].wpol.al_y+
				ffparams->iparams[type].wpol.al_z)/3.0;
	      shell[nsi].k  += sqr(qS)*ONE_4PI_EPS0/alpha;
	      break;
	    default:
	      gmx_fatal(FARGS,"Death Horror: %s, %d",__FILE__,__LINE__);
	    }
	    shell[nsi].nnucl++;
	  }
	  ia += nra+1;
	  i  += nra+1;
	}
      }
      a_offset += molt->atoms.nr;
    }
    /* Done with this molecule type */
    sfree(at2cg);
  }
  
  /* Verify whether it's all correct */
  if (ns != nshell)
    gmx_fatal(FARGS,"Something weird with shells. They may not be bonded to something");
  
  for(i=0; (i<ns); i++)
    shell[i].k_1 = 1.0/shell[i].k;
  
  if (debug)
    pr_shell(debug,ns,shell);

  
  shfc->nshell_gl      = ns;
  shfc->shell_gl       = shell;
  shfc->shell_index_gl = shell_index;

  shfc->bPredict   = (getenv("GMX_NOPREDICT") == NULL);
  shfc->bForceInit = FALSE;
  if (!shfc->bPredict) {
    if (fplog)
      fprintf(fplog,"\nWill never predict shell positions\n");
  } else {
    shfc->bForceInit = (getenv("GMX_FORCEINIT") != NULL);
    if (shfc->bForceInit && fplog)
      fprintf(fplog,"\nWill always initiate shell positions\n");
  }

  if (shfc->bPredict) {
    if (x) {
      predict_shells(fplog,x,NULL,0,shfc->nshell_gl,shfc->shell_gl,
		     NULL,mtop,TRUE);
    }

    if (shfc->bInterCG) {
      if (fplog)
	fprintf(fplog,"\nNOTE: there all shells that are connected to particles outside thier own charge group, will not predict shells positions during the run\n\n");
      shfc->bPredict = FALSE;
    }
  }

  return shfc;
}
Beispiel #22
0
/* Parse atom data from line. 
   Return MOLFILE_SUCCESS, if data was sucessfully parsed, 
   MOLFILE_ERROR if an error occured. */
static int vtf_parse_atom(char *line, vtf_data *d) {
  static molfile_atom_t atom;
  static char keyword[255];
  static char msg[255];
  static char aid_specifier[255];
  int n;
  char *s;
  int rest_is_userdata;
  int *aid_list = NULL;

  atom = default_atom;
  s = line;

#ifdef DEBUG
  printf("\tatom record\n");
  printf("line: %s\n", s);
#endif

  /* HANDLE THE AID SPECIFIER */

  /* save the aid specifier */
  if (sscanf(s, " %255s%n", aid_specifier, &n) < 1) {
    vtf_error("atom specifier is missing", line);
    return MOLFILE_ERROR;
  }
  s += n;

  aid_list = vtf_parse_aid_specifier(aid_specifier, d);
  if (aid_list == NULL) return MOLFILE_ERROR;

  /* A -1 in the aid_list denotes the end of the list */
#define AIDLOOP(assignment)                                             \
  {                                                                     \
    int *aid_ptr;                                                       \
    for (aid_ptr = aid_list; *aid_ptr != -1; aid_ptr++) {               \
      int aid = *aid_ptr;                                               \
      molfile_atom_t *cur_atom = &d->atoms[aid];                        \
      assignment;                                                       \
    }                                                                   \
  }
  
  /* handle the keywords */
  rest_is_userdata = 0;
  while (sscanf(s, " %255s%n", keyword, &n) == 1) {
    s += n;
#ifdef DEBUG
    printf("keyword: \"%s\" rest: \"%s\"\n", keyword, s);
#endif
    switch (tolower(keyword[0])) {
    case 'n': {
      /* name */
      if (sscanf(s, " %16s%n", atom.name, &n) == 1) {
        AIDLOOP(strcpy(cur_atom->name, atom.name));
      } else {
        vtf_error("could not get name in atom record", line);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 't': {
      /* type */
      if (sscanf(s, " %16s%n", atom.type, &n) == 1) {
        AIDLOOP(strcpy(cur_atom->type, atom.type));
      } else {
        vtf_error("could not get type in atom record", line);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 'r': {
      /* resname, resid, radius */
      if (strlen(keyword) == 1 || 
          strncmp(keyword, "rad", 3) == 0) { 
        /* radius */
        if (sscanf(s, " %f%n", &atom.radius, &n) == 1) {
          AIDLOOP(cur_atom->radius = atom.radius);
        } else {
          vtf_error("could not get radius in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
        d->optflags |= MOLFILE_RADIUS;
      } else if (strcmp(keyword, "resid") == 0) {
        /* resid */
        if (sscanf(s, " %d%n", &atom.resid, &n) == 1) {
          AIDLOOP(cur_atom->resid = atom.resid);
        } else {
          vtf_error("could not get resid in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
      } else if (strcmp(keyword, "res") == 0 || 
                 strcmp(keyword, "resname") == 0) {
        /* resname */
        if (sscanf(s, " %8s%n", atom.resname, &n) == 1) {
          AIDLOOP(strcpy(cur_atom->resname, atom.resname));
        } else {
          vtf_error("could not get resname in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
      } else {
        strcpy(msg, "unrecognized keyword in atom record: ");
        strncat(msg, keyword, 200);
        vtf_error(msg, line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 's': {
      /* segid */
      if (sscanf(s, " %8s%n", atom.segid, &n) == 1) {
        AIDLOOP(strcpy(cur_atom->segid, atom.segid));
      } else {
        vtf_error("could not get segid in atom record", line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 'i': {
      /* insertion */
      if (sscanf(s, " %2s%n", atom.insertion, &n) == 1) {
        AIDLOOP(strcpy(cur_atom->insertion, atom.insertion));
      } else {
        vtf_error("could not get insertion in atom record", line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      d->optflags |= MOLFILE_INSERTION;
      s += n;
      break;
    }
    case 'c': {
      /* chain, charge */
      if (strlen(keyword) == 1 || 
          strcmp(keyword, "chain") == 0) {
        if (sscanf(s, " %2s%n", atom.chain, &n) == 1) {
          AIDLOOP(strcpy(cur_atom->chain, atom.chain));
          s += n;
          break;
        } else {
          vtf_error("could not get chain in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
      }
    } /* if "chain" is not recognized, continue with next case */
    case 'q': {
      /* q and charge */
      if (strlen(keyword) == 1 ||
          strcmp(keyword, "charge") == 0) {
        if (sscanf(s, " %f%n", &atom.charge, &n) == 1) {
          AIDLOOP(cur_atom->charge = atom.charge);
        } else {
          vtf_error("could not get charge in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
        d->optflags |= MOLFILE_CHARGE;
      } else {
        strcpy(msg, "unrecognized keyword in atom record: ");
        strncat(msg, keyword, 200);
        vtf_error(msg, line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 'a': {
      /* altloc, atomicnumber */
      if (strlen(keyword)== 1 || 
          strcmp(keyword, "atomicnumber") == 0) {
        if (sscanf(s, " %d%n", &atom.atomicnumber, &n) == 1) {
          AIDLOOP(cur_atom->atomicnumber = atom.atomicnumber);
        } else {
          vtf_error("could not get atomicnumber in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
        d->optflags |= MOLFILE_ATOMICNUMBER;
      } else if (strcmp(keyword, "altloc")) {
        if (sscanf(s, " %2s%n", atom.altloc, &n) == 1) {
          AIDLOOP(strcpy(cur_atom->altloc, atom.altloc));
        } else {
          vtf_error("could not get altloc in atom record", line);
          sfree(aid_list);
          return MOLFILE_ERROR;
        }
        d->optflags |= MOLFILE_ALTLOC;
      } else { 
        strcpy(msg, "unrecognized keyword in atom record: ");
        strncat(msg, keyword, 200);
        vtf_error(msg, line);
          sfree(aid_list);
        return MOLFILE_ERROR;
      }
      s += n;
      break;
    }
    case 'o': {
      /* occupancy */
      if (sscanf(s, " %f%n", &atom.occupancy, &n) == 1) {
        AIDLOOP(cur_atom->occupancy = atom.occupancy);
      } else {
        vtf_error("could not get occupancy in atom record", line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      d->optflags |= MOLFILE_OCCUPANCY;
      s += n;
      break;
    }
    case 'b': {
      /* bfactor */
      if (sscanf(s, " %f%n", &atom.bfactor, &n) == 1) {
        AIDLOOP(cur_atom->bfactor = atom.bfactor);
      } else {
        vtf_error("could not get bfactor in atom record", line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      d->optflags |= MOLFILE_BFACTOR;
      s += n;
      break;
    }
    case 'm': {
      /* mass */
      if (sscanf(s, " %f%n", &atom.mass, &n) == 1) {
        AIDLOOP(cur_atom->mass = atom.mass);
      } else {
        vtf_error("could not get mass in atom record", line);
        sfree(aid_list);
        return MOLFILE_ERROR;
      }
      d->optflags |= MOLFILE_MASS;
      s += n;
      break;
    }
    case 'u': {
      /* userdata: the rest of the line is user data */
      rest_is_userdata = 1;
#ifdef _USE_TCL
      if (d->read_mode != VTF_MOLFILE) {
        AIDLOOP(vtf_set_atom_userdata(aid, s));
      }
#endif
      break;
    }
    default: { 
      /* unrecognized */
      strcpy(msg, "unrecognized keyword in atom record: ");
      strncat(msg, keyword, 200);
      vtf_error(msg, line);
      sfree(aid_list);
      return MOLFILE_ERROR;
    }
    }
    if (rest_is_userdata) break;
  }

  /* if the aid_list is empty, modify the default atom */
  if (*aid_list == -1) {
      default_atom = atom;
      if (d->read_mode != VTF_MOLFILE) {
        sfree(default_userdata);
        default_userdata = strdup(s);
      }
  }

  sfree(aid_list);

#ifdef DEBUG
  printf("\tparsed keywords\n");
#endif

  return MOLFILE_SUCCESS;
}
Beispiel #23
0
void clear_constr(gmx_constr_t constr)
{
    sfree(constr);
    constr = NULL;
}
Beispiel #24
0
/* Called by _vtf_open_file_read() to parse the structure data. */
static void vtf_parse_structure(vtf_data *d) {
  char *line;                   /* next line in the file */
  char s[255];
  int n;
  
  /* initialize the default atom */
  strcpy(default_atom.name, "X");
  strcpy(default_atom.type, "X");
  strcpy(default_atom.resname, "X");
  default_atom.resid = 0;
  strcpy(default_atom.segid, "");
  strcpy(default_atom.chain, "");

  strcpy(default_atom.altloc, "");
  strcpy(default_atom.insertion, "");
  default_atom.occupancy = 1.0;
  default_atom.bfactor = 1.0;
  default_atom.mass = 1.0;
  default_atom.charge = 0.0;
  default_atom.radius = 1.0;

  default_userdata = NULL;

  do {
    line = vtf_getline(d->file);
    if (line == NULL) break;
#ifdef DEBUG
    printf("parsing line %d: \"%s\"\n", vtf_lineno, line);
#endif
    switch (tolower(line[0])) {
      /* ATOM RECORD */
    case 'a': {
      /* Remove the "atom" keyword" */
     sscanf(line, " %255s%n", s, &n);
      line += n;
    }
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':   
    case 'd': { 
      /* parse atom */
      d->return_code = vtf_parse_atom(line, d);
      break; 
    }

      /* BOND RECORD */
    case 'b': {
      /* Remove the "bond" keyword" */
      sscanf(line, " %255s%n", s, &n);
      line += n;
      d->return_code = vtf_parse_bond(line, d);
      break;
    }

      /* PBC/UNITCELL RECORD */
    case 'u':
    case 'p': {
      /* Remove the "pbc"/"unitcell" keyword */
      sscanf(line, " %255s%n", s, &n);
      line += n;
      d->return_code = vtf_parse_pbc(line, d);
      break;
    }

      /* TIMESTEP RECORD*/
    case 'c': 
    case 't': {
      /* Remove the "timestep" or "coordinates" keyword */
      sscanf(line, " %255s%n", s, &n);
      line += n;
    }
    case 'i': 
    case 'o': { 
      d->return_code = vtf_parse_timestep(line, d);
      line = NULL; /* indicate the end of the structure block */
      break; 
    }

      /* UNKNOWN RECORD */
    default: {
      vtf_error("unknown line type", line);
      d->return_code = MOLFILE_ERROR;
      break;
    }
    }
  } while (line != NULL && 
           d->return_code == MOLFILE_SUCCESS);

  /* test if structure data was parsed */
  if (d->read_mode == VTF_MOLFILE &&
      d->atoms == NULL && 
      d->return_code == MOLFILE_SUCCESS) {
    d->return_code = MOLFILE_NOSTRUCTUREDATA;
  }

  /* test whether another error has occured */
  if (errno != 0) {
    perror("vtfplugin");
    d->return_code = MOLFILE_ERROR;
  }

  sfree(default_userdata);
}
Beispiel #25
0
int gmx_do_dssp(int argc, char *argv[])
{
    const char        *desc[] = {
        "[THISMODULE] ",
        "reads a trajectory file and computes the secondary structure for",
        "each time frame ",
        "calling the dssp program. If you do not have the dssp program,",
        "get it from http://swift.cmbi.ru.nl/gv/dssp. [THISMODULE] assumes ",
        "that the dssp executable is located in ",
        "[TT]/usr/local/bin/dssp[tt]. If this is not the case, then you should",
        "set an environment variable [TT]DSSP[tt] pointing to the dssp",
        "executable, e.g.: [PAR]",
        "[TT]setenv DSSP /opt/dssp/bin/dssp[tt][PAR]",
        "Since version 2.0.0, dssp is invoked with a syntax that differs",
        "from earlier versions. If you have an older version of dssp,",
        "use the [TT]-ver[tt] option to direct do_dssp to use the older syntax.",
        "By default, do_dssp uses the syntax introduced with version 2.0.0.",
        "Even newer versions (which at the time of writing are not yet released)",
        "are assumed to have the same syntax as 2.0.0.[PAR]",
        "The structure assignment for each residue and time is written to an",
        "[TT].xpm[tt] matrix file. This file can be visualized with for instance",
        "[TT]xv[tt] and can be converted to postscript with [TT]xpm2ps[tt].",
        "Individual chains are separated by light grey lines in the [TT].xpm[tt] and",
        "postscript files.",
        "The number of residues with each secondary structure type and the",
        "total secondary structure ([TT]-sss[tt]) count as a function of",
        "time are also written to file ([TT]-sc[tt]).[PAR]",
        "Solvent accessible surface (SAS) per residue can be calculated, both in",
        "absolute values (A^2) and in fractions of the maximal accessible",
        "surface of a residue. The maximal accessible surface is defined as",
        "the accessible surface of a residue in a chain of glycines.",
        "[BB]Note[bb] that the program [gmx-sas] can also compute SAS",
        "and that is more efficient.[PAR]",
        "Finally, this program can dump the secondary structure in a special file",
        "[TT]ssdump.dat[tt] for usage in the program [gmx-chi]. Together",
        "these two programs can be used to analyze dihedral properties as a",
        "function of secondary structure type."
    };
    static gmx_bool    bVerbose;
    static const char *ss_string   = "HEBT";
    static int         dsspVersion = 2;
    t_pargs            pa[]        = {
        { "-v",  FALSE, etBOOL, {&bVerbose},
          "HIDDENGenerate miles of useless information" },
        { "-sss", FALSE, etSTR, {&ss_string},
          "Secondary structures for structure count"},
        { "-ver", FALSE, etINT, {&dsspVersion},
          "DSSP major version. Syntax changed with version 2"}
    };

    t_trxstatus       *status;
    FILE              *tapein;
    FILE              *ss, *acc, *fTArea, *tmpf;
    const char        *fnSCount, *fnArea, *fnTArea, *fnAArea;
    const char        *leg[] = { "Phobic", "Phylic" };
    t_topology         top;
    int                ePBC;
    t_atoms           *atoms;
    t_matrix           mat;
    int                nres, nr0, naccr, nres_plus_separators;
    gmx_bool          *bPhbres, bDoAccSurf;
    real               t;
    int                i, j, natoms, nframe = 0;
    matrix             box = {{0}};
    int                gnx;
    char              *grpnm, *ss_str;
    atom_id           *index;
    rvec              *xp, *x;
    int               *average_area;
    real             **accr, *accr_ptr = NULL, *av_area, *norm_av_area;
    char               pdbfile[32], tmpfile[32], title[256];
    char               dssp[256];
    const char        *dptr;
    output_env_t       oenv;
    gmx_rmpbc_t        gpbc = NULL;

    t_filenm           fnm[] = {
        { efTRX, "-f",   NULL,      ffREAD },
        { efTPS, NULL,   NULL,      ffREAD },
        { efNDX, NULL,   NULL,      ffOPTRD },
        { efDAT, "-ssdump", "ssdump", ffOPTWR },
        { efMAP, "-map", "ss",      ffLIBRD },
        { efXPM, "-o",   "ss",      ffWRITE },
        { efXVG, "-sc",  "scount",  ffWRITE },
        { efXPM, "-a",   "area",    ffOPTWR },
        { efXVG, "-ta",  "totarea", ffOPTWR },
        { efXVG, "-aa",  "averarea", ffOPTWR }
    };
#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv,
                           PCA_CAN_TIME | PCA_CAN_VIEW | PCA_TIME_UNIT,
                           NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }
    fnSCount   = opt2fn("-sc", NFILE, fnm);
    fnArea     = opt2fn_null("-a", NFILE, fnm);
    fnTArea    = opt2fn_null("-ta", NFILE, fnm);
    fnAArea    = opt2fn_null("-aa", NFILE, fnm);
    bDoAccSurf = (fnArea || fnTArea || fnAArea);

    read_tps_conf(ftp2fn(efTPS, NFILE, fnm), title, &top, &ePBC, &xp, NULL, box, FALSE);
    atoms = &(top.atoms);
    check_oo(atoms);
    bPhbres = bPhobics(atoms);

    get_index(atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, &gnx, &index, &grpnm);
    nres = 0;
    nr0  = -1;
    for (i = 0; (i < gnx); i++)
    {
        if (atoms->atom[index[i]].resind != nr0)
        {
            nr0 = atoms->atom[index[i]].resind;
            nres++;
        }
    }
    fprintf(stderr, "There are %d residues in your selected group\n", nres);

    strcpy(pdbfile, "ddXXXXXX");
    gmx_tmpnam(pdbfile);
    if ((tmpf = fopen(pdbfile, "w")) == NULL)
    {
        sprintf(pdbfile, "%ctmp%cfilterXXXXXX", DIR_SEPARATOR, DIR_SEPARATOR);
        gmx_tmpnam(pdbfile);
        if ((tmpf = fopen(pdbfile, "w")) == NULL)
        {
            gmx_fatal(FARGS, "Can not open tmp file %s", pdbfile);
        }
    }
    else
    {
        fclose(tmpf);
    }

    strcpy(tmpfile, "ddXXXXXX");
    gmx_tmpnam(tmpfile);
    if ((tmpf = fopen(tmpfile, "w")) == NULL)
    {
        sprintf(tmpfile, "%ctmp%cfilterXXXXXX", DIR_SEPARATOR, DIR_SEPARATOR);
        gmx_tmpnam(tmpfile);
        if ((tmpf = fopen(tmpfile, "w")) == NULL)
        {
            gmx_fatal(FARGS, "Can not open tmp file %s", tmpfile);
        }
    }
    else
    {
        fclose(tmpf);
    }

    if ((dptr = getenv("DSSP")) == NULL)
    {
        dptr = "/usr/local/bin/dssp";
    }
    if (!gmx_fexist(dptr))
    {
        gmx_fatal(FARGS, "DSSP executable (%s) does not exist (use setenv DSSP)",
                  dptr);
    }
    if (dsspVersion >= 2)
    {
        if (dsspVersion > 2)
        {
            printf("\nWARNING: You use DSSP version %d, which is not explicitly\nsupported by do_dssp. Assuming version 2 syntax.\n\n", dsspVersion);
        }

        sprintf(dssp, "%s -i %s -o %s > /dev/null %s",
                dptr, pdbfile, tmpfile, bVerbose ? "" : "2> /dev/null");
    }
    else
    {
        sprintf(dssp, "%s %s %s %s > /dev/null %s",
                dptr, bDoAccSurf ? "" : "-na", pdbfile, tmpfile, bVerbose ? "" : "2> /dev/null");

    }
    fprintf(stderr, "dssp cmd='%s'\n", dssp);

    if (fnTArea)
    {
        fTArea = xvgropen(fnTArea, "Solvent Accessible Surface Area",
                          output_env_get_xvgr_tlabel(oenv), "Area (nm\\S2\\N)", oenv);
        xvgr_legend(fTArea, 2, leg, oenv);
    }
    else
    {
        fTArea = NULL;
    }

    mat.map  = NULL;
    mat.nmap = readcmap(opt2fn("-map", NFILE, fnm), &(mat.map));

    natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box);
    if (natoms > atoms->nr)
    {
        gmx_fatal(FARGS, "\nTrajectory does not match topology!");
    }
    if (gnx > natoms)
    {
        gmx_fatal(FARGS, "\nTrajectory does not match selected group!");
    }

    snew(average_area, atoms->nres);
    snew(av_area, atoms->nres);
    snew(norm_av_area, atoms->nres);
    accr  = NULL;
    naccr = 0;

    gpbc = gmx_rmpbc_init(&top.idef, ePBC, natoms);
    do
    {
        t = output_env_conv_time(oenv, t);
        if (bDoAccSurf && nframe >= naccr)
        {
            naccr += 10;
            srenew(accr, naccr);
            for (i = naccr-10; i < naccr; i++)
            {
                snew(accr[i], 2*atoms->nres-1);
            }
        }
        gmx_rmpbc(gpbc, natoms, box, x);
        tapein = gmx_ffopen(pdbfile, "w");
        write_pdbfile_indexed(tapein, NULL, atoms, x, ePBC, box, ' ', -1, gnx, index, NULL, TRUE);
        gmx_ffclose(tapein);

#ifdef GMX_NO_SYSTEM
        printf("Warning-- No calls to system(3) supported on this platform.");
        printf("Warning-- Skipping execution of 'system(\"%s\")'.", dssp);
        exit(1);
#else
        if (0 != system(dssp))
        {
            gmx_fatal(FARGS, "Failed to execute command: %s\n",
                      "Try specifying your dssp version with the -ver option.", dssp);
        }
#endif

        /* strip_dssp returns the number of lines found in the dssp file, i.e.
         * the number of residues plus the separator lines */

        if (bDoAccSurf)
        {
            accr_ptr = accr[nframe];
        }

        nres_plus_separators = strip_dssp(tmpfile, nres, bPhbres, t,
                                          accr_ptr, fTArea, &mat, average_area, oenv);
        remove(tmpfile);
        remove(pdbfile);
        nframe++;
    }
    while (read_next_x(oenv, status, &t, x, box));
    fprintf(stderr, "\n");
    close_trj(status);
    if (fTArea)
    {
        gmx_ffclose(fTArea);
    }
    gmx_rmpbc_done(gpbc);

    prune_ss_legend(&mat);

    ss        = opt2FILE("-o", NFILE, fnm, "w");
    mat.flags = 0;
    write_xpm_m(ss, mat);
    gmx_ffclose(ss);

    if (opt2bSet("-ssdump", NFILE, fnm))
    {
        ss = opt2FILE("-ssdump", NFILE, fnm, "w");
        snew(ss_str, nres+1);
        fprintf(ss, "%d\n", nres);
        for (j = 0; j < mat.nx; j++)
        {
            for (i = 0; (i < mat.ny); i++)
            {
                ss_str[i] = mat.map[mat.matrix[j][i]].code.c1;
            }
            ss_str[i] = '\0';
            fprintf(ss, "%s\n", ss_str);
        }
        gmx_ffclose(ss);
        sfree(ss_str);
    }
    analyse_ss(fnSCount, &mat, ss_string, oenv);

    if (bDoAccSurf)
    {
        write_sas_mat(fnArea, accr, nframe, nres_plus_separators, &mat);

        for (i = 0; i < atoms->nres; i++)
        {
            av_area[i] = (average_area[i] / (real)nframe);
        }

        norm_acc(atoms, nres, av_area, norm_av_area);

        if (fnAArea)
        {
            acc = xvgropen(fnAArea, "Average Accessible Area",
                           "Residue", "A\\S2", oenv);
            for (i = 0; (i < nres); i++)
            {
                fprintf(acc, "%5d  %10g %10g\n", i+1, av_area[i], norm_av_area[i]);
            }
            gmx_ffclose(acc);
        }
    }

    view_all(oenv, NFILE, fnm);

    return 0;
}
Beispiel #26
0
/* Opens the file for reading.  To determine the number of atoms in
   the file, it is necessary to parse the structure information,
   anyway. Therefore, this function will parse the structure data and
   save the information in the plugin's data structure.

   The read_mode defines whether the file is read from VMD via the
   plugin API (VTF_MOLFILE) to read structure and timestep data, or
   via the vtftools to read userdata (VTF_USERDATA).

   The function vtf_open_file_read() that is actually called by the
   molfile reader plugin is defined below this function.
*/
static vtf_data *
_vtf_open_file_read(const char *filepath, 
                    const char *filetype, 
                    int *natoms,
                    int read_mode) {
  vtf_data *d;

  /* printf("Loading file %s\n  of type %s using vtfplugin v%i.%i.\n", 
     filepath, filetype, VERSION_MAJOR, VERSION_MINOR); */

  /* initialize the data structure */
  d = malloc(sizeof(vtf_data));
  
  errno = 0;

  d->return_code = MOLFILE_SUCCESS;
  d->read_mode = read_mode;

  /* initialize structure data */
  d->optflags = MOLFILE_NOOPTIONS;
  d->natoms = 0;
  d->atoms = NULL;
  d->nbonds = 0;
  d->from = NULL;
  d->to = NULL;

  /* initialize timestep data */
  d->timestep = 0;
  d->timestep_mode = TIMESTEP_ORDERED;
  d->coords = NULL;
  d->A = 0.0;
  d->B = 0.0;
  d->C = 0.0;
  d->alpha = 90.0;
  d->beta = 90.0;
  d->gamma = 90.0;

  /* Open the file */
  d->file = fopen(filepath, "rb");
  if (d->file == NULL) {
    /* Could not open file */
    char msg[255];
    sprintf(msg, "vtfplugin: %s", filepath);
    perror(msg);
    sfree(d);
    return NULL;
  }

  if (strcmp(filetype, "vcf") == 0) {
    d->timestep_mode = TIMESTEP_VCFSTART;
    d->natoms = MOLFILE_NUMATOMS_UNKNOWN;
    *natoms = MOLFILE_NUMATOMS_UNKNOWN;
    d->return_code = MOLFILE_NOSTRUCTUREDATA;
  } else {
    vtf_parse_structure(d);
    
    if (d->return_code != MOLFILE_SUCCESS) {
      /* close the file */
      fclose(d->file);

      /* free the data */
      sfree(d->atoms);
      sfree(d->coords);
      sfree(d->from);
      sfree(d->to);
      sfree(d);
      return NULL;
    }
   
    *natoms = d->natoms;
  }

  return d;
}
Beispiel #27
0
/* generate a random valid board; uses validate_board. */
static void make_board(int *board, int w, int h, random_state *rs) {
    int *dsf;

    const unsigned int sz = w * h;

    /* w=h=2 is a special case which requires a number > max(w, h) */
    /* TODO prove that this is the case ONLY for w=h=2. */
    const int maxsize = min(max(max(w, h), 3), 9);

    /* Note that if 1 in {w, h} then it's impossible to have a region
     * of size > w*h, so the special case only affects w=h=2. */

    int nboards = 0;
    int i;

    assert(w >= 1);
    assert(h >= 1);

    assert(board);

    dsf = snew_dsf(sz); /* implicit dsf_init */

    /* I abuse the board variable: when generating the puzzle, it
     * contains a shuffled list of numbers {0, ..., nsq-1}. */
    for (i = 0; i < (int)sz; ++i) board[i] = i;

    while (1) {
	int change;
	++nboards;
	shuffle(board, sz, sizeof (int), rs);
	/* while the board can in principle be fixed */
	do {
	    change = FALSE;
	    for (i = 0; i < (int)sz; ++i) {
		int a = SENTINEL;
		int b = SENTINEL;
		int c = SENTINEL;
		const int aa = dsf_canonify(dsf, board[i]);
		int cc = sz;
		int j;
		for (j = 0; j < 4; ++j) {
		    const int x = (board[i] % w) + dx[j];
		    const int y = (board[i] / w) + dy[j];
		    int bb;
		    if (x < 0 || x >= w || y < 0 || y >= h) continue;
		    bb = dsf_canonify(dsf, w*y + x);
		    if (aa == bb) continue;
		    else if (dsf_size(dsf, aa) == dsf_size(dsf, bb)) {
			a = aa;
			b = bb;
			c = cc;
		    } else if (cc == sz) c = cc = bb;
		}
		if (a != SENTINEL) {
		    a = dsf_canonify(dsf, a);
		    assert(a != dsf_canonify(dsf, b));
		    if (c != sz) assert(a != dsf_canonify(dsf, c));
		    dsf_merge(dsf, a, c == sz? b: c);
		    /* if repair impossible; make a new board */
		    if (dsf_size(dsf, a) > maxsize) goto retry;
		    change = TRUE;
		}
	    }
	} while (change);

	for (i = 0; i < (int)sz; ++i) board[i] = dsf_size(dsf, i);

	sfree(dsf);
	printv("returning board number %d\n", nboards);
	return;

    retry:
	dsf_init(dsf, sz);
    }
    assert(FALSE); /* unreachable */
}
Beispiel #28
0
static int scan_ene_files(char **fnms, int nfiles,
                          real *readtime, real *timestep, int *nremax)
{
    /* Check number of energy terms and start time of all files */
    int          f, i, nre, nremin = 0, nresav = 0;
    ener_file_t  in;
    real         t1, t2;
    char         inputstring[STRLEN];
    gmx_enxnm_t *enm;
    t_enxframe  *fr;

    snew(fr, 1);

    for (f = 0; f < nfiles; f++)
    {
        in  = open_enx(fnms[f], "r");
        enm = NULL;
        do_enxnms(in, &nre, &enm);

        if (f == 0)
        {
            nresav  = nre;
            nremin  = nre;
            *nremax = nre;
            do_enx(in, fr);
            t1 = fr->t;
            do_enx(in, fr);
            t2          = fr->t;
            *timestep   = t2-t1;
            readtime[f] = t1;
            close_enx(in);
        }
        else
        {
            nremin  = min(nremin, fr->nre);
            *nremax = max(*nremax, fr->nre);
            if (nre != nresav)
            {
                fprintf(stderr,
                        "Energy files don't match, different number of energies:\n"
                        " %s: %d\n %s: %d\n", fnms[f-1], nresav, fnms[f], fr->nre);
                fprintf(stderr,
                        "\nContinue conversion using only the first %d terms (n/y)?\n"
                        "(you should be sure that the energy terms match)\n", nremin);
                if (NULL == fgets(inputstring, STRLEN-1, stdin))
                {
                    gmx_fatal(FARGS, "Error reading user input");
                }
                if (inputstring[0] != 'y' && inputstring[0] != 'Y')
                {
                    fprintf(stderr, "Will not convert\n");
                    exit(0);
                }
                nresav = fr->nre;
            }
            do_enx(in, fr);
            readtime[f] = fr->t;
            close_enx(in);
        }
        fprintf(stderr, "\n");
        free_enxnms(nre, enm);
    }

    free_enxframe(fr);
    sfree(fr);

    return nremin;
}
Beispiel #29
0
Socket platform_new_connection(SockAddr addr, char *hostname,
			       int port, int privport,
			       int oobinline, int nodelay, int keepalive,
			       Plug plug, Conf *conf)
{
    char *cmd;
    HANDLE us_to_cmd, us_from_cmd, cmd_to_us, cmd_from_us;
    SECURITY_ATTRIBUTES sa;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    if (conf_get_int(conf, CONF_proxy_type) != PROXY_CMD)
	return NULL;

    cmd = format_telnet_command(addr, port, conf);

    /* We are responsible for this and don't need it any more */
    sk_addr_free(addr);

    {
	char *msg = dupprintf("Starting local proxy command: %s", cmd);
	/* We're allowed to pass NULL here, because we're part of the Windows
	 * front end so we know logevent doesn't expect any data. */
	logevent(NULL, msg);
	sfree(msg);
    }

    /*
     * Create the pipes to the proxy command, and spawn the proxy
     * command process.
     */
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;    /* default */
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&us_from_cmd, &cmd_to_us, &sa, 0)) {
	Socket ret =
            new_error_socket("Unable to create pipes for proxy command", plug);
        sfree(cmd);
	return ret;
    }

    if (!CreatePipe(&cmd_from_us, &us_to_cmd, &sa, 0)) {
	Socket ret =
            new_error_socket("Unable to create pipes for proxy command", plug);
        sfree(cmd);
	CloseHandle(us_from_cmd);
	CloseHandle(cmd_to_us);
	return ret;
    }

    SetHandleInformation(us_to_cmd, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(us_from_cmd, HANDLE_FLAG_INHERIT, 0);

    si.cb = sizeof(si);
    si.lpReserved = NULL;
    si.lpDesktop = NULL;
    si.lpTitle = NULL;
    si.dwFlags = STARTF_USESTDHANDLES;
    si.cbReserved2 = 0;
    si.lpReserved2 = NULL;
    si.hStdInput = cmd_from_us;
    si.hStdOutput = cmd_to_us;
    si.hStdError = NULL;
    CreateProcess(NULL, cmd, NULL, NULL, TRUE,
		  CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS,
		  NULL, NULL, &si, &pi);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    sfree(cmd);

    CloseHandle(cmd_from_us);
    CloseHandle(cmd_to_us);

    return make_handle_socket(us_to_cmd, us_from_cmd, plug, FALSE);
}
Beispiel #30
0
static void calc_axes(rvec x[], t_atom atom[], int gnx[], atom_id *index[],
                      gmx_bool bRot, t_bundle *bun)
{
    int   end, i, div, d;
    real *mtot, m;
    rvec  axis[MAX_ENDS], cent;

    snew(mtot, bun->n);

    for (end = 0; end < bun->nend; end++)
    {
        for (i = 0; i < bun->n; i++)
        {
            clear_rvec(bun->end[end][i]);
            mtot[i] = 0;
        }
        div = gnx[end]/bun->n;
        for (i = 0; i < gnx[end]; i++)
        {
            m = atom[index[end][i]].m;
            for (d = 0; d < DIM; d++)
            {
                bun->end[end][i/div][d] += m*x[index[end][i]][d];
            }
            mtot[i/div] += m;
        }
        clear_rvec(axis[end]);
        for (i = 0; i < bun->n; i++)
        {
            svmul(1.0/mtot[i], bun->end[end][i], bun->end[end][i]);
            rvec_inc(axis[end], bun->end[end][i]);
        }
        svmul(1.0/bun->n, axis[end], axis[end]);
    }
    sfree(mtot);

    rvec_add(axis[0], axis[1], cent);
    svmul(0.5, cent, cent);
    /* center the bundle on the origin */
    for (end = 0; end < bun->nend; end++)
    {
        rvec_dec(axis[end], cent);
        for (i = 0; i < bun->n; i++)
        {
            rvec_dec(bun->end[end][i], cent);
        }
    }
    if (bRot)
    {
        /* rotate the axis parallel to the z-axis */
        rotate_ends(bun, axis[0], YY, ZZ);
        rotate_ends(bun, axis[0], XX, ZZ);
    }
    for (i = 0; i < bun->n; i++)
    {
        rvec_add(bun->end[0][i], bun->end[1][i], bun->mid[i]);
        svmul(0.5, bun->mid[i], bun->mid[i]);
        rvec_sub(bun->end[0][i], bun->end[1][i], bun->dir[i]);
        bun->len[i] = norm(bun->dir[i]);
        unitv(bun->dir[i], bun->dir[i]);
    }
}