示例#1
0
 public boolean ok(String out, String reference) {
   // log.fine("out1: " + a);
   // log.fine("out2: " + b);
   Scanner sa = new Scanner(out);
   Scanner sb = new Scanner(reference);
   while (sa.hasNext() && sb.hasNext()) {
     if (sa.hasNextDouble() || sb.hasNextDouble()) {
       if (!sa.hasNextDouble() || !sb.hasNextDouble()) return true;
       double da = sa.nextDouble();
       double db = sb.nextDouble();
       double d_abs = Math.abs(da - db);
       double d_rel = d_abs / Math.abs(db);
       if (!(d_abs < EPS || d_rel < EPS)) {
         log.fine("NOK, " + da + " too far from " + db);
         return false;
       }
     } else {
       String xa = sa.next();
       String xb = sb.next();
       if (!xa.equals(xb)) {
         log.fine("NOK, " + xa + " != " + xb);
         return false;
       }
     }
   }
   if (sa.hasNext() || sb.hasNext()) {
     log.fine("NOK: different number of tokens.");
     return false;
   }
   return true;
 }
示例#2
0
  public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = new Scanner(new FileReader("Lab3_input.txt"));
    PrintWriter outFile = new PrintWriter("Lab3_Exercise_output.txt");

    // Declare variables
    String lastName, firstName;
    double salary, pctRaise, salaryFinal;

    // set up while loop
    while (inFile.hasNext()) // condition checks to see if there is anything in the input file
    {
      // Read information from input file
      lastName = inFile.next();
      firstName = inFile.next();
      salary = inFile.nextDouble();
      pctRaise = inFile.nextDouble();

      // Calculate final salary
      salaryFinal = salary + (salary * pctRaise / 100);

      // Write file
      outFile.printf("%s %s %.2f%n", lastName, firstName, salaryFinal);
    }

    // Close input/output methods
    outFile.close();
    inFile.close();
  }
示例#3
0
  /**
   * Loads into a double[][] a plain text file of numbers, with newlines dividing the numbers into
   * rows and tabs or spaces delimiting columns. The Y dimension is not flipped.
   */
  public static double[][] loadTextFile(InputStream stream) throws IOException {
    Scanner scan = new Scanner(stream);

    ArrayList rows = new ArrayList();
    int width = -1;

    while (scan.hasNextLine()) {
      String srow = scan.nextLine().trim();
      if (srow.length() > 0) {
        int w = 0;
        if (width == -1) // first time compute width
        {
          ArrayList firstRow = new ArrayList();
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            firstRow.add(new Double(rowScan.nextDouble())); // ugh, boxed
            w++;
          }
          width = w;
          double[] row = new double[width];
          for (int i = 0; i < width; i++) row[i] = ((Double) (firstRow.get(i))).doubleValue();
          rows.add(row);
        } else {
          double[] row = new double[width];
          Scanner rowScan = new Scanner(new StringReader(srow));
          while (rowScan.hasNextDouble()) {
            if (w == width) // uh oh
            throw new IOException("Row lengths do not match in text file");
            row[w] = rowScan.nextDouble();
            w++;
          }
          if (w < width) // uh oh
          throw new IOException("Row lengths do not match in text file");
          rows.add(row);
        }
      }
    }

    if (width == -1) // got nothing
    return new double[0][0];

    double[][] fieldTransposed = new double[rows.size()][];
    for (int i = 0; i < rows.size(); i++) fieldTransposed[i] = ((double[]) (rows.get(i)));

    // now transpose because we have width first
    double[][] field = new double[width][fieldTransposed.length];
    for (int i = 0; i < field.length; i++)
      for (int j = 0; j < field[i].length; j++) field[i][j] = fieldTransposed[j][i];

    return field;
  }
  public static void main(String[] args) throws IOException {

    Scanner sc = new Scanner(new File("B.in"));

    int cases = 0;
    while (true) {
      int B = sc.nextInt();
      int C = sc.nextInt();
      int R = sc.nextInt();
      int Q = sc.nextInt();
      if (B + C + R + Q == 0) break;
      cases++;

      Point2D.Double[] BTS = new Point2D.Double[B];
      Point2D.Double[] cities = new Point2D.Double[C];

      int[][] edges = new int[C][C];
      for (int i = 0; i < C; i++) Arrays.fill(edges[i], -1);

      for (int i = 0; i < B; i++) {
        BTS[i] = new Point2D.Double(sc.nextDouble(), sc.nextDouble());
      }

      for (int i = 0; i < C; i++) {
        cities[i] = new Point2D.Double(sc.nextDouble(), sc.nextDouble());
      }

      for (int i = 0; i < R; i++) {
        int src = sc.nextInt() - 1;
        int dst = sc.nextInt() - 1;
        edges[src][dst] = edgesBetween(BTS, cities, src, dst);
        edges[dst][src] = edges[src][dst];
      }
      /*
      for (int i = 0; i < C; i++) {
      	for (int j = 0; j < C; j++) {
      		System.out.print(edges[i][j] + " ");
      	}
      	System.out.println();
      }
      */
      System.out.println("Case " + cases + ":");
      for (int i = 0; i < Q; i++) {
        int src = sc.nextInt() - 1;
        int dst = sc.nextInt() - 1;
        int ans = dijk(edges, src, dst);
        if (ans == -1) System.out.println("Impossible");
        else System.out.println(ans);
      }
    }
  }
  protected static ArrayList<Position> readReferencePositions(String filePath)
      throws FileNotFoundException {
    ArrayList<Position> positions = new ArrayList<Position>();
    Scanner scanner = new Scanner(new File(filePath));

    while (scanner.hasNextDouble()) {
      double lat = scanner.nextDouble();
      double lon = scanner.nextDouble();
      double elevation = scanner.nextDouble();
      positions.add(Position.fromDegrees(lat, lon, elevation));
    }

    return positions;
  }
  /*
   *  Making sure that the user input is in range
   *  @param1 Scanner object for input
   *  @param2 lowerbound integer
   *  @param3 upperbound integer
   *  @param4 String that specifies for which attribute/field input is for
   *  printing purposes
   *  @param5 ValType enum that specifies whether the primitive value is
   *  an int or double
   *  @param6 boolean that specifies whether the input is an Enum value
   *  @param7 boolean that specifies whether to return the value if out of
   *  range (false) or not (true)
   */
  public static Number makeSureValInRange(
      Scanner input,
      int lowerbound,
      int upperbound,
      String inputFor,
      ValType valType,
      boolean enumeration,
      boolean withinRange) {

    boolean valid = !withinRange;
    Number val = 0;

    while (!valid) {

      System.out.println(inputString(inputFor, null, StringOption.SELECT, enumeration));

      val = valType == ValType.INTEGER ? input.nextInt() : input.nextDouble();

      if (val.intValue() < lowerbound || val.intValue() > upperbound) {
        System.out.println(inputString(inputFor, null, StringOption.INCORRECT, enumeration));
      } else {
        valid = true;
      }
    }
    return val;
  }
示例#7
0
	public static void main(String[] args) throws IOException {
		Scanner scan = new Scanner(System.in);
		int test = scan.nextInt();
		double limit;
		while (test-- > 0) {
			limit = scan.nextDouble();
			n = scan.nextInt();
			V = 0;
			mm = new int[n];
			pp = new float[n];
			for (int i = 0; i < n; i++) {
				mm[i] = scan.nextInt();
				pp[i] = scan.nextFloat();
				V += mm[i];
			}
			dp = new float[V + 1];
			Arrays.fill(dp, 0);
			dp[0] = 1;
			for (int i = 0; i < n; i++)
				ZeroPack(mm[i], 1 - pp[i]);

			for (int i = V; i >= 0; i--)
				if (dp[i] > 1 - limit) {
					out.println(i);
					break;
				}

		}
		out.flush();
		out.close();
	}
示例#8
0
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   System.out.println("Enter name of the file: ");
   String a = input.next();
   File file = new File(a);
   if (!file.exists()) {
     System.out.println("The file does not exist");
     System.exit(1);
   }
   double sum = 0;
   double count = 0;
   double avg = 0;
   try {
     Scanner input2 = new Scanner(file);
     while (input2.hasNext()) {
       double score = input2.nextDouble();
       sum = sum + score;
       count++;
     }
   } catch (Exception e) {
     System.out.println("Error!");
   }
   avg = sum / count;
   System.out.println("Total scores: " + count);
   System.out.println("Sum of all scores: " + sum);
   System.out.println("Average of all scores: " + avg);
   input.close();
 }
  public static void main(String[] args) {
    int i = 4;
    double d = 4.0;
    String s = "HackerRank ";

    Scanner scan = new Scanner(System.in);

    /* Declare second integer, double, and String variables. */
    int j;
    double e;
    String t;
    /* Read and save an integer, double, and String to your variables.*/
    j = scan.nextInt();
    e = scan.nextDouble();
    scan.nextLine();
    t = scan.nextLine();
    /* Print the sum of both integer variables on a new line. */
    System.out.println(i + j);
    /* Print the sum of the double variables on a new line. */
    System.out.println(d + e);
    /* Concatenate and print the String variables on a new line;
    the 's' variable above should be printed first. */
    System.out.println(s + t);

    scan.close();
  }
示例#10
0
 public static void main(String args[]) throws IOException {
   Scanner sf = new Scanner(new File("D:\\IB CS\\temp_Aman\\StudentsScores.in.txt"));
   int maxIndx = -1;
   String text[] = new String[1000];
   while (sf.hasNext()) // this allows the program to assign each line in the text file a variable
   {
     maxIndx++;
     text[maxIndx] = sf.nextLine();
   }
   for (int j = 0; j <= 4; j++) {
     Scanner sc = new Scanner(text[j]);
     String name =
         sc.next(); // this helps identify the Strings, which are the names of students, in each
     // line
     double sum =
         0.0; // it starts the sum and count variables with zero because they change as they move
     // along with the while loop
     int count = 0;
     while (sc.hasNext()) {
       sum = sum + sc.nextDouble(); // this while loop helps find out the number of integers in the
       // line and adds all of these numbers as well
       count = count + 1;
     }
     double avg = sum / count;
     int y = (int) Math.round(avg); // this converts the double variable avg to an integer
     System.out.println(name + "," + " average = " + y);
   }
 }
示例#11
0
 public static Bravo load(Scanner scanner) {
   int nn = scanner.nextInt();
   assert 1 <= nn && nn <= 100 : "out of range, nn: " + nn;
   double vv = scanner.nextDouble();
   assert 1e-4 <= vv && vv <= 1e4 : "out of range, vv: " + vv;
   double xx = scanner.nextDouble();
   assert 0.1 <= xx && xx <= 99.9 : "out of range, xx: " + xx;
   double[] R = new double[nn];
   double[] C = new double[nn];
   for (int i = 0; i < nn; i++) {
     R[i] = scanner.nextDouble();
     C[i] = scanner.nextDouble();
     assert 1e-4 <= R[i] && R[i] <= 1e4 : "out of range, R[i]: " + R[i];
     assert 0.1 <= C[i] && C[i] <= 99.9 : "out of range, C[i]: " + C[i];
   }
   return new Bravo(nn, vv, xx, R, C);
 }
示例#12
0
 public static void main(String... args) {
   System.setIn(
       new ByteArrayInputStream(
           "2\n5\n0 0\n1 0\n1 1\n1 2\n0 2\n6\n1.0 1.0\n30.91 8\n4.0 7.64\n21.12 6.0\n11.39 3.0\n5.31 11.0"
               .getBytes()));
   Scanner scanner = new Scanner(System.in);
   int t = scanner.nextInt();
   for (int i = 0; i < t; i++) {
     int n = scanner.nextInt();
     Coord[] towers = new Coord[n];
     for (int j = 0; j < n; j++) {
       towers[j] = new Coord(scanner.nextDouble(), scanner.nextDouble());
     }
     Arctic arctic = new Arctic(towers);
     arctic.minPower(0, new boolean[n], new double[n - 1]);
     System.out.printf("%.2f\n", arctic.min);
   }
 }
  /**
   * Returns the next hourly employee from the specified Scanner object.
   *
   * @param sc the Scanner object used to scan in the next employee.
   * @return the next hourly employee scanned in from sc.
   */
  protected HourlyEmployee getNextEmployee(Scanner sc) {
    Scanner lineScanner = new Scanner(sc.nextLine());

    String name = lineScanner.next();

    int hoursWorked = lineScanner.nextInt();

    double payRate = lineScanner.nextDouble();

    return new HourlyEmployee(name, hoursWorked, payRate);
  } // method getNextEmployee
 public static void main(String[] args) {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Enter the area of the circle here: ");
   double area = keyboard.nextDouble();
   System.out.println("The radius of the circle is: " + Math.sqrt(area / Math.PI));
   System.out.print("What is your fist name? ");
   String first = keyboard.next();
   System.out.print("What is your last name? ");
   String last = keyboard.next();
   System.out.println("Your full name is " + first + " " + last);
 }
示例#15
0
  public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
    // s.useLocale(Locale.US);

    double sum = 0;

    while (s.hasNext()) {
      sum += s.nextDouble();
    }
    s.close();

    System.out.println(sum);
  }
示例#16
0
文件: Main.java 项目: MakeNowJust/aoj
 public static void main(String[] args) {
   while (scan.hasNextDouble()) {
     double t1 = scan.nextDouble();
     double t2 = scan.nextDouble();
     int i1, i2;
     for (i1 = 0; i1 < s1.length; i1++) {
       if (t1 < s1[i1]) break;
     }
     for (i2 = 0; i2 < s2.length; i2++) {
       if (t2 < s2[i2]) break;
     }
     System.out.println(r[Math.max(i1, i2)]);
   }
 }
示例#17
0
 public static void main(String[] args) throws IOException {
   Scanner s = new Scanner(new File("number.txt")).useDelimiter(";");
   int noo1 = 0, noo2 = 0, noo3 = 0, noo4 = 0, noo5 = 0;
   String line;
   while (s.hasNextDouble()) {
     double val = s.nextDouble();
     if ((val > 0) && (val < 20)) noo1++;
     else if ((val > 20) && (val < 40)) noo2++;
     else if ((val > 40) && (val < 60)) noo3++;
     else if ((val > 60) && (val < 80)) noo4++;
     else if ((val > 80) && (val < 100)) noo5++;
   }
   s.close();
   System.out.println("Range 0 to 20: " + noo1);
   System.out.println("Range 20 to 40: " + noo2);
   System.out.println("Range 40 to 60: " + noo3);
   System.out.println("Range 60 to 80: " + noo4);
   System.out.println("Range 80 to 100: " + noo5);
 }
示例#18
0
 void run() {
   System.out.println("INTERSECTING LINES OUTPUT");
   for (N = input.nextInt(); N != 0; --N) {
     P p[] = new P[4];
     for (int i = 0; i < 4; ++i) {
       double x = input.nextDouble();
       double y = input.nextDouble();
       p[i] = new P(x, y);
     }
     P ans = isLL(p[0], p[1], p[2], p[3]);
     if (ans != null) {
       System.out.printf("POINT %.2f %.2f", ans.x, ans.y);
       System.out.println();
     } else {
       System.out.println(oneLine(p) ? "LINE" : "NONE");
     }
   }
   System.out.println("END OF OUTPUT");
 }
  /** @param args the command line arguments */
  public static void main(String[] args) throws FileNotFoundException {
    // ask the user for the file name
    System.out.print("Please enter the name of the file: ");
    Scanner keyboard = new Scanner(System.in);

    // create the new file object
    File newFile = new File(keyboard.nextLine());

    // link the file to the new Scanner object
    Scanner inputFile = new Scanner(newFile);

    // create a new linked list
    MyLinkedList myList = new MyLinkedList();

    // loop through the file to add each score to the linked list
    while (inputFile.hasNext()) {
      // get the next score
      double x = inputFile.nextDouble();

      // create the node and add to the linkedList
      MyLinkedListNode newNode = new MyLinkedListNode(x);
      myList.appendNode(newNode);
    }

    // loop through the list to find the total
    MyLinkedListNode p1 = myList.getHead();
    double total = 0;
    int count = 0;

    while (p1 != null) {
      total += p1.getNum();
      count++;

      // move along to the next node
      p1 = p1.getNext();
    }

    System.out.println("/nThe total of all the scores is: " + total);
    System.out.printf("The average of all the scores is: %.02f %n", total / count);
  }
  // 加载待访问的url
  private static void SetPriorQueue(String filePath) throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(filePath));
    Scanner sc = null;
    String line = null;
    String url = null;
    UrlValue cur = null;

    while ((line = br.readLine()) != null) {
      line = line.trim();
      if (!line.equals("")) {
        sc = new Scanner(line);
        url = sc.next();
        if (!visitedUrl.contains(url)) {
          cur = new UrlValue();
          cur.url = url;
          cur.value = sc.nextDouble();
          pq.offer(cur);
        }
      }
    }
    br.close();
  }
示例#21
0
 public double askInput(String questionType) {
   questionType = questionType.trim();
   System.out.print("Please enter " + questionType + ": ");
   Scanner keyboard = new Scanner(System.in);
   return keyboard.nextDouble();
 }
示例#22
0
 // Driver
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   System.out.println("What file do you want to use for input/output?");
   String filename = input.nextLine();
   Airline a = new Airline(filename);
   String city1, city2;
   loop:
   while (true) {
     System.out.println("\n\tWhat would you like to do?");
     System.out.println("\t1: See All Direct Routes");
     System.out.println("\t2: Find Minimum Spanning Tree");
     System.out.println("\t3: Find Shortest Path by Distance");
     System.out.println("\t4: Find Shortest Path by Cost");
     System.out.println("\t5: Find Shortest Path by Hops");
     System.out.println("\t6: Find Trips Under Cost");
     System.out.println("\t7: Add a Route");
     System.out.println("\t8: Remove a Route");
     System.out.println("\t9: Add a City");
     System.out.println("\t10: Remove a City");
     System.out.println("\t11: Quit");
     System.out.println("\t12: Quit Without Saving");
     System.out.print("Enter numeric choice: ");
     int choice = input.nextInt();
     input.nextLine(); // throw out leftover newline
     switch (choice) {
       case 1:
         a.showAllRoutes();
         break;
       case 2:
         a.mst();
         break;
       case 3:
         System.out.print("Enter the first city: ");
         city1 = input.nextLine();
         System.out.print("Enter the second city: ");
         city2 = input.nextLine();
         a.shortestByDistance(city1, city2);
         break;
       case 4:
         System.out.print("Enter the first city: ");
         city1 = input.nextLine();
         System.out.print("Enter the second city: ");
         city2 = input.nextLine();
         a.shortestByCost(city1, city2);
         break;
       case 5:
         System.out.print("Enter the first city: ");
         city1 = input.nextLine();
         System.out.print("Enter the second city: ");
         city2 = input.nextLine();
         a.shortestByHops(city1, city2);
         break;
       case 6:
         System.out.print("Enter max cost: ");
         double cost = input.nextInt();
         a.pathsUnderCost(cost);
         break;
       case 7:
         System.out.print("Enter the first city: ");
         city1 = input.nextLine();
         System.out.print("Enter the second city: ");
         city2 = input.nextLine();
         System.out.print("Enter the distance: ");
         int distance = input.nextInt();
         System.out.print("Enter the price: ");
         double price = input.nextDouble();
         a.addRoute(city1, city2, distance, price);
         break;
       case 8:
         System.out.print("Enter the first city: ");
         city1 = input.nextLine();
         System.out.print("Enter the second city: ");
         city2 = input.nextLine();
         a.removeRoute(city1, city2);
         break;
       case 9:
         System.out.print("Enter the city name: ");
         city1 = input.nextLine();
         a.addCity(city1);
         break;
       case 10:
         System.out.print("Enter the city name: ");
         city1 = input.nextLine();
         a.removeCity(city1);
         break;
       case 11:
         a.saveRoutes(filename);
         break loop;
       case 12:
         break loop;
     }
   }
 }
  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    File file = new File("/users/Sriram/Desktop/2014-15/Neural Nets/weightsDiffAct.txt");
    if (!file.exists()) file.createNewFile();
    Scanner scan = new Scanner(file);
    Scanner scanIn =
        new Scanner(new File("/users/Sriram/Desktop/2014-15/Neural Nets/StarterInput.txt"));
    System.out.println("Type train or run");
    String t = in.next();
    double[][] iWeights1 = new double[Hidden][Input];
    double[][] hWeights1 = new double[Output][Hidden];
    if (t.equals("train")) {
      BufferedWriter bout = new BufferedWriter(new FileWriter(file));
      ReverseNetDiffAct autobot = new ReverseNetDiffAct(iWeights1, hWeights1);
      autobot.initializeWeights();

      // taking in the inputs
      cases = 4;
      double[][] ktrainingInputs1 = new double[cases][Input];
      // scans files and takes in the inputs, scans line and then by character.
      for (int n = 0; n < cases; n++) {
        for (int k = 0; k < Math.sqrt(Input); k++) {
          String line = scanIn.nextLine();
          for (int b = 0; b < Math.sqrt(Input); b++) {
            ktrainingInputs1[n][k * (int) (Math.sqrt(Input)) + b] =
                Character.getNumericValue(line.charAt(b));
            //
            // System.out.println(ktrainingInputs1[n][k*9+b]);
          }
        }
      }
      autobot.setInput(ktrainingInputs1);
      autobot.initOut(cases);
      autobot.initHid(cases);
      autobot.setOut();
      // setting ideal output and initializing real output
      // itargetOutput[0][k]

      autobot.changeWeights();
      iWeights1 = autobot.getIWeights();
      hWeights1 = autobot.getHWeights();
      for (int j = 0; j < Hidden; j++) {
        for (int k = 0; k < Input; k++) {
          bout.write(iWeights1[j][k] + "\n");
        }
      }

      for (int i = 0; i < Output; i++) {
        for (int j = 0; j < Hidden; j++) {
          bout.write(hWeights1[i][j] + "\n");
        }
      }
      bout.close();
      System.out.println("Done");
    } else if (t.equals("run")) {
      // getting the weights from the optimized weights file

      for (int j = 0; j < Hidden; j++) {
        for (int k = 0; k < Input; k++) {
          iWeights1[j][k] = scan.nextDouble();
        }
      }

      for (int i = 0; i < Output; i++) {
        for (int j = 0; j < Hidden; j++) {
          hWeights1[i][j] = scan.nextDouble();
        }
      }

      // getting in all the inputs that will be propogated to check output
      cases = 4;
      ReverseNetDiffAct autobot = new ReverseNetDiffAct(iWeights1, hWeights1);
      // need to set cases first, because of constructor
      double[][] ktrainingInputs1 = new double[cases][Input];
      autobot.initOut(cases);
      autobot.initHid(cases);
      for (int n = 0; n < cases; n++) {
        for (int k = 0; k < Math.sqrt(Input); k++) {
          String line = scanIn.nextLine();
          for (int b = 0; b < Math.sqrt(Input); b++) {
            ktrainingInputs1[n][k * (int) (Math.sqrt(Input)) + b] =
                Character.getNumericValue(line.charAt(b));
            // System.out.println(ktrainingInputs1[n][k*9+b]);
          }
        }
      }
      autobot.setInput(ktrainingInputs1);
      // setting ideal output

      autobot.propagateNet(cases); // with 5 cases
      double[][] irealOutput1 = autobot.getOutput();
      for (int n = 0; n < cases; n++) {
        for (int i = 0; i < Output; i++) {
          System.out.println("Case " + n + " Output " + i + ": " + irealOutput1[n][i]);
        }
      }
      System.out.println("Done");
    }
  }
示例#24
0
  public static void main(String[] args) {
    //////////////////////////
    // The values in following 4 lines should be user input
    int startPos = 200;
    int endPos = 1000;
    int totalNumPixel = 1044;
    double threshhold = 0.0001;
    /////////////////////////
    int numPixel = endPos - startPos;
    double wavelength[] = new double[totalNumPixel];
    double photonCount[] = new double[totalNumPixel];
    double SpecNoBk[] = new double[numPixel];
    double ThisSpectrum[] = new double[numPixel];
    double ThisXaxis[] = new double[numPixel];
    double Po[] = new double[numPixel];
    double Re[] = new double[numPixel];
    double P[] = new double[6];
    double Re2[] = new double[numPixel - 1];
    double mySUM[] = new double[numPixel];
    int ind[];
    double DEV;
    double prevDEV;
    Connection connection = null;
    Statement stmt = null;
    String pattern = "##.##";

    try {
      Scanner in = new Scanner(new FileReader(args[0]));
      int i = 0;
      while (in.hasNextDouble()) {
        wavelength[i] = in.nextDouble();
        photonCount[i] = in.nextDouble();
        ++i;
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    ThisSpectrum = Arrays.copyOfRange(photonCount, startPos, endPos);
    ThisXaxis = Arrays.copyOfRange(wavelength, startPos, endPos);
    final WeightedObservedPoints obs = new WeightedObservedPoints();

    for (int i = 0; i < numPixel; i++) {
      obs.add(ThisXaxis[i], ThisSpectrum[i]);
    }

    final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(5);
    P = fitter.fit(obs.toList());
    Polyval pVal = new Polyval(P, ThisXaxis, numPixel);
    Po = pVal.evl();

    for (int i = 0; i < numPixel; i++) {
      Re[i] = ThisSpectrum[i] - Po[i];
    }

    for (int i = 0; i < numPixel - 1; i++) {
      Re2[i] = Re[i + 1] - Re[i];
    }

    DEV = Math.sqrt(StatUtils.populationVariance(Re2, 0, Re2.length));
    for (int i = 0; i < numPixel; i++) {
      mySUM[i] = Po[i] + DEV;
    }

    int jj = 0; // jj is the length of points to be removed
    for (int i = 0; i < numPixel; i++) {
      if (ThisSpectrum[i] > mySUM[i]) {
        jj++;
        ;
      }
    }
    ind = new int[jj];

    int jjj = 0;
    for (int i = 0; i < numPixel; i++) {
      if (ThisSpectrum[i] > mySUM[i]) {
        ind[jjj] = i;
        jjj++;
      }
    }

    int indKeepLength = numPixel - ind.length;
    int indKeep[] = new int[indKeepLength];
    int k = 0;
    for (int i = 0; i < numPixel; i++) {
      if (!ArrayUtils.contains(ind, i)) {
        indKeep[k] = i;
        k++;
      }
    }
    double ThisSpectrumKeep[] = new double[indKeepLength];
    double ThisXaxisKeep[] = new double[indKeepLength];
    double PoKeep[] = new double[indKeepLength];
    double ReKeep[] = new double[indKeepLength];
    double Re2Keep[] = new double[indKeepLength - 1];
    double mySUMKeep[] = new double[indKeepLength];

    for (int i = 0; i < indKeepLength; i++) {
      ThisSpectrumKeep[i] = ThisSpectrum[indKeep[i]];
      ThisXaxisKeep[i] = ThisXaxis[indKeep[i]];
    }

    prevDEV = DEV;

    // at the point, ThisSpectrum and ThisXaxis should have reduced size
    final WeightedObservedPoints obs1 = new WeightedObservedPoints();

    for (int i = 0; i < indKeepLength; i++) {
      obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]);
    }

    while (true) {
      final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(5);
      P = fitter1.fit(obs1.toList());
      Polyval pVal1 = new Polyval(P, ThisXaxisKeep, indKeepLength);
      PoKeep = pVal1.evl();

      for (int i = 0; i < indKeepLength; i++) {
        ReKeep[i] = ThisSpectrumKeep[i] - PoKeep[i];
      }

      for (int i = 0; i < indKeepLength - 1; i++) {
        Re2Keep[i] = ReKeep[i + 1] - ReKeep[i];
      }

      DEV = Math.sqrt(StatUtils.populationVariance(Re2Keep, 0, Re2Keep.length));

      for (int i = 0; i < indKeepLength; i++) {
        mySUMKeep[i] = PoKeep[i] + DEV;
      }

      for (int i = 0; i < indKeepLength; i++) {
        if (ThisSpectrumKeep[i] > mySUMKeep[i]) ThisSpectrumKeep[i] = mySUMKeep[i];
      }
      if ((Math.abs(DEV - prevDEV) / DEV) < threshhold) break;
      prevDEV = DEV;

      obs1.clear();
      for (int i = 0; i < indKeepLength; i++) {
        obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]);
      }
    }
    Polyval pVal2 = new Polyval(P, ThisXaxis, numPixel);
    double FLbk[] = pVal2.evl();
    for (int i = 0; i < ThisXaxis.length; i++) {
      SpecNoBk[i] = ThisSpectrum[i] - FLbk[i];
    }

    // the write-to-file part is only for testing purpose, ThisXaxis and SpecNoBk are two outputs
    try {
      FileWriter fr = new FileWriter(args[1]);
      BufferedWriter br = new BufferedWriter(fr);
      PrintWriter out = new PrintWriter(br);
      DecimalFormat df = new DecimalFormat(pattern);
      for (int j = 0; j < ThisXaxis.length; j++) {
        if (Double.toString(wavelength[j]) != null) out.write(ThisXaxis[j] + "\t" + SpecNoBk[j]);
        out.write("\r\n");
      }
      out.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
示例#25
0
文件: Viewer3D.java 项目: psava/cwp12
  public void loadView(String filename) {
    Point3 point;
    Vector3 tvec;
    double radius;
    double azimuth;
    double elevation;
    double scale;
    double x, y, z;
    double vx, vy, vz;

    try {
      if (_ipg == null) throw new Exception("Must load a cube first!");
      Scanner s = new Scanner(new File(filename));
      radius = s.nextDouble();
      x = s.nextDouble();
      y = s.nextDouble();
      z = s.nextDouble();
      point = new Point3(x, y, z);
      azimuth = s.nextDouble();
      elevation = s.nextDouble();
      scale = s.nextDouble();
      vx = s.nextDouble();
      vy = s.nextDouble();
      vz = s.nextDouble();
      tvec = new Vector3(vx, vy, vz);
      Iterator<ImagePanel> itr = _ipg.getImagePanels();
      while (itr.hasNext()) {
        ImagePanel ip = itr.next();
        AxisAlignedFrame aaf = ip.getFrame();
        double lx = s.nextDouble();
        double ly = s.nextDouble();
        double lz = s.nextDouble();
        double mx = s.nextDouble();
        double my = s.nextDouble();
        double mz = s.nextDouble();

        Point3 min = new Point3(lx, ly, lz);
        Point3 max = new Point3(mx, my, mz);
        aaf.setCorners(min, max);
      }
      _pmax = s.nextFloat();
      int code = s.nextInt();
      _color = ColorList.getMatch(code);
      setColorMap();
      _view.setWorldSphere(new BoundingSphere(point, radius));
      _view.setTranslate(tvec);
      _view.setAzimuth(azimuth);
      _view.setElevation(elevation);
      _view.setScale(scale);
      _ipg.setPercentiles(_pmin, _pmax);

    } catch (Exception e) {
      System.out.println("Failed to load view point!");
      System.out.println(e);
    }
  }