List of usage examples for java.util TreeSet TreeSet
public TreeSet()
From source file:CollectionAll.java
public static void main(String[] args) { List list1 = new LinkedList(); list1.add("list"); list1.add("dup"); list1.add("x"); list1.add("dup"); traverse(list1);//from w w w .ja v a2 s . c o m List list2 = new ArrayList(); list2.add("list"); list2.add("dup"); list2.add("x"); list2.add("dup"); traverse(list2); Set set1 = new HashSet(); set1.add("set"); set1.add("dup"); set1.add("x"); set1.add("dup"); traverse(set1); SortedSet set2 = new TreeSet(); set2.add("set"); set2.add("dup"); set2.add("x"); set2.add("dup"); traverse(set2); LinkedHashSet set3 = new LinkedHashSet(); set3.add("set"); set3.add("dup"); set3.add("x"); set3.add("dup"); traverse(set3); Map m1 = new HashMap(); m1.put("map", "Java2s"); m1.put("dup", "Kava2s"); m1.put("x", "Mava2s"); m1.put("dup", "Lava2s"); traverse(m1.keySet()); traverse(m1.values()); SortedMap m2 = new TreeMap(); m2.put("map", "Java2s"); m2.put("dup", "Kava2s"); m2.put("x", "Mava2s"); m2.put("dup", "Lava2s"); traverse(m2.keySet()); traverse(m2.values()); LinkedHashMap /* from String to String */ m3 = new LinkedHashMap(); m3.put("map", "Java2s"); m3.put("dup", "Kava2s"); m3.put("x", "Mava2s"); m3.put("dup", "Lava2s"); traverse(m3.keySet()); traverse(m3.values()); }
From source file:be.vdab.util.Programma.java
public static void main(String[] args) { SortedSet<Voertuig> voertuigen = new TreeSet<Voertuig>(); Datum datum = null;// w w w . j ava 2s . c om Volume volumePickup = null; Volume volumeVrachtwagen = null; try { datum = new Datum(21, 11, 2012); } catch (DatumException de) { System.out.println(de.getMessage()); } Mens bestuurder_BC = new Mens("Albert", Rijbewijs.B, Rijbewijs.C); Mens inzittende_A = new Mens("Karolien", Rijbewijs.A); Mens inzittende = new Mens("Zora"); Mens inzittende_B = new Mens("David", Rijbewijs.B); Mens inzittende_DDE = new Mens("Evert", Rijbewijs.D, Rijbewijs.DE); Mens bestuurder_DE = new Mens("Boris", Rijbewijs.DE); Personenwagen wagen1Opel = new Personenwagen("Opel", datum, 250000, 4, Color.blue, bestuurder_BC, inzittende_A, inzittende); Personenwagen wagen2 = new Personenwagen("Mazda", datum, 27000, 5, Color.blue, bestuurder_BC, inzittende_A); try { volumePickup = new Volume(3, 3, 2, Maat.meter); volumeVrachtwagen = new Volume(3, 6, 2, Maat.meter); } catch (VolumeException ve) { System.out.println(ve.getMessage()); } Pickup pickup1Opel = new Pickup("Opel", datum, 400000, 5, Color.RED, volumePickup, bestuurder_BC, inzittende_B, inzittende_DDE, inzittende_A); Pickup pickup2 = new Pickup("Toyota", datum, 39000, 4, Color.blue, volumePickup, bestuurder_BC); Vrachtwagen vrachtwagen1 = new Vrachtwagen("BMW", datum, 90000, 2, volumeVrachtwagen, 3000, 6, bestuurder_BC, inzittende_A); Vrachtwagen vrachtwagen2 = new Vrachtwagen("Mercedes", datum, 120000, 3, volumeVrachtwagen, 2000, 8, bestuurder_BC, inzittende); voertuigen.add(wagen1Opel); //gesorteerd op nummerplaat voertuigen.add(wagen2); voertuigen.add(pickup1Opel); voertuigen.add(pickup2); voertuigen.add(vrachtwagen1); voertuigen.add(vrachtwagen2); print(voertuigen); /* //copy manier1 //copy (niet nodig dadelijk naar list omzetten, maar dan zit het niet in een SortedSet, oplossing: zelf copy uitvoeren, maar niet enkel referenties Set<Voertuig> voertuigen2=null;//=new TreeSet<Voertuig>(voertuigen); //new TreeSet<Voertuig>( org.apache.commons.collections.ComparatorUtils.reversedComparator( Voertuig.getAankoopprijsComparator())); //transformeren naar List, ook een copy List<Voertuig> lijst=new ArrayList<Voertuig>(voertuigen);//niet voertuigen 2 //sort Collections.sort(lijst, org.apache.commons.collections.ComparatorUtils.reversedComparator( Voertuig.getAankoopprijsComparator())); print(lijst); */ Set<Voertuig> voertuigen2 = new TreeSet<Voertuig>(org.apache.commons.collections.ComparatorUtils .reversedComparator(Voertuig.getAankoopprijsComparator())); voertuigen2.addAll(voertuigen); print(voertuigen2); //Copy manier 2: beter Set<Voertuig> voertuigen3 = new TreeSet<Voertuig>(Voertuig.getMerkComparator()); voertuigen3.addAll(voertuigen);//deep copy of niet , staat niet in de api. Maakt het uit hier? wanneer wel?als je de vrachtwagens gaat wijzigen en je wil dat die alleen in de copy gewijzigd zijn dan deep copy nodig print(voertuigen3); try { schrijweg((TreeSet) voertuigen3, "wagenpark.ser"); } catch (FileNotFoundException fnfe) { System.out.println(fnfe.getMessage()); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } TreeSet<Voertuig> voertuigen4 = lees("wagenpark.ser"); System.out.println("Voertuigen4"); print(voertuigen4); }
From source file:TreeSetTest.java
public static void main(String[] args) { SortedSet<Item> parts = new TreeSet<Item>(); parts.add(new Item("Toaster", 1234)); parts.add(new Item("Widget", 4562)); parts.add(new Item("Modem", 9912)); System.out.println(parts);/*from w w w . j ava2s. c o m*/ SortedSet<Item> sortByDescription = new TreeSet<Item>(new Comparator<Item>() { public int compare(Item a, Item b) { String descrA = a.getDescription(); String descrB = b.getDescription(); return descrA.compareTo(descrB); } }); sortByDescription.addAll(parts); System.out.println(sortByDescription); }
From source file:Main.java
public static void main(String args[]) { TreeSet<Character> set1 = new TreeSet<Character>(); TreeSet<Character> set2 = new TreeSet<Character>(); set1.add('A'); set1.add('B'); set1.add('C'); set1.add('D'); set2.add('C'); set2.add('D'); set2.add('E'); set2.add('F'); System.out.println("set1: " + set1); System.out.println("set2: " + set2); System.out.println("Union: " + union(set1, set2)); System.out.println("Intersection: " + intersection(set1, set2)); System.out.println("Difference (set1 - set2): " + difference(set1, set2)); System.out.println("Symmetric Difference: " + symDifference(set1, set2)); TreeSet<Character> set3 = new TreeSet<Character>(set1); set3.remove('D'); System.out.println("set3: " + set3); System.out.println("Is set1 a subset of set2? " + isSubset(set1, set3)); System.out.println("Is set1 a superset of set2? " + isSuperset(set1, set3)); System.out.println("Is set3 a subset of set1? " + isSubset(set3, set1)); System.out.println("Is set3 a superset of set1? " + isSuperset(set3, set1)); }
From source file:eval.dataset.ParseWikiLog.java
public static void main(String[] ss) throws FileNotFoundException, ParserConfigurationException, IOException { FileInputStream fin = new FileInputStream("data/enwiki-20151201-pages-logging.xml.gz"); GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fin); InputStreamReader reader = new InputStreamReader(gzIn); BufferedReader br = new BufferedReader(reader); PrintWriter pw = new PrintWriter(new FileWriter("data/user_page.txt")); pw.println(// w w w. j a v a2 s . c om "#list of user names and pages that they have edited, deleted or created. These info are mined from logitems of enwiki-20150304-pages-logging.xml.gz"); TreeMap<String, Set<String>> userPageList = new TreeMap(); TreeSet<String> pageList = new TreeSet(); int counterEntry = 0; String currentUser = null; String currentPage = null; try { for (String line = br.readLine(); line != null; line = br.readLine()) { if (line.trim().equals("</logitem>")) { counterEntry++; if (currentUser != null && currentPage != null) { updateMap(userPageList, currentUser, currentPage); pw.println(currentUser + "\t" + currentPage); pageList.add(currentPage); } currentUser = null; currentPage = null; } else if (line.trim().startsWith("<username>")) { currentUser = line.trim().split(">")[1].split("<")[0].replace(" ", "_"); } else if (line.trim().startsWith("<logtitle>")) { String content = line.trim().split(">")[1].split("<")[0]; if (content.split(":").length == 1) { currentPage = content.replace(" ", "_"); } } } } catch (IOException ex) { Logger.getLogger(ParseWikiLog.class.getName()).log(Level.SEVERE, null, ex); } pw.println("#analysed " + counterEntry + " entries of wikipesia log file"); pw.println("#gathered a list of unique user of size " + userPageList.size()); pw.println("#gathered a list of pages of size " + pageList.size()); pw.close(); gzIn.close(); PrintWriter pwUser = new PrintWriter(new FileWriter("data/user_list_page_edited.txt")); pwUser.println( "#list of unique users and pages that they have edited, extracted from logitems of enwiki-20150304-pages-logging.xml.gz"); for (String user : userPageList.keySet()) { pwUser.print(user); Set<String> getList = userPageList.get(user); for (String page : getList) { pwUser.print("\t" + page); } pwUser.println(); } pwUser.close(); PrintWriter pwPage = new PrintWriter(new FileWriter("data/all_pages.txt")); pwPage.println("#list of the unique pages that are extracted from enwiki-20150304-pages-logging.xml.gz"); for (String page : pageList) { pwPage.println(page); } pwPage.close(); System.out.println("#analysed " + counterEntry + " entries of wikipesia log file"); System.out.println("#gathered a list of unique user of size " + userPageList.size()); System.out.println("#gathered a list of pages of size " + pageList.size()); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java
public static void main(String[] args) throws Exception { String inputDir = args[0];/*from w w w . j a va 2 s. c o m*/ // /tmp File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // pseudo-random final Random random = new Random(1); int totalPairsCount = 0; // read all debates for (File file : IOHelper.listXmlFiles(new File(inputDir))) { Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8")); // get two stances SortedSet<String> originalStances = debate.getStances(); // cleaning: some debate has three or more stances (data are inconsistent) // remove those with only one argument SortedSet<String> stances = new TreeSet<>(); for (String stance : originalStances) { if (debate.getArgumentsForStance(stance).size() > 1) { stances.add(stance); } } if (stances.size() != 2) { throw new IllegalStateException( "2 stances per debate expected, was " + stances.size() + ", " + stances); } // for each stance, get pseudo-random N arguments for (String stance : stances) { List<Argument> argumentsForStance = debate.getArgumentsForStance(stance); // shuffle Collections.shuffle(argumentsForStance, random); // and get max first N arguments List<Argument> selectedArguments = argumentsForStance.subList(0, argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size() : MAX_SELECTED_ARGUMENTS_PRO_SIDE); List<ArgumentPair> argumentPairs = new ArrayList<>(); // now create pairs for (int i = 0; i < selectedArguments.size(); i++) { for (int j = (i + 1); j < selectedArguments.size(); j++) { Argument arg1 = selectedArguments.get(i); Argument arg2 = selectedArguments.get(j); ArgumentPair argumentPair = new ArgumentPair(); argumentPair.setDebateMetaData(debate.getDebateMetaData()); // assign arg1 and arg2 pseudo-randomly // (not to have the same argument as arg1 all the time) if (random.nextBoolean()) { argumentPair.setArg1(arg1); argumentPair.setArg2(arg2); } else { argumentPair.setArg1(arg2); argumentPair.setArg2(arg1); } // set unique id argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId()); argumentPairs.add(argumentPair); } } String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); totalPairsCount += argumentPairs.size(); } } System.out.println("Total pairs generated: " + totalPairsCount); }
From source file:ie.pars.bnc.preprocess.MainBNCProcess.java
/** * Main method use for processing BNC text. Claws PoSs are replaced by * Stanford CoreNLP results for consistency with the rest of data! Currently * the structure of BNC is mainly discarded, only paragraphs and sentences * * @param sugare//ww w . ja v a 2s . co m * @throws IOException * @throws ArchiveException * @throws Exception */ public static void main(String[] sugare) throws IOException, ArchiveException, Exception { pathInput = sugare[0]; pathOutput = sugare[1]; letter = sugare[2]; filesProcesed = new TreeSet(); File folder = new File(pathOutput); if (folder.exists()) { for (File f : folder.listFiles()) { if (f.isFile()) { String pfile = f.getName().split("\\.")[0]; filesProcesed.add(pfile); } } } else { folder.mkdirs(); } getZippedFile(); }
From source file:fr.cs.examples.attitude.EarthObservation.java
/** Program entry point. * @param args program arguments (unused here) *//* w ww .ja v a2s.c o m*/ public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); final SortedSet<String> output = new TreeSet<String>(); // Initial state definition : date, orbit final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC()); final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity), FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU); // Attitudes sequence definition final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0); final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH); final PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth(); final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>()); final AttitudesSequence attitudesSequence = new AttitudesSequence(); final AttitudesSequence.SwitchHandler switchHandler = new AttitudesSequence.SwitchHandler() { public void switchOccurred(AttitudeProvider preceding, AttitudeProvider following, SpacecraftState s) { if (preceding == dayObservationLaw) { output.add(s.getDate() + ": switching to night law"); } else { output.add(s.getDate() + ": switching to day law"); } } }; attitudesSequence.addSwitchingCondition(dayObservationLaw, nightRestingLaw, dayNightEvent, false, true, 10.0, AngularDerivativesFilter.USE_R, switchHandler); attitudesSequence.addSwitchingCondition(nightRestingLaw, dayObservationLaw, nightDayEvent, true, false, 10.0, AngularDerivativesFilter.USE_R, switchHandler); if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) { // initial position is in daytime attitudesSequence.resetActiveProvider(dayObservationLaw); } else { // initial position is in nighttime attitudesSequence.resetActiveProvider(nightRestingLaw); } // Propagator : consider the analytical Eckstein-Hechler model final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence, Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU, Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40, Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60); // Register the switching events to the propagator attitudesSequence.registerSwitchEvents(propagator); propagator.setMasterMode(180.0, new OrekitFixedStepHandler() { public void init(final SpacecraftState s0, final AbsoluteDate t) { } public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException { try { DecimalFormatSymbols angleDegree = new DecimalFormatSymbols(Locale.US); angleDegree.setDecimalSeparator('\u00b0'); DecimalFormat ad = new DecimalFormat(" 00.000;-00.000", angleDegree); // the Earth position in spacecraft frame should be along spacecraft Z axis // during nigthtime and away from it during daytime due to roll and pitch offsets final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO); final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K); // the g function is the eclipse indicator, its an angle between Sun and Earth limb, // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb final double eclipseAngle = dayNightEvent.g(currentState); output.add(currentState.getDate() + " " + ad.format(FastMath.toDegrees(eclipseAngle)) + " " + ad.format(FastMath.toDegrees(pointingOffset))); } catch (OrekitException oe) { throw new PropagationException(oe); } } }); // Propagate from the initial date for the fixed duration SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(12600.)); // we print the lines according to lexicographic order, which is chronological order here // to make sure out of orders calls between step handler and event handlers don't mess things up for (final String line : output) { System.out.println(line); } System.out.println("Propagation ended at " + finalState.getDate()); } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }
From source file:com.jwm123.loggly.reporter.AppLauncher.java
public static void main(String args[]) throws Exception { try {//ww w .j av a 2 s .c om CommandLine cl = parseCLI(args); try { config = new Configuration(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: Failed to read in persisted configuration."); } if (cl.hasOption("h")) { HelpFormatter help = new HelpFormatter(); String jarName = AppLauncher.class.getProtectionDomain().getCodeSource().getLocation().getFile(); if (jarName.contains("/")) { jarName = jarName.substring(jarName.lastIndexOf("/") + 1); } help.printHelp("java -jar " + jarName + " [options]", opts); } if (cl.hasOption("c")) { config.update(); } if (cl.hasOption("q")) { Client client = new Client(config); client.setQuery(cl.getOptionValue("q")); if (cl.hasOption("from")) { client.setFrom(cl.getOptionValue("from")); } if (cl.hasOption("to")) { client.setTo(cl.getOptionValue("to")); } List<Map<String, Object>> report = client.getReport(); if (report != null) { List<Map<String, String>> reportContent = new ArrayList<Map<String, String>>(); ReportGenerator generator = null; if (cl.hasOption("file")) { generator = new ReportGenerator(new File(cl.getOptionValue("file"))); } byte reportFile[] = null; if (cl.hasOption("g")) { System.out.println("Search results: " + report.size()); Set<Object> values = new TreeSet<Object>(); Map<Object, Integer> counts = new HashMap<Object, Integer>(); for (String groupBy : cl.getOptionValues("g")) { for (Map<String, Object> result : report) { if (mapContains(result, groupBy)) { Object value = mapGet(result, groupBy); values.add(value); if (counts.containsKey(value)) { counts.put(value, counts.get(value) + 1); } else { counts.put(value, 1); } } } System.out.println("For key: " + groupBy); for (Object value : values) { System.out.println(" " + value + ": " + counts.get(value)); } } if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); for (Object value : values) { reportAddition = new LinkedHashMap<String, String>(); reportAddition.put(value.toString(), "" + counts.get(value)); reportContent.add(reportAddition); } reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Total", "" + report.size()); reportContent.add(reportAddition); } } else { System.out.println("The Search [" + cl.getOptionValue("q") + "] yielded " + report.size() + " results."); if (cl.hasOption("file")) { Map<String, String> reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Month", MONTH_FORMAT.format(new Date())); reportContent.add(reportAddition); reportAddition = new LinkedHashMap<String, String>(); reportAddition.put("Count", "" + report.size()); reportContent.add(reportAddition); } } if (cl.hasOption("file")) { reportFile = generator.build(reportContent); File reportFileObj = new File(cl.getOptionValue("file")); FileUtils.writeByteArrayToFile(reportFileObj, reportFile); if (cl.hasOption("e")) { ReportMailer mailer = new ReportMailer(config, cl.getOptionValues("e"), cl.getOptionValue("s"), reportFileObj.getName(), reportFile); mailer.send(); } } } } } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); System.exit(1); } }
From source file:fr.cs.examples.attitude.EarthObservation_day_night_switch_with_fixed_transitions.java
/** Program entry point. * @param args program arguments (unused here) */// w w w . j ava2 s.c om public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); final SortedSet<String> output = new TreeSet<String>(); //---------------------------------------- // Initial state definition : date, orbit //---------------------------------------- final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 02, 00, 00, 00.000, TimeScalesFactory.getUTC()); final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity), FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU); //------------------------------ // Attitudes sequence definition //------------------------------ final AttitudesSequence attitudesSequence = new AttitudesSequence(); // Attitude laws definition //------------------------- // Mode : day final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0); // Mode : night final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH); // Mode : day-night rdv 1 final AttitudeProvider dayNightRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0); // Mode : day-night rdv 2 final AttitudeProvider dayNightRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), 0, 0); // Mode : night-day rdv 1 final AttitudeProvider nightDayRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), 0, 0); // Mode : night-day rdv 2 final AttitudeProvider nightDayRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH, RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0); // Event detectors definition //--------------------------- final PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth(); // Detectors : end day-night rdv 2 final DateDetector endDayNightRdV2Event_increase = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (increasing) { output.add(s.getDate() + ": switching to night law"); System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-day-night-2 night-mode"); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); final DateDetector endDayNightRdV2Event_decrease = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (!increasing) { output.add(s.getDate() + ": switching to night law"); System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-day-night-2 night-mode"); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); // Detectors : end day-night rdv 1 final DateDetector endDayNightRdV1Event_increase = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (increasing) { output.add(s.getDate() + ": switching to day-night rdv 2 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-day-night-1 day-night-rdv2-mode"); endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20)); endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20)); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); final DateDetector endDayNightRdV1Event_decrease = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (!increasing) { output.add(s.getDate() + ": switching to day-night rdv 2 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-day-night-1 day-night-rdv2-mode"); endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20)); endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20)); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); // Detector : eclipse entry final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() { public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector, final boolean increasing) { if (!increasing) { output.add(s.getDate() + ": switching to day-night rdv 1 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " eclipse-entry day-night-rdv1-mode"); endDayNightRdV1Event_increase.addEventDate(s.getDate().shiftedBy(40)); endDayNightRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(40)); } return Action.CONTINUE; } public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) { return oldState; } }); // Detectors : end night-day rdv 2 final DateDetector endNightDayRdV2Event_increase = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (increasing) { output.add(s.getDate() + ": switching to day law"); System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-night-day-2 day-mode"); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); final DateDetector endNightDayRdV2Event_decrease = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (!increasing) { output.add(s.getDate() + ": switching to day law"); System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-night-day-2 day-mode"); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); // Detectors : end night-day rdv 1 final DateDetector endNightDayRdV1Event_increase = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (increasing) { output.add(s.getDate() + ": switching to night-day rdv 2 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-night-day-1 night-day-rdv2-mode"); endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40)); endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40)); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); final DateDetector endNightDayRdV1Event_decrease = new DateDetector(10, 1e-04) .withHandler(new EventHandler<DateDetector>() { public Action eventOccurred(final SpacecraftState s, final DateDetector detector, final boolean increasing) { if (!increasing) { output.add(s.getDate() + ": switching to night-day rdv 2 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " end-night-day-1 night-day-rdv2-mode"); endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40)); endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40)); } return Action.CONTINUE; } public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) { return oldState; } }); // Detector : eclipse exit final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth, Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() { public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector, final boolean increasing) { if (increasing) { output.add(s.getDate() + ": switching to night-day rdv 1 law"); System.out .println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " eclipse-exit night-day-rdv1-mode"); endNightDayRdV1Event_increase.addEventDate(s.getDate().shiftedBy(20)); endNightDayRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(20)); } return Action.CONTINUE; } public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) { return oldState; } }); // Attitude sequences definition //------------------------------ attitudesSequence.addSwitchingCondition(dayObservationLaw, dayNightEvent, false, true, dayNightRdV1Law); attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_increase, true, false, dayNightRdV2Law); attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_decrease, false, true, dayNightRdV2Law); attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_increase, true, false, nightRestingLaw); attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_decrease, false, true, nightRestingLaw); attitudesSequence.addSwitchingCondition(nightRestingLaw, nightDayEvent, true, false, nightDayRdV1Law); attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_increase, true, false, nightDayRdV2Law); attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_decrease, false, true, nightDayRdV2Law); attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_increase, true, false, dayObservationLaw); attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_decrease, false, true, dayObservationLaw); // Initialisation //--------------- if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) { // initial position is in daytime attitudesSequence.resetActiveProvider(dayObservationLaw); System.out .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " begin with day law"); } else { // initial position is in nighttime attitudesSequence.resetActiveProvider(nightRestingLaw); System.out .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " begin with night law"); } //---------------------- // Propagator definition //---------------------- // Propagator : consider the analytical Eckstein-Hechler model final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence, Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU, Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40, Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60); // Register the switching events to the propagator attitudesSequence.registerSwitchEvents(propagator); propagator.setMasterMode(10.0, new OrekitFixedStepHandler() { private DecimalFormat f1 = new DecimalFormat("0.0000000000000000E00", new DecimalFormatSymbols(Locale.US)); private Vector3DFormat f2 = new Vector3DFormat(" ", " ", " ", f1); private PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); private PVCoordinatesProvider moon = CelestialBodyFactory.getMoon(); private Frame eme2000 = FramesFactory.getEME2000(); private Frame itrf2005 = FramesFactory.getITRF(IERSConventions.IERS_2010, true); private String printVector3D(final String name, final Vector3D v) { return name + " " + f2.format(v); } private String printRotation(final String name, final Rotation r) { return name + " " + f1.format(r.getQ1()) + " " + f1.format(r.getQ2()) + " " + f1.format(r.getQ3()) + " " + f1.format(r.getQ0()); } private String printRotation2(final String name, final Rotation r) { return name + " " + f1.format(-r.getQ1()) + " " + f1.format(-r.getQ2()) + " " + f1.format(-r.getQ3()) + " " + f1.format(-r.getQ0()); } public void init(final SpacecraftState s0, final AbsoluteDate t) { } public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException { try { // the Earth position in spacecraft should be along spacecraft Z axis // during nigthtime and away from it during daytime due to roll and pitch offsets final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO); final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K); // the g function is the eclipse indicator, its an angle between Sun and Earth limb, // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb final double eclipseAngle = dayNightEvent.g(currentState); final double endNightDayTimer1 = endNightDayRdV1Event_decrease.g(currentState); final double endNightDayTimer2 = endNightDayRdV2Event_decrease.g(currentState); final double endDayNightTimer1 = endDayNightRdV1Event_decrease.g(currentState); final double endDayNightTimer2 = endDayNightRdV2Event_decrease.g(currentState); output.add(currentState.getDate() + " " + FastMath.toDegrees(eclipseAngle) + " " + endNightDayTimer1 + " " + endNightDayTimer2 + " " + endDayNightTimer1 + " " + endDayNightTimer2 + " " + FastMath.toDegrees(pointingOffset)); final AbsoluteDate date = currentState.getDate(); final PVCoordinates pv = currentState.getPVCoordinates(eme2000); final Rotation lvlhRot = new Rotation(pv.getPosition(), pv.getMomentum(), Vector3D.MINUS_K, Vector3D.MINUS_J); final Rotation earthRot = eme2000.getTransformTo(itrf2005, date).getRotation(); System.out.println("Scenario::setVectorMap 0x960b7e0 " + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " " + printVector3D("sun", sun.getPVCoordinates(date, eme2000).getPosition()) + " " + printVector3D("moon", moon.getPVCoordinates(date, eme2000).getPosition()) + " " + printVector3D("satPos", pv.getPosition()) + " " + printVector3D("satVel", pv.getVelocity()) + " " + printVector3D("orbMom", pv.getMomentum())); System.out.println("Scenario::setQuatMap 0x960b7e0 " + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " " + printRotation("earthFrame", earthRot) + " " + printRotation("LVLHFrame", lvlhRot)); System.out.println("Scenario::computeStep 0x960b7e0 " + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)); System.out.println(" -> " + printRotation2("", currentState.getAttitude().getRotation()) + " " + printVector3D("", currentState.getAttitude().getSpin())); } catch (OrekitException oe) { throw new PropagationException(oe); } } }); //---------- // Propagate //---------- // Propagate from the initial date for the fixed duration propagator.propagate(initialDate.shiftedBy(1.75 * 3600.)); //-------------- // Print results //-------------- // we print the lines according to lexicographic order, which is chronological order here // to make sure out of orders calls between step handler and event handlers don't mess things up for (final String line : output) { System.out.println(line); } } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }