Esempio n. 1
0
  public static double test(
      String filename,
      Vector<Vector<Double>> setOfNodes,
      String inputRepresentation,
      int outputRepresentation) {
    Vector<Double> testError = new Vector<Double>();
    int target = 0;
    String binary = "";
    int baseTen = 0;
    inputs.clear();
    firstRead = true;

    while ((target = readFileIntoInputVector(inputRepresentation)) != -2) {
      firstRead = false;
      double minError = 10;
      int solution = 0;
      for (int i = 0; i < setOfNodes.size(); i++) {
        double currentError = testNode(outputRepresentation, target, setOfNodes.get(i));
        double absValCurrentError = Math.abs(currentError);
        if (absValCurrentError < minError) {
          minError =
              absValCurrentError; // update minimum error across function if we find a smaller one
        }
        if (outputRepresentation == 4) {
          binary = binary + ((int) (target - currentError)); // fills with binary representation
          baseTen = Integer.parseInt(binary, 2);
        }
      }
      if (outputRepresentation == 4) {
        if (target - baseTen == 0) {
          countCorrect++;
        }
      } else if (target - Math.round(minError)
          == target) { // if error is low enough that we will get the right digit for this node
        countCorrect++;
      }
      baseTen = 0;
      binary = "";

      countTotal++;
      testError.add(minError);
      inputs.clear();
    }

    double euclidianDistance = 0;
    for (double err : testError) {
      euclidianDistance += Math.pow(err, 2);
    }
    euclidianDistance = Math.sqrt(euclidianDistance);
    System.out.println("Test Mean Squared Error: " + euclidianDistance);
    System.out.println("Test Percent: " + (100 * (double) countCorrect / (double) countTotal));
    return 0;
  }
Esempio n. 2
0
  /**
   * Performs a remote tuple space operation.
   *
   * @param template
   * @param dest
   * @param type
   * @return The matching tuple or null if none was found.
   */
  private Tuple doMonoOp(Tuple template, int dest, int type) {
    AgillaTSReqMsgJ request;
    if (type == REMOVE)
      request = new AgillaTSReqMsgJ(dest, TOS_UART_ADDRESS, BasicOpcodes.OPrinp, template);
    else request = new AgillaTSReqMsgJ(dest, TOS_UART_ADDRESS, BasicOpcodes.OPrrdp, template);

    log("doMonoOp: request = " + request + ", dest = " + dest);

    response.clear();

    try {
      log("doMonoOp: Sent inp or rdp request.");
      // results = null;
      sni.send(request);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }

    TimeoutTimer timer = new TimeoutTimer(response, AGILLA_RTS_TIMEOUT, timerid++);
    MessageJ rMsg = waitForResponse();

    if (rMsg instanceof TimeoutMsgJ && ((TimeoutMsgJ) rMsg).id() == timer.id()) {
      log("doMonoOp: Remote TS operation timed out.");
      return null;
    } else if (rMsg instanceof AgillaTSResMsgJ) {
      AgillaTSResMsgJ results = (AgillaTSResMsgJ) rMsg;
      log("doMonoOp: Got results, " + (results.isSuccess() ? "SUCCESS" : "FAIL"));
      if (results.isSuccess()) return results.getTuple();
      else return null;
    }
    return null;
  }
Esempio n. 3
0
 /**
  * Re-scans the bus for devices. <i>ScanForDevices()</i> is called automatically by <i>{@link
  * #open() open()}</i>. <i>You must terminate use of all USB devices before calling
  * scanForDevices()!</i> After calling <i>scanForDevices()</i> you can reestablish connections to
  * USB devices.
  *
  * @return This device manager, useful for chaining together multiple operations.
  * @throws OperationFailedException
  */
 public USBDeviceManager scanForDevices() {
   if (isOpen()) {
     deviceList.clear();
     final int MAX_DEVICES = 100;
     int devices[] = new int[1 + MAX_DEVICES * 2]; // device index-product ID pairs
     final int result =
         getDeviceByProductID(MIN_PRODUCT_ID, MAX_PRODUCT_ID, devices); // get all devices
     if (result != SUCCESS) throw new OperationFailedException(result);
     final int numDevices = devices[0];
     for (int index = 0; index < numDevices; index++) {
       USBDevice device = null;
       final int deviceIndex = devices[1 + index * 2];
       final int productID = devices[1 + index * 2 + 1];
       if (USB_AI16_Family.isSupportedProductID(productID)) {
         device = new USB_AI16_Family(productID, deviceIndex);
       } else if (USB_AO16_Family.isSupportedProductID(productID)) {
         device = new USB_AO16_Family(productID, deviceIndex);
       } else if (USB_CTR_15_Family.isSupportedProductID(productID)) {
         device = new USB_CTR_15_Family(productID, deviceIndex);
       } else if (USB_DA12_8A_Family.isSupportedProductID(productID)) {
         device = new USB_DA12_8A_Family(productID, deviceIndex);
       } else if (USB_DA12_8E_Family.isSupportedProductID(productID)) {
         device = new USB_DA12_8E_Family(productID, deviceIndex);
       } else if (USB_DIO_16_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_16_Family(productID, deviceIndex);
       } else if (USB_DIO_32_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_32_Family(productID, deviceIndex);
       } else if (USB_DIO_Family.isSupportedProductID(productID)) {
         device = new USB_DIO_Family(productID, deviceIndex);
       } // else if( USB_DIO_Family.isSupportedProductID( ...
       if (device != null) deviceList.add(device);
     } // for( int index ...
   } else throw new OperationFailedException(MESSAGE_NOT_OPEN);
   return this;
 } // scanForDevices()
Esempio n. 4
0
 /**
  * "Closes" the USB device manager for use. When finished using the USB device manager, and
  * assuming <i>{@link #open() open()}</i> was properly called, <i>close()</i> must be called.
  * <i>Close()</i> terminates use of the underlying AIOUSB module and discards the list of devices
  * found. <i>You must terminate use of all USB devices before calling close()!</i> You can call
  * <i>open()</i> again to reinitialize things and reestablish connections to USB devices.
  *
  * @return This device manager, useful for chaining together multiple operations.
  * @throws OperationFailedException
  */
 public USBDeviceManager close() {
   if (isOpen()) {
     deviceList.clear();
     openStatus = 0;
     exit();
   } else throw new OperationFailedException(MESSAGE_NOT_OPEN);
   return this;
 } // close()
Esempio n. 5
0
 /** Met à jour le cache en fonction de la liste todo */
 private void updateCache() {
   aladin.trace(2, "Start cache updater...");
   Vector v;
   synchronized (this) {
     v = (Vector) todo.clone();
     todo.clear();
   }
   Enumeration e = v.elements();
   while (e.hasMoreElements()) {
     String url = (String) e.nextElement();
     try {
       putInCache(url);
     } catch (Exception e1) {
     }
     Util.pause(1000); // Pose entre deux
   }
   fin();
 }
Esempio n. 6
0
 /** Initializes the cpu. */
 public void boot() {
   stackSegment.setStartAddress(Definitions.STACK_START_ADDRESS);
   workingStackSegment.setStartAddress(Definitions.STACK_START_ADDRESS);
   localSegment.setEnabledRange(
       Definitions.STACK_START_ADDRESS, Definitions.STACK_END_ADDRESS, true);
   argSegment.setEnabledRange(
       Definitions.STACK_START_ADDRESS, Definitions.STACK_END_ADDRESS, true);
   thisSegment.setEnabledRange(Definitions.HEAP_START_ADDRESS, Definitions.HEAP_END_ADDRESS, true);
   thatSegment.setEnabledRange(
       Definitions.HEAP_START_ADDRESS, Definitions.SCREEN_END_ADDRESS, true);
   staticSegment.setStartAddress(Definitions.VAR_START_ADDRESS);
   staticSegment.setEnabledRange(
       Definitions.VAR_START_ADDRESS, Definitions.VAR_END_ADDRESS - 1, true);
   setSP(Definitions.STACK_START_ADDRESS);
   stackFrames.clear();
   if (builtInFunctionsRunner != null) {
     builtInFunctionsRunner.killAllRunningBuiltInFunctions();
   }
 }
Esempio n. 7
0
  // Parse a method declaration.
  static String getMethod(SamTokenizer f) throws TokenizerException {
    try {
      // The return type for all methods must be int.
      myCheck(f, "int");

      // methodName stores the name of the method.
      String methodName = f.getWord();
      if (symMap.containsKey(methodName))
        throw new TokenizerException("Error: Duplicate declaration of method " + methodName);
      String asmCode = methodName;

      // The name of the method <-> index of the symbol table of the method in the symTables vector
      symMap.put(methodName, symTables.size());
      symTables.addElement(new LinkedHashMap<String, Integer>());

      // Since there cannot be another method declaration inside of a, the symbol table we are
      // dealing with is
      // always the last element of the symTables vector.
      symTables.lastElement().put(methodName, 0);

      asmCode += ":\n";
      myCheck(f, '(');
      if (!f.check(')')) {
        // No SaM code generated by getFormals
        getFormals(f);
        myCheck(f, ')');
      }
      actMap.put(methodName, params.size());
      for (int i = 1; i <= params.size(); ++i) {
        // Add all formals to the symbol tabel
        symTables.lastElement().put(params.elementAt(params.size() - i), -i);
      }
      asmCode += getBody(f);
      // Clear the params vector and set varCounter back to 2.
      params.clear();
      varCounter = 2;
      return asmCode;
    } catch (Exception e) {
      System.out.println(e.getMessage());
      throw new TokenizerException("Error: Invalid method declaration.");
    }
  }
Esempio n. 8
0
  public static void main(String[] args) throws Exception {
    /*
    // Graph in Figure 4.3, format: list of unweighted edges
    // This example shows another form of reading graph input
    13 16
    0 1    1 2    2  3   0  4   1  5   2  6    3  7   5  6
    4 8    8 9    5 10   6 11   7 12   9 10   10 11  11 12
    */

    File f = new File("in_04.txt");
    Scanner sc = new Scanner(f);

    V = sc.nextInt();
    E = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      Vector<IntegerPair> Neighbor = new Vector<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      a = sc.nextInt();
      b = sc.nextInt();
      AdjList.get(a).add(new IntegerPair(b, 0));
      AdjList.get(b).add(new IntegerPair(a, 0));
    }

    // as an example, we start from this source, see Figure 4.3
    s = 5;

    // BFS routine
    // inside void main(String[] args) -- we do not use recursion, thus we do not need to create
    // separate function!
    Vector<Integer> dist = new Vector<Integer>();
    dist.addAll(Collections.nCopies(V, 1000000000));
    dist.set(s, 0); // start from source
    Queue<Integer> q = new LinkedList<Integer>();
    q.offer(s);
    p.clear();
    p.addAll(
        Collections.nCopies(V, -1)); // to store parent information (p must be a global variable!)
    int layer = -1; // for our output printing purpose
    Boolean isBipartite = true;

    while (!q.isEmpty()) {
      int u = q.poll(); // queue: layer by layer!
      if (dist.get(u) != layer) System.out.printf("\nLayer %d:", dist.get(u));
      layer = dist.get(u);
      System.out.printf(", visit %d", u);
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // for each neighbours of u
        IntegerPair v = (IntegerPair) it.next();
        if (dist.get(v.first()) == 1000000000) { // if v not visited before
          dist.set(v.first(), dist.get(u) + 1); // then v is reachable from u
          q.offer(v.first()); // enqueue v for next steps
          p.set(v.first(), u); // parent of v is u
        } else if ((dist.get(v.first()) % 2) == (dist.get(u) % 2)) // same parity
        isBipartite = false;
      }
    }

    System.out.printf("\nShortest path: ");
    printpath(7);
    System.out.printf("\n");
    System.out.printf("isBipartite? %d\n", isBipartite ? 1 : 0);
  }
Esempio n. 9
0
  @SuppressWarnings({"unchecked", "unchecked"})
  public static void main(String[] args) {
    Vector<String> v = new Vector<String>();
    DataInputStream inn;
    PrintStream out;
    Indexer w = new Indexer("myhash");
    try {
      FileInputStream indexSource = new FileInputStream("foo.txt");
      w.restore(indexSource);
      // w.disp();
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    try {
      ServerSocket serv = new ServerSocket(4402);
      System.out.println(serv.getInetAddress());
      System.out.println("server started");
      while (true) {

        Socket client = serv.accept();
        System.out.println("Just connected to " + client.getRemoteSocketAddress());

        inn = new DataInputStream(client.getInputStream());

        System.out.println("client IP : " + client.getInetAddress());
        String ob = inn.readLine();
        System.out.println("ob is " + ob);
        String[] h = ob.split(" ");
        for (String i : h) {
          v.addElement(i.toLowerCase());
        }

        // Take care to use the right usage of the Index structure
        // hash - Dictionary Structure based on a Hashtable or HashMap from the Java collections
        // list - Dictionary Structure based on Linked List
        // myhash - Dictionary Structure based on a Hashtable implemented by the students
        // bst - Dictionary Structure based on a Binary Search Tree implemented by the students
        // avl - Dictionary Structure based on AVL Tree implemented by the students

        // System.out.println(perform);
        System.out.println("search request for : " + v.toString());

        // w.disp();

        ObjectIterator<vecnod> i = w.retrievePages(new ObjectIterator<String>(v));

        Vector<vecnod> no_dup_vec = new Vector<vecnod>();
        Vector<vecnod> dup_vec = new Vector<vecnod>();

        int argcount = v.size();

        v.clear();

        if (i == null) {
          System.out.println("Search complete.  0  hits found.");
          return;
        }
        vecnod temp = new vecnod();
        System.out.println("Search results:");

        while (i.hasNext()) {

          temp = i.next();
          String s = temp.url.toString();

          int bc = 1;
          for (int j = 0; j < s.length(); j++) {
            if (s.charAt(j) == '/') bc++;
          }
          temp.freq = temp.freq * 100 * 1 / (bc - 2); // ressigning rank
          System.out.println("URL is: " + s + " Rank is: " + temp.freq);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 10
0
  public String Play(String input) {
    Vector<String> v = new Vector<String>();

    String output = "";
    Indexer w = new Indexer("myhash");
    try {
      FileInputStream indexSource = new FileInputStream("foo.txt");
      w.restore(indexSource);
      // w.disp();
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    try {

      String ob = input;
      System.out.println("ob is " + ob);
      String[] h = ob.split(" ");
      for (String i : h) {
        v.addElement(i.toLowerCase());
      }

      // Take care to use the right usage of the Index structure
      // hash - Dictionary Structure based on a Hashtable or HashMap from the Java collections
      // list - Dictionary Structure based on Linked List
      // myhash - Dictionary Structure based on a Hashtable implemented by the students
      // bst - Dictionary Structure based on a Binary Search Tree implemented by the students
      // avl - Dictionary Structure based on AVL Tree implemented by the students

      // System.out.println(perform);
      System.out.println("search request for : " + v.toString());

      // w.disp();

      ObjectIterator<vecnod> i = w.retrievePages(new ObjectIterator<String>(v));

      Vector<vecnod> no_dup_vec = new Vector<vecnod>();
      Vector<vecnod> dup_vec = new Vector<vecnod>();

      int argcount = v.size();

      v.clear();

      if (i == null) {
        System.out.println("Search complete.  0  hits found.");
        return "";
      }
      vecnod temp = new vecnod();
      System.out.println("Search results:");

      while (i.hasNext()) {

        temp = i.next();
        String s = temp.url.toString();

        int bc = 1;
        for (int j = 0; j < s.length(); j++) {
          if (s.charAt(j) == '/') bc++;
        }
        temp.freq = temp.freq * 100 * 1 / (bc - 2); // ressigning rank
        // System.out.println("URL is: "+s+" Rank is: "+temp.freq);
        output = output + s + "\n";
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return output;
  }
 public void clearEvents() {
   events.clear();
 }
Esempio n. 12
0
  public static Vector<Double> trainNode(
      String filename,
      int outputRepresentation,
      String inputRepresentation,
      int filter,
      double learningRate,
      int epochs) {
    Vector<Double> node = null; // initialize node to null
    double error = 1; // initialize error
    double output = 0; // initialize output
    Vector<Double> trainError = new Vector<Double>();
    double meansq = 0;
    String binTarget = "";
    String binaryRep = "";
    int target;
    openFile(filename); // open our file for training
    firstRead = true;
    int targetCounter = 0;
    while ((target = readFileIntoInputVector(inputRepresentation))
        != -2) { // while we have not reached out end of file error
      if (outputRepresentation == 4) {
        binTarget = Integer.toBinaryString(target); // convert target to binary
        int[] targetArray = new int[4]; // array to hold binary ints
        for (int h = 0; h < targetArray.length; h++) { // add binary elements to int array
          try {
            targetArray[targetArray.length - h - 1] =
                Character.digit(binTarget.charAt(binTarget.length() - h - 1), 10);
          } catch (IndexOutOfBoundsException e) { // if there is empty spaces, fill with zeros
            targetArray[targetArray.length - h - 1] = 0;
          }
        }
        target = targetArray[filter];
        binTarget = "";
        for (int i = 0; i < targetArray.length; i++) {
          binTarget = binTarget + targetArray[i];
        }
      }

      if ((filter == target && outputRepresentation == 10) || outputRepresentation != 10) {
        if (node == null) {
          node = new Vector<Double>();
          for (int i = 0; i < inputs.size(); i++) { // for each input
            double randWeight = 1; // initialize random weight
            while (randWeight > 0.15) // while out random isn't less than 0.15
            randWeight = random.nextDouble(); // get a new random double
            if (random.nextBoolean()) randWeight = randWeight * -1; // randomly set to negative
            node.addElement(new Double(randWeight)); // store random weight
          }
        }
        targetCounter++;
        // train for number of epochs
        for (int i = 0; i < epochs; i++) { // for each epoch
          double weightedSum = 0; // set/reset the weighted sum to 0
          for (int j = 0; j < inputs.size(); j++) {
            weightedSum += (inputs.elementAt(j) * node.elementAt(j)); // calculate weighted sum
          }
          output = activation(weightedSum); // retrieve output
          if (outputRepresentation == 1 || outputRepresentation == 10) output = output * 10;
          else if (outputRepresentation == 4) { // each node must have a whole number
            if (output > 0.5) output = 1;
            else output = 0;
          }

          error = target - output; // calculate error

          if (i == epochs - 1) {
            if (outputRepresentation == 4) {
              if (filter == 0) {
                allOutputs.ensureCapacity(targetCounter);
                allOutputs.add(Integer.toString((int) output));
              } else {
                allOutputs.set(
                    targetCounter - 1, allOutputs.get(targetCounter - 1) + ((int) output));
              }
            }
            trainError.add(error);
            if (Math.round(error) == 0 && outputRepresentation != 4) {
              trainCountCorrect++;
            } else if (outputRepresentation == 4 && filter == 3) {
              if (allOutputs.get(targetCounter - 1).equals(binTarget)) {
                trainCountCorrect++;
              }
            }
          }

          for (int k = 0; k < inputs.size(); k++) { // for each input
            double derivative =
                (1.64872 * Math.exp(weightedSum))
                    / (Math.pow(1.64872 + Math.exp(weightedSum), 2)); // calculate new weights
            double newWeight =
                node.elementAt(k)
                    + (learningRate * inputs.elementAt(k) * error * derivative); // cont.
            node.setElementAt(newWeight, k); // update weights
          }
        }
      }
      inputs.clear();
    }
    errorVect.addElement((Vector<Double>) trainError.clone());
    trainError.clear();
    if (outputRepresentation == 4 && filter == 3)
      System.out.println(
          "Training Percent: " + (100 * (double) trainCountCorrect / (double) targetCounter));
    if (outputRepresentation == 10 && filter == 9)
      System.out.println(
          "Training Percent: " + (10 * (double) trainCountCorrect / (double) targetCounter));
    if (outputRepresentation == 1)
      System.out.println(
          "Training Percent: " + (100 * (double) trainCountCorrect / (double) targetCounter));
    closeFile();
    return node; // node is now trained for an epoch
  }
Esempio n. 13
0
  public int processCmd(String cmd) throws TException, HiveException {
    SessionState ss = SessionState.get();
    ss.setiscli(true);

    String cmd_trimmed = cmd.trim();
    String[] tokens = cmd_trimmed.split("\\s+");
    String cmd_1 = cmd_trimmed.substring(tokens[0].length()).trim();
    int ret = 0;

    if (tokens[0].equalsIgnoreCase("delete")) {
      Vector<String> nexttoken = new Vector<String>();
      nexttoken.add("jar");
      nexttoken.add("file");
      nexttoken.add("from");
      if (tokens.length < 2 || !nexttoken.contains(tokens[1].toLowerCase())) {
        String errorMessage =
            "\nif delete resource:\n"
                + "Usage: delete [FILE|JAR] <value> [<value>]*\n"
                + "if delete table rows:\n"
                + "Usage: delete from tableName [where searchCondition]";
        console.printError(errorMessage);
        ret = 1;

        return ret;
      }
    }

    if (tokens[0].equalsIgnoreCase("dfs") || tokens[0].equalsIgnoreCase("zktest")) {
      String errorMessage = "\ntdw hive do not support " + tokens[0].toLowerCase() + " operation\n";
      throw new HiveException(errorMessage);
    }

    if (cmd_trimmed.toLowerCase().equals("quit") || cmd_trimmed.toLowerCase().equals("exit")) {

      System.exit(0);

    } else if (cmd_trimmed.startsWith("!")) {

      String shell_cmd = cmd_trimmed.substring(1);

      try {
        Process executor = Runtime.getRuntime().exec(shell_cmd);
        StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, ss.out);
        StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, ss.err);

        outPrinter.start();
        errPrinter.start();

        ret = executor.waitFor();
        if (ret != 0) {
          console.printError("Command failed with exit code = " + ret);
        }
      } catch (Exception e) {
        console.printError(
            "Exception raised from Shell command " + e.getLocalizedMessage(),
            org.apache.hadoop.util.StringUtils.stringifyException(e));
        ret = 1;
      }

    } else if (tokens[0].toLowerCase().equals("list")) {

      SessionState.ResourceType t;
      if (tokens.length < 2 || (t = SessionState.find_resource_type(tokens[1])) == null) {
        console.printError(
            "Usage: list ["
                + StringUtils.join(SessionState.ResourceType.values(), "|")
                + "] [<value> [<value>]*]");
        ret = 1;
      } else {
        List<String> filter = null;
        if (tokens.length >= 3) {
          System.arraycopy(tokens, 2, tokens, 0, tokens.length - 2);
          filter = Arrays.asList(tokens);
        }
        Set<String> s = ss.list_resource(t, filter);
        if (s != null && !s.isEmpty()) ss.out.println(StringUtils.join(s, "\n"));
      }

    } else {
      CommandProcessor proc = CommandProcessorFactory.get(tokens);
      if (proc != null) {
        if (proc instanceof Driver) {
          Driver qp = (Driver) proc;
          PrintStream out = ss.out;
          long start = System.currentTimeMillis();

          try {
            ret = qp.run(cmd);
          } catch (Exception e1) {
            e1.printStackTrace();
          }
          if (ret != 0) {
            qp.close();
            return ret;
          }

          Vector<String> res = new Vector<String>();
          try {
            while (qp.getResults(res)) {
              for (String r : res) {
                out.println(r);
              }
              res.clear();
              if (out.checkError()) {
                break;
              }
            }
          } catch (IOException e) {
            console.printError(
                "Failed with exception " + e.getClass().getName() + ":" + e.getMessage(),
                "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e));
            ret = 1;
          }

          int cret = qp.close();
          if (ret == 0) {
            ret = cret;
          }

          long end = System.currentTimeMillis();
          if (end > start) {
            double timeTaken = (double) (end - start) / 1000.0;
            console.printInfo("Time taken: " + timeTaken + " seconds", null);
          }

        } else {
          try {
            ret = proc.run(cmd_1);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }

    return ret;
  }
Esempio n. 14
0
  private void parsePostScript() {
    try {
      BufferedReader PSIn = new BufferedReader(new FileReader("data/out/" + name + ".ps"));

      // parse header
      while (PSIn.ready()) {
        String S = PSIn.readLine().trim();
        if (S.contains("EndSetup")) {
          break;
        } else {
          if (S.startsWith("/magfont")) {
            fontInfo.add(S);
          } else if (S.startsWith("/lily-output-units")) {
            outputUnits = Float.parseFloat(S.split(" ")[1]);
            for (String T : fontInfo) {
              addFont(
                  T.split(" ")[0].substring(1),
                  T.split(" ")[2].substring(1),
                  (float) outputUnits * Float.parseFloat(T.split(" ")[3]));
            }
          } else if (S.startsWith("/output-scale")) {
            outputScale = Float.parseFloat(S.split(" ")[1]);
          } else if (S.startsWith("/staff-height")) {
            staffLineHeight = Float.parseFloat(S.split(" ")[1]) / 4;
          }
        }
      }
      scale = outputUnits * outputScale;

      for (int layer = 0; layer < staves; ++layer) {
        Vector<Vector<Double>> staff = new Vector<Vector<Double>>();
        for (int page = 0; page < pages; ++page) {
          staff.add(new Vector<Double>());
        }
        staffLines.add(staff);
      }
      Vector<Double> cStaffs = new Vector<Double>();

      String prevLine = "";
      int currPage = 1;

      // parse the rest of the file
      while (PSIn.ready()) {
        String S = PSIn.readLine().trim();
        if (S.contains("noteheads") || S.contains("rests")) {
          // extract coordinate, glyph, and font information
          String T[] = S.split(" ");
          NotePanel N = new NotePanel();
          N.setCoordinates(Double.parseDouble(T[0]), -Double.parseDouble(T[1]))
              .setGlyph(T[4].substring(1))
              .setGonville(fonts.get(T[3]));
          if (S.contains("rests")) {
            T = S.substring(S.lastIndexOf("rests")).split("[. ]");
            N.setRest(Integer.parseInt(T[1]));
          }

          T = prevLine.substring(prevLine.lastIndexOf(this.name + ".ly")).split(":");
          N.setLine(Integer.parseInt(T[1]), Integer.parseInt(T[2])).setPage(currPage);

          if (N.lyLine < staffLine || staffLine == 0) {
            notes[0].add(N);
          } else {
            notes[1].add(N);
          }
        } else if (S.contains("accidentals")) {
          // String T[] = S.split(" ");
          // lastNote.setAccidentals(Double.parseDouble(T[0]), -Double.parseDouble(T[1]),
          // T[4].substring(1), T[3]);
        } else if (S.startsWith("%%Page:")) {
          currPage = Integer.parseInt(S.split(" ")[1]);
        }

        if (S.contains("draw_line")) {
          cStaffs.add(-Double.parseDouble(S.split(" ")[1]));
          if (cStaffs.size() >= 5 * staves) {
            // found a full staff
            Collections.sort(cStaffs);
            staffLines.get(0).get(currPage - 1).add(cStaffs.get(4) + staffLineHeight);
            if (staves > 1) {
              staffLines.get(1).get(currPage - 1).add(cStaffs.get(5) - staffLineHeight);
            }
            cStaffs.clear();
          }
        } else if (!S.contains("draw_round_box")) {
          cStaffs.clear();
        }

        if (S.contains(this.name + ".ly")) {
          prevLine = S;
        }
      }

      // sort the notes we found from the PS by where they occurred in the .ly
      for (int i = 0; i < staves; ++i) {
        Collections.sort(notes[i]);
      }

      // find tied notes
      for (int i = 0; i < staves; ++i) {
        int cTie = 0;
        int cNote = 0;

        while (cTie < ties.size() && cNote < notes[i].size() - 1) {
          ArrayList<Integer> tie = ties.get(cTie);
          NotePanel prevNote = notes[i].get(cNote);
          NotePanel nextNote = notes[i].get(cNote + 1);
          if (pairComp(tie.get(0), tie.get(1), prevNote.lyLine, prevNote.lyNumber) != -1
              && pairComp(tie.get(0), tie.get(1), nextNote.lyLine, nextNote.lyNumber) != 1) {
            // tie is located between these notes
            nextNote.setTie(true);
            ++cNote;
            ++cTie;
          } else if (pairComp(tie.get(0), tie.get(1), prevNote.lyLine, prevNote.lyNumber) != -1) {
            ++cNote;
          } else {
            ++cTie;
          }
        }
      }

      PSIn.close();
    } catch (Exception e) {
      System.err.println("Parsing the score from Lilypond's output has failed. Error: ");
      e.printStackTrace();
    }
  }