Beispiel #1
0
 @SuppressWarnings("unchecked")
 public static String escape(Object x) {
   if (x instanceof String) return escape((String) x);
   if (x instanceof List<?>) return escape((ArrayList<ScriptVariable>) x);
   if (x instanceof BitSet) return escape((BitSet) x, true);
   if (x instanceof Matrix3f)
     return TextFormat.simpleReplace(((Matrix3f) x).toString(), "\t", ",\t");
   if (x instanceof Matrix4f)
     return TextFormat.simpleReplace(((Matrix4f) x).toString(), "\t", ",\t");
   if (x instanceof Tuple3f) return escape((Tuple3f) x);
   if (x instanceof Point4f) {
     Point4f xyzw = (Point4f) x;
     return "{" + xyzw.x + " " + xyzw.y + " " + xyzw.z + " " + xyzw.w + "}";
   }
   if (x instanceof AxisAngle4f) {
     AxisAngle4f a = (AxisAngle4f) x;
     return "{" + a.x + " " + a.y + " " + a.z + " " + (float) (a.angle * 180d / Math.PI) + "}";
   }
   if (x instanceof String[]) return escape((String[]) x, true);
   if (x instanceof int[]
       || x instanceof int[][]
       || x instanceof float[]
       || x instanceof double[]
       || x instanceof float[][]
       || x instanceof float[][][]) return toJSON(null, x);
   if (x instanceof Point3f[]) return escapeArray(x);
   if (x instanceof Map) return escape((Map<String, Object>) x);
   return (x == null ? "null" : x.toString());
 }
Beispiel #2
0
 private static String fixString(String s) {
   if (s == null || s.indexOf("{\"") == 0) // don't doubly fix JSON strings when retrieving status
   return s;
   s = TextFormat.simpleReplace(s, "\"", "''");
   s = TextFormat.simpleReplace(s, "\n", " | ");
   return "\"" + s + "\"";
 }
Beispiel #3
0
 public static String escapeUrl(String url) {
   url = TextFormat.simpleReplace(url, "\n", "");
   url = TextFormat.simpleReplace(url, "%", "%25");
   url = TextFormat.simpleReplace(url, "[", "%5B");
   url = TextFormat.simpleReplace(url, "]", "%5D");
   url = TextFormat.simpleReplace(url, " ", "%20");
   return url;
 }
Beispiel #4
0
  private void readAtoms() throws Exception {

    // format (4X,I4,4X,F10.8,3X,F10.8,3X,F10.8)

    readLine();
    while (line != null && (line.indexOf("ATOM") == 0 || !doSymmetry && line.indexOf(":") == 8)) {
      int thisAtom = atomSetCollection.getAtomCount();
      addAtom();
      if (readLine().indexOf("MULT=") == 10)
        for (int i = parseInt(line.substring(15, 18)); --i >= 0; ) {
          readLine();
          if (!doSymmetry) addAtom();
        }
      // format (A10,5X,I5,5X,F10.8,5X,F10.5,5X,F5.2)

      String atomName = line.substring(0, 10);
      String sym = atomName.substring(0, 2).trim();
      if (sym.length() == 2 && Character.isDigit(sym.charAt(1))) sym = sym.substring(0, 1);
      atomName = TextFormat.simpleReplace(atomName, " ", "");
      int n = 0;
      for (int i = atomSetCollection.getAtomCount(); --i >= thisAtom; ) {
        Atom atom = atomSetCollection.getAtom(i);
        atom.elementSymbol = sym;
        atom.atomName = atomName + "_" + (n++);
      }
      while (readLine() != null && line.indexOf("ATOM") < 0 && line.indexOf("SYMMETRY") < 0) {}
    }
    // return with "SYMMETRY" line in buffer
  }
 String getDebugFooter(int iType, double energy) {
   String s = "";
   switch (iType) {
     case CALC_DISTANCE:
       s = "BOND STRETCHING";
       break;
     case CALC_ANGLE:
       s = "ANGLE BENDING";
       break;
     case CALC_TORSION:
       s = "TORSIONAL";
       break;
     case CALC_OOP:
       s = "OUT-OF-PLANE BENDING";
       break;
     case CALC_VDW:
       s = "VAN DER WAALS";
       break;
     case CALC_ES:
       s = "ELECTROSTATIC ENERGY";
       break;
   }
   return TextFormat.sprintf(
       "\n     TOTAL %s ENERGY = %8.3f %s\n",
       new String[] {s, getUnit()}, new float[] {(float) energy});
 }
 private static String localizeFileReferences(String script, String[] origFileList, String [] copiedFileNames) {
   for (int i = 0; i < origFileList.length; i++) {
     String fullPathName = origFileList[i];
     String fullCopiedName = copiedFileNames[i];
     String name = fullCopiedName.substring(fullCopiedName.lastIndexOf('/') + 1);
     if (!name.equals(fullPathName))
       script = TextFormat.simpleReplace(script, fullPathName,name);
   }
   return script;
 }
Beispiel #7
0
  public static JmolData getJmol(int width, int height, String commandOptions) {
    JmolApp jmolApp = new JmolApp();
    jmolApp.startupHeight = height;
    jmolApp.startupWidth = width;
    jmolApp.haveConsole = false;
    jmolApp.isDataOnly = true;
    // jmolApp.info.put("exit", Boolean.TRUE);

    String[] args = TextFormat.split(commandOptions, ' '); // doesn't allow for double-quoted
    jmolApp.parseCommandLine(args);
    return new JmolData(jmolApp);
  }
Beispiel #8
0
  /*
    //
    //          f(x + 2delta) - 2f(x + delta) + f(x)
    // f''(x) = ------------------------------------
    //                        (delta)^2
    //
    void getNumericalSecondDerivative(MinAtom atom, int terms, Vector3d dir) {
      double delta = 1.0e-5;
      double e0 = getEnergy(terms, false);
      double dx = getDx2(atom, terms, 0, e0, delta);
      double dy = getDx2(atom, terms, 1, e0, delta);
      double dz = getDx2(atom, terms, 2, e0, delta);
      dir.set(dx, dy, dz);
    }

    private double getDx2(MinAtom atom, int terms, int i,
                                       double e0, double delta) {
      // calculate f(1)
      atom.coord[i] += delta;
      double e1 = getEnergy(terms, false);
      // calculate f(2)
      atom.coord[i] += delta;
      double e2 = getEnergy(terms, false);
      atom.coord[i] -= 2 * delta;
      return (e2 - 2 * e1 + e0) / (delta * delta);
    }

  */
  public double energyFull(boolean gradients, boolean isSilent) {
    double energy;

    if (gradients) clearForces();

    energy =
        energyBond(gradients)
            + energyAngle(gradients)
            + energyTorsion(gradients)
            + energyStretchBend(gradients)
            + energyOOP(gradients)
            + energyVDW(gradients)
            + energyES(gradients);

    if (!isSilent && calc.loggingEnabled)
      calc.appendLogData(
          TextFormat.sprintf(
              "\nTOTAL %s ENERGY = %8.3f %s/mol\n",
              new Object[] {name, Float.valueOf(toUserUnits(energy)), minimizer.units}));
    return energy;
  }
 String getAtomList(String title) {
   String trailer =
       "----------------------------------------"
           + "-------------------------------------------------------\n";
   StringBuffer sb = new StringBuffer();
   sb.append(
       "\n"
           + title
           + "\n\n"
           + " ATOM    X        Y        Z    TYPE     GRADX    GRADY    GRADZ  "
           + "---------BONDED ATOMS--------\n"
           + trailer);
   for (int i = 0; i < atomCount; i++) {
     MinAtom atom = atoms[i];
     int[] others = atom.getBondedAtomIndexes();
     int[] iVal = new int[others.length + 1];
     iVal[0] = atom.atom.getAtomNumber();
     String s = "   ";
     for (int j = 0; j < others.length; j++) {
       s += " %3d";
       iVal[j + 1] = atoms[others[j]].atom.getAtomNumber();
     }
     sb.append(
         TextFormat.sprintf(
             "%3d %8.3f %8.3f %8.3f  %-5s %8.3f %8.3f %8.3f" + s + "\n",
             new String[] {atom.type},
             new float[] {
               (float) atom.coord[0],
               (float) atom.coord[1],
               (float) atom.coord[2],
               (float) atom.force[0],
               (float) atom.force[1],
               (float) atom.force[2],
             },
             iVal));
   }
   sb.append(trailer + "\n\n");
   return sb.toString();
 }
Beispiel #10
0
 public void steepestDescentInitialize(int stepMax, double criterion) {
   this.stepMax = stepMax; // 1000
   // The criterion must be in the units of the calculation.
   // However, the user is setting this, so they will be in Minimizer units.
   //
   this.criterion = criterion / toUserUnits(1); // 1e-3
   currentStep = 0;
   clearForces();
   calc.setLoggingEnabled(true);
   calc.setLoggingEnabled(stepMax == 0 || Logger.isActiveLevel(Logger.LEVEL_DEBUGHIGH));
   String s =
       name
           + " "
           + calc.getDebugHeader(-1)
           + "Jmol Minimization Version "
           + Viewer.getJmolVersion()
           + "\n";
   calc.appendLogData(s);
   Logger.info(s);
   calc.getConstraintList();
   if (calc.loggingEnabled)
     calc.appendLogData(calc.getAtomList("S T E E P E S T   D E S C E N T"));
   dE = 0;
   calc.setPreliminary(stepMax > 0);
   e0 = energyFull(false, false);
   s =
       TextFormat.sprintf(
           " Initial "
               + name
               + " E = %10.3f "
               + minimizer.units
               + " criterion = %8.6f max steps = "
               + stepMax,
           new Object[] {Float.valueOf(toUserUnits(e0)), Float.valueOf(toUserUnits(criterion))});
   minimizer.report(s, false);
   calc.appendLogData(s);
 }
  boolean fileWriter(File file, JList InstanceList) throws IOException { //returns true if successful.
    useAppletJS = JmolViewer.checkOption(viewer, "webMakerCreateJS");
    //          JOptionPane.showMessageDialog(null, "Creating directory for data...");
    String datadirPath = file.getPath();
    String datadirName = file.getName();
    String fileName = null;
    if (datadirName.indexOf(".htm") > 0) {
      fileName = datadirName;
      datadirPath = file.getParent();
      file = new File(datadirPath);
      datadirName = file.getName();
    } else {
      fileName = datadirName + ".html";
    }
    datadirPath = datadirPath.replace('\\', '/');
    boolean made_datadir = (file.exists() && file.isDirectory() || file.mkdir());
    DefaultListModel listModel = (DefaultListModel) InstanceList.getModel();
    LogPanel.log("");
    if (made_datadir) {
      LogPanel.log(GT._("Using directory {0}", datadirPath));
      LogPanel.log("  " + GT._("adding JmolPopIn.js"));
 
      viewer.writeTextFile(datadirPath + "/JmolPopIn.js",
          WebExport.getResourceString(this, "JmolPopIn.js"));
      for (int i = 0; i < listModel.getSize(); i++) {
        JmolInstance thisInstance = (JmolInstance) (listModel.getElementAt(i));
        String javaname = thisInstance.javaname;
        String script = thisInstance.script;
        LogPanel.log("  ...jmolApplet" + i);
        LogPanel.log("      ..." + GT._("adding {0}.png", javaname));
        try {
          thisInstance.movepict(datadirPath);
        } catch (IOException IOe) {
          throw IOe;
        }

        String fileList = "";
        fileList += addFileList(script, "/*file*/");
        fileList += addFileList(script, "FILE0=");
        fileList += addFileList(script, "FILE1=");
        if (localAppletPath.getText().equals(".")
            || remoteAppletPath.getText().equals("."))
          fileList += "Jmol.js\nJmolApplet.jar";
        String[] filesToCopy = fileList.split("\n");
        String[] copiedFileNames = new String[filesToCopy.length];
        String f;
        int pt;
        for (int iFile = 0; iFile < filesToCopy.length; iFile++) {
          if ((pt = (f = filesToCopy[iFile]).indexOf("|")) >= 0)
            filesToCopy[iFile] = f.substring(0, pt);
          copiedFileNames[iFile] = copyBinaryFile(filesToCopy[iFile],
              datadirPath);
        }
        script = localizeFileReferences(script, filesToCopy, copiedFileNames);
        LogPanel.log("      ..." + GT._("adding {0}.spt", javaname));
        viewer.writeTextFile(datadirPath + "/" + javaname + ".spt", script);
      }
      String html = WebExport.getResourceString(this, panelName + "_template");
      html = fixHtml(html);
      appletInfoDivs = "";
      StringBuffer appletDefs = new StringBuffer();
      if (!useAppletJS)
        htmlAppletTemplate = WebExport.getResourceString(this, panelName + "_template2");
      for (int i = 0; i < listModel.getSize(); i++)
        html = getAppletDefs(i, html, appletDefs, (JmolInstance) listModel
            .getElementAt(i));
      html = TextFormat.simpleReplace(html, "@AUTHOR@", GT.escapeHTML(pageAuthorName
          .getText()));
      html = TextFormat.simpleReplace(html, "@TITLE@", GT.escapeHTML(webPageTitle.getText()));
      html = TextFormat.simpleReplace(html, "@REMOTEAPPLETPATH@",
          remoteAppletPath.getText());
      html = TextFormat.simpleReplace(html, "@LOCALAPPLETPATH@",
          localAppletPath.getText());
      html = TextFormat.simpleReplace(html, "@DATADIRNAME@", datadirName);
      if (appletInfoDivs.length() > 0)
        appletInfoDivs = "\n<div style='display:none'>\n" + appletInfoDivs
            + "\n</div>\n";
      String str = appletDefs.toString();
      if (useAppletJS)
        str = "<script type='text/javascript'>\n" + str + "\n</script>";
      html = TextFormat.simpleReplace(html, "@APPLETINFO@", appletInfoDivs);
      html = TextFormat.simpleReplace(html, "@APPLETDEFS@", str);
      html = TextFormat.simpleReplace(html, "@CREATIONDATA@", GT.escapeHTML(WebExport
          .TimeStamp_WebLink()));
      html = TextFormat.simpleReplace(html, "@AUTHORDATA@",
          GT.escapeHTML(GT._("Based on template by A. Herr&#x00E1;ez as modified by J. Gutow")));
      html = TextFormat.simpleReplace(html, "@LOGDATA@", "<pre>\n"
          + LogPanel.getText() + "\n</pre>\n");
      LogPanel.log("      ..." + GT._("creating {0}", fileName));
      viewer.writeTextFile(datadirPath + "/" + fileName, html);
    } else {
      IOException IOe = new IOException("Error creating directory: "
          + datadirPath);
      throw IOe;
    }
    LogPanel.log("");
    return true;
  }
Beispiel #12
0
  // Vector3d dir = new Vector3d();
  public boolean steepestDescentTakeNSteps(int n) {
    if (stepMax == 0) return false;
    boolean isPreliminary = true;
    for (int iStep = 1; iStep <= n; iStep++) {
      currentStep++;
      calc.setSilent(true);
      for (int i = 0; i < minAtomCount; i++)
        if (bsFixed == null || !bsFixed.get(i))
          setForcesUsingNumericalDerivative(minAtoms[i], ENERGY);
      linearSearch();
      calc.setSilent(false);

      if (calc.loggingEnabled) calc.appendLogData(calc.getAtomList("S T E P    " + currentStep));

      double e1 = energyFull(false, false);
      dE = e1 - e0;
      boolean done = Util.isNear(e1, e0, criterion);

      if (done || currentStep % 10 == 0 || stepMax <= currentStep) {
        String s =
            TextFormat.sprintf(
                name + " Step %-4d E = %10.6f    dE = %8.6f ",
                new Object[] {
                  new float[] {(float) e1, (float) (dE), (float) criterion},
                  Integer.valueOf(currentStep)
                });
        minimizer.report(s, false);
        calc.appendLogData(s);
      }
      e0 = e1;
      if (done || stepMax <= currentStep) {
        if (calc.loggingEnabled) calc.appendLogData(calc.getAtomList("F I N A L  G E O M E T R Y"));
        if (done) {
          String s =
              TextFormat.formatString(
                  "\n    "
                      + name
                      + " STEEPEST DESCENT HAS CONVERGED: E = %8.5f "
                      + minimizer.units
                      + " after "
                      + currentStep
                      + " steps",
                  "f",
                  toUserUnits(e1));
          calc.appendLogData(s);
          minimizer.report(s, true);
          Logger.info(s);
        }
        return false;
      }
      // System.out.println(isPreliminary + " " + getNormalizedDE() + " " + currentStep);
      if (isPreliminary && getNormalizedDE() >= 2) {
        // looking back at this after some time, I don't exactly see why I wanted
        // this to stay in preliminary mode unless |DE| >= 2 * crit.
        // It's hard to ever have |DE| NOT >= 2 * crit -- that would be very close to the criterion.
        // And when that IS the case, why would you want to STAY in preliminary mode? Hmm.
        calc.setPreliminary(isPreliminary = false);
        e0 = energyFull(false, false);
      }
    }
    return true; // continue
  }
 String getDebugLine(int iType, Calculation c) {
   switch (iType) {
     case CALC_DISTANCE:
       return TextFormat.sprintf(
           "%3d %3d  %-5s %-5s  %4.2f%8.3f   %8.3f     %8.3f   %8.3f   %8.3f",
           new String[] {atoms[c.ia].type, atoms[c.ib].type},
           new float[] {
             (float) c.dData[2] /*rab*/,
             (float) c.rab,
             (float) c.dData[0],
             (float) c.dData[1],
             (float) c.delta,
             (float) c.energy
           },
           new int[] {atoms[c.ia].atom.getAtomNumber(), atoms[c.ib].atom.getAtomNumber()});
     case CALC_ANGLE:
       return TextFormat.sprintf(
           "%3d %3d %3d  %-5s %-5s %-5s  %8.3f  %8.3f     %8.3f   %8.3f",
           new String[] {atoms[c.ia].type, atoms[c.ib].type, atoms[c.ic].type},
           new float[] {
             (float) (c.theta * RAD_TO_DEG),
             (float) c.dData[4] /*THETA0*/,
             (float) c.dData[0] /*Kijk*/,
             (float) c.energy
           },
           new int[] {
             atoms[c.ia].atom.getAtomNumber(),
             atoms[c.ib].atom.getAtomNumber(),
             atoms[c.ic].atom.getAtomNumber()
           });
     case CALC_TORSION:
       return TextFormat.sprintf(
           "%3d %3d %3d %3d  %-5s %-5s %-5s %-5s  %8.3f     %8.3f     %8.3f",
           new String[] {atoms[c.ia].type, atoms[c.ib].type, atoms[c.ic].type, atoms[c.id].type},
           new float[] {
             (float) c.dData[0] /*V*/, (float) (c.theta * RAD_TO_DEG), (float) c.energy
           },
           new int[] {
             atoms[c.ia].atom.getAtomNumber(),
             atoms[c.ib].atom.getAtomNumber(),
             atoms[c.ic].atom.getAtomNumber(),
             atoms[c.id].atom.getAtomNumber()
           });
     case CALC_OOP:
       return TextFormat.sprintf(
           "" + "%3d %3d %3d %3d  %-5s %-5s %-5s %-5s  %8.3f   %8.3f     %8.3f",
           new String[] {atoms[c.ia].type, atoms[c.ib].type, atoms[c.ic].type, atoms[c.id].type},
           new float[] {
             (float) (c.theta * RAD_TO_DEG), (float) c.dData[0] /*koop*/, (float) c.energy
           },
           new int[] {
             atoms[c.ia].atom.getAtomNumber(),
             atoms[c.ib].atom.getAtomNumber(),
             atoms[c.ic].atom.getAtomNumber(),
             atoms[c.id].atom.getAtomNumber()
           });
     case CALC_VDW:
       return TextFormat.sprintf(
           "%3d %3d  %-5s %-5s %6.3f  %8.3f  %8.3f",
           new String[] {atoms[c.iData[0]].type, atoms[c.iData[1]].type},
           new float[] {(float) c.rab, (float) c.dData[0] /*kab*/, (float) c.energy},
           new int[] {atoms[c.ia].atom.getAtomNumber(), atoms[c.ib].atom.getAtomNumber()});
     case CALC_ES:
       return TextFormat.sprintf(
           "%3d %3d  %-5s %-5s %6.3f  %8.3f  %8.3f",
           new String[] {atoms[c.iData[0]].type, atoms[c.iData[1]].type},
           new float[] {(float) c.rab, (float) c.dData[0] /*qq*/, (float) c.energy},
           new int[] {atoms[c.ia].atom.getAtomNumber(), atoms[c.ib].atom.getAtomNumber()});
   }
   return "";
 }