file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
TestDateTime.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestDateTime.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static org.hermit.test.NumericAsserts.assertTolerance;
import java.util.Calendar;
import java.util.TimeZone;
import junit.framework.TestCase;
import org.hermit.astro.Instant;
import org.hermit.astro.Observation;
/**
* Test code.
*/
public class TestDateTime
extends TestCase
{
private static void testJulian(int y, int m, double d, double check) {
String lab = String.format("%5d/%02d/%06.3f", y, m, d);
Instant i = new Instant(y, m, d);
double j = i.getUt();
assertTolerance(lab + ": ymdToJulian", j, check, 0.0001);
double[] ymd = i.getYmd();
assertEquals(lab + ": julianToYmd y", (double) y, ymd[0]);
assertEquals(lab + ": julianToYmd m", (double) m, ymd[1]);
assertTolerance(lab + ": julianToYmd d", ymd[2], d, 0.000001);
}
public void testJulian() {
testJulian(1970, 1, 1.0, Instant.JD_UNIX);
testJulian(1985, 2, 17.25, 2446113.75);
testJulian(1989, 12, 31.0, 2447891.5);
testJulian(1979, 12, 31.0, 2444238.5);
testJulian(1899, 12, 31.5, Instant.J1900);
testJulian(1957, 10, 4.81, 2436116.31);
}
private static void testJavaJulian(int y, int m, double d, double check) {
String lab = String.format("%5d/%02d/%06.3f", y, m, d);
// Use Calendar to process the y/m/d.
TimeZone UTC = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(UTC);
int day = (int) d;
double rem = (d - day) * 24.0;
int hour = (int) rem;
rem = (rem - hour) * 60;
int min = (int) rem;
rem = (rem - min) * 60;
int sec = (int) rem;
cal.set(y, m - 1, day, hour, min, sec);
// Get the Java time in ms. Make an Instant from it.
long time = cal.getTimeInMillis();
Instant i = new Instant(time);
// Check that the Julian is right.
double j = i.getUt();
assertTolerance(lab + ": javaToJulian", j, check, 0.0001);
}
public void testJavaJulian() {
testJavaJulian(1970, 1, 1.0, Instant.JD_UNIX);
testJavaJulian(1985, 2, 17.25, 2446113.75);
testJavaJulian(1989, 12, 31.0, 2447891.5);
testJavaJulian(1979, 12, 31.0, 2444238.5);
testJavaJulian(1899, 12, 31.5, Instant.J1900);
testJavaJulian(1957, 10, 4.81, 2436116.31);
}
private static void testUtToGmst(int y, int m, int d, double UT, double check) {
String lab = String.format("%5d/%02d/%02d", y, m, d);
Observation o = new Observation();
o.setDate(y, m, (double) d + UT / 24.0);
double GMST = o.get(Observation.OField.GMST_INSTANT);
assertTolerance(lab + ": Gmst", GMST, check, 0.000001);
}
public void testUtToGmst() {
testUtToGmst(1980, 4, 22, 14.614353, 4.668119);
testUtToGmst(1987, 4, 10, 0, 13.1795463333333);
testUtToGmst(1987, 4, 10, 19.0 + 21.0/60.0, 8.0 + 34.0/60.0 + 57.0896 / 3600.0);
}
private static void testUtToGast(int y, int m, int d, double UT, double check) {
String lab = String.format("%5d/%02d/%02d", y, m, d);
Observation o = new Observation();
o.setDate(y, m, (double) d + UT / 24.0);
double GAST = o.get(Observation.OField.GAST_INSTANT);
assertTolerance(lab + ": Gast", GAST, check, 0.000001);
double GAST_M = o.get(Observation.OField.GAST_MIDNIGHT);
assertTolerance(lab + ": Gast", GAST_M, check, 0.000001);
}
public void testUtToGast() {
testUtToGast(1987, 4, 10, 0, 13.0 + 10.0/60.0 + 46.1351/3600.0);
testUtToGast(1988, 3, 20, 0, 177.74208 / 15);
}
}
| 4,176 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestIllum.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestIllum.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static java.lang.Math.toDegrees;
import static org.hermit.test.NumericAsserts.assertDegrees;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.AstroError;
import org.hermit.astro.Body;
import org.hermit.astro.Instant;
import org.hermit.astro.Moon;
import org.hermit.astro.Observation;
import org.hermit.astro.Planet;
import org.hermit.astro.Sun;
import org.hermit.astro.Body.Field;
import org.hermit.geo.Position;
/**
* Test code.
*/
public class TestIllum
extends TestCase
{
// ******************************************************************** //
// Phase.
// ******************************************************************** //
private static void testPhase(Body b, double cp, double cl) throws AstroError {
String n = b.getId().toString();
String lab = "SkyPosition " + n;
double k = b.get(Field.PHASE);
double Χ = Math.toDegrees(b.get(Field.ABS_BRIGHT_LIMB));
assertTolerance(lab + " phase", k, cp, 0.002);
assertDegrees(lab + " limb", Χ, cl, 0.2);
}
public void testPhase() throws AstroError {
// From Meeus chapter 41. Bright limb added manually.
Instant instant = Instant.fromTd(1992, 12, 20.0);
Observation o = new Observation(instant);
Planet venus = o.getPlanet(Planet.Name.VENUS);
testPhase(venus, 0.647, 255.42);
// From Meeus chapter 48.
instant = Instant.fromTd(1992, 4, 12.0);
o.setTime(instant);
Moon moon = o.getMoon();
testPhase(moon, 0.6786, 285.0);
}
// ******************************************************************** //
// Distance and Size.
// ******************************************************************** //
private static void testDistSize(String lab, Body b, double cr, double cd)
throws AstroError
{
double r = b.get(Field.EARTH_DISTANCE);
double d = toDegrees(b.get(Field.APPARENT_DIAMETER)) * 3600;
assertTolerance(lab + " dist", r, cr, 0.0002);
assertTolerance(lab + " size", d, cd, 0.34);
}
public void testSunDistSize() throws AstroError {
// From NASA Horizons:
// Sun 1988-Jul-27 16:30 UT
// Dist = 1.01539413765642 AU
// Diam = 1890.192 s
Observation o = new Observation();
o.setTime(new Instant(1988, 7, 27, 16, 30, 0));
o.setObserverPosition(Position.fromDegrees(42.3333, -71.0833));
Sun s = o.getSun();
testDistSize("NH 1988-Jul-27", s, 1.01539413765642, 1890.192);
}
public void testMoonDistSize() throws AstroError {
// From NASA Horizons:
// Moon 1988-Jul-27 00:30 UT
// Altitude = 11.7334°
// Dist = 0.002454383735427 AU
// Diam = 1952.040 s
Observation o = new Observation();
o.setTime(new Instant(1988, 7, 27, 0, 30, 0));
o.setObserverPosition(Position.fromDegrees(42.3333, -71.0833));
Moon moon = o.getMoon();
testDistSize("NH 1988-Jul-27", moon, 0.002454383735427, 1952.040);
}
public void testPlanetDistSize() throws AstroError {
// From NASA Horizons:
// Jupiter 1988-Jul-27 00:30 UT
// Altitude = 11.7334°
// Dist = 5.36552671511285 AU
// Diam = 36.743 s
Observation o = new Observation();
o.setTime(new Instant(1988, 7, 27, 0, 30, 0));
o.setObserverPosition(Position.fromDegrees(42.3333, -71.0833));
Planet jupiter = o.getPlanet(Planet.Name.JUPITER);
testDistSize("NH 1988-Jul-27", jupiter, 5.36552671511285, 36.743);
}
// ******************************************************************** //
// Magnitude.
// ******************************************************************** //
private static void testMagnitude(String lab, Body b, double check)
throws AstroError
{
double M = b.get(Field.MAGNITUDE);
assertTolerance(lab + " mag", M, check, 0.1);
}
public void testPlanetMagnitude() throws AstroError {
// From NASA Horizons:
// Venus 1987-Apr-10 19:21 UT
// Mag = -3.96
Observation o = new Observation();
o.setTime(new Instant(1987, 4, 10, 19, 21, 0));
o.setObserverPosition(Position.fromDegrees(38.9213889, -77.0655556));
Planet venus = o.getPlanet(Planet.Name.VENUS);
testMagnitude("NH 1988-Jul-27", venus, -3.96);
}
}
| 4,961 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestObliquity.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestObliquity.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.Observation;
/**
* Test code.
*/
public class TestObliquity
extends TestCase
{
// ******************************************************************** //
// Test Code.
// ******************************************************************** //
private static void testMeanObliq(Observation o, double check) {
double e = Math.toDegrees(o.get(Observation.OField.MEAN_OBLIQUITY));
assertTolerance("mean obliquity", e, check, 0.000001);
}
public void testMeanObliq() {
Observation o = new Observation();
o.setDate(1979, 12, 31.0);
testMeanObliq(o, 23.441893);
}
private static void testTrueObliq(Observation o, double check) {
double e = Math.toDegrees(o.get(Observation.OField.TRUE_OBLIQUITY));
assertTolerance("true obliquity", e, check, 0.000001);
}
public void testTrueObliq() {
Observation o = new Observation();
o.setDate(1987, 04, 10.0);
testTrueObliq(o, 23.4435694);
}
}
| 1,916 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestPosition.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestPosition.java |
/**
* astro: astronomical functions, utilities and data
*
* This package was created by Ian Cameron Smith in February 2009, based
* on the formulae in "Practical Astronomy with your Calculator" by
* Peter Duffett-Smith, ISBN-10: 0521356997.
*
* Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.test.astro;
import static java.lang.Math.toDegrees;
import static org.hermit.test.NumericAsserts.assertDegrees;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.AstroError;
import org.hermit.astro.AstroConstants;
import org.hermit.astro.Body;
import org.hermit.astro.Instant;
import org.hermit.astro.Moon;
import org.hermit.astro.Observation;
import org.hermit.astro.Planet;
import org.hermit.astro.Sun;
import org.hermit.astro.Body.Field;
import org.hermit.geo.Position;
import org.hermit.utils.Angle;
/**
* Test code.
*/
public class TestPosition
extends TestCase
{
// ******************************************************************** //
// Heliocentric Co-Ordinates.
// ******************************************************************** //
private static void testHeliocentric(String lab, Body b,
double cl, double cb, double cr)
throws AstroError
{
double L = toDegrees(b.get(Field.HE_LONGITUDE));
double B = toDegrees(b.get(Field.HE_LATITUDE));
double R = b.get(Field.HE_RADIUS);
assertDegrees(lab + " Lon", L, cl, 0.00001);
assertTolerance(lab + " Lat", B, cb, 0.00001);
assertTolerance(lab + " Rad", R, cr, 0.00001);
}
public void testVenusHe() throws AstroError {
Observation o = new Observation();
Body venus = o.getBody(Body.Name.VENUS);
// Meeus chapter 33.
o.setTime(Instant.fromTd(1992, 12, 20.0));
testHeliocentric("Meeus 33", venus, 26.11428, -2.62070, 0.724603);
}
// ******************************************************************** //
// Equatorial Co-Ordinates.
// ******************************************************************** //
private static void testEquatorial(String lab, Body b,
double cα, double cδ, double cd)
throws AstroError
{
double α = toDegrees(b.get(Field.RIGHT_ASCENSION_AP));
double δ = toDegrees(b.get(Field.DECLINATION_AP));
double d = b.get(Field.EARTH_DISTANCE);
assertDegrees(lab + " α", α, cα, 0.0005);
assertTolerance(lab + " δ", δ, cδ, 0.0005);
assertTolerance(lab + " d", d, cd, 0.000051);
}
private static void testEquatorial(String lab, Body b,
int ah, int am, double as,
int dd, int dm, double ds,
double r)
throws AstroError
{
Angle ra = Angle.fromRightAscension(ah, am, as);
Angle dec = Angle.fromDegrees(dd, dm, ds);
testEquatorial(lab, b, ra.getDegrees(), dec.getDegrees(), r);
}
public void testSunEq() throws AstroError {
// From Meeus chapter 25.
Observation o = new Observation(Instant.fromTd(1992, 10, 13.0));
Sun sun = o.getSun();
testEquatorial("Meeus 25", sun, 198.378178, -7.783871, 0.99760775);
}
public void testMoonEq() throws AstroError {
// From Meeus chapter 47.
Observation o = new Observation(Instant.fromTd(1992, 4, 12.0));
Moon moon = o.getMoon();
testEquatorial("Meeus 47", moon,
134.688470, 13.768368, 368405.6 / AstroConstants.AU);
}
public void testMercuryEq() throws AstroError {
// From NASA Horizons:
// Mercury 1988-Nov-22 00:00 UT
// RA = 15 29 04.27 = 232.267791667°
// Dec = -18 42 40.2 = -18.7111667°
// Dist = 1.41999975439192
Observation o = new Observation(new Instant(1988, 11, 22));
Planet mercury = o.getPlanet(Planet.Name.MERCURY);
testEquatorial("NH 1988-Nov-22", mercury,
232.267791667, -18.7111667, 1.4199997543919);
}
public void testVenusEq() throws AstroError {
// From NASA Horizons:
// Venus 1992-Dec-20 00:00 TT
// RA = 21 04 41.45 = 316.172708333°
// Dec = -18 53 16.8 = -18.8880000°
// Dist = 0.910947738674360
Observation o = new Observation(Instant.fromTd(1992, 12, 20.0));
Planet venus = o.getPlanet(Planet.Name.VENUS);
testEquatorial("NH 1992-Dec-20", venus,
316.172708, -18.8880000, 0.9109477);
}
public void testMarsEq() throws AstroError {
// From NASA Horizons:
// Mars 2003-Aug-28 03:17 UT
// Geocentric
// RA = 22 38 07.25
// Dec = -15 46 15.9
// Dist = 0.372756755997547
Instant instant = new Instant(2003, 8, 28.0 + (3.0+17.0/60.0)/24.0);
Observation o = new Observation(instant);
Planet mars = o.getPlanet(Planet.Name.MARS);
testEquatorial("NH 2003-Aug-28", mars,
339.530208333, -15.7710833, 0.372756755997547);
// From NASA Horizons:
// Mars 2007-Mar-14 03:17
// RA = 20 59 59.06
// Dec = -18 10 02.4
// Dist = 2.02010322
o.setTime(new Instant(2007, 3, 14, 3, 17, 0));
testEquatorial("NH 2007-Mar-14", mars,
20,59,59.06, -18,10,2.4, 2.02010322);
}
public void testJupiterEq() throws AstroError {
// From NASA Horizons:
// Jupiter 1988-Nov-22 00:00 UT
// RA = 03 57 10.50 = 59.293750000°
// Dec = +19 23 35.8 = 19.3932778°
// Dist = 4.03398209416213
Observation o = new Observation(new Instant(1988, 11, 22));
Planet jupiter = o.getPlanet(Planet.Name.JUPITER);
testEquatorial("NH 1988-Nov-22", jupiter,
59.293750000, 19.3932778, 4.03398209416213);
}
public void testSaturnEq() throws AstroError {
// From NASA Horizons:
// Saturn 2007-Mar-14 03:17 UT
// RA = 09 28 41.52
// Dec = +16 17 31.7
// Dist = 8.35204965
Observation o = new Observation(new Instant(2007, 3, 14, 3, 17, 0));
Planet saturn = o.getPlanet(Planet.Name.SATURN);
testEquatorial("NH 2007-Mar-14", saturn,
9,28,41.52, 16,17,31.7, 8.35204965);
}
public void testUranusEq() throws AstroError {
// From NASA Horizons:
// Uranus 2007-Mar-14 03:17 UT
// RA = 23 06 31.02
// Dec = -06 31 26.3
// Dist = 21.07300984
Observation o = new Observation(new Instant(2007, 3, 14, 3, 17, 0));
Planet uranus = o.getPlanet(Planet.Name.URANUS);
testEquatorial("NH 2007-Mar-14", uranus,
23,6,31.02, -6,31,26.3, 21.07300984);
}
public void testNeptuneEq() throws AstroError {
// From NASA Horizons:
// Neptune 2002-Sep-21 19:17 UT
// RA = 23 06 31.02
// Dec = -06 31 26.3
// Dist = 29.43560887
Observation o = new Observation(new Instant(2002, 9, 21, 19, 17, 0));
Planet neptune = o.getPlanet(Planet.Name.NEPTUNE);
testEquatorial("NH 2002-Sep-21", neptune,
20,43,17.57, -18,6,4.1, 29.43560887);
}
// ******************************************************************** //
// Horizontal Co-Ordinates.
// ******************************************************************** //
private static void testHorizontal(String lab, Body b,
double cA, double ch)
throws AstroError
{
double A = toDegrees(b.get(Field.LOCAL_AZIMUTH));
double h = toDegrees(b.get(Field.LOCAL_ALTITUDE));
assertDegrees(lab + " A", A, cA, 0.002);
assertTolerance(lab + " h", h, ch, 0.002);
}
public void testVenusHoriz() throws AstroError {
// From NASA Horizons:
// Venus 1987-Apr-10 19:21 UT
// Azimuth = 248.0327
// Altitude = 15.1240
Observation o = new Observation(new Instant(1987, 4, 10, 19, 21, 0));
o.setObserverPosition(Position.fromDegrees(38.9213889, -77.0655556));
Planet venus = o.getPlanet(Planet.Name.VENUS);
testHorizontal("NH 1987-Apr-10", venus, 248.0327, 15.1240);
// From Meeus chapter 13.
o.setTime(new Instant(1987, 4, 10, 19, 21, 0));
o.setObserverPosition(Position.fromDegrees(38.9213889, -77.0655556));
testHorizontal("Meeus 13", venus, 68.0337 + 180.0, 15.12495);
}
}
| 8,226 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TestDeltaT.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/test/org/hermit/test/astro/TestDeltaT.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.test.astro;
import static org.hermit.test.NumericAsserts.assertTolerance;
import junit.framework.TestCase;
import org.hermit.astro.Instant;
/**
* Test astro methods.
*
* @author Ian Cameron Smith
*/
public class TestDeltaT
extends TestCase
{
// ******************************************************************** //
// Test Definitions.
// ******************************************************************** //
private static final class TestData {
public TestData(int year, double dt, double tol) {
this.year = year;
this.deltaT = dt;
this.tolerance = tol;
}
final int year;
final double deltaT;
final double tolerance;
}
/**
* Table of test data. Each row contains:
* - Test name, ellipsoid to use
* - Station 1 latitude, degrees; longitude, degrees
* - Station 2 latitude, degrees; longitude, degrees
* - Forward azimuth, degrees; back azimuth, degrees
* - Distance, metres
*/
private static final TestData[] testData = {
new TestData(1650, +46, 4.2),
new TestData(1652, +44, 4),
new TestData(1654, 42, 2.5),
new TestData(1656, 40, 2.0),
new TestData(1658, 38, 2.0),
new TestData(1660, +35, 2.0),
new TestData(1662, 33, 2.0),
new TestData(1664, 31, 2.0),
new TestData(1666, 29, 2.0),
new TestData(1668, 26, 2.0),
new TestData(1670, +24, 2.0),
new TestData(1672, 22, 2.0),
new TestData(1674, 20, 2.0),
new TestData(1676, 18, 2.0),
new TestData(1678, 16, 2.0),
new TestData(1680, +14, 2.0),
new TestData(1682, 12, 2.0),
new TestData(1684, 11, 2.0),
new TestData(1686, 10, 2.0),
new TestData(1688, 9, 2.0),
new TestData(1690, +8, 2.0),
new TestData(1692, 7, 2.4),
new TestData(1694, 7, 2.0),
new TestData(1696, 7, 2.0),
new TestData(1698, 7, 2.0),
new TestData(1700, +7, 1.9),
new TestData(1702, 7, 2.2),
new TestData(1704, 8, 1.75),
new TestData(1706, 8, 1.75),
new TestData(1708, 9, 1.75),
new TestData(1710, +9, 1.75),
new TestData(1712, 9, 1.75),
new TestData(1714, 9, 1.75),
new TestData(1716, 9, 1.75),
new TestData(1718, 10, 1.75),
new TestData(1720, +10, 1.75),
new TestData(1722, 10, 1.75),
new TestData(1724, 10, 1.75),
new TestData(1726, 10, 1.75),
new TestData(1728, 10, 1.75),
new TestData(1730, 10, 1.75),
new TestData(1732, 10, 1.75),
new TestData(1734, 11, 1.75),
new TestData(1736, 11, 1.75),
new TestData(1738, 11, 1.75),
new TestData(1740, +11, 1.75),
new TestData(1742, 11, 1.75),
new TestData(1744, 12, 1.75),
new TestData(1746, 12, 1.75),
new TestData(1748, 12, 1.75),
new TestData(1750, +12, 1.75),
new TestData(1752, 13, 1.75),
new TestData(1754, 13, 1.75),
new TestData(1756, 13, 1.75),
new TestData(1758, 14, 1.75),
new TestData(1760, +14, 1.75),
new TestData(1762, 14, 1.75),
new TestData(1764, 14, 1.75),
new TestData(1766, 15, 1.75),
new TestData(1768, 15, 1.75),
new TestData(1770, +15, 1.75),
new TestData(1772, 15, 1.75),
new TestData(1774, 15, 1.75),
new TestData(1776, 16, 1.75),
new TestData(1778, 16, 1.75),
new TestData(1780, +16, 1.75),
new TestData(1782, 16, 1.75),
new TestData(1784, 16, 1.75),
new TestData(1786, 16, 1.75),
new TestData(1788, 16, 1.75),
new TestData(1790, +16, 1.75),
new TestData(1792, 15, 1.75),
new TestData(1794, 15, 1.75),
new TestData(1796, 14, 1.75),
new TestData(1798, 13, 1.75),
new TestData(1800, +13.1, 0.75),
new TestData(1802, 12.5, 0.75),
new TestData(1804, 12.2, 0.75),
new TestData(1806, 12.0, 0.75),
new TestData(1808, 12.0, 0.75),
new TestData(1810, +12.0, 0.75),
new TestData(1812, 12.0, 0.75),
new TestData(1814, 12.0, 0.75),
new TestData(1816, 12.0, 0.75),
new TestData(1818, 11.9, 0.75),
new TestData(1820, +11.6, 0.75),
new TestData(1822, 11.0, 0.75),
new TestData(1824, 10.2, 0.75),
new TestData(1826, 9.2, 0.75),
new TestData(1828, 8.2, 0.75),
new TestData(1830, +7.1, 0.75),
new TestData(1832, 6.2, 0.75),
new TestData(1834, 5.6, 0.75),
new TestData(1836, 5.4, 0.75),
new TestData(1838, 5.3, 0.75),
new TestData(1840, +5.4, 0.75),
new TestData(1842, 5.6, 0.75),
new TestData(1844, 5.9, 0.75),
new TestData(1846, 6.2, 0.75),
new TestData(1848, 6.5, 0.75),
new TestData(1850, +6.8, 0.75),
new TestData(1852, 7.1, 0.75),
new TestData(1854, 7.3, 0.75),
new TestData(1856, 7.5, 0.75),
new TestData(1858, 7.6, 0.75),
new TestData(1860, +7.7, 0.75),
new TestData(1862, 7.3, 0.75),
new TestData(1864, 6.2, 0.75),
new TestData(1866, 5.2, 0.75),
new TestData(1868, 2.7, 0.75),
new TestData(1870, +1.4, 0.75),
new TestData(1872, -1.2, 0.75),
new TestData(1874, -2.8, 0.75),
new TestData(1876, -3.8, 0.75),
new TestData(1878, -4.8, 0.75),
new TestData(1880, -5.5, 0.75),
new TestData(1882, -5.3, 0.75),
new TestData(1884, -5.6, 0.75),
new TestData(1886, -5.7, 0.75),
new TestData(1888, -5.9, 0.75),
new TestData(1890, -6.0, 0.75),
new TestData(1892, -6.3, 0.75),
new TestData(1894, -6.5, 0.75),
new TestData(1896, -6.2, 0.75),
new TestData(1898, -4.7, 0.75),
new TestData(1900, -2.8, 0.21),
new TestData(1902, -0.1, 0.21),
new TestData(1904, +2.6, 0.21),
new TestData(1906, 5.3, 0.21),
new TestData(1908, 7.7, 0.21),
new TestData(1910, +10.4, 0.21),
new TestData(1912, 13.3, 0.21),
new TestData(1914, 16.0, 0.21),
new TestData(1916, 18.2, 0.21),
new TestData(1918, 20.2, 0.21),
new TestData(1920, +21.1, 0.21),
new TestData(1922, 22.4, 0.21),
new TestData(1924, 23.5, 0.21),
new TestData(1926, 23.8, 0.21),
new TestData(1928, 24.3, 0.21),
new TestData(1930, +24.0, 0.21),
new TestData(1932, 23.9, 0.21),
new TestData(1934, 23.9, 0.21),
new TestData(1936, 23.7, 0.21),
new TestData(1938, 24.0, 0.21),
new TestData(1940, +24.3, 0.21),
new TestData(1942, 25.3, 0.21),
new TestData(1944, 26.2, 0.21),
new TestData(1946, 27.3, 0.14),
new TestData(1948, 28.2, 0.14),
new TestData(1950, +29.1, 0.14),
new TestData(1952, 30.0, 0.14),
new TestData(1954, 30.7, 0.14),
new TestData(1956, 31.4, 0.14),
new TestData(1958, 32.2, 0.14),
new TestData(1960, +33.1, 0.14),
new TestData(1962, 34.0, 0.14),
new TestData(1964, 35.0, 0.14),
new TestData(1966, 36.5, 0.14),
new TestData(1968, 38.3, 0.14),
new TestData(1970, +40.2, 0.14),
new TestData(1972, 42.2, 0.14),
new TestData(1974, 44.5, 0.12),
new TestData(1976, 46.5, 0.1),
new TestData(1978, 48.5, 0.1),
new TestData(1980, +50.5, 0.1),
new TestData(1982, 52.2, 0.1),
new TestData(1984, 53.8, 0.1),
new TestData(1986, 54.9, 0.1),
new TestData(1988, 55.8, 0.1),
new TestData(1990, +56.9, 0.1),
new TestData(1992, 58.3, 0.1),
new TestData(1994, 60.0, 0.1),
new TestData(1996, 61.6, 0.1),
new TestData(1998, 63.0, 0.1),
new TestData(2000, +63.8, 0.1),
new TestData(2002, 64.3, 0.1),
new TestData(2004, 64.6, 0.1),
// Selected fixed dates.
new TestData(1500, 198.28, 0.1),
new TestData(1800, 13.7, 0.1),
new TestData(1900, -2.73, 0.1),
new TestData(2000, 63.874, 0.015),
new TestData(2009, 66.33, 0.06),
new TestData(2017, 70.03, 0.06),
};
// ******************************************************************** //
// Tests.
// ******************************************************************** //
private void doYear(TestData test) {
int year = test.year;
double month = 0.0;
double dt = Instant.calculateDeltaT(year, month);
// double err = dt - test.deltaT;
// String ok = Math.abs(err) < test.tolerance ? "OK" : "BAD";
// System.out.format("%04d: got %8.4f want %8.4f err %8.3f : %s\n",
// year, dt, test.deltaT, err, ok);
assertTolerance("" + year, dt, test.deltaT, test.tolerance);
}
public void testDeltaT() {
for (TestData test : testData)
doYear(test);
}
}
| 9,104 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
ComplexDoubleFFT.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/ComplexDoubleFFT.java | package ca.uol.aig.fftpack;
/**
* FFT transform of a complex periodic sequence.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class ComplexDoubleFFT extends ComplexDoubleFFT_Mixed
{
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward transform
* (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
public double norm_factor;
private double wavetable[];
private int ndim;
/**
* Construct a wavenumber table with size <em>n</em> for Complex FFT.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a complex data sequence. When <em>n</em> is a multiplication of small
* numbers (4, 2, 3, 5), this FFT transform is very efficient.
*/
public ComplexDoubleFFT(int n)
{
ndim = n;
norm_factor = n;
if(wavetable == null || wavetable.length !=(4*ndim+15))
{
wavetable = new double[4*ndim + 15];
}
cffti(ndim, wavetable);
}
/**
* Forward complex FFT transform.
*
* @param x 2*<em>n</em> real double data representing <em>n</em> complex double data.
* As an input parameter, <em>x</em> is an array of 2*<em>n</em> real
* data representing <em>n</em> complex data. As an output parameter, <em>x</em> represents <em>n</em>
* FFT'd complex data. Their relation as follows:
* <br>
* x[2*i] is the real part of <em>i</em>-th complex data;
* <br>
* x[2*i+1] is the imaginary part of <em>i</em>-the complex data.
*
*/
public void ft(double x[])
{
if(x.length != 2*ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
cfftf(ndim, x, wavetable);
}
/**
* Forward complex FFT transform.
*
* @param x an array of <em>n</em> Complex data
*/
public void ft(Complex1D x)
{
if(x.x.length != ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
double[] y = new double[2*ndim];
for(int i=0; i<ndim; i++)
{
y[2*i] = x.x[i];
y[2*i+1] = x.y[i];
}
cfftf(ndim, y, wavetable);
for(int i=0; i<ndim; i++)
{
x.x[i]=y[2*i];
x.y[i]=y[2*i+1];
}
}
/**
* Backward complex FFT transform. It is the unnormalized inverse transform of <em>ft</em>(double[]).
*
* @param x 2*<em>n</em> real double data representing <em>n</em> complex double data.
*
* As an input parameter, <em>x</em> is an array of 2*<em>n</em>
* real data representing <em>n</em> complex data. As an output parameter, <em>x</em> represents
* <em>n</em> FFT'd complex data. Their relation as follows:
* <br>
* x[2*<em>i</em>] is the real part of <em>i</em>-th complex data;
* <br>
* x[2*<em>i</em>+1] is the imaginary part of <em>i</em>-the complex data.
*
*/
public void bt(double x[])
{
if(x.length != 2*ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
cfftb(ndim, x, wavetable);
}
/**
* Backward complex FFT transform. It is the unnormalized inverse transform of <em>ft</em>(Complex1D[]).
*
*
* @param x an array of <em>n</em> Complex data
*/
public void bt(Complex1D x)
{
if(x.x.length != ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
double[] y = new double[2*ndim];
for(int i=0; i<ndim; i++)
{
y[2*i] = x.x[i];
y[2*i+1] = x.y[i];
}
cfftb(ndim, y, wavetable);
for(int i=0; i<ndim; i++)
{
x.x[i]=y[2*i];
x.y[i]=y[2*i+1];
}
}
}
| 4,141 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT_Mixed.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT_Mixed.java |
package ca.uol.aig.fftpack;
/**
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
class RealDoubleFFT_Mixed
{
// ******************************************************************** //
// Real-Valued FFT Initialization.
// ******************************************************************** //
/**
* Initialization of Real FFT.
*/
void rffti(int n, double wtable[]) /* length of wtable = 2*n + 15 */
{
if (n == 1)
return;
rffti1(n, wtable, 0);
}
/*---------------------------------------------------------
rffti1: further initialization of Real FFT
--------------------------------------------------------*/
void rffti1(int n, double wtable[], int offset)
{
double argh;
int ntry=0, i, j;
double argld;
int k1, l1, l2, ib;
double fi;
int ld, ii, nf, ip, nl, is, nq, nr;
double arg;
int ido, ipm;
int nfm1;
// Create a working array.
tempData = new double[n];
nl=n;
nf=0;
j=0;
factorize_loop:
while(true)
{
++j;
if(j<=4)
ntry=NTRY_H[j-1];
else
ntry+=2;
do
{
nq=nl / ntry;
nr=nl-ntry*nq;
if(nr !=0) continue factorize_loop;
++nf;
wtable[nf+1+2*n+offset]=ntry;
nl=nq;
if(ntry==2 && nf !=1)
{
for(i=2; i<=nf; i++)
{
ib=nf-i+2;
wtable[ib+1+2*n+offset]=wtable[ib+2*n+offset];
}
wtable[2+2*n+offset]=2;
}
}while(nl !=1);
break factorize_loop;
}
wtable[0+2*n+offset] = n;
wtable[1+2*n+offset] = nf;
argh=TWO_PI /(double)(n);
is=0;
nfm1=nf-1;
l1=1;
if(nfm1==0) return;
for(k1=1; k1<=nfm1; k1++)
{
ip=(int)wtable[k1+1+2*n+offset];
ld=0;
l2=l1*ip;
ido=n / l2;
ipm=ip-1;
for(j=1; j<=ipm;++j)
{
ld+=l1;
i=is;
argld=(double)ld*argh;
fi=0;
for(ii=3; ii<=ido; ii+=2)
{
i+=2;
fi+=1;
arg=fi*argld;
wtable[i-2+n+offset] = Math.cos(arg);
wtable[i-1+n+offset] = Math.sin(arg);
}
is+=ido;
}
l1=l2;
}
} /*rffti1*/
// ******************************************************************** //
// Real-Valued FFT -- Forward Transform.
// ******************************************************************** //
/*---------------------------------------------------------
rfftf: Real forward FFT
--------------------------------------------------------*/
void rfftf(int n, double r[], double wtable[])
{
if(n==1) return;
rfftf1(n, r, wtable, 0);
} /*rfftf*/
/*---------------------------------------------------------
rfftf1: further processing of Real forward FFT
--------------------------------------------------------*/
void rfftf1(int n, double[] c, final double[] wtable, int offset)
{
final double[] td = tempData;
System.arraycopy(wtable, offset, td, 0, n);
int nf = (int) wtable[1 + 2 * n + offset];
int na = 1;
int l2 = n;
int iw = n - 1 + n + offset;
for (int k1 = 1; k1 <= nf; ++k1) {
int kh = nf - k1;
int ip = (int) wtable[kh + 2 + 2 * n + offset];
int l1 = l2 / ip;
int ido = n / l2;
int idl1 = ido * l1;
iw -= (ip - 1) * ido;
na = 1 - na;
if (ip == 4) {
if (na == 0)
radf4(ido, l1, c, td, wtable, iw);
else
radf4(ido, l1, td, c, wtable, iw);
} else if (ip == 2) {
if (na == 0)
radf2(ido, l1, c, td, wtable, iw);
else
radf2(ido, l1, td, c, wtable, iw);
} else if (ip == 3) {
if (na == 0)
radf3(ido, l1, c, td, wtable, iw);
else
radf3(ido, l1, td, c, wtable, iw);
} else if (ip == 5) {
if (na == 0)
radf5(ido, l1, c, td, wtable, iw);
else
radf5(ido, l1, td, c, wtable, iw);
} else {
if (ido == 1)
na = 1 - na;
if (na == 0) {
radfg(ido, ip, l1, idl1, c, c, c, td, td, wtable, iw);
na = 1;
} else {
radfg(ido, ip, l1, idl1, td, td, td, c, c, wtable, iw);
na = 0;
}
}
l2 = l1;
}
// If na == 1, the results are in c. Otherwise they're in tempData.
if (na == 0)
for (int i = 0; i < n; i++)
c[i] = td[i];
}
// ******************************************************************** //
// Real-Valued FFT -- Reverse Transform.
// ******************************************************************** //
/*---------------------------------------------------------
rfftb: Real backward FFT
--------------------------------------------------------*/
void rfftb(int n, double r[], double wtable[])
{
if(n==1) return;
rfftb1(n, r, wtable, 0);
} /*rfftb*/
/*---------------------------------------------------------
rfftb1: further processing of Real backward FFT
--------------------------------------------------------*/
void rfftb1(int n, double c[], final double wtable[], int offset)
{
int k1, l1, l2, na, nf, ip, iw, ido, idl1;
final double[] td = tempData;
System.arraycopy(wtable, offset, td, 0, n);
nf=(int)wtable[1+2*n+offset];
na=0;
l1=1;
iw=n+offset;
for(k1=1; k1<=nf; k1++)
{
ip=(int)wtable[k1+1+2*n+offset];
l2=ip*l1;
ido=n / l2;
idl1=ido*l1;
if(ip==4)
{
if(na==0)
{
radb4(ido, l1, c, td, wtable, iw);
}
else
{
radb4(ido, l1, td, c, wtable, iw);
}
na=1-na;
}
else if(ip==2)
{
if(na==0)
{
radb2(ido, l1, c, td, wtable, iw);
}
else
{
radb2(ido, l1, td, c, wtable, iw);
}
na=1-na;
}
else if(ip==3)
{
if(na==0)
{
radb3(ido, l1, c, td, wtable, iw);
}
else
{
radb3(ido, l1, td, c, wtable, iw);
}
na=1-na;
}
else if(ip==5)
{
if(na==0)
{
radb5(ido, l1, c, td, wtable, iw);
}
else
{
radb5(ido, l1, td, c, wtable, iw);
}
na=1-na;
}
else
{
if(na==0)
{
radbg(ido, ip, l1, idl1, c, c, c, td, td, wtable, iw);
}
else
{
radbg(ido, ip, l1, idl1, td, td, td, c, c, wtable, iw);
}
if(ido==1) na=1-na;
}
l1=l2;
iw+=(ip-1)*ido;
}
if (na == 1)
for (int i = 0; i < n; i++)
c[i] = td[i];
}
// ******************************************************************** //
// Real-Valued FFT -- General Subroutines.
// ******************************************************************** //
/*---------------------------------------------------------
radfg: Real FFT's forward processing of general factor
--------------------------------------------------------*/
private void radfg(int ido, int ip, int l1, int idl1, double cc[],
double c1[], double c2[], double ch[], double ch2[],
final double wtable[], int offset)
{
int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is, nbd;
double dc2, ai1, ai2, ar1, ar2, ds2, dcp, arg, dsp, ar1h, ar2h;
int iw1 = offset;
arg=TWO_PI / (double)ip;
dcp=Math.cos(arg);
dsp=Math.sin(arg);
ipph=(ip+1)/ 2;
nbd=(ido-1)/ 2;
if(ido !=1)
{
for(ik=0; ik<idl1; ik++) ch2[ik]=c2[ik];
for(j=1; j<ip; j++)
for(k=0; k<l1; k++)
ch[(k+j*l1)*ido]=c1[(k+j*l1)*ido];
if(nbd<=l1)
{
is=-ido;
for(j=1; j<ip; j++)
{
is+=ido;
idij=is-1;
for(i=2; i<ido; i+=2)
{
idij+=2;
for(k=0; k<l1; k++)
{
ch[i-1+(k+j*l1)*ido]=
wtable[idij-1+iw1]*c1[i-1+(k+j*l1)*ido]
+wtable[idij+iw1]*c1[i+(k+j*l1)*ido];
ch[i+(k+j*l1)*ido]=
wtable[idij-1+iw1]*c1[i+(k+j*l1)*ido]
-wtable[idij+iw1]*c1[i-1+(k+j*l1)*ido];
}
}
}
}
else
{
is=-ido;
for(j=1; j<ip; j++)
{
is+=ido;
for(k=0; k<l1; k++)
{
idij=is-1;
for(i=2; i<ido; i+=2)
{
idij+=2;
ch[i-1+(k+j*l1)*ido]=
wtable[idij-1+iw1]*c1[i-1+(k+j*l1)*ido]
+wtable[idij+iw1]*c1[i+(k+j*l1)*ido];
ch[i+(k+j*l1)*ido]=
wtable[idij-1+iw1]*c1[i+(k+j*l1)*ido]
-wtable[idij+iw1]*c1[i-1+(k+j*l1)*ido];
}
}
}
}
if(nbd>=l1)
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
c1[i-1+(k+j*l1)*ido]=ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido];
c1[i-1+(k+jc*l1)*ido]=ch[i+(k+j*l1)*ido]-ch[i+(k+jc*l1)*ido];
c1[i+(k+j*l1)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido];
c1[i+(k+jc*l1)*ido]=ch[i-1+(k+jc*l1)*ido]-ch[i-1+(k+j*l1)*ido];
}
}
}
}
else
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(i=2; i<ido; i+=2)
{
for(k=0; k<l1; k++)
{
c1[i-1+(k+j*l1)*ido]=
ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido];
c1[i-1+(k+jc*l1)*ido]=ch[i+(k+j*l1)*ido]-ch[i+(k+jc*l1)*ido];
c1[i+(k+j*l1)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido];
c1[i+(k+jc*l1)*ido]=ch[i-1+(k+jc*l1)*ido]-ch[i-1+(k+j*l1)*ido];
}
}
}
}
}
else
{
for(ik=0; ik<idl1; ik++) c2[ik]=ch2[ik];
}
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
c1[(k+j*l1)*ido]=ch[(k+j*l1)*ido]+ch[(k+jc*l1)*ido];
c1[(k+jc*l1)*ido]=ch[(k+jc*l1)*ido]-ch[(k+j*l1)*ido];
}
}
ar1=1;
ai1=0;
for(l=1; l<ipph; l++)
{
lc=ip-l;
ar1h=dcp*ar1-dsp*ai1;
ai1=dcp*ai1+dsp*ar1;
ar1=ar1h;
for(ik=0; ik<idl1; ik++)
{
ch2[ik+l*idl1]=c2[ik]+ar1*c2[ik+idl1];
ch2[ik+lc*idl1]=ai1*c2[ik+(ip-1)*idl1];
}
dc2=ar1;
ds2=ai1;
ar2=ar1;
ai2=ai1;
for(j=2; j<ipph; j++)
{
jc=ip-j;
ar2h=dc2*ar2-ds2*ai2;
ai2=dc2*ai2+ds2*ar2;
ar2=ar2h;
for(ik=0; ik<idl1; ik++)
{
ch2[ik+l*idl1]+=ar2*c2[ik+j*idl1];
ch2[ik+lc*idl1]+=ai2*c2[ik+jc*idl1];
}
}
}
for(j=1; j<ipph; j++)
for(ik=0; ik<idl1; ik++)
ch2[ik]+=c2[ik+j*idl1];
if(ido>=l1)
{
for(k=0; k<l1; k++)
{
for(i=0; i<ido; i++)
{
cc[i+k*ip*ido]=ch[i+k*ido];
}
}
}
else
{
for(i=0; i<ido; i++)
{
for(k=0; k<l1; k++)
{
cc[i+k*ip*ido]=ch[i+k*ido];
}
}
}
for(j=1; j<ipph; j++)
{
jc=ip-j;
j2=2*j;
for(k=0; k<l1; k++)
{
cc[ido-1+(j2-1+k*ip)*ido]=ch[(k+j*l1)*ido];
cc[(j2+k*ip)*ido]=ch[(k+jc*l1)*ido];
}
}
if(ido==1) return;
if(nbd>=l1)
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
j2=2*j;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
cc[i-1+(j2+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido];
cc[ic-1+(j2-1+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]-ch[i-1+(k+jc*l1)*ido];
cc[i+(j2+k*ip)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido];
cc[ic+(j2-1+k*ip)*ido]=ch[i+(k+jc*l1)*ido]-ch[i+(k+j*l1)*ido];
}
}
}
}
else
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
j2=2*j;
for(i=2; i<ido; i+=2)
{
ic=ido-i;
for(k=0; k<l1; k++)
{
cc[i-1+(j2+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]+ch[i-1+(k+jc*l1)*ido];
cc[ic-1+(j2-1+k*ip)*ido]=ch[i-1+(k+j*l1)*ido]-ch[i-1+(k+jc*l1)*ido];
cc[i+(j2+k*ip)*ido]=ch[i+(k+j*l1)*ido]+ch[i+(k+jc*l1)*ido];
cc[ic+(j2-1+k*ip)*ido]=ch[i+(k+jc*l1)*ido]-ch[i+(k+j*l1)*ido];
}
}
}
}
}
/*---------------------------------------------------------
radbg: Real FFT's backward processing of general factor
--------------------------------------------------------*/
private void radbg(int ido, int ip, int l1, int idl1, double cc[], double c1[],
double c2[], double ch[], double ch2[], final double wtable[], int offset)
{
int idij, ipph, i, j, k, l, j2, ic, jc, lc, ik, is;
double dc2, ai1, ai2, ar1, ar2, ds2;
int nbd;
double dcp, arg, dsp, ar1h, ar2h;
int iw1 = offset;
arg=TWO_PI / (double)ip;
dcp=Math.cos(arg);
dsp=Math.sin(arg);
nbd=(ido-1)/ 2;
ipph=(ip+1)/ 2;
if(ido>=l1)
{
for(k=0; k<l1; k++)
{
for(i=0; i<ido; i++)
{
ch[i+k*ido]=cc[i+k*ip*ido];
}
}
}
else
{
for(i=0; i<ido; i++)
{
for(k=0; k<l1; k++)
{
ch[i+k*ido]=cc[i+k*ip*ido];
}
}
}
for(j=1; j<ipph; j++)
{
jc=ip-j;
j2=2*j;
for(k=0; k<l1; k++)
{
ch[(k+j*l1)*ido]=cc[ido-1+(j2-1+k*ip)*ido]+cc[ido-1+(j2-1+k*ip)*ido];
ch[(k+jc*l1)*ido]=cc[(j2+k*ip)*ido]+cc[(j2+k*ip)*ido];
}
}
if(ido !=1)
{
if(nbd>=l1)
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
ch[i-1+(k+j*l1)*ido]=cc[i-1+(2*j+k*ip)*ido]+cc[ic-1+(2*j-1+k*ip)*ido];
ch[i-1+(k+jc*l1)*ido]=cc[i-1+(2*j+k*ip)*ido]-cc[ic-1+(2*j-1+k*ip)*ido];
ch[i+(k+j*l1)*ido]=cc[i+(2*j+k*ip)*ido]-cc[ic+(2*j-1+k*ip)*ido];
ch[i+(k+jc*l1)*ido]=cc[i+(2*j+k*ip)*ido]+cc[ic+(2*j-1+k*ip)*ido];
}
}
}
}
else
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(i=2; i<ido; i+=2)
{
ic=ido-i;
for(k=0; k<l1; k++)
{
ch[i-1+(k+j*l1)*ido]=cc[i-1+(2*j+k*ip)*ido]+cc[ic-1+(2*j-1+k*ip)*ido];
ch[i-1+(k+jc*l1)*ido]=cc[i-1+(2*j+k*ip)*ido]-cc[ic-1+(2*j-1+k*ip)*ido];
ch[i+(k+j*l1)*ido]=cc[i+(2*j+k*ip)*ido]-cc[ic+(2*j-1+k*ip)*ido];
ch[i+(k+jc*l1)*ido]=cc[i+(2*j+k*ip)*ido]+cc[ic+(2*j-1+k*ip)*ido];
}
}
}
}
}
ar1=1;
ai1=0;
for(l=1; l<ipph; l++)
{
lc=ip-l;
ar1h=dcp*ar1-dsp*ai1;
ai1=dcp*ai1+dsp*ar1;
ar1=ar1h;
for(ik=0; ik<idl1; ik++)
{
c2[ik+l*idl1]=ch2[ik]+ar1*ch2[ik+idl1];
c2[ik+lc*idl1]=ai1*ch2[ik+(ip-1)*idl1];
}
dc2=ar1;
ds2=ai1;
ar2=ar1;
ai2=ai1;
for(j=2; j<ipph; j++)
{
jc=ip-j;
ar2h=dc2*ar2-ds2*ai2;
ai2=dc2*ai2+ds2*ar2;
ar2=ar2h;
for(ik=0; ik<idl1; ik++)
{
c2[ik+l*idl1]+=ar2*ch2[ik+j*idl1];
c2[ik+lc*idl1]+=ai2*ch2[ik+jc*idl1];
}
}
}
for(j=1; j<ipph; j++)
{
for(ik=0; ik<idl1; ik++)
{
ch2[ik]+=ch2[ik+j*idl1];
}
}
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
ch[(k+j*l1)*ido]=c1[(k+j*l1)*ido]-c1[(k+jc*l1)*ido];
ch[(k+jc*l1)*ido]=c1[(k+j*l1)*ido]+c1[(k+jc*l1)*ido];
}
}
if(ido==1) return;
if(nbd>=l1)
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ch[i-1+(k+j*l1)*ido]=c1[i-1+(k+j*l1)*ido]-c1[i+(k+jc*l1)*ido];
ch[i-1+(k+jc*l1)*ido]=c1[i-1+(k+j*l1)*ido]+c1[i+(k+jc*l1)*ido];
ch[i+(k+j*l1)*ido]=c1[i+(k+j*l1)*ido]+c1[i-1+(k+jc*l1)*ido];
ch[i+(k+jc*l1)*ido]=c1[i+(k+j*l1)*ido]-c1[i-1+(k+jc*l1)*ido];
}
}
}
}
else
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(i=2; i<ido; i+=2)
{
for(k=0; k<l1; k++)
{
ch[i-1+(k+j*l1)*ido]=c1[i-1+(k+j*l1)*ido]-c1[i+(k+jc*l1)*ido];
ch[i-1+(k+jc*l1)*ido]=c1[i-1+(k+j*l1)*ido]+c1[i+(k+jc*l1)*ido];
ch[i+(k+j*l1)*ido]=c1[i+(k+j*l1)*ido]+c1[i-1+(k+jc*l1)*ido];
ch[i+(k+jc*l1)*ido]=c1[i+(k+j*l1)*ido]-c1[i-1+(k+jc*l1)*ido];
}
}
}
}
for(ik=0; ik<idl1; ik++) c2[ik]=ch2[ik];
for(j=1; j<ip; j++)
for(k=0; k<l1; k++)
c1[(k+j*l1)*ido]=ch[(k+j*l1)*ido];
if(nbd<=l1)
{
is=-ido;
for(j=1; j<ip; j++)
{
is+=ido;
idij=is-1;
for(i=2; i<ido; i+=2)
{
idij+=2;
for(k=0; k<l1; k++)
{
c1[i-1+(k+j*l1)*ido] = wtable[idij-1+iw1]*ch[i-1+(k+j*l1)*ido]
-wtable[idij+iw1]*ch[i+(k+j*l1)*ido];
c1[i+(k+j*l1)*ido] = wtable[idij-1+iw1]*ch[i+(k+j*l1)*ido]
+wtable[idij+iw1]*ch[i-1+(k+j*l1)*ido];
}
}
}
}
else
{
is=-ido;
for(j=1; j<ip; j++)
{
is+=ido;
for(k=0; k<l1; k++)
{
idij=is-1;
for(i=2; i<ido; i+=2)
{
idij+=2;
c1[i-1+(k+j*l1)*ido] = wtable[idij-1+iw1]*ch[i-1+(k+j*l1)*ido]
-wtable[idij+iw1]*ch[i+(k+j*l1)*ido];
c1[i+(k+j*l1)*ido] = wtable[idij-1+iw1]*ch[i+(k+j*l1)*ido]
+wtable[idij+iw1]*ch[i-1+(k+j*l1)*ido];
}
}
}
}
}
// ******************************************************************** //
// Real-Valued FFT -- Factor-Specific Optimized Subroutines.
// ******************************************************************** //
/*-------------------------------------------------
radf2: Real FFT's forward processing of factor 2
-------------------------------------------------*/
private void radf2(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
int i, k, ic;
double ti2, tr2;
int iw1;
iw1 = offset;
for(k=0; k<l1; k++)
{
ch[2*k*ido]=cc[k*ido]+cc[(k+l1)*ido];
ch[(2*k+1)*ido+ido-1]=cc[k*ido]-cc[(k+l1)*ido];
}
if(ido<2) return;
if(ido !=2)
{
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
tr2 = wtable[i-2+iw1]*cc[i-1+(k+l1)*ido]
+wtable[i-1+iw1]*cc[i+(k+l1)*ido];
ti2 = wtable[i-2+iw1]*cc[i+(k+l1)*ido]
-wtable[i-1+iw1]*cc[i-1+(k+l1)*ido];
ch[i+2*k*ido]=cc[i+k*ido]+ti2;
ch[ic+(2*k+1)*ido]=ti2-cc[i+k*ido];
ch[i-1+2*k*ido]=cc[i-1+k*ido]+tr2;
ch[ic-1+(2*k+1)*ido]=cc[i-1+k*ido]-tr2;
}
}
if(ido%2==1)return;
}
for(k=0; k<l1; k++)
{
ch[(2*k+1)*ido]=-cc[ido-1+(k+l1)*ido];
ch[ido-1+2*k*ido]=cc[ido-1+k*ido];
}
}
/*-------------------------------------------------
radb2: Real FFT's backward processing of factor 2
-------------------------------------------------*/
private void radb2(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
int i, k, ic;
double ti2, tr2;
int iw1 = offset;
for(k=0; k<l1; k++)
{
ch[k*ido]=cc[2*k*ido]+cc[ido-1+(2*k+1)*ido];
ch[(k+l1)*ido]=cc[2*k*ido]-cc[ido-1+(2*k+1)*ido];
}
if(ido<2) return;
if(ido !=2)
{
for(k=0; k<l1;++k)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
ch[i-1+k*ido]=cc[i-1+2*k*ido]+cc[ic-1+(2*k+1)*ido];
tr2=cc[i-1+2*k*ido]-cc[ic-1+(2*k+1)*ido];
ch[i+k*ido]=cc[i+2*k*ido]-cc[ic+(2*k+1)*ido];
ti2=cc[i+(2*k)*ido]+cc[ic+(2*k+1)*ido];
ch[i-1+(k+l1)*ido]=wtable[i-2+iw1]*tr2-wtable[i-1+iw1]*ti2;
ch[i+(k+l1)*ido]=wtable[i-2+iw1]*ti2+wtable[i-1+iw1]*tr2;
}
}
if(ido%2==1) return;
}
for(k=0; k<l1; k++)
{
ch[ido-1+k*ido]=2*cc[ido-1+2*k*ido];
ch[ido-1+(k+l1)*ido]=-2*cc[(2*k+1)*ido];
}
}
/*-------------------------------------------------
radf3: Real FFT's forward processing of factor 3
-------------------------------------------------*/
private void radf3(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
int i, k, ic;
double ci2, di2, di3, cr2, dr2, dr3, ti2, ti3, tr2, tr3;
int iw1, iw2;
iw1 = offset;
iw2 = iw1 + ido;
for(k=0; k<l1; k++)
{
cr2=cc[(k+l1)*ido]+cc[(k+2*l1)*ido];
ch[3*k*ido]=cc[k*ido]+cr2;
ch[(3*k+2)*ido]=TAU_I*(cc[(k+l1*2)*ido]-cc[(k+l1)*ido]);
ch[ido-1+(3*k+1)*ido]=cc[k*ido]+TAU_R*cr2;
}
if(ido==1) return;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
dr2 = wtable[i-2+iw1]*cc[i-1+(k+l1)*ido]
+wtable[i-1+iw1]*cc[i+(k+l1)*ido];
di2 = wtable[i-2+iw1]*cc[i+(k+l1)*ido]
-wtable[i-1+iw1]*cc[i-1+(k+l1)*ido];
dr3 = wtable[i-2+iw2]*cc[i-1+(k+l1*2)*ido]
+wtable[i-1+iw2]*cc[i+(k+l1*2)*ido];
di3 = wtable[i-2+iw2]*cc[i+(k+l1*2)*ido]
-wtable[i-1+iw2]*cc[i-1+(k+l1*2)*ido];
cr2 = dr2+dr3;
ci2 = di2+di3;
ch[i-1+3*k*ido]=cc[i-1+k*ido]+cr2;
ch[i+3*k*ido]=cc[i+k*ido]+ci2;
tr2=cc[i-1+k*ido]+TAU_R*cr2;
ti2=cc[i+k*ido]+TAU_R*ci2;
tr3=TAU_I*(di2-di3);
ti3=TAU_I*(dr3-dr2);
ch[i-1+(3*k+2)*ido]=tr2+tr3;
ch[ic-1+(3*k+1)*ido]=tr2-tr3;
ch[i+(3*k+2)*ido]=ti2+ti3;
ch[ic+(3*k+1)*ido]=ti3-ti2;
}
}
}
/*-------------------------------------------------
radb3: Real FFT's backward processing of factor 3
-------------------------------------------------*/
private void radb3(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
int i, k, ic;
double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
int iw1, iw2;
iw1 = offset;
iw2 = iw1 + ido;
for(k=0; k<l1; k++)
{
tr2=2*cc[ido-1+(3*k+1)*ido];
cr2=cc[3*k*ido]+TAU_R*tr2;
ch[k*ido]=cc[3*k*ido]+tr2;
ci3=2*TAU_I*cc[(3*k+2)*ido];
ch[(k+l1)*ido]=cr2-ci3;
ch[(k+2*l1)*ido]=cr2+ci3;
}
if(ido==1) return;
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
tr2=cc[i-1+(3*k+2)*ido]+cc[ic-1+(3*k+1)*ido];
cr2=cc[i-1+3*k*ido]+TAU_R*tr2;
ch[i-1+k*ido]=cc[i-1+3*k*ido]+tr2;
ti2=cc[i+(3*k+2)*ido]-cc[ic+(3*k+1)*ido];
ci2=cc[i+3*k*ido]+TAU_R*ti2;
ch[i+k*ido]=cc[i+3*k*ido]+ti2;
cr3=TAU_I*(cc[i-1+(3*k+2)*ido]-cc[ic-1+(3*k+1)*ido]);
ci3=TAU_I*(cc[i+(3*k+2)*ido]+cc[ic+(3*k+1)*ido]);
dr2=cr2-ci3;
dr3=cr2+ci3;
di2=ci2+cr3;
di3=ci2-cr3;
ch[i-1+(k+l1)*ido] = wtable[i-2+iw1]*dr2
-wtable[i-1+iw1]*di2;
ch[i+(k+l1)*ido] = wtable[i-2+iw1]*di2
+wtable[i-1+iw1]*dr2;
ch[i-1+(k+2*l1)*ido] = wtable[i-2+iw2]*dr3
-wtable[i-1+iw2]*di3;
ch[i+(k+2*l1)*ido] = wtable[i-2+iw2]*di3
+wtable[i-1+iw2]*dr3;
}
}
}
/*-------------------------------------------------
radf4: Real FFT's forward processing of factor 4
-------------------------------------------------*/
private void radf4(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
final double hsqt2=0.7071067811865475D;
int i, k, ic;
double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4;
int iw1, iw2, iw3;
iw1 = offset;
iw2 = offset + ido;
iw3 = iw2 + ido;
for(k=0; k<l1; k++)
{
tr1=cc[(k+l1)*ido]+cc[(k+3*l1)*ido];
tr2=cc[k*ido]+cc[(k+2*l1)*ido];
ch[4*k*ido]=tr1+tr2;
ch[ido-1+(4*k+3)*ido]=tr2-tr1;
ch[ido-1+(4*k+1)*ido]=cc[k*ido]-cc[(k+2*l1)*ido];
ch[(4*k+2)*ido]=cc[(k+3*l1)*ido]-cc[(k+l1)*ido];
}
if(ido<2) return;
if(ido !=2)
{
for(k=0; k<l1; k++)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
cr2 = wtable[i-2+iw1]*cc[i-1+(k+l1)*ido]
+wtable[i-1+iw1]*cc[i+(k+l1)*ido];
ci2 = wtable[i-2+iw1]*cc[i+(k+l1)*ido]
-wtable[i-1+iw1]*cc[i-1+(k+l1)*ido];
cr3 = wtable[i-2+iw2]*cc[i-1+(k+2*l1)*ido]
+wtable[i-1+iw2]*cc[i+(k+2*l1)*ido];
ci3 = wtable[i-2+iw2]*cc[i+(k+2*l1)*ido]
-wtable[i-1+iw2]*cc[i-1+(k+2*l1)*ido];
cr4 = wtable[i-2+iw3]*cc[i-1+(k+3*l1)*ido]
+wtable[i-1+iw3]*cc[i+(k+3*l1)*ido];
ci4 = wtable[i-2+iw3]*cc[i+(k+3*l1)*ido]
-wtable[i-1+iw3]*cc[i-1+(k+3*l1)*ido];
tr1=cr2+cr4;
tr4=cr4-cr2;
ti1=ci2+ci4;
ti4=ci2-ci4;
ti2=cc[i+k*ido]+ci3;
ti3=cc[i+k*ido]-ci3;
tr2=cc[i-1+k*ido]+cr3;
tr3=cc[i-1+k*ido]-cr3;
ch[i-1+4*k*ido]=tr1+tr2;
ch[ic-1+(4*k+3)*ido]=tr2-tr1;
ch[i+4*k*ido]=ti1+ti2;
ch[ic+(4*k+3)*ido]=ti1-ti2;
ch[i-1+(4*k+2)*ido]=ti4+tr3;
ch[ic-1+(4*k+1)*ido]=tr3-ti4;
ch[i+(4*k+2)*ido]=tr4+ti3;
ch[ic+(4*k+1)*ido]=tr4-ti3;
}
}
if(ido%2==1) return;
}
for(k=0; k<l1; k++)
{
ti1=-hsqt2*(cc[ido-1+(k+l1)*ido]+cc[ido-1+(k+3*l1)*ido]);
tr1=hsqt2*(cc[ido-1+(k+l1)*ido]-cc[ido-1+(k+3*l1)*ido]);
ch[ido-1+4*k*ido]=tr1+cc[ido-1+k*ido];
ch[ido-1+(4*k+2)*ido]=cc[ido-1+k*ido]-tr1;
ch[(4*k+1)*ido]=ti1-cc[ido-1+(k+2*l1)*ido];
ch[(4*k+3)*ido]=ti1+cc[ido-1+(k+2*l1)*ido];
}
}
/*-------------------------------------------------
radb4: Real FFT's backward processing of factor 4
-------------------------------------------------*/
private void radb4(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
int i, k, ic;
double ci2, ci3, ci4, cr2, cr3, cr4;
double ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4;
int iw1, iw2, iw3;
iw1 = offset;
iw2 = iw1 + ido;
iw3 = iw2 + ido;
for(k=0; k<l1; k++)
{
tr1=cc[4*k*ido]-cc[ido-1+(4*k+3)*ido];
tr2=cc[4*k*ido]+cc[ido-1+(4*k+3)*ido];
tr3=cc[ido-1+(4*k+1)*ido]+cc[ido-1+(4*k+1)*ido];
tr4=cc[(4*k+2)*ido]+cc[(4*k+2)*ido];
ch[k*ido]=tr2+tr3;
ch[(k+l1)*ido]=tr1-tr4;
ch[(k+2*l1)*ido]=tr2-tr3;
ch[(k+3*l1)*ido]=tr1+tr4;
}
if(ido<2) return;
if(ido !=2)
{
for(k=0; k<l1;++k)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
ti1=cc[i+4*k*ido]+cc[ic+(4*k+3)*ido];
ti2=cc[i+4*k*ido]-cc[ic+(4*k+3)*ido];
ti3=cc[i+(4*k+2)*ido]-cc[ic+(4*k+1)*ido];
tr4=cc[i+(4*k+2)*ido]+cc[ic+(4*k+1)*ido];
tr1=cc[i-1+4*k*ido]-cc[ic-1+(4*k+3)*ido];
tr2=cc[i-1+4*k*ido]+cc[ic-1+(4*k+3)*ido];
ti4=cc[i-1+(4*k+2)*ido]-cc[ic-1+(4*k+1)*ido];
tr3=cc[i-1+(4*k+2)*ido]+cc[ic-1+(4*k+1)*ido];
ch[i-1+k*ido]=tr2+tr3;
cr3=tr2-tr3;
ch[i+k*ido]=ti2+ti3;
ci3=ti2-ti3;
cr2=tr1-tr4;
cr4=tr1+tr4;
ci2=ti1+ti4;
ci4=ti1-ti4;
ch[i-1+(k+l1)*ido] = wtable[i-2+iw1]*cr2
-wtable[i-1+iw1]*ci2;
ch[i+(k+l1)*ido] = wtable[i-2+iw1]*ci2
+wtable[i-1+iw1]*cr2;
ch[i-1+(k+2*l1)*ido] = wtable[i-2+iw2]*cr3
-wtable[i-1+iw2]*ci3;
ch[i+(k+2*l1)*ido] = wtable[i-2+iw2]*ci3
+wtable[i-1+iw2]*cr3;
ch[i-1+(k+3*l1)*ido] = wtable[i-2+iw3]*cr4
-wtable[i-1+iw3]*ci4;
ch[i+(k+3*l1)*ido] = wtable[i-2+iw3]*ci4
+wtable[i-1+iw3]*cr4;
}
}
if(ido%2==1) return;
}
for(k=0; k<l1; k++)
{
ti1=cc[(4*k+1)*ido]+cc[(4*k+3)*ido];
ti2=cc[(4*k+3)*ido]-cc[(4*k+1)*ido];
tr1=cc[ido-1+4*k*ido]-cc[ido-1+(4*k+2)*ido];
tr2=cc[ido-1+4*k*ido]+cc[ido-1+(4*k+2)*ido];
ch[ido-1+k*ido]=tr2+tr2;
ch[ido-1+(k+l1)*ido]=SQRT_2*(tr1-ti1);
ch[ido-1+(k+2*l1)*ido]=ti2+ti2;
ch[ido-1+(k+3*l1)*ido]=-SQRT_2*(tr1+ti1);
}
}
/*-------------------------------------------------
radf5: Real FFT's forward processing of factor 5
-------------------------------------------------*/
private void radf5(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
final double tr11=0.309016994374947D;
final double ti11=0.951056516295154D;
final double tr12=-0.809016994374947D;
final double ti12=0.587785252292473D;
int i, k, ic;
double ci2, di2, ci4, ci5, di3, di4, di5, ci3, cr2, cr3, dr2, dr3,
dr4, dr5, cr5, cr4, ti2, ti3, ti5, ti4, tr2, tr3, tr4, tr5;
int iw1, iw2, iw3, iw4;
iw1 = offset;
iw2 = iw1 + ido;
iw3 = iw2 + ido;
iw4 = iw3 + ido;
for(k=0; k<l1; k++)
{
cr2=cc[(k+4*l1)*ido]+cc[(k+l1)*ido];
ci5=cc[(k+4*l1)*ido]-cc[(k+l1)*ido];
cr3=cc[(k+3*l1)*ido]+cc[(k+2*l1)*ido];
ci4=cc[(k+3*l1)*ido]-cc[(k+2*l1)*ido];
ch[5*k*ido]=cc[k*ido]+cr2+cr3;
ch[ido-1+(5*k+1)*ido]=cc[k*ido]+tr11*cr2+tr12*cr3;
ch[(5*k+2)*ido]=ti11*ci5+ti12*ci4;
ch[ido-1+(5*k+3)*ido]=cc[k*ido]+tr12*cr2+tr11*cr3;
ch[(5*k+4)*ido]=ti12*ci5-ti11*ci4;
}
if(ido==1) return;
for(k=0; k<l1;++k)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
dr2 = wtable[i-2+iw1]*cc[i-1+(k+l1)*ido]
+wtable[i-1+iw1]*cc[i+(k+l1)*ido];
di2 = wtable[i-2+iw1]*cc[i+(k+l1)*ido]
-wtable[i-1+iw1]*cc[i-1+(k+l1)*ido];
dr3 = wtable[i-2+iw2]*cc[i-1+(k+2*l1)*ido]
+wtable[i-1+iw2]*cc[i+(k+2*l1)*ido];
di3 = wtable[i-2+iw2]*cc[i+(k+2*l1)*ido]
-wtable[i-1+iw2]*cc[i-1+(k+2*l1)*ido];
dr4 = wtable[i-2+iw3]*cc[i-1+(k+3*l1)*ido]
+wtable[i-1+iw3]*cc[i+(k+3*l1)*ido];
di4 = wtable[i-2+iw3]*cc[i+(k+3*l1)*ido]
-wtable[i-1+iw3]*cc[i-1+(k+3*l1)*ido];
dr5 = wtable[i-2+iw4]*cc[i-1+(k+4*l1)*ido]
+wtable[i-1+iw4]*cc[i+(k+4*l1)*ido];
di5 = wtable[i-2+iw4]*cc[i+(k+4*l1)*ido]
-wtable[i-1+iw4]*cc[i-1+(k+4*l1)*ido];
cr2=dr2+dr5;
ci5=dr5-dr2;
cr5=di2-di5;
ci2=di2+di5;
cr3=dr3+dr4;
ci4=dr4-dr3;
cr4=di3-di4;
ci3=di3+di4;
ch[i-1+5*k*ido]=cc[i-1+k*ido]+cr2+cr3;
ch[i+5*k*ido]=cc[i+k*ido]+ci2+ci3;
tr2=cc[i-1+k*ido]+tr11*cr2+tr12*cr3;
ti2=cc[i+k*ido]+tr11*ci2+tr12*ci3;
tr3=cc[i-1+k*ido]+tr12*cr2+tr11*cr3;
ti3=cc[i+k*ido]+tr12*ci2+tr11*ci3;
tr5=ti11*cr5+ti12*cr4;
ti5=ti11*ci5+ti12*ci4;
tr4=ti12*cr5-ti11*cr4;
ti4=ti12*ci5-ti11*ci4;
ch[i-1+(5*k+2)*ido]=tr2+tr5;
ch[ic-1+(5*k+1)*ido]=tr2-tr5;
ch[i+(5*k+2)*ido]=ti2+ti5;
ch[ic+(5*k+1)*ido]=ti5-ti2;
ch[i-1+(5*k+4)*ido]=tr3+tr4;
ch[ic-1+(5*k+3)*ido]=tr3-tr4;
ch[i+(5*k+4)*ido]=ti3+ti4;
ch[ic+(5*k+3)*ido]=ti4-ti3;
}
}
}
/*-------------------------------------------------
radb5: Real FFT's backward processing of factor 5
-------------------------------------------------*/
private void radb5(int ido, int l1, final double cc[], double ch[],
final double wtable[], int offset)
{
final double tr11=0.309016994374947D;
final double ti11=0.951056516295154D;
final double tr12=-0.809016994374947D;
final double ti12=0.587785252292473D;
int i, k, ic;
double ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4,
ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5;
int iw1, iw2, iw3, iw4;
iw1 = offset;
iw2 = iw1 + ido;
iw3 = iw2 + ido;
iw4 = iw3 + ido;
for(k=0; k<l1; k++)
{
ti5=2*cc[(5*k+2)*ido];
ti4=2*cc[(5*k+4)*ido];
tr2=2*cc[ido-1+(5*k+1)*ido];
tr3=2*cc[ido-1+(5*k+3)*ido];
ch[k*ido]=cc[5*k*ido]+tr2+tr3;
cr2=cc[5*k*ido]+tr11*tr2+tr12*tr3;
cr3=cc[5*k*ido]+tr12*tr2+tr11*tr3;
ci5=ti11*ti5+ti12*ti4;
ci4=ti12*ti5-ti11*ti4;
ch[(k+l1)*ido]=cr2-ci5;
ch[(k+2*l1)*ido]=cr3-ci4;
ch[(k+3*l1)*ido]=cr3+ci4;
ch[(k+4*l1)*ido]=cr2+ci5;
}
if(ido==1) return;
for(k=0; k<l1;++k)
{
for(i=2; i<ido; i+=2)
{
ic=ido-i;
ti5=cc[i+(5*k+2)*ido]+cc[ic+(5*k+1)*ido];
ti2=cc[i+(5*k+2)*ido]-cc[ic+(5*k+1)*ido];
ti4=cc[i+(5*k+4)*ido]+cc[ic+(5*k+3)*ido];
ti3=cc[i+(5*k+4)*ido]-cc[ic+(5*k+3)*ido];
tr5=cc[i-1+(5*k+2)*ido]-cc[ic-1+(5*k+1)*ido];
tr2=cc[i-1+(5*k+2)*ido]+cc[ic-1+(5*k+1)*ido];
tr4=cc[i-1+(5*k+4)*ido]-cc[ic-1+(5*k+3)*ido];
tr3=cc[i-1+(5*k+4)*ido]+cc[ic-1+(5*k+3)*ido];
ch[i-1+k*ido]=cc[i-1+5*k*ido]+tr2+tr3;
ch[i+k*ido]=cc[i+5*k*ido]+ti2+ti3;
cr2=cc[i-1+5*k*ido]+tr11*tr2+tr12*tr3;
ci2=cc[i+5*k*ido]+tr11*ti2+tr12*ti3;
cr3=cc[i-1+5*k*ido]+tr12*tr2+tr11*tr3;
ci3=cc[i+5*k*ido]+tr12*ti2+tr11*ti3;
cr5=ti11*tr5+ti12*tr4;
ci5=ti11*ti5+ti12*ti4;
cr4=ti12*tr5-ti11*tr4;
ci4=ti12*ti5-ti11*ti4;
dr3=cr3-ci4;
dr4=cr3+ci4;
di3=ci3+cr4;
di4=ci3-cr4;
dr5=cr2+ci5;
dr2=cr2-ci5;
di5=ci2-cr5;
di2=ci2+cr5;
ch[i-1+(k+l1)*ido] = wtable[i-2+iw1]*dr2
-wtable[i-1+iw1]*di2;
ch[i+(k+l1)*ido] = wtable[i-2+iw1]*di2
+wtable[i-1+iw1]*dr2;
ch[i-1+(k+2*l1)*ido] = wtable[i-2+iw2]*dr3
-wtable[i-1+iw2]*di3;
ch[i+(k+2*l1)*ido] = wtable[i-2+iw2]*di3
+wtable[i-1+iw2]*dr3;
ch[i-1+(k+3*l1)*ido] = wtable[i-2+iw3]*dr4
-wtable[i-1+iw3]*di4;
ch[i+(k+3*l1)*ido] = wtable[i-2+iw3]*di4
+wtable[i-1+iw3]*dr4;
ch[i-1+(k+4*l1)*ido] = wtable[i-2+iw4]*dr5
-wtable[i-1+iw4]*di5;
ch[i+(k+4*l1)*ido] = wtable[i-2+iw4]*di5
+wtable[i-1+iw4]*dr5;
}
}
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
private static final int[] NTRY_H = { 4, 2, 3, 5 };
private static final double TWO_PI = 2.0 * Math.PI;
private static final double SQRT_2 = 1.414213562373095;
private static final double TAU_R = -0.5;
private static final double TAU_I = 0.866025403784439;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Working data array for FFT.
private double[] tempData = null;
}
| 44,066 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
ComplexDoubleFFT_Mixed.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/ComplexDoubleFFT_Mixed.java | package ca.uol.aig.fftpack;
/**
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
class ComplexDoubleFFT_Mixed
{
/*----------------------------------------------------------------------
passf2: Complex FFT's forward/backward processing of factor 2;
isign is +1 for backward and -1 for forward transforms
----------------------------------------------------------------------*/
void passf2(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset, int isign)
/*isign==+1 for backward transform*/
{
int i, k, ah, ac;
double ti2, tr2;
int iw1;
iw1 = offset;
if(ido<=2)
{
for(k=0; k<l1; k++)
{
ah=k*ido;
ac=2*k*ido;
ch[ah]=cc[ac]+cc[ac+ido];
ch[ah+ido*l1]=cc[ac]-cc[ac+ido];
ch[ah+1]=cc[ac+1]+cc[ac+ido+1];
ch[ah+ido*l1+1]=cc[ac+1]-cc[ac+ido+1];
}
}
else
{
for(k=0; k<l1; k++)
{
for(i=0; i<ido-1; i+=2)
{
ah=i+k*ido;
ac=i+2*k*ido;
ch[ah]=cc[ac]+cc[ac+ido];
tr2=cc[ac]-cc[ac+ido];
ch[ah+1]=cc[ac+1]+cc[ac+1+ido];
ti2=cc[ac+1]-cc[ac+1+ido];
ch[ah+l1*ido+1]=wtable[i+iw1]*ti2+isign*wtable[i+1+iw1]*tr2;
ch[ah+l1*ido]=wtable[i+iw1]*tr2-isign*wtable[i+1+iw1]*ti2;
}
}
}
}
/*----------------------------------------------------------------------
passf3: Complex FFT's forward/backward processing of factor 3;
isign is +1 for backward and -1 for forward transforms
----------------------------------------------------------------------*/
void passf3(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset, int isign)
{
final double taur=-0.5;
final double taui=0.866025403784439;
int i, k, ac, ah;
double ci2, ci3, di2, di3, cr2, cr3, dr2, dr3, ti2, tr2;
int iw1, iw2;
iw1 = offset;
iw2 = iw1 + ido;
if(ido==2)
{
for(k=1; k<=l1; k++)
{
ac=(3*k-2)*ido;
tr2=cc[ac]+cc[ac+ido];
cr2=cc[ac-ido]+taur*tr2;
ah=(k-1)*ido;
ch[ah]=cc[ac-ido]+tr2;
ti2=cc[ac+1]+cc[ac+ido+1];
ci2=cc[ac-ido+1]+taur*ti2;
ch[ah+1]=cc[ac-ido+1]+ti2;
cr3=isign*taui*(cc[ac]-cc[ac+ido]);
ci3=isign*taui*(cc[ac+1]-cc[ac+ido+1]);
ch[ah+l1*ido]=cr2-ci3;
ch[ah+2*l1*ido]=cr2+ci3;
ch[ah+l1*ido+1]=ci2+cr3;
ch[ah+2*l1*ido+1]=ci2-cr3;
}
}
else
{
for(k=1; k<=l1; k++)
{
for(i=0; i<ido-1; i+=2)
{
ac=i+(3*k-2)*ido;
tr2=cc[ac]+cc[ac+ido];
cr2=cc[ac-ido]+taur*tr2;
ah=i+(k-1)*ido;
ch[ah]=cc[ac-ido]+tr2;
ti2=cc[ac+1]+cc[ac+ido+1];
ci2=cc[ac-ido+1]+taur*ti2;
ch[ah+1]=cc[ac-ido+1]+ti2;
cr3=isign*taui*(cc[ac]-cc[ac+ido]);
ci3=isign*taui*(cc[ac+1]-cc[ac+ido+1]);
dr2=cr2-ci3;
dr3=cr2+ci3;
di2=ci2+cr3;
di3=ci2-cr3;
ch[ah+l1*ido+1]=wtable[i+iw1]*di2+isign*wtable[i+1+iw1]*dr2;
ch[ah+l1*ido]=wtable[i+iw1]*dr2-isign*wtable[i+1+iw1]*di2;
ch[ah+2*l1*ido+1]=wtable[i+iw2]*di3+isign*wtable[i+1+iw2]*dr3;
ch[ah+2*l1*ido]=wtable[i+iw2]*dr3-isign*wtable[i+1+iw2]*di3;
}
}
}
}
/*----------------------------------------------------------------------
passf4: Complex FFT's forward/backward processing of factor 4;
isign is +1 for backward and -1 for forward transforms
----------------------------------------------------------------------*/
void passf4(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset, int isign)
{
int i, k, ac, ah;
double ci2, ci3, ci4, cr2, cr3, cr4, ti1, ti2, ti3, ti4, tr1, tr2, tr3, tr4;
int iw1, iw2, iw3;
iw1 = offset;
iw2 = iw1 + ido;
iw3 = iw2 + ido;
if(ido==2)
{
for(k=0; k<l1; k++)
{
ac=4*k*ido+1;
ti1=cc[ac]-cc[ac+2*ido];
ti2=cc[ac]+cc[ac+2*ido];
tr4=cc[ac+3*ido]-cc[ac+ido];
ti3=cc[ac+ido]+cc[ac+3*ido];
tr1=cc[ac-1]-cc[ac+2*ido-1];
tr2=cc[ac-1]+cc[ac+2*ido-1];
ti4=cc[ac+ido-1]-cc[ac+3*ido-1];
tr3=cc[ac+ido-1]+cc[ac+3*ido-1];
ah=k*ido;
ch[ah]=tr2+tr3;
ch[ah+2*l1*ido]=tr2-tr3;
ch[ah+1]=ti2+ti3;
ch[ah+2*l1*ido+1]=ti2-ti3;
ch[ah+l1*ido]=tr1+isign*tr4;
ch[ah+3*l1*ido]=tr1-isign*tr4;
ch[ah+l1*ido+1]=ti1+isign*ti4;
ch[ah+3*l1*ido+1]=ti1-isign*ti4;
}
}
else
{
for(k=0; k<l1; k++)
{
for(i=0; i<ido-1; i+=2)
{
ac=i+1+4*k*ido;
ti1=cc[ac]-cc[ac+2*ido];
ti2=cc[ac]+cc[ac+2*ido];
ti3=cc[ac+ido]+cc[ac+3*ido];
tr4=cc[ac+3*ido]-cc[ac+ido];
tr1=cc[ac-1]-cc[ac+2*ido-1];
tr2=cc[ac-1]+cc[ac+2*ido-1];
ti4=cc[ac+ido-1]-cc[ac+3*ido-1];
tr3=cc[ac+ido-1]+cc[ac+3*ido-1];
ah=i+k*ido;
ch[ah]=tr2+tr3;
cr3=tr2-tr3;
ch[ah+1]=ti2+ti3;
ci3=ti2-ti3;
cr2=tr1+isign*tr4;
cr4=tr1-isign*tr4;
ci2=ti1+isign*ti4;
ci4=ti1-isign*ti4;
ch[ah+l1*ido]=wtable[i+iw1]*cr2-isign*wtable[i+1+iw1]*ci2;
ch[ah+l1*ido+1]=wtable[i+iw1]*ci2+isign*wtable[i+1+iw1]*cr2;
ch[ah+2*l1*ido]=wtable[i+iw2]*cr3-isign*wtable[i+1+iw2]*ci3;
ch[ah+2*l1*ido+1]=wtable[i+iw2]*ci3+isign*wtable[i+1+iw2]*cr3;
ch[ah+3*l1*ido]=wtable[i+iw3]*cr4-isign*wtable[i+1+iw3]*ci4;
ch[ah+3*l1*ido+1]=wtable[i+iw3]*ci4+isign*wtable[i+1+iw3]*cr4;
}
}
}
}
/*----------------------------------------------------------------------
passf5: Complex FFT's forward/backward processing of factor 5;
isign is +1 for backward and -1 for forward transforms
----------------------------------------------------------------------*/
void passf5(int ido, int l1, final double cc[], double ch[], final double wtable[], int offset, int isign)
/*isign==-1 for forward transform and+1 for backward transform*/
{
final double tr11=0.309016994374947;
final double ti11=0.951056516295154;
final double tr12=-0.809016994374947;
final double ti12=0.587785252292473;
int i, k, ac, ah;
double ci2, ci3, ci4, ci5, di3, di4, di5, di2, cr2, cr3, cr5, cr4,
ti2, ti3, ti4, ti5, dr3, dr4, dr5, dr2, tr2, tr3, tr4, tr5;
int iw1, iw2, iw3, iw4;
iw1 = offset;
iw2 = iw1 + ido;
iw3 = iw2 + ido;
iw4 = iw3 + ido;
if(ido==2)
{
for(k=1; k<=l1;++k)
{
ac=(5*k-4)*ido+1;
ti5=cc[ac]-cc[ac+3*ido];
ti2=cc[ac]+cc[ac+3*ido];
ti4=cc[ac+ido]-cc[ac+2*ido];
ti3=cc[ac+ido]+cc[ac+2*ido];
tr5=cc[ac-1]-cc[ac+3*ido-1];
tr2=cc[ac-1]+cc[ac+3*ido-1];
tr4=cc[ac+ido-1]-cc[ac+2*ido-1];
tr3=cc[ac+ido-1]+cc[ac+2*ido-1];
ah=(k-1)*ido;
ch[ah]=cc[ac-ido-1]+tr2+tr3;
ch[ah+1]=cc[ac-ido]+ti2+ti3;
cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3;
ci2=cc[ac-ido]+tr11*ti2+tr12*ti3;
cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3;
ci3=cc[ac-ido]+tr12*ti2+tr11*ti3;
cr5=isign*(ti11*tr5+ti12*tr4);
ci5=isign*(ti11*ti5+ti12*ti4);
cr4=isign*(ti12*tr5-ti11*tr4);
ci4=isign*(ti12*ti5-ti11*ti4);
ch[ah+l1*ido]=cr2-ci5;
ch[ah+4*l1*ido]=cr2+ci5;
ch[ah+l1*ido+1]=ci2+cr5;
ch[ah+2*l1*ido+1]=ci3+cr4;
ch[ah+2*l1*ido]=cr3-ci4;
ch[ah+3*l1*ido]=cr3+ci4;
ch[ah+3*l1*ido+1]=ci3-cr4;
ch[ah+4*l1*ido+1]=ci2-cr5;
}
}
else
{
for(k=1; k<=l1; k++)
{
for(i=0; i<ido-1; i+=2)
{
ac=i+1+(k*5-4)*ido;
ti5=cc[ac]-cc[ac+3*ido];
ti2=cc[ac]+cc[ac+3*ido];
ti4=cc[ac+ido]-cc[ac+2*ido];
ti3=cc[ac+ido]+cc[ac+2*ido];
tr5=cc[ac-1]-cc[ac+3*ido-1];
tr2=cc[ac-1]+cc[ac+3*ido-1];
tr4=cc[ac+ido-1]-cc[ac+2*ido-1];
tr3=cc[ac+ido-1]+cc[ac+2*ido-1];
ah=i+(k-1)*ido;
ch[ah]=cc[ac-ido-1]+tr2+tr3;
ch[ah+1]=cc[ac-ido]+ti2+ti3;
cr2=cc[ac-ido-1]+tr11*tr2+tr12*tr3;
ci2=cc[ac-ido]+tr11*ti2+tr12*ti3;
cr3=cc[ac-ido-1]+tr12*tr2+tr11*tr3;
ci3=cc[ac-ido]+tr12*ti2+tr11*ti3;
cr5=isign*(ti11*tr5+ti12*tr4);
ci5=isign*(ti11*ti5+ti12*ti4);
cr4=isign*(ti12*tr5-ti11*tr4);
ci4=isign*(ti12*ti5-ti11*ti4);
dr3=cr3-ci4;
dr4=cr3+ci4;
di3=ci3+cr4;
di4=ci3-cr4;
dr5=cr2+ci5;
dr2=cr2-ci5;
di5=ci2-cr5;
di2=ci2+cr5;
ch[ah+l1*ido]=wtable[i+iw1]*dr2-isign*wtable[i+1+iw1]*di2;
ch[ah+l1*ido+1]=wtable[i+iw1]*di2+isign*wtable[i+1+iw1]*dr2;
ch[ah+2*l1*ido]=wtable[i+iw2]*dr3-isign*wtable[i+1+iw2]*di3;
ch[ah+2*l1*ido+1]=wtable[i+iw2]*di3+isign*wtable[i+1+iw2]*dr3;
ch[ah+3*l1*ido]=wtable[i+iw3]*dr4-isign*wtable[i+1+iw3]*di4;
ch[ah+3*l1*ido+1]=wtable[i+iw3]*di4+isign*wtable[i+1+iw3]*dr4;
ch[ah+4*l1*ido]=wtable[i+iw4]*dr5-isign*wtable[i+1+iw4]*di5;
ch[ah+4*l1*ido+1]=wtable[i+iw4]*di5+isign*wtable[i+1+iw4]*dr5;
}
}
}
}
/*----------------------------------------------------------------------
passfg: Complex FFT's forward/backward processing of general factor;
isign is +1 for backward and -1 for forward transforms
----------------------------------------------------------------------*/
void passfg(int nac[], int ido, int ip, int l1, int idl1,
final double cc[], double c1[], double c2[], double ch[], double ch2[],
final double wtable[], int offset, int isign)
{
int idij, idlj, idot, ipph, i, j, k, l, jc, lc, ik, idj, idl, inc, idp;
double wai, war;
int iw1;
iw1 = offset;
idot=ido / 2;
ipph=(ip+1)/ 2;
idp=ip*ido;
if(ido>=l1)
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(k=0; k<l1; k++)
{
for(i=0; i<ido; i++)
{
ch[i+(k+j*l1)*ido]=cc[i+(j+k*ip)*ido]+cc[i+(jc+k*ip)*ido];
ch[i+(k+jc*l1)*ido]=cc[i+(j+k*ip)*ido]-cc[i+(jc+k*ip)*ido];
}
}
}
for(k=0; k<l1; k++)
for(i=0; i<ido; i++)
ch[i+k*ido]=cc[i+k*ip*ido];
}
else
{
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(i=0; i<ido; i++)
{
for(k=0; k<l1; k++)
{
ch[i+(k+j*l1)*ido]=cc[i+(j+k*ip)*ido]+cc[i+(jc+k*ip)*ido];
ch[i+(k+jc*l1)*ido]=cc[i+(j+k*ip)*ido]-cc[i+(jc+k*ip)*ido];
}
}
}
for(i=0; i<ido; i++)
for(k=0; k<l1; k++)
ch[i+k*ido]=cc[i+k*ip*ido];
}
idl=2-ido;
inc=0;
for(l=1; l<ipph; l++)
{
lc=ip-l;
idl+=ido;
for(ik=0; ik<idl1; ik++)
{
c2[ik+l*idl1]=ch2[ik]+wtable[idl-2+iw1]*ch2[ik+idl1];
c2[ik+lc*idl1]=isign*wtable[idl-1+iw1]*ch2[ik+(ip-1)*idl1];
}
idlj=idl;
inc+=ido;
for(j=2; j<ipph; j++)
{
jc=ip-j;
idlj+=inc;
if(idlj>idp) idlj-=idp;
war=wtable[idlj-2+iw1];
wai=wtable[idlj-1+iw1];
for(ik=0; ik<idl1; ik++)
{
c2[ik+l*idl1]+=war*ch2[ik+j*idl1];
c2[ik+lc*idl1]+=isign*wai*ch2[ik+jc*idl1];
}
}
}
for(j=1; j<ipph; j++)
for(ik=0; ik<idl1; ik++)
ch2[ik]+=ch2[ik+j*idl1];
for(j=1; j<ipph; j++)
{
jc=ip-j;
for(ik=1; ik<idl1; ik+=2)
{
ch2[ik-1+j*idl1]=c2[ik-1+j*idl1]-c2[ik+jc*idl1];
ch2[ik-1+jc*idl1]=c2[ik-1+j*idl1]+c2[ik+jc*idl1];
ch2[ik+j*idl1]=c2[ik+j*idl1]+c2[ik-1+jc*idl1];
ch2[ik+jc*idl1]=c2[ik+j*idl1]-c2[ik-1+jc*idl1];
}
}
nac[0]=1;
if(ido==2) return;
nac[0]=0;
for(ik=0; ik<idl1; ik++) c2[ik]=ch2[ik];
for(j=1; j<ip; j++)
{
for(k=0; k<l1; k++)
{
c1[(k+j*l1)*ido+0]=ch[(k+j*l1)*ido+0];
c1[(k+j*l1)*ido+1]=ch[(k+j*l1)*ido+1];
}
}
if(idot<=l1)
{
idij=0;
for(j=1; j<ip; j++)
{
idij+=2;
for(i=3; i<ido; i+=2)
{
idij+=2;
for(k=0; k<l1; k++)
{
c1[i-1+(k+j*l1)*ido]=
wtable[idij-2+iw1]*ch[i-1+(k+j*l1)*ido]-
isign*wtable[idij-1+iw1]*ch[i+(k+j*l1)*ido];
c1[i+(k+j*l1)*ido]=
wtable[idij-2+iw1]*ch[i+(k+j*l1)*ido]+
isign*wtable[idij-1+iw1]*ch[i-1+(k+j*l1)*ido];
}
}
}
}
else
{
idj=2-ido;
for(j=1; j<ip; j++)
{
idj+=ido;
for(k=0; k<l1; k++)
{
idij=idj;
for(i=3; i<ido; i+=2)
{
idij+=2;
c1[i-1+(k+j*l1)*ido]=
wtable[idij-2+iw1]*ch[i-1+(k+j*l1)*ido]-
isign*wtable[idij-1+iw1]*ch[i+(k+j*l1)*ido];
c1[i+(k+j*l1)*ido]=
wtable[idij-2+iw1]*ch[i+(k+j*l1)*ido]+
isign*wtable[idij-1+iw1]*ch[i-1+(k+j*l1)*ido];
}
}
}
}
}
/*---------------------------------------------------------
cfftf1: further processing of Complex forward FFT
--------------------------------------------------------*/
void cfftf1(int n, double c[], final double wtable[], int isign)
{
int idot, i;
int k1, l1, l2;
int na, nf, ip, iw, ido, idl1;
int[] nac = new int[1];
int iw1, iw2;
double[] ch = new double[2*n];
iw1=2*n;
iw2=4*n;
System.arraycopy(wtable, 0, ch, 0, 2*n);
nac[0] = 0;
nf=(int)wtable[1+iw2];
na=0;
l1=1;
iw=iw1;
for(k1=2; k1<=nf+1; k1++)
{
ip=(int)wtable[k1+iw2];
l2=ip*l1;
ido=n / l2;
idot=ido+ido;
idl1=idot*l1;
if(ip==4)
{
if(na==0)
{
passf4(idot, l1, c, ch, wtable, iw, isign);
}
else
{
passf4(idot, l1, ch, c, wtable, iw, isign);
}
na=1-na;
}
else if(ip==2)
{
if(na==0)
{
passf2(idot, l1, c, ch, wtable, iw, isign);
}
else
{
passf2(idot, l1, ch, c, wtable, iw, isign);
}
na=1-na;
}
else if(ip==3)
{
if(na==0)
{
passf3(idot, l1, c, ch, wtable, iw, isign);
}
else
{
passf3(idot, l1, ch, c, wtable, iw, isign);
}
na=1-na;
}
else if(ip==5)
{
if(na==0)
{
passf5(idot, l1, c, ch, wtable, iw, isign);
}
else
{
passf5(idot, l1, ch, c, wtable, iw, isign);
}
na=1-na;
}
else
{
if(na==0)
{
passfg(nac, idot, ip, l1, idl1, c, c, c, ch, ch, wtable, iw, isign);
}
else
{
passfg(nac, idot, ip, l1, idl1, ch, ch, ch, c, c, wtable, iw, isign);
}
if(nac[0] !=0) na=1-na;
}
l1=l2;
iw+=(ip-1)*idot;
}
if(na==0) return;
for(i=0; i<2*n; i++) c[i]=ch[i];
}
/*---------------------------------------------------------
cfftf: Complex forward FFT
--------------------------------------------------------*/
void cfftf(int n, double c[], double wtable[])
{
cfftf1(n, c, wtable, -1);
}
/*---------------------------------------------------------
cfftb: Complex borward FFT
--------------------------------------------------------*/
void cfftb(int n, double c[], double wtable[])
{
cfftf1(n, c, wtable, +1);
}
/*---------------------------------------------------------
cffti1: further initialization of Complex FFT
--------------------------------------------------------*/
void cffti1(int n, double wtable[])
{
final int[] ntryh = {3, 4, 2, 5};
final double twopi=2.0D*Math.PI;
double argh;
int idot, ntry=0, i, j;
double argld;
int i1, k1, l1, l2, ib;
double fi;
int ld, ii, nf, ip, nl, nq, nr;
double arg;
int ido, ipm;
nl=n;
nf=0;
j=0;
factorize_loop:
while(true)
{
j++;
if(j<=4)
ntry=ntryh[j-1];
else
ntry+=2;
do
{
nq=nl / ntry;
nr=nl-ntry*nq;
if(nr !=0) continue factorize_loop;
nf++;
wtable[nf+1+4*n]=ntry;
nl=nq;
if(ntry==2 && nf !=1)
{
for(i=2; i<=nf; i++)
{
ib=nf-i+2;
wtable[ib+1+4*n]=wtable[ib+4*n];
}
wtable[2+4*n]=2;
}
} while(nl !=1);
break factorize_loop;
}
wtable[0+4*n]=n;
wtable[1+4*n]=nf;
argh=twopi /(double)n;
i=1;
l1=1;
for(k1=1; k1<=nf; k1++)
{
ip=(int)wtable[k1+1+4*n];
ld=0;
l2=l1*ip;
ido=n / l2;
idot=ido+ido+2;
ipm=ip-1;
for(j=1; j<=ipm; j++)
{
i1=i;
wtable[i-1+2*n]=1;
wtable[i+2*n]=0;
ld+=l1;
fi=0;
argld=ld*argh;
for(ii=4; ii<=idot; ii+=2)
{
i+=2;
fi+=1;
arg=fi*argld;
wtable[i-1+2*n]=Math.cos(arg);
wtable[i+2*n]=Math.sin(arg);
}
if(ip>5)
{
wtable[i1-1+2*n]=wtable[i-1+2*n];
wtable[i1+2*n]=wtable[i+2*n];
}
}
l1=l2;
}
}
/*---------------------------------------------------------
cffti: Initialization of Real forward FFT
--------------------------------------------------------*/
void cffti(int n, double wtable[])
{
if(n==1) return;
cffti1(n, wtable);
} /*cffti*/
}
| 19,242 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT_Odd.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT_Odd.java | package ca.uol.aig.fftpack;
/**
* sine FFT transform of a real odd sequence.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class RealDoubleFFT_Odd extends RealDoubleFFT_Mixed
{
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward
* transform (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
public double norm_factor;
private double wavetable[];
private int ndim;
/**
* Construct a wavenumber table with size <em>n</em>.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a real data sequence. When (<em>n</em>+1) is a multiplication of small
* numbers (4, 2, 3, 5), this FFT transform is very efficient.
*/
public RealDoubleFFT_Odd(int n)
{
ndim = n;
norm_factor = 2*(n+1);
int wtable_length = 2*ndim + ndim/2 + 3 + 15;
if(wavetable == null || wavetable.length != wtable_length)
{
wavetable = new double[wtable_length];
}
sinti(ndim, wavetable);
}
/**
* Forward sine FFT transform. It computes the discrete sine transform of
* an odd sequence.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
public void ft(double x[])
{
sint(ndim, x, wavetable);
}
/**
* Backward sine FFT transform. It is the unnormalized inverse transform of <em>ft</em>.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
public void bt(double x[])
{
sint(ndim, x, wavetable);
}
/*---------------------------------------
sint1: further processing of sine FFT.
--------------------------------------*/
void sint1(int n, double war[], double wtable[])
{
final double sqrt3=1.73205080756888;
int modn, i, k;
double xhold, t1, t2;
int kc, np1, ns2;
int iw1, iw2, iw3;
double[] wtable_p1 = new double[2*(n+1)+15];
iw1=n / 2;
iw2=iw1+n+1;
iw3=iw2+n+1;
double[] x = new double[n+1];
for(i=0; i<n; i++)
{
wtable[i+iw1]=war[i];
war[i]=wtable[i+iw2];
}
if(n<2)
{
wtable[0+iw1]+=wtable[0+iw1];
}
else if(n==2)
{
xhold=sqrt3*(wtable[0+iw1]+wtable[1+iw1]);
wtable[1+iw1]=sqrt3*(wtable[0+iw1]-wtable[1+iw1]);
wtable[0+iw1]=xhold;
}
else
{
np1=n+1;
ns2=n / 2;
wtable[0+iw2]=0;
for(k=0; k<ns2; k++)
{
kc=n-k-1;
t1=wtable[k+iw1]-wtable[kc+iw1];
t2=wtable[k]*(wtable[k+iw1]+wtable[kc+iw1]);
wtable[k+1+iw2]=t1+t2;
wtable[kc+1+iw2]=t2-t1;
}
modn=n%2;
if(modn !=0)
wtable[ns2+1+iw2]=4*wtable[ns2+iw1];
System.arraycopy(wtable, iw1, wtable_p1, 0, n+1);
System.arraycopy(war, 0, wtable_p1, n+1, n);
System.arraycopy(wtable, iw3, wtable_p1, 2*(n+1), 15);
System.arraycopy(wtable, iw2, x, 0, n+1);
rfftf1(np1, x, wtable_p1, 0);
System.arraycopy(x, 0, wtable, iw2, n+1);
wtable[0+iw1]=0.5*wtable[0+iw2];
for(i=2; i<n; i+=2)
{
wtable[i-1+iw1]=-wtable[i+iw2];
wtable[i+iw1]=wtable[i-2+iw1]+wtable[i-1+iw2];
}
if(modn==0)
wtable[n-1+iw1]=-wtable[n+iw2];
}
for(i=0; i<n; i++)
{
wtable[i+iw2]=war[i];
war[i]=wtable[i+iw1];
}
}
/*----------------
sint: sine FFT
---------------*/
void sint(int n, double x[], double wtable[])
{
sint1(n, x, wtable);
}
/*----------------------------------------------------------------------
sinti: initialization of sin-FFT
----------------------------------------------------------------------*/
void sinti(int n, double wtable[])
{
final double pi=Math.PI; //3.14159265358979;
int k, ns2;
double dt;
if(n<=1) return;
ns2=n / 2;
dt=pi /(double)(n+1);
for(k=0; k<ns2; k++)
wtable[k]=2*Math.sin((k+1)*dt);
rffti1(n+1, wtable, ns2);
}
}
| 4,700 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Complex1D.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/Complex1D.java | package ca.uol.aig.fftpack;
/**
* Construct a 1-D complex data sequence.
*/
public class Complex1D
{
/**
* <em>x</em>[<em>i</em>] is the real part of <em>i</em>-th complex data.
*/
public double x[];
/**
* <em>y</em>[<em>i</em>] is the imaginary part of <em>i</em>-th complex data.
*/
public double y[];
}
| 320 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT_Even_Odd.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT_Even_Odd.java | package ca.uol.aig.fftpack;
/**
* cosine FFT transform with odd wave numbers.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class RealDoubleFFT_Even_Odd extends RealDoubleFFT_Mixed
{
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward transform
* (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
public double norm_factor;
double wavetable[];
int ndim;
/**
* Construct a wavenumber table with size <em>n</em>.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a real data sequence. When <em>n</em> is a multiplication of small
* numbers(4, 2, 3, 5), this FFT transform is very efficient.
*/
public RealDoubleFFT_Even_Odd(int n) {
ndim = n;
norm_factor = 4*n;
if(wavetable == null || wavetable.length !=(3*ndim+15))
{
wavetable = new double[3*ndim + 15];
}
cosqi(ndim, wavetable);
}
/**
* Forward FFT transform of quarter wave data. It computes the coeffients in
* cosine series representation with only odd wave numbers.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
public void ft(double x[]) {
cosqf(ndim, x, wavetable);
}
/**
* Backward FFT transform of quarter wave data. It is the unnormalized inverse transform
* of <em>ft</em>.
*
* @param x an array which contains the sequence to be tranformed. After FFT, <em>x</em> contains
* the transform coeffients.
*/
public void bt(double x[]) {
cosqb(ndim, x, wavetable);
}
/*----------------------------------------------------------------------
cosqf1: further processing of forward cos-FFT with odd wave numbers.
----------------------------------------------------------------------*/
void cosqf1(int n, double x[], double wtable[])
{
int modn, i, k;
int kc, ns2;
double xim1;
ns2=(n+1)/ 2;
for(k=1; k<ns2; k++)
{
kc=n-k;
wtable[k+n]=x[k]+x[kc];
wtable[kc+n]=x[k]-x[kc];
}
modn=n%2;
if(modn==0) wtable[ns2+n]=x[ns2]+x[ns2];
for(k=1; k<ns2; k++)
{
kc=n-k;
x[k]=wtable[k-1]*wtable[kc+n]+wtable[kc-1]*wtable[k+n];
x[kc]=wtable[k-1]*wtable[k+n]-wtable[kc-1]*wtable[kc+n];
}
if(modn==0) x[ns2]=wtable[ns2-1]*wtable[ns2+n];
rfftf1(n, x, wtable, n);
for(i=2; i<n; i+=2)
{
xim1=x[i-1]-x[i];
x[i]=x[i-1]+x[i];
x[i-1]=xim1;
}
}
/*----------------------------------------------------------------------
cosqb1: further processing of backward cos-FFT with odd wave numbers.
----------------------------------------------------------------------*/
void cosqb1(int n, double x[], double wtable[])
{
int modn, i, k;
int kc, ns2;
double xim1;
ns2=(n+1)/ 2;
for(i=2; i<n; i+=2)
{
xim1=x[i-1]+x[i];
x[i]-=x[i-1];
x[i-1]=xim1;
}
x[0]+=x[0];
modn=n%2;
if(modn==0) x[n-1]+=x[n-1];
rfftb1(n, x, wtable, n);
for(k=1; k<ns2; k++)
{
kc=n-k;
wtable[k+n]=wtable[k-1]*x[kc]+wtable[kc-1]*x[k];
wtable[kc+n]=wtable[k-1]*x[k]-wtable[kc-1]*x[kc];
}
if(modn==0) x[ns2]=wtable[ns2-1]*(x[ns2]+x[ns2]);
for(k=1; k<ns2; k++)
{
kc=n-k;
x[k]=wtable[k+n]+wtable[kc+n];
x[kc]=wtable[k+n]-wtable[kc+n];
}
x[0]+=x[0];
}
/*-----------------------------------------------
cosqf: forward cosine FFT with odd wave numbers.
----------------------------------------------*/
void cosqf(int n, double x[], final double wtable[])
{
final double sqrt2=1.4142135623731;
double tsqx;
if(n<2)
{
return;
}
else if(n==2)
{
tsqx=sqrt2*x[1];
x[1]=x[0]-tsqx;
x[0]+=tsqx;
}
else
{
cosqf1(n, x, wtable);
}
}
/*-----------------------------------------------
cosqb: backward cosine FFT with odd wave numbers.
----------------------------------------------*/
void cosqb(int n, double x[], double wtable[])
{
final double tsqrt2=2.82842712474619;
double x1;
if(n<2)
{
x[0]*=4;
}
else if(n==2)
{
x1=4*(x[0]+x[1]);
x[1]=tsqrt2*(x[0]-x[1]);
x[0]=x1;
}
else
{
cosqb1(n, x, wtable);
}
}
/*-----------------------------------------------------------
cosqi: initialization of cosine FFT with odd wave numbers.
----------------------------------------------------------*/
void cosqi(int n, double wtable[])
{
final double pih=Math.PI/2.0D; //1.57079632679491;
int k;
double dt;
dt=pih / (double)n;
for(k=0; k<n; k++) wtable[k]=Math.cos((k+1)*dt);
rffti1(n, wtable, n);
}
}
| 5,649 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT.java |
package ca.uol.aig.fftpack;
/**
* FFT transform of a real periodic sequence.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class RealDoubleFFT
extends RealDoubleFFT_Mixed
{
/**
* Construct a wavenumber table with size <em>n</em>.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a real data sequence. When <em>n</em> is a multiplication of small
* numbers (4, 2, 3, 5), this FFT transform is very efficient.
*/
public RealDoubleFFT(int n)
{
ndim = n;
norm_factor = n;
if(wavetable == null || wavetable.length !=(2*ndim+15))
{
wavetable = new double[2*ndim + 15];
}
rffti(ndim, wavetable);
}
/**
* Forward real FFT transform. It computes the discrete transform
* of a real data sequence.
*
* <p>The x parameter is both input and output data. After the FFT, x
* contains the transform coefficients used to construct n
* complex FFT coefficients.
*
* <p>The real part of the first complex FFT coefficients is x[0];
* its imaginary part is 0. If n is even set m = n/2, if n is odd set
* m = (n+1)/2, then for k = 1, ..., m-1:
* <ul>
* <li>the real part of k-th complex FFT coefficient is x[2 * k];
* <li>the imaginary part of k-th complex FFT coefficient is x[2 * k - 1].
* </ul>
*
* <p>If n is even, the real of part of (n/2)-th complex FFT
* coefficient is x[n - 1]; its imaginary part is 0.
*
* <p>The remaining complex FFT coefficients can be obtained by the
* symmetry relation: the (n-k)-th complex FFT coefficient is the
* conjugate of n-th complex FFT coefficient.
*
* @param x An array which contains the sequence to be
* transformed.
*/
public void ft(double[] x) {
if (x.length != ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
rfftf(ndim, x, wavetable);
}
/**
* Forward real FFT transform. It computes the discrete transform of a real data sequence.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients used to construct <em>n</em> complex FFT coeffients.
* <br>
* @param y the first complex (<em>n</em>+1)/2 (when <em>n</em> is odd) or (<em>n</em>/2+1) (when
* <em>n</em> is even) FFT coefficients.
* The remaining complex FFT coefficients can be obtained by the symmetry relation:
* the (<em>n</em>-<em>k</em>)-th complex FFT coefficient is the conjugate of <em>n</em>-th complex FFT coeffient.
*
*/
public void ft(double x[], Complex1D y) {
if (x.length != ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
rfftf(ndim, x, wavetable);
if(ndim%2 == 0)
{
y.x = new double[ndim/2 + 1];
y.y = new double[ndim/2 + 1];
}
else
{
y.x = new double[(ndim+1)/2];
y.y = new double[(ndim+1)/2];
}
y.x[0] = x[0];
y.y[0] = 0.0D;
for(int i=1; i<(ndim+1)/2; i++)
{
y.x[i] = x[2*i-1];
y.y[i] = x[2*i];
}
if(ndim%2 == 0)
{
y.x[ndim/2] = x[ndim-1];
y.y[ndim/2] = 0.0D;
}
}
/**
* Backward real FFT transform. It is the unnormalized inverse transform of <em>ft</em>(double[]).
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients. Also see the comments of <em>ft</em>(double[])
* for the relation between <em>x</em> and complex FFT coeffients.
*/
public void bt(double x[])
{
if(x.length != ndim)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
rfftb(ndim, x, wavetable);
}
/**
* Backward real FFT transform. It is the unnormalized inverse transform of <em>ft</em>(Complex1D, double[]).
*
* @param x an array which contains the sequence to be transformed. When <em>n</em> is odd, it contains the first
* (<em>n</em>+1)/2 complex data; when <em>n</em> is even, it contains (<em>n</em>/2+1) complex data.
* @param y the real FFT coeffients.
* <br>
* Also see the comments of <em>ft</em>(double[]) for the relation
* between <em>x</em> and complex FFT coeffients.
*/
public void bt(Complex1D x, double y[])
{
if(ndim%2 == 0)
{
if(x.x.length != ndim/2+1)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
}
else
{
if(x.x.length != (ndim+1)/2)
throw new IllegalArgumentException("The length of data can not match that of the wavetable");
}
y[0] = x.x[0];
for(int i=1; i<(ndim+1)/2; i++)
{
y[2*i-1]=x.x[i];
y[2*i]=x.y[i];
}
if(ndim%2 == 0)
{
y[ndim-1]=x.x[ndim/2];
}
rfftb(ndim, y, wavetable);
}
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward transform
* (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
public double norm_factor;
private double wavetable[];
private int ndim;
}
| 5,911 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT_Odd_Odd.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT_Odd_Odd.java | package ca.uol.aig.fftpack;
/**
* sine FFT transform with odd wave numbers.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class RealDoubleFFT_Odd_Odd extends RealDoubleFFT_Even_Odd
{
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward transform
* (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
/**
* Construct a wavenumber table with size n.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a real data sequence. When <em>n</em> is a multiplication of small
* numbers (4, 2, 3, 5), this FFT transform is very efficient.
*/
public RealDoubleFFT_Odd_Odd(int n)
{
super(n);
}
/**
* Forward FFT transform of quarter wave data. It computes the coeffients in
* sine series representation with only odd wave numbers.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
@Override
public void ft(double x[])
{
sinqf(ndim, x, wavetable);
}
/**
* Backward FFT transform of quarter wave data. It is the unnormalized inverse transform
* of <em>ft</em>.
*
* @param x an array which contains the sequence to be tranformed. After FFT, <em>x</em> contains
* the transform coeffients.
*/
@Override
public void bt(double x[])
{
sinqb(ndim, x, wavetable);
}
/*-----------------------------------------------
sinqf: forward sine FFT with odd wave numbers.
----------------------------------------------*/
void sinqf(int n, double x[], double wtable[])
{
int k;
double xhold;
int kc, ns2;
if(n==1) return;
ns2=n / 2;
for(k=0; k<ns2; k++)
{
kc=n-k-1;
xhold=x[k];
x[k]=x[kc];
x[kc]=xhold;
}
cosqf(n, x, wtable);
for(k=1; k<n; k+=2) x[k]=-x[k];
}
/*-----------------------------------------------
sinqb: backward sine FFT with odd wave numbers.
----------------------------------------------*/
void sinqb(int n, double x[], double wtable[])
{
int k;
double xhold;
int kc, ns2;
if(n<=1)
{
x[0]*=4;
return;
}
ns2=n / 2;
for(k=1; k<n; k+=2) x[k]=-x[k];
cosqb(n, x, wtable);
for(k=0; k<ns2; k++)
{
kc=n-k-1;
xhold=x[k];
x[k]=x[kc];
x[kc]=xhold;
}
}
/*
void sinqi(int n, double wtable[])
{
cosqi(n, wtable);
}
*/
}
| 3,038 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RealDoubleFFT_Even.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/ca/uol/aig/fftpack/RealDoubleFFT_Even.java |
package ca.uol.aig.fftpack;
/**
* cosine FFT transform of a real even sequence.
* @author Baoshe Zhang
* @author Astronomical Instrument Group of University of Lethbridge.
*/
public class RealDoubleFFT_Even extends RealDoubleFFT_Mixed
{
/**
* <em>norm_factor</em> can be used to normalize this FFT transform. This is because
* a call of forward transform (<em>ft</em>) followed by a call of backward transform
* (<em>bt</em>) will multiply the input sequence by <em>norm_factor</em>.
*/
public double norm_factor;
private double wavetable[];
private int ndim;
/**
* Construct a wavenumber table with size <em>n</em>.
* The sequences with the same size can share a wavenumber table. The prime
* factorization of <em>n</em> together with a tabulation of the trigonometric functions
* are computed and stored.
*
* @param n the size of a real data sequence. When (<em>n</em>-1) is a multiplication of small
* numbers (4, 2, 3, 5), this FFT transform is very efficient.
*/
public RealDoubleFFT_Even(int n)
{
ndim = n;
norm_factor = 2 * (n - 1);
if (wavetable == null || wavetable.length != (3 * ndim + 15))
wavetable = new double[3 * ndim + 15];
costi(ndim, wavetable);
}
/**
* Forward cosine FFT transform. It computes the discrete sine transform of
* an odd sequence.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
public void ft(double[] x) {
cost(ndim, x, wavetable);
}
/**
* Backward cosine FFT transform. It is the unnormalized inverse transform of <em>ft</em>.
*
* @param x an array which contains the sequence to be transformed. After FFT,
* <em>x</em> contains the transform coeffients.
*/
public void bt(double[] x) {
cost(ndim, x, wavetable);
}
/*-------------------------------------------------------------
cost: cosine FFT. Backward and forward cos-FFT are the same.
------------------------------------------------------------*/
void cost(int n, double x[], final double wtable[])
{
int modn, i, k;
double c1, t1, t2;
int kc;
double xi;
int nm1;
double x1h;
int ns2;
double tx2, x1p3, xim2;
nm1=n-1;
ns2=n / 2;
if(n-2<0) return;
else if(n==2)
{
x1h=x[0]+x[1];
x[1]=x[0]-x[1];
x[0]=x1h;
}
else if(n==3)
{
x1p3=x[0]+x[2];
tx2=x[1]+x[1];
x[1]=x[0]-x[2];
x[0]=x1p3+tx2;
x[2]=x1p3-tx2;
}
else
{
c1=x[0]-x[n-1];
x[0]+=x[n-1];
for(k=1; k<ns2; k++)
{
kc=nm1-k;
t1=x[k]+x[kc];
t2=x[k]-x[kc];
c1+=wtable[kc]*t2;
t2=wtable[k]*t2;
x[k]=t1-t2;
x[kc]=t1+t2;
}
modn=n%2;
if(modn !=0) x[ns2]+=x[ns2];
rfftf1(nm1, x, wtable, n);
xim2=x[1];
x[1]=c1;
for(i=3; i<n; i+=2)
{
xi=x[i];
x[i]=x[i-2]-x[i-1];
x[i-1]=xim2;
xim2=xi;
}
if(modn !=0) x[n-1]=xim2;
}
}
/*----------------------------------
costi: initialization of cos-FFT
---------------------------------*/
void costi(int n, double wtable[])
{
final double pi=Math.PI; //3.14159265358979;
int k, kc, ns2;
double dt;
if(n<=3) return;
ns2=n / 2;
dt=pi /(double)(n-1);
for(k=1; k<ns2; k++)
{
kc=n-k-1;
wtable[k]=2*Math.sin(k*dt);
wtable[kc]=2*Math.cos(k*dt);
}
rffti1(n-1, wtable, n);
}
}
| 4,055 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Region.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/Region.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
import java.util.Random;
/**
* An immutable rectangular region in the plane. This immutable
* class represents a rectangle as two sets of X and Y co-ordinates.
*/
public class Region {
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Point from individual co-ordinates.
*
* @param x1 One X co-ordinate.
* @param y1 One Y co-ordinate.
* @param x2 The other X co-ordinate.
* @param y2 The other Y co-ordinate.
*/
public Region(double x1, double y1, double x2, double y2) {
// Make sure we store the coordinates in order.
this.x1 = Math.min(x1, x2);
this.y1 = Math.min(y1, y2);
this.x2 = Math.max(x1, x2);
this.y2 = Math.max(y1, y2);
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the lower X co-ordinate of this region.
*
* @return The lower X co-ordinate of this region.
*/
public double getX1() {
return x1;
}
/**
* Get the lower Y co-ordinate of this region.
*
* @return The lower Y co-ordinate of this region.
*/
public double getY1() {
return y1;
}
/**
* Get the upper X co-ordinate of this region.
*
* @return The upper X co-ordinate of this region.
*/
public double getX2() {
return x2;
}
/**
* Get the upper Y co-ordinate of this region.
*
* @return The upper Y co-ordinate of this region.
*/
public double getY2() {
return y2;
}
/**
* Get the width of this region.
*
* @return The width of this region.
*/
public double getWidth() {
return x2 - x1;
}
/**
* Get the height of this region.
*
* @return The height of this region.
*/
public double getHeight() {
return y2 - y1;
}
// ******************************************************************** //
// Data Manipulation.
// ******************************************************************** //
/**
* Get a random point within this region.
*
* @return An evenly-distributed random point within this region.
*/
public Point randomPoint() {
double x = rnd.nextDouble() * (x2 - x1) + x1;
double y = rnd.nextDouble() * (y2 - y1) + y1;
return new Point(x, y);
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + x1 + "," + y1 + " -> " + x2 + "," + y2 + ">";
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// RNG used for random points.
private static Random rnd = new Random();
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The lower-valued coordinates of this region.
private final double x1;
private final double y1;
// The higher-valued coordinates of this region.
private final double x2;
private final double y2;
}
| 4,773 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Vector.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/Vector.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
/**
* An immutable vector in the plane. This immutable class represents
* a vector as an X and Y offset.
*/
public class Vector implements Comparable<Vector> {
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Vector from individual offsets.
*
* @param x The X offset.
* @param y The Y offset.
*/
public Vector(double x, double y) {
this.x = x;
this.y = y;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the X component of this vector.
*
* @return The X component of this vector.
*/
public double getX() {
return x;
}
/**
* Get the Y component of this vector.
*
* @return The Y component of this vector.
*/
public double getY() {
return y;
}
/**
* Get the length of this vector.
*
* @return The length of this vector.
*/
public double length() {
return Math.sqrt(x * x + y * y);
}
// ******************************************************************** //
// Static Methods.
// ******************************************************************** //
/**
* Calculate the vector sum of two vectors.
*
* @param a The first vector to add.
* @param b The second vector.
* @return The sum.
*/
public static Vector add(Vector a, Vector b) {
return new Vector(a.x + b.x, a.y + b.y);
}
/**
* Calculate the vector difference of two vectors.
*
* @param a The first vector to add.
* @param b The second vector.
* @return The difference, a - b.
*/
public static Vector sub(Vector a, Vector b) {
return new Vector(a.x - b.x, a.y - b.y);
}
/**
* Scale a vector by a given value.
*
* @param vec The vector to scale.
* @param scale The value to scale by.
* @return The product of vec and scale.
*/
public static Vector scale(Vector vec, double scale) {
return new Vector(vec.x * scale, vec.y * scale);
}
// ******************************************************************** //
// Sorting Support.
// ******************************************************************** //
/**
* Indicates whether some other object is "equal to" this one.
* This method implements an equivalence relation
* on non-null object references.
*
* <p>This method simply compares the components of the two vectors,
* with a limited precision.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close vectors will be considered equal.
*
* @param obj The reference object with which to compare.
* @return true if this object is the same as the obj
* argument, to within the given precision;
* false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Vector))
return false;
final Vector o = (Vector) obj;
return MathTools.eq(x, o.x) && MathTools.eq(y, o.y);
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* <p>This method compares the components of the two vectors,
* with a limited precision. The Y component is given precedence;
* that is, the smaller Y will be considered less than the larger Y.
* If the Y values are equal to within the configured precision, then the X
* values are compared.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close vectors will be considered equal.
*
* @param o The object to be compared to this one.
* @return A negative integer, zero, or a positive
* integer as this object is less than, equal
* to, or greater than the specified object.
* @throws ClassCastException The specified object's type prevents it
* from being compared to this object.
*/
public int compareTo(Vector o) {
// Note: in the following, we check for less than *AND* greater than,
// AFTER eliminating equality. The other option is that the values
// are infinite; hence these tests are required.
if (!MathTools.eq(y, o.y)) {
if (y < o.y)
return -1;
else if (y > o.y)
return 1;
} else if (!MathTools.eq(x, o.x)) {
if (x < o.x)
return -1;
else if (x > o.x)
return 1;
}
return 0;
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables.
*
* <p>The hash code returned here is based on the components of this
* Vector, and is designed to be different for different vectors.
* The least significant bits of the components are not compared,
* in line with the precision set in
* {@link MathTools#setPrecision(double)}. Hence, this method should
* be consistent with equals() and compareTo().
*
* @return A hash code value for this object.
*/
@Override
public int hashCode() {
long xb = Double.doubleToLongBits(MathTools.round(x));
long yb = Double.doubleToLongBits(MathTools.round(y));
// Fold the co-ordinates into 32 bits. At the same time don't
// map equivalent bits of x and y into the same bits of the hash.
return (int) xb ^ (int) (xb >> 32) ^
(int) (yb >> 53) ^ (int) (yb >> 21) ^ (int) (yb << 11);
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + x + "," + y + ">";
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The components of this Vector.
private final double x;
private final double y;
}
| 8,268 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Edge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/Edge.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
/**
* An immutable edge in a geometric graph.
*
* <p>This immutable class embodies an edge in a graph where the vertices are
* assumed to be points in the plane. Either or both of the vertices
* may be at infinity, in which case this class can provide the position
* and direction of the line representing the edge.
*/
public class Edge
implements Comparable<Edge>
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create an Edge from individual vertices.
*
* @param a One vertex, in no particular order. Must be
* a real Point.
* @param b The other vertex. Must be a real Point.
*/
public Edge(Point a, Point b) {
if (a.isNaN() || b.isNaN())
throw new IllegalArgumentException("Undefined vertices" +
" not allowed in an Edge.");
if (a.isInfinite() || b.isInfinite())
throw new IllegalArgumentException("Infinite co-ordinates" +
" not allowed in an Edge.");
VVertexA = a;
VVertexB = b;
leftDatum = null;
rightDatum = null;
}
/**
* Create an Edge from two data points and individual vertices.
*
* @param ld One data point for the edge. This is a point
* which the edge passes through, and defines
* the position and direction of an infinite edge.
* @param rd Other data point for the edge.
* @param a One vertex, in no particular order. Must be
* Point.INFINITE or a real Point.
* @param b The other vertex. May be
* Point.INFINITE or a real Point.
*/
public Edge(Point a, Point b, Point ld, Point rd) {
if (a.isNaN() || b.isNaN())
throw new IllegalArgumentException("Undefined vertices" +
" not allowed in an Edge.");
if (ld.isNaN() || rd.isNaN())
throw new IllegalArgumentException("Undefined data points" +
" not allowed in an Edge.");
if (ld.isInfinite() || rd.isInfinite())
throw new IllegalArgumentException("Infinite data points" +
" not allowed in an Edge.");
leftDatum = ld;
rightDatum = rd;
VVertexA = a;
VVertexB = b;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get one vertex of this edge (denoted "A").
*
* @return The "A" vertex of this edge. May be
* Point.INFINITE or a real Point.
*/
public Point getVertexA() {
return VVertexA;
}
/**
* Get one vertex of this edge (denoted "B").
*
* @return The "B" vertex of this edge. May be
* Point.INFINITE or a real Point.
*/
public Point getVertexB() {
return VVertexB;
}
/**
* Get one datum point of this edge (denoted "A").
*
* @return The "A" datum of this edge. Will be null
* if there is no datum, as may be the case for
* non-infinite edges.
*/
public Point getDatumA() {
return leftDatum;
}
/**
* Get one datum point of this edge (denoted "B").
*
* @return The "B" datum of this edge. Will be null
* if there is no datum, as may be the case for
* non-infinite edges.
*/
public Point getDatumB() {
return rightDatum;
}
/**
* Determine whether this edge is infinite.
*
* @return True if both vertices are infinite; false else.
*/
public boolean isInfinite() {
return VVertexA == Point.INFINITE && VVertexB == Point.INFINITE;
}
/**
* Determine whether this edge is partly infinite.
*
* @return True if either vertex is infinite; false else.
*/
public boolean isPartlyInfinite() {
return VVertexA == Point.INFINITE || VVertexB == Point.INFINITE;
}
/**
* Get a reference point which fixes the position of this edge.
*
* @return A reference point which can be used to fix the
* position of this edge. If the edge is fully
* infinite, this will be some point which the edge
* passes through; if the edge is partly infinite,
* it will be the non-infinite vertex; otherwise
* it will be one of the vertices.
*/
public Point referencePoint() {
if (isInfinite())
return Point.mid(leftDatum, rightDatum);
if (VVertexA != Point.INFINITE)
return VVertexA;
return VVertexB;
}
/**
* Get the direction vector for this edge. If the edge is partly
* or fully infinite, this can be used to draw the edge in conjunction
* with referencePoint().
*
* @return The direction vector for this edge.
*/
public Vector directionVector() {
// If this is a non-infinite edge, calculate the direction based
// on the two vertices. Scale to a unit vector.
if (!isPartlyInfinite()) {
final Vector diff = Point.vector(VVertexA, VVertexB);
return Vector.scale(diff, 1.0 / diff.length());
}
// Base it on the passed-through points.
final double lx = leftDatum.getX();
final double ly = leftDatum.getY();
final double rx = rightDatum.getX();
final double ry = rightDatum.getY();
// If the edge is vertical, we have to handle it specially to avoid
// divide by zero below. Return a unit vector either up or
// down as appropriate.
if (lx == rx) {
if (ly < ry)
return new Vector(-1, 0);
else
return new Vector(1, 0);
}
// Calculate the direction from the two direction points. Scale
// to a unit vector.
final double x = -(ry - ly) / (rx - lx);
final double y = 1;
final double len = Math.sqrt(x * x + y * y);
final double scale = 1.0 / len * (rx < lx ? -1 : 1);
return new Vector(x * scale, y * scale);
}
/**
* Get the length of this edge.
*
* @return The length of this edge; this will be
* Double.POSITIVE_INFINITY if the edge is infinite
* or partly infinite.
*/
public double length() {
if (isPartlyInfinite())
return Double.POSITIVE_INFINITY;
return VVertexA.dist(VVertexB);
}
// ******************************************************************** //
// Sorting Support.
// ******************************************************************** //
/**
* Indicates whether some other object is "equal to" this one.
* This method implements an equivalence relation
* on non-null object references.
*
* <p>This method simply compares the co-ordinates of the two points,
* with a limited precision.
*
* <p>This comparison has little objective value; it is used to enforce
* a natural ordering on edges, so that arrays of edges can be compared
* easily for equality. This is in turn used for testing. Because
* compareTo() only compares vertices, so does this method.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close points will be considered equal.
*
* @param obj The reference object with which to compare.
* @return true if this object is the same as the obj
* argument, to within the given precision;
* false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Edge))
return false;
final Edge o = (Edge) obj;
return VVertexA.equals(o.VVertexA) && VVertexB.equals(o.VVertexB);
}
/**
* Compare an edge against another edge. The comparison is based on
* comparing the two vertices, as per {@link Point#compareTo(Point)}.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close points will be considered equal.
*
* <p>This comparison has little objective value; it is used to enforce
* a natural ordering on edges, so that arrays of edges can be compared
* easily for equality. This is in turn used for testing.
*
* @param ev The other edge to compare to.
* @return A negative, zero or positive integer, as this
* edge is less than, equal to, or greater than ev.
*/
public int compareTo(Edge ev) {
Point me1, me2;
if (VVertexA.compareTo(VVertexB) < 0) {
me1 = VVertexA;
me2 = VVertexB;
} else {
me1 = VVertexB;
me2 = VVertexA;
}
Point o1, o2;
if (ev.VVertexA.compareTo(ev.VVertexB) < 0) {
o1 = ev.VVertexA;
o2 = ev.VVertexB;
} else {
o1 = ev.VVertexB;
o2 = ev.VVertexA;
}
int stat = me1.compareTo(o1);
if (stat == 0)
stat = me2.compareTo(o2);
return stat;
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables.
*
* <p>The hash code returned here is based on the hash codes of
* the vertices. See {@link Point#hashCode()}. This means that
* the least significant bits of the co-ordinates are not compared,
* in line with the precision set in
* {@link MathTools#setPrecision(double)}. Hence, this method should
* be consistent with equals() and compareTo().
*
* @return A hash code value for this object.
*/
@Override
public int hashCode() {
return VVertexA.hashCode() ^ VVertexB.hashCode();
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "{" + VVertexA + "," + VVertexB +
":L=" + leftDatum + ",R=" + rightDatum + "}";
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
private final Point leftDatum;
private final Point rightDatum;
private final Point VVertexA;
private final Point VVertexB;
}
| 12,632 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
MathTools.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/MathTools.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
/**
* Mathematical utilities for geometric calculations.
*
* <p>This package provides mathematical comparisons which ignore the
* lowest bits of the provided values. This is useful when comparing
* values which should be equal, except for floating-point representability
* and rounding.
*/
public class MathTools {
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set the precision for calculations. The precision is given
* as a scaling factor; values are scaled by this value and rounded to 1.
*
* @param val The precision as a scaling factor.
*/
public static final void setPrecision(double val) {
precision = val;
}
// ******************************************************************** //
// Comparisons.
// ******************************************************************** //
/**
* Return the given value rounded according to the current precision.
*
* @param val The value to round.
* @return The rounded value.
*/
public static final double round(double val) {
return Math.rint(val * precision) / precision;
}
/**
* Determine whether two values are equal to within the current precision.
*
* @param a One value to compare.
* @param b The other value to compare.
* @return True if the values do not differ within the
* current precision.
*/
public static final boolean eq(double a, double b) {
return Math.abs(a - b) * precision < 1.0;
}
/**
* Determine whether a value is less than another to within the current precision.
*
* @param a One value to compare.
* @param b The other value to compare.
* @return True if a < b by at least the current precision.
*/
public static final boolean lt(double a, double b) {
return (b - a) * precision > 1.0;
}
// ******************************************************************** //
// Private Class Data.
// ******************************************************************** //
// The required precision for comparisons, expressed as a
// scaling factor; values are scaled by this value and rounded to 1.
private static double precision = 10000000000.0;
}
| 3,385 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Graph.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/Graph.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
import java.util.HashSet;
import java.util.Iterator;
/**
* An immutable graph, with possibly infinite edges.
*
* <p>This immutable class represents a graph as a collection of Edge
* objects. These edges can be infinite.
*/
public class Graph {
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Construct a graph with a given set of edges.
*
* @param e The set of edges which define the graph.
* May include infinite edges.
*/
public Graph(HashSet<Edge> e) {
graphVertices = null;
graphEdges = e;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the number of edges in the graph.
*
* @return The number of edges in the graph. Note that
* this number includes an infinite point if
* there are any infinite edges in the graph.
*/
public int getNumEdges() {
return graphEdges.size();
}
/**
* Get the edges in the graph.
*
* @return An iterator over the edges in the graph. Note that
* this iterator includes an infinite point if
* there are any infinite edges in the graph.
*/
public Iterator<Edge> getEdges() {
return graphEdges.iterator();
}
/**
* Get an array of the edges in the graph.
*
* @return A newly-allocated array containing the
* edges in the graph. Note that this is somewhat
* inefficient, as this array is allocated each time.
* Note that this array includes an infinite point if
* there are any infinite edges in the graph.
*/
public Edge[] getEdgeArray() {
Edge[] vEdges = new Edge[graphEdges.size()];
graphEdges.toArray(vEdges);
return vEdges;
}
/**
* Get the number of vertices in the graph.
*
* @return The number of vertices in the graph.
*/
public int getNumVertices() {
if (graphVertices == null)
listVertices();
return graphVertices.size();
}
/**
* Get the vertices in the graph.
*
* @return An iterator over the vertices in the graph.
*/
public Iterator<Point> getVertices() {
if (graphVertices == null)
listVertices();
return graphVertices.iterator();
}
/**
* Get an array of the vertices in the graph.
*
* @return A newly-allocated array containing the
* vertices in the graph. Note that this is somewhat
* inefficient, as this array is allocated each time.
*/
public Point[] getVertexArray() {
if (graphVertices == null)
listVertices();
Point[] vVerts = new Point[graphVertices.size()];
graphVertices.toArray(vVerts);
return vVerts;
}
/**
* Create the list of the vertices in the graph. This is called
* to set up the vertex list based on the edge list, if and when
* it is required.
*/
private void listVertices() {
// Now list all the vertices which are used in our new edge list.
graphVertices = new HashSet<Point>();
for (final Edge VE : graphEdges) {
graphVertices.add(VE.getVertexA());
graphVertices.add(VE.getVertexB());
}
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return getClass().getSimpleName();
}
/**
* Dump the entire set of edges in this graph to the console.
*
* @param prefix Prefix for each output line.
*/
public void dump(String prefix) {
System.out.println(prefix + "Graph [");
for (Edge e : graphEdges)
System.out.println(prefix + " " + e);
System.out.println(prefix + "]");
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The edges which make up this graph.
private HashSet<Edge> graphEdges;
// The vertices in this graph. This list is normally null, and is
// generated from the edges when required.
private HashSet<Point> graphVertices = null;
}
| 5,824 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Point.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/Point.java |
/**
* geometry: basic geometric classes.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry;
/**
* An immutable point in the plane. This immutable class represents
* a point as an X and Y co-ordinate.
*/
public class Point
implements Comparable<Point>
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* A constant representing a point at infinity. This is the only Point
* whose co-ordinates can be infinite.
*/
public static final Point INFINITE =
new Point(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, true);
/**
* A constant representing an unknown point (the 2-D equivalent of NaN).
* This is the only Point whose co-ordinates can be NaN.
*/
public static final Point UNKNOWN = new Point(Double.NaN, Double.NaN, true);
/**
* Index value which specifies the X co-ordinate within a point.
* @see #getComponent(int)
*/
public static final int X_INDEX = 0;
/**
* Index value which specifies the Y co-ordinate within a point.
* @see #getComponent(int)
*/
public static final int Y_INDEX = 1;
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Point from individual co-ordinates.
*
* @param x The X co-ordinate.
* @param y The Y co-ordinate.
*/
public Point(double x, double y) {
this(x, y, false);
}
/**
* Create a Point from individual co-ordinates.
*
* @param x The X co-ordinate.
* @param y The Y co-ordinate.
* @param allowOdd Iff true, allow infinities and NaNs.
*/
private Point(double x, double y, boolean allowOdd) {
if (!allowOdd) {
if (Double.isInfinite(x) || Double.isInfinite(y))
throw new IllegalArgumentException("Infinite co-ordinates" +
" not allowed in a Point.");
if (Double.isNaN(x) || Double.isNaN(y))
throw new IllegalArgumentException("NaN co-ordinates" +
" not allowed in a Point.");
}
this.x = x;
this.y = y;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Determine whether this point is infinite.
*
* @return True if this point is at infinity.
*/
public boolean isInfinite() {
return Double.isInfinite(x) || Double.isInfinite(y);
}
/**
* Determine whether this point is NaN.
*
* @return True if this point is an undefined point.
*/
public boolean isNaN() {
return Double.isNaN(x) || Double.isNaN(y);
}
/**
* Get the X co-ordinate of this point.
*
* @return The X co-ordinate of this point.
*/
public double getX() {
return x;
}
/**
* Get the Y co-ordinate of this point.
*
* @return The Y co-ordinate of this point.
*/
public double getY() {
return y;
}
/**
* Get the specified co-ordinate of this point. This method is useful
* where Points are passed to methods which can work on either
* co-ordinate.
*
* @param i Index of the desired co-ordinate; either
* {@link #X_INDEX} or {@link #Y_INDEX}.
* @return The specified co-ordinate of this point.
* @throws IllegalArgumentException Bad index.
*/
public double getComponent(int i) throws IllegalArgumentException {
if (i == X_INDEX)
return x;
else if (i == Y_INDEX)
return y;
throw new IllegalArgumentException("Invalid index " + i + " in getComponent");
}
/**
* Get the X co-ordinate of this point as a float. This can be
* convenient for graphics methods, for example.
*
* @return The X co-ordinate of this point as a float.
*/
public float getXf() {
return (float) x;
}
/**
* Get the Y co-ordinate of this point as a float. This can be
* convenient for graphics methods, for example.
*
* @return The Y co-ordinate of this point as a float.
*/
public float getYf() {
return (float) y;
}
// ******************************************************************** //
// Calculations.
// ******************************************************************** //
/**
* Calculate the distance between this point and another.
*
* @param o The other point.
* @return The scalar distance between this point
* and o -- always positive.
*/
public double dist(Point o) {
final double dx = x - o.x;
final double dy = y - o.y;
return Math.sqrt(dx * dx + dy * dy);
}
// ******************************************************************** //
// Static Methods.
// ******************************************************************** //
/**
* Calculate the Vector between two points.
*
* @param a The starting point.
* @param b The ending point.
* @return A Vector which would translate a to b.
*/
public static Vector vector(Point a, Point b) {
return new Vector(b.x - a.x, b.y - a.y);
}
/**
* Calculate the midpoint between two points.
*
* @param a One point.
* @param b The other point.
* @return The point midway between a and b.
*/
public static Point mid(Point a, Point b) {
return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
// ******************************************************************** //
// Sorting Support.
// ******************************************************************** //
/**
* Indicates whether some other object is "equal to" this one.
* This method implements an equivalence relation
* on non-null object references.
*
* <p>This method simply compares the co-ordinates of the two points,
* with a limited precision.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close points will be considered equal.
*
* @param obj The reference object with which to compare.
* @return true if this object is the same as the obj
* argument, to within the given precision;
* false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Point))
return false;
final Point o = (Point) obj;
return MathTools.eq(x, o.x) && MathTools.eq(y, o.y);
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* <p>This method compares the co-ordinates of the two points,
* with a limited precision. The Y co-ordinate is given precedence;
* that is, the smaller Y will be considered less than the larger Y.
* If the Y values are equal to within the configured precision, then the X
* values are compared.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close points will be considered equal.
*
* @param o The object to be compared to this one.
* @return A negative integer, zero, or a positive
* integer as this object is less than, equal
* to, or greater than the specified object.
* @throws ClassCastException The specified object's type prevents it
* from being compared to this object.
*/
public int compareTo(Point o) {
// Note: in the following, we check for less than *AND* greater than,
// AFTER eliminating equality. The other option is that the values
// are infinite; hence these tests are required.
if (!MathTools.eq(y, o.y)) {
if (y < o.y)
return -1;
else if (y > o.y)
return 1;
} else if (!MathTools.eq(x, o.x)) {
if (x < o.x)
return -1;
else if (x > o.x)
return 1;
}
return 0;
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables.
*
* <p>The hash code returned here is based on the co-ordinates of this
* Point, and is designed to be different for different points.
* The least significant bits of the co-ordinates are not compared,
* in line with the precision set in
* {@link MathTools#setPrecision(double)}. Hence, this method should
* be consistent with equals() and compareTo().
*
* @return A hash code value for this object.
*/
@Override
public int hashCode() {
long xb = Double.doubleToLongBits(MathTools.round(x));
long yb = Double.doubleToLongBits(MathTools.round(y));
// Fold the co-ordinates into 32 bits. At the same time don't
// map equivalent bits of x and y into the same bits of the hash.
return (int) xb ^ (int) (xb >> 32) ^
(int) (yb >> 53) ^ (int) (yb >> 21) ^ (int) (yb << 11);
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + x + "," + y + ">";
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The coordinates of this point.
private final double x;
private final double y;
}
| 11,977 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Generator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/generator/Generator.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.generator;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* A generic interface to a data generating algorithm.
*/
public interface Generator {
/**
* Create a set of data points within the given region.
*
* @param region The region of the plane in which the points
* must lie.
* @param num The desired number of points.
* @return The generated data points.
*/
public Point[] createPoints(Region region, int num);
/**
* Get reference points, if any, associated with the most recently
* generated data set.
*
* @return The reference points, if any, used to generate
* the most recent data set. null if none.
*/
public Point[] getReferencePoints();
}
| 1,587 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
NuclearGenerator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/generator/NuclearGenerator.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.generator;
import java.util.Random;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* A data generator which generates clustered random points.
*/
public class NuclearGenerator
implements Generator
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a clustering data generator.
*
* @param nclusters The desired number of clusters in each generated
* data set.
*/
public NuclearGenerator(int nclusters) {
numClusters = nclusters;
}
// ******************************************************************** //
// Data Generator.
// ******************************************************************** //
/**
* Create a set of data points within the given region.
*
* @param region The region of the plane in which the points
* must lie.
* @param npoints The desired number of points.
* @return The generated data points.
*/
public Point[] createPoints(Region region, int npoints) {
// First, create the randomly-placed nuclear plants within the region.
// Don't put two close together.
refPoints = new Point[numClusters];
makeCentres:
for (int i = 0; i < numClusters; ) {
Point p = region.randomPoint();
for (int c = 0; c < i; ++c)
if (p.dist(refPoints[c]) < 80)
continue makeCentres;
refPoints[i++] = p;
}
// Now, create random points,
Point[] points = new Point[npoints];
for (int i = 0; i < npoints; ) {
// Create a random point in the plane.
Point p = region.randomPoint();
// The chance of this point existing depends on the distance to
// one or more nuclear plants. Being close to multiple plants
// increases our chances.
boolean exists = false;
for (int c = 0; c < numClusters; ++c) {
double dist = p.dist(refPoints[c]);
double r = Math.abs(rnd.nextGaussian()) * 2.0;
exists |= dist < 20 * r;
}
if (exists)
points[i++] = p;
}
return points;
}
/**
* Get reference points, if any, associated with the most recently
* generated data set.
*
* @return The reference points, if any, used to generate
* the most recent data set. null if none.
*/
public Point[] getReferencePoints() {
return refPoints;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// RNG used for random points.
private static Random rnd = new Random();
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The number of clusters in the generated data.
private int numClusters;
// The reference points for the most recent data set.
private Point[] refPoints = null;
}
| 4,217 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
RandomGenerator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/generator/RandomGenerator.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.generator;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* A data generator which generates evenly-distributed random points.
*/
public class RandomGenerator
implements Generator
{
// ******************************************************************** //
// Data Generator.
// ******************************************************************** //
/**
* Create a set of data points within the given region.
*
* @param region The region of the plane in which the points
* must lie.
* @param num The desired number of points.
* @return The generated data points.
*/
public Point[] createPoints(Region region, int num) {
Point[] points = new Point[num];
for (int i = 0; i < num; ++i)
points[i] = region.randomPoint();
return points;
}
/**
* Get reference points, if any, associated with the most recently
* generated data set.
*
* @return The reference points, if any, used to generate
* the most recent data set. null if none.
*/
public Point[] getReferencePoints() {
return null;
}
}
| 2,016 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
FuzzyClusterer.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/cluster/FuzzyClusterer.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.cluster;
import java.util.Random;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* An implementation of Lloyd's k-clusterMeans clustering algorithm.
*/
public class FuzzyClusterer
extends Clusterer
{
/**
* Prepare a clustering pass on the indicated data.
*
* @param points The array of dataPoints to be clustered.
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which to place centroids
* of the clusters.
* @param region The region of the plane in which the points lie.
*/
@Override
public void prepare(Point[] points, int[] ids, double[][] means, Region region) {
super.prepare(points, ids, means, region);
// Save the data arrays.
dataPoints = points;
pointClusters = ids;
clusterMeans = means;
numPoints = points.length;
numClusters = means.length;
// Set up the strengths array.
clusterStrengths = new double[numPoints][numClusters];
// Set the initial cluster centroids to be random values
// within the data region.
double x = region.getX1();
double y = region.getY1();
double w = region.getWidth();
double h = region.getHeight();
for (int i = 0; i < numClusters; ++i) {
means[i][0] = random.nextDouble() * w + x;
means[i][1] = random.nextDouble() * h + y;
}
// Make an initial assignment of points to clusters, so on the first
// iteration we have a basis for computing centroids.
assignPoints(ids, means);
}
/**
* Runs a single iteration of the clustering algorithm on the stored data.
* The results are stored in the arrays that were passed into
* {@link #prepare(Point[], int[], double[][], Region)}.
*
* <p>After each iteration, the cluster IDs and cluster means should
* be consistent with each other.
*
* @return true if the algorithm has converged.
*/
@Override
public boolean iterate() {
System.out.println("Fuzzy: iterate");
// Compute the new centroids of the clusters, based on the existing
// point assignments.
boolean converged = computeCentroids(pointClusters, clusterMeans);
// Assign data points to clusters based on the new centroids.
if (!converged)
assignPoints(pointClusters, clusterMeans);
// Our convergence criterion is no change in the means.
return converged;
}
/**
* Compute the centroids of all the clusters.
*
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which we will place the
* centroids of the clusters.
* @return true iff none of the means moved by a significant
* amount.
*/
private boolean computeCentroids(int[] ids, double[][] means) {
boolean dirty = false;
for (int c = 0; c < numClusters; ++c) {
// Compute the weighted sum of the data points.
double tx = 0.0, ty = 0.0, tot = 0.0;
for (int p = 0; p < numPoints; ++p) {
Point point = dataPoints[p];
double str = Math.pow(clusterStrengths[p][c], M);
tx += point.getX() * str;
ty += point.getY() * str;
tot += str;
}
// Calculate the mean, and see if it's different from
// the previous one.
final double nx = tx / tot;
final double ny = ty / tot;
if (!MathTools.eq(means[c][0], nx) || !MathTools.eq(means[c][1], ny)) {
means[c][0] = nx;
means[c][1] = ny;
dirty = true;
}
}
return !dirty;
}
/**
* Assign each point in the data array to the cluster whose centroid
* it is closest to.
*
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which we will place the
* centroids of the clusters.
* @return true iff none of the points changed to a different
* cluster.
*/
private boolean assignPoints(int[] ids, double[][] means) {
// Accumulate the sum of the distances squared between each
// point and its closest mean.
sumDistSquared = 0.0;
// Assign each point to a cluster, according to which cluster
// centroid it is closest to. Set dirty to true if any point
// changes to a different cluster.
boolean dirty = false;
for (int p = 0; p < numPoints; ++p) {
Point point = dataPoints[p];
int closest = -1;
double minDistance = Double.MAX_VALUE;
double maxStrength = 0;
for (int c = 0; c < means.length; ++c) {
double distsq = computeDistanceSquared(point, means[c]);
double dist = Math.sqrt(distsq);
double sum = 0.0;
for (int j = 0; j < means.length; ++j) {
double djsq = computeDistanceSquared(point, means[j]);
double dj = Math.sqrt(djsq);
sum += Math.pow(dist / dj, 2 / (M - 1));
}
clusterStrengths[p][c] = 1 / sum;
if (1 / sum > maxStrength) {
maxStrength = 1 / sum;
closest = c;
minDistance = distsq;
}
}
sumDistSquared += minDistance;
if (closest != ids[p]) {
ids[p] = closest;
dirty = true;
}
}
return !dirty;
}
/**
* Computes the absolute squared Cartesian distance between two points.
*/
private static final double computeDistanceSquared(Point a, double[] b) {
final double dx = a.getX() - b[0];
final double dy = a.getY() - b[1];
return dx * dx + dy * dy;
}
/**
* Calculate a quality metric for the current clustering solution.
* This number is available after each call to {@link #iterate()}.
*
* @return Quality metric for this solution; small is better.
*/
@Override
public double metric() {
return sumDistSquared;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// RNG used to set initial mean values.
private static final Random random = new Random();
// M (power factor) used for calculating weights. Must be > 1.0.
private static final double M = 2.0;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The number of points in the data set on a given pass.
private int numPoints;
// The desired number of clusters.
private int numClusters;
// During a pass -- multiple iterations -- this points to the
// array of data points.
private Point[] dataPoints;
// Cluster IDs to which the points have been assigned by the most
// recent iteration. This will be null if prepare() hasn't been called,
// and is filled in by each call to iterate().
private int[] pointClusters = null;
// Calculated centroid positions of the clusters. This will be null
// if prepare() hasn't been called, and is filled in by each call
// to iterate().
private double[][] clusterMeans = null;
// The sum of the squares of the distances from each point to the mean
// of its assigned cluster in the current solution.
private double sumDistSquared = 0.0;
// For each point p, clusterStrengths[p][c] is its degree of
// belonging to each cluster c.
private double[][] clusterStrengths;
}
| 9,596 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Clusterer.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/cluster/Clusterer.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.cluster;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* A generic interface to a clustering algorithm.
*/
public abstract class Clusterer {
/**
* Prepare a clustering pass on the indicated data.
*
* <p>Subclasses can override this to do their own preparation, but
* must call through to this method.
*
* @param points The array of points to be clustered.
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which to place centroids
* of the clusters.
* @param region The region of the plane in which the points lie.
*/
public void prepare(Point[] points, int[] ids, double[][] means, Region region) {
}
/**
* Runs a single iteration of the clustering algorithm on the stored data.
* The results are stored in the arrays that were passed into
* {@link #prepare(Point[], int[], double[][], Region)}.
*
* <p>After each iteration, the cluster IDs and cluster means should
* be consistent with each other.
*
* @return true if the algorithm has converged.
*/
public abstract boolean iterate();
/**
* Calculate a quality metric for the current clustering solution.
* This number is available after each call to {@link #iterate()}.
*
* @return Quality metric for this solution; small is better.
*/
public abstract double metric();
}
| 2,457 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
KMeansClusterer.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/cluster/KMeansClusterer.java |
/**
* cluster: routines for cluster analysis.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.cluster;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
import org.hermit.geometry.Region;
/**
* An implementation of Lloyd's k-clusterMeans clustering algorithm.
*/
public class KMeansClusterer
extends Clusterer
{
/**
* Prepare a clustering pass on the indicated data.
*
* @param points The array of dataPoints to be clustered.
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which to place centroids
* of the clusters.
* @param region The region of the plane in which the points lie.
*/
@Override
public void prepare(Point[] points, int[] ids, double[][] means, Region region) {
super.prepare(points, ids, means, region);
// Save the data arrays.
dataRegion = region;
dataPoints = points;
pointClusters = ids;
clusterMeans = means;
numPoints = points.length;
numClusters = means.length;
// Make the working data arrays.
sumXs = new int[numClusters];
sumYs = new int[numClusters];
clusterSizes = new int[numClusters];
// Set the initial cluster centroids to be random values
// within the data region.
for (int i = 0; i < numClusters; ++i) {
Point p = dataRegion.randomPoint();
means[i][0] = p.getX();
means[i][1] = p.getY();
}
// Make an initial assignment of points to clusters, so on the first
// iteration we have a basis for computing centroids.
assignPoints(pointClusters, clusterMeans);
}
/**
* Runs a single iteration of the clustering algorithm on the stored data.
* The results are stored in the arrays that were passed into
* {@link #prepare(Point[], int[], double[][], Region)}.
*
* <p>After each iteration, the cluster IDs and cluster means should
* be consistent with each other.
*
* @return true if the algorithm has converged.
*/
@Override
public boolean iterate() {
System.out.println("K-Means: iterate");
// Compute the new centroids of the clusters, based on the existing
// point assignments.
boolean converged = computeCentroids(pointClusters, clusterMeans);
// Assign data points to clusters based on the new centroids.
if (!converged)
assignPoints(pointClusters, clusterMeans);
// Our convergence criterion is no change in the means.
return converged;
}
/**
* Compute the centroids of all the clusters.
*
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which we will place the
* centroids of the clusters.
* @return true iff none of the means moved by a significant
* amount.
*/
private boolean computeCentroids(int[] ids, double[][] means) {
// Clear the working data.
for (int i = 0; i < numClusters; ++i)
sumXs[i] = sumYs[i] = clusterSizes[i] = 0;
// Calculate the sums of the points in each cluster.
for (int i = 0; i < numPoints; ++i) {
Point point = dataPoints[i];
int c = ids[i];
sumXs[c] += point.getX();
sumYs[c] += point.getY();
clusterSizes[c] += 1;
}
// Now calculate the means for each cluster, and see if any has
// changed since the previous round.
boolean dirty = false;
for (int c = 0; c < numClusters; ++c) {
int s = clusterSizes[c];
// If the cluster is empty, assign a random mean. Else calculate
// the average of the points in the cluster.
double nx, ny;
if (s == 0) {
Point p = dataRegion.randomPoint();
nx = p.getX();
ny = p.getY();
} else {
nx = sumXs[c] / s;
ny = sumYs[c] / s;
}
if (!MathTools.eq(means[c][0], nx) || !MathTools.eq(means[c][1], ny)) {
means[c][0] = nx;
means[c][1] = ny;
dirty = true;
}
}
return !dirty;
}
/**
* Assign each point in the data array to the cluster whose centroid
* it is closest to.
*
* @param ids Array of cluster numbers which this call will
* fill in, defining which cluster each point
* belongs to. The caller must leave the data here
* intact between iterations.
* @param means Array of x,y values in which we will place the
* centroids of the clusters.
* @return true iff none of the points changed to a different
* cluster.
*/
private boolean assignPoints(int[] ids, double[][] means) {
// Accumulate the sum of the distances squared between each
// point and its closest mean.
sumDistSquared = 0.0;
// Assign each point to a cluster, according to which cluster
// centroid it is closest to. Set dirty to true if any point
// changes to a different cluster.
boolean dirty = false;
for (int i = 0; i < numPoints; ++i) {
// Find the closest mean to the current data point. Also
// accumulate the sum of the distances squared.
Point point = dataPoints[i];
int closest = -1;
double minDistance = Double.MAX_VALUE;
for (int c = 0; c < means.length; ++c) {
double distance = computeDistanceSquared(point, means[c]);
if (distance < minDistance) {
minDistance = distance;
closest = c;
}
}
sumDistSquared += minDistance;
if (closest != ids[i]) {
ids[i] = closest;
dirty = true;
}
}
return !dirty;
}
/**
* Computes the absolute squared Cartesian distance between two points.
*/
private static final double computeDistanceSquared(Point a, double[] b) {
final double dx = a.getX() - b[0];
final double dy = a.getY() - b[1];
return dx * dx + dy * dy;
}
/**
* Calculate a quality metric for the current clustering solution.
* This number is available after each call to {@link #iterate()}.
*
* @return Quality metric for this solution; small is better.
*/
@Override
public double metric() {
return sumDistSquared;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The region of the plane in which we're working.
private Region dataRegion;
// The number of points in the data set on a given pass.
private int numPoints;
// The desired number of clusters.
private int numClusters;
// During a pass -- multiple iterations -- this points to the
// array of data points.
private Point[] dataPoints;
// Cluster IDs to which the points have been assigned by the most
// recent iteration. This will be null if prepare() hasn't been called,
// and is filled in by each call to iterate().
private int[] pointClusters = null;
// Calculated centroid positions of the clusters. This will be null
// if prepare() hasn't been called, and is filled in by each call
// to iterate().
private double[][] clusterMeans = null;
// The sum of the squares of the distances from each point to the mean
// of its assigned cluster in the current solution.
private double sumDistSquared = 0.0;
// Working data -- sums and counts, used to average the clusters.
private int[] sumXs;
private int[] sumYs;
private int[] clusterSizes;
}
| 9,328 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
CubicSpline.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/spline/CubicSpline.java |
/**
* spline: routines for spline interpolation.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.spline;
import org.hermit.geometry.Point;
/**
* Implementation of a natural cubic spline.
*/
public class CubicSpline
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a cubic spline curve with a specified set of control points.
*
* @param points The control points for this curve.
*/
public CubicSpline(Point[] points) {
final int len = points.length;
if (len < 2)
throw new IllegalArgumentException("A ControlCurve needs" +
" at least 2 control points");
controlPoints = points;
// Flatten out the control points array.
controlsX = new double[len];
controlsY = new double[len];
for (int i = 0; i < len; ++i) {
controlsX[i] = controlPoints[i].getX();
controlsY[i] = controlPoints[i].getY();
}
// Calculate the gamma values just once.
final int n = controlPoints.length - 1;
double[] gamma = new double[n + 1];
gamma[0] = 1.0 / 2.0;
for (int i = 1; i < n; ++i)
gamma[i] = 1 / (4 - gamma[i - 1]);
gamma[n] = 1 / (2 - gamma[n - 1]);
// Calculate the cubic segments.
cubicX = calcNaturalCubic(n, controlsX, gamma);
cubicY = calcNaturalCubic(n, controlsY, gamma);
}
// ******************************************************************** //
// Spline Calculation.
// ******************************************************************** //
/**
* Calculate the natural cubic spline that interpolates x[0-n].
*
* @return The spline as a set of cubic segments, each over the
* range x = [0-1[.
*/
private Cubic[] calcNaturalCubic(int n, double[] x, double[] gamma) {
double[] delta = new double[n + 1];
delta[0] = 3 * (x[1] - x[0]) * gamma[0];
for (int i = 1; i < n; ++i)
delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i];
delta[n] = (3 * (x[n] - x[n - 1])-delta[n - 1]) * gamma[n];
double[] D = new double[n + 1];
D[n] = delta[n];
for (int i = n - 1; i >= 0; --i) {
D[i] = delta[i] - gamma[i] * D[i + 1];
}
// Calculate the cubic segments.
Cubic[] C = new Cubic[n];
for (int i = 0; i < n; i++) {
final double a = x[i];
final double b = D[i];
final double c = 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1];
final double d = 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1];
C[i] = new Cubic(a, b, c, d);
}
return C;
}
/**
* Interpolate the spline.
*
* @param steps The number of steps to interpolate in each segment.
* @return The interpolated values.
*/
public Point[] interpolate(int steps) {
Point[] p = new Point[cubicX.length * steps + 1];
int np = 0;
/* very crude technique - just break each segment up into steps lines */
p[np++] = new Point(cubicX[0].eval(0), cubicY[0].eval(0));
for (int i = 0; i < cubicX.length; i++) {
for (int j = 1; j <= steps; j++) {
double x = (double) j / (double) steps;
p[np++] = new Point(cubicX[i].eval(x), cubicY[i].eval(x));
}
}
return p;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The control points for this curve.
private final Point[] controlPoints;
// The X and Y co-ordinates of the control points.
private final double[] controlsX;
private final double[] controlsY;
// Cubic spline segments. Each segment is a polynomial over the
// range x = [0-1[.
private Cubic[] cubicX;
private Cubic[] cubicY;
}
| 4,882 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Cubic.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/spline/Cubic.java |
/**
* spline: routines for spline interpolation.
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geometry.spline;
/**
* Representation of a cubic polynomial.
*/
public final class Cubic {
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a cubic polynomial of form a + b*x + c*x^2 + d*x^3.
*
* @param a A coefficient.
* @param b B coefficient.
* @param c C coefficient.
* @param d D coefficient.
*/
public Cubic(double a, double b, double c, double d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
// ******************************************************************** //
// Evaluation.
// ******************************************************************** //
/**
* Evaluate the polynomial for a given value.
*
* @param x X value to evaluate for.
* @return The value of the polynomial for the given X.
*/
public double eval(double x) {
return ((d * x + c) * x + b) * x + a;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The coefficients.
private final double a, b, c, d;
}
| 2,132 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Event.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/Event.java | /**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import java.util.ArrayList;
import java.util.HashSet;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
abstract class Event implements Comparable<Event> {
/**
* Note: subclasses override this!
*
* @return
*/
abstract double getX();
/**
* Note: subclasses override this!
*
* @return
*/
abstract double getY();
abstract Node process(Node Root, double ys,
HashSet<Point> vertList,
HashSet<VoronoiEdge> edgeList,
ArrayList<DataNode> CircleCheckList);
public int compareTo(Event ev) {
if (!MathTools.eq(getY(), ev.getY())) {
if (getY() < ev.getY())
return -1;
else if (getY() > ev.getY())
return 1;
} else {
if (getX() < ev.getX())
return -1;
else if (getX() > ev.getX())
return 1;
}
return 0;
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + getX() + "," + getY() + ">";
}
}
| 2,059 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
VoronoiEdge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/VoronoiEdge.java |
/**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import org.hermit.geometry.Edge;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
class VoronoiEdge
{
// ******************************************************************** //
// Building.
// ******************************************************************** //
void AddVertex(Point V) {
if (VVertexA == Point.UNKNOWN)
VVertexA = V;
else if (VVertexB == Point.UNKNOWN)
VVertexB = V;
else
throw new RuntimeException("Tried to add third vertex!");
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Determine whether this edge is infinite.
*
* @return True if both vertices are infinite; false else.
*/
boolean isInfinite() {
return VVertexA == Point.INFINITE && VVertexB == Point.INFINITE;
}
/**
* Determine whether this edge is partly infinite.
*
* @return True if either vertex is infinite; false else.
*/
boolean isPartlyInfinite() {
return VVertexA == Point.INFINITE || VVertexB == Point.INFINITE;
}
// ******************************************************************** //
// Conversion.
// ******************************************************************** //
/**
* Convert this VoronoiEdge to an immutable Edge.
*
* @return An Edge equivalent to this object.
*/
Edge toEdge() {
return new Edge(VVertexA, VVertexB, LeftData, RightData);
}
// ******************************************************************** //
// Package-Visible Data.
// ******************************************************************** //
boolean Done = false;
Point RightData = Point.UNKNOWN, LeftData = Point.UNKNOWN;
Point VVertexA = Point.UNKNOWN, VVertexB = Point.UNKNOWN;
}
| 2,578 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Node.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/Node.java | /**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import org.hermit.geometry.Point;
/**
* VoronoiVertex or VoronoiDataPoint are represented as Vector
*/
abstract class Node {
public Node() {
_Left = null;
_Right = null;
}
public Node(Node left, Node right) {
setLeft(left);
setRight(right);
}
public Node getLeft() {
return _Left;
}
private void setLeft(Node value) {
_Left = value;
value._Parent = this;
}
public Node getRight() {
return _Right;
}
private void setRight(Node value) {
_Right = value;
value._Parent = this;
}
public Node getParent() {
return _Parent;
}
public void Replace(Node ChildOld, Node ChildNew) {
if (_Left == ChildOld)
setLeft(ChildNew);
else if (_Right == ChildOld)
setRight(ChildNew);
else
throw new RuntimeException("Child not found in Node.Replace!");
ChildOld._Parent = null;
}
public static DataNode FirstDataNode(Node Root) {
Node C = Root;
while (C._Left != null)
C = C._Left;
return (DataNode) C;
}
public static DataNode LeftDataNode(DataNode Current) {
Node C = Current;
// 1. Up
do {
if (C._Parent == null)
return null;
if (C._Parent._Left == C) {
C = C._Parent;
continue;
} else {
C = C._Parent;
break;
}
} while (true);
// 2. One Left
C = C._Left;
// 3. Down
while (C._Right != null)
C = C._Right;
return (DataNode) C; // Cast statt 'as' damit eine Exception kommt
}
public static DataNode RightDataNode(DataNode Current) {
Node C = Current;
// 1. Up
do {
if (C._Parent == null)
return null;
if (C._Parent._Right == C) {
C = C._Parent;
continue;
} else {
C = C._Parent;
break;
}
} while (true);
// 2. One Right
C = C._Right;
// 3. Down
while (C._Left != null)
C = C._Left;
return (DataNode) C; // Cast statt 'as' damit eine Exception kommt
}
public static EdgeNode EdgeToRightDataNode(DataNode Current) {
Node C = Current;
// 1. Up
do {
if (C._Parent == null)
throw new RuntimeException("No Left Leaf found!");
if (C._Parent._Right == C) {
C = C._Parent;
continue;
} else {
C = C._Parent;
break;
}
} while (true);
return (EdgeNode) C;
}
public static DataNode FindDataNode(Node Root, double ys, double x) {
Node C = Root;
do {
if (C instanceof DataNode)
return (DataNode) C;
if (((EdgeNode) C).Cut(ys, x) < 0)
C = C._Left;
else
C = C._Right;
} while (true);
}
static Point CircumCircleCenter(Point A, Point B, Point C) {
if (A == B || B == C || A == C)
throw new IllegalArgumentException("Need three different points!");
final double tx = (A.getX() + C.getX()) / 2;
final double ty = (A.getY() + C.getY()) / 2;
final double vx = (B.getX() + C.getX()) / 2;
final double vy = (B.getY() + C.getY()) / 2;
double ux, uy, wx, wy;
if (A.getX() == C.getX()) {
ux = 1;
uy = 0;
} else {
ux = (C.getY() - A.getY()) / (A.getX() - C.getX());
uy = 1;
}
if (B.getX() == C.getX()) {
wx = -1;
wy = 0;
} else {
wx = (B.getY() - C.getY()) / (B.getX() - C.getX());
wy = -1;
}
final double alpha = (wy * (vx - tx) - wx * (vy - ty))
/ (ux * wy - wx * uy);
return new Point(tx + alpha * ux, ty + alpha * uy);
}
void CleanUpTree() {
if (!(this instanceof EdgeNode))
return;
final EdgeNode VE = (EdgeNode) this;
VE.cleanupEdge();
_Left.CleanUpTree();
_Right.CleanUpTree();
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
private Node _Parent = null;
private Node _Left = null, _Right = null;
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return getClass().getSimpleName();
}
/**
* Convert the tree of nodes rooted at this instance to a String
* suitable for display.
*
* @param prefix Prefix for each output line.
*/
public void dump(String prefix) {
System.out.println(prefix + this + " [");
if (_Parent != null)
System.out.println(prefix + " " + "Parent=" + _Parent);
else
System.out.println(prefix + " " + "Parent=<null>");
if (_Left != null)
_Left.dump(prefix + " ");
else
System.out.println(prefix + " " + "<null>");
if (_Right != null)
_Right.dump(prefix + " ");
else
System.out.println(prefix + " " + "<null>");
System.out.println(prefix + "]");
}
}
| 6,466 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Fortune.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/Fortune.java |
/**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.PriorityQueue;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
import org.hermit.geometry.Edge;
import org.hermit.geometry.Graph;
/**
* Fortune's algorithm for generating a Voronoi diagram.
*
* <p>This class takes a set of points in the plane and generates
* the corresponding Voronoi diagram using Fortune's algorithm.
*/
public abstract class Fortune {
// ******************************************************************** //
// Public Methods.
// ******************************************************************** //
/**
* Compute the Voronoi diagram for the given set of points.
*
* @param points The data points.
* @return A Graph representing the generated diagram.
*/
public static Graph ComputeVoronoiGraph(Iterable<Point> points) {
// Create a priority queue of data events for each point,
// and pass that to the main algorithm. Ignore dupes in the
// input points.
final PriorityQueue<Event> queue = new PriorityQueue<Event>();
for (final Point v : points) {
DataEvent ev = new DataEvent(v);
if (!queue.contains(ev))
queue.add(ev);
}
return ComputeVoronoiGraph(queue);
}
/**
* Compute the Voronoi diagram for the given set of points.
*
* @param points The data points.
* @return A Graph representing the generated diagram.
*/
public static Graph ComputeVoronoiGraph(Point[] points) {
// Create a priority queue of data events for each point,
// and pass that to the main algorithm. Ignore dupes in the
// input points.
final PriorityQueue<Event> queue = new PriorityQueue<Event>();
for (final Point v : points) {
DataEvent ev = new DataEvent(v);
if (!queue.contains(ev))
queue.add(ev);
}
return ComputeVoronoiGraph(queue);
}
/**
* Filter the given graph, removing any edges whose data points are
* closer than min.
*
* @param graph The graph to filter.
* @param min The minimum data point separation for any
* edge we wish to keep.
* @return A new Graph, represenging the filtered input
* graph.
*/
public static Graph FilterVG(Graph graph, double min) {
// Go through all the edges, and copy the ones which aren't too
// small to a new edge list.
final HashSet<Edge> edgeList = new HashSet<Edge>();
Iterator<Edge> edges = graph.getEdges();
while (edges.hasNext()) {
Edge e = edges.next();
Point da = e.getDatumA();
Point db = e.getDatumB();
if (da.dist(db) >= min)
edgeList.add(e);
}
// Make a new graph of the new edges.
return new Graph(edgeList);
}
// ******************************************************************** //
// Private Methods.
// ******************************************************************** //
/**
* This routine implements the Fortune algorithm.
*
* @param queue A priority queue of data events for each
* input point.
* @return A Graph representing the generated diagram.
*/
private static Graph ComputeVoronoiGraph(PriorityQueue<Event> queue) {
final HashMap<DataNode, CircleEvent> CurrentCircles = new HashMap<DataNode, CircleEvent>();
final HashSet<Point> vertexList = new HashSet<Point>();
final HashSet<VoronoiEdge> edgeList = new HashSet<VoronoiEdge>();
Node RootNode = null;
while (queue.size() > 0) {
final Event VE = queue.poll();
final ArrayList<DataNode> CircleCheckList = new ArrayList<DataNode>();
if (VE instanceof CircleEvent) {
CircleEvent cev = (CircleEvent) VE;
CurrentCircles.remove(cev.NodeN);
if (!cev.Valid)
continue;
}
RootNode = VE.process(RootNode, VE.getY(), vertexList, edgeList, CircleCheckList);
for (final DataNode VD : CircleCheckList) {
if (CurrentCircles.containsKey(VD)) {
final CircleEvent cev = CurrentCircles.remove(VD);
cev.Valid = false;
}
final CircleEvent VCE = VD.CircleCheckDataNode(VE.getY());
if (VCE != null) {
queue.add(VCE);
CurrentCircles.put(VD, VCE);
}
}
if (VE instanceof DataEvent) {
final Point DP = ((DataEvent) VE).getDatum();
for (final CircleEvent VCE : CurrentCircles.values()) {
double dist = DP.dist(VCE.Center);
double offs = VCE.getY() - VCE.Center.getY();
if (MathTools.lt(dist, offs))
VCE.Valid = false;
}
}
}
RootNode.CleanUpTree();
for (final VoronoiEdge VE : edgeList) {
if (VE.Done)
continue;
if (VE.VVertexB == Point.UNKNOWN) {
VE.AddVertex(Point.INFINITE);
if (MathTools.eq(VE.LeftData.getY(), VE.RightData.getY())
&& VE.LeftData.getX() < VE.RightData.getX()) {
final Point T = VE.LeftData;
VE.LeftData = VE.RightData;
VE.RightData = T;
}
}
}
final ArrayList<VoronoiEdge> MinuteEdges = new ArrayList<VoronoiEdge>();
for (final VoronoiEdge VE : edgeList) {
if (!VE.isPartlyInfinite() && VE.VVertexA.equals(VE.VVertexB)) {
MinuteEdges.add(VE);
// prevent rounding errors from expanding to holes
for (final VoronoiEdge VE2 : edgeList) {
if (VE2.VVertexA.equals(VE.VVertexA))
VE2.VVertexA = VE.VVertexA;
if (VE2.VVertexB.equals(VE.VVertexA))
VE2.VVertexB = VE.VVertexA;
}
}
}
for (final VoronoiEdge VE : MinuteEdges)
edgeList.remove(VE);
// Now build the Graph to pass back to the caller.
final HashSet<Edge> finalEdges = new HashSet<Edge>();
for (final VoronoiEdge VE : edgeList)
finalEdges.add(VE.toEdge());
return new Graph(finalEdges);
}
}
| 7,670 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
CircleEvent.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/CircleEvent.java |
/**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import java.util.ArrayList;
import java.util.HashSet;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
class CircleEvent extends Event {
CircleEvent(DataNode n, DataNode l, DataNode r, Point c) {
NodeN = n;
NodeL = l;
NodeR = r;
Center = c;
Valid = true;
}
@Override
public double getX() {
return Center.getX();
}
@Override
public double getY() {
double dist = NodeN.DataPoint.dist(Center);
return MathTools.round(Center.getY() + dist);
}
@Override
Node process(Node Root, double ys,
HashSet<Point> vertList,
HashSet<VoronoiEdge> edgeList,
ArrayList<DataNode> CircleCheckList)
{
final DataNode b = NodeN;
final DataNode a = Node.LeftDataNode(b);
final DataNode c = Node.RightDataNode(b);
if (a == null || b.getParent() == null || c == null
|| !a.DataPoint.equals(NodeL.DataPoint)
|| !c.DataPoint.equals(NodeR.DataPoint)) {
// Abbruch da sich der Graph ver�ndert hat
return Root;
}
final EdgeNode eu = (EdgeNode) b.getParent();
CircleCheckList.add(a);
CircleCheckList.add(c);
// 1. Create the new Vertex
final Point VNew = new Point(Center.getX(), Center.getY());
// VNew[0] =
// Fortune.ParabolicCut(a.DataPoint[0],a.DataPoint[1],c.DataPoint[0],c.DataPoint[1],ys);
// VNew[1] = (ys + a.DataPoint[1])/2 -
// 1/(2*(ys-a.DataPoint[1]))*(VNew[0]-a.DataPoint[0])*(VNew[0]-a.DataPoint[0]);
vertList.add(VNew);
// 2. Find out if a or c are in a distand part of the tree (the other
// is then b's sibling) and assign the new vertex
EdgeNode eo;
final Node eleft = eu.getLeft();
final Node eright = eu.getRight();
if (eleft == b) {
// c is sibling
eo = Node.EdgeToRightDataNode(a);
// replace eu by eu's Right
eu.getParent().Replace(eu, eright);
} else {
// a is sibling
eo = Node.EdgeToRightDataNode(b);
// replace eu by eu's Left
eu.getParent().Replace(eu, eleft);
}
eu.Edge.AddVertex(VNew);
// ///////////////////// uncertain
// if(eo==eu)
// return Root;
// /////////////////////
// complete & cleanup eo
eo.Edge.AddVertex(VNew);
// while(eo.Edge.VVertexB == Fortune.VVUnkown)
// {
// eo.Flipped = !eo.Flipped;
// eo.Edge.AddVertex(Fortune.VVInfinite);
// }
// if(eo.Flipped)
// {
// Vector T = eo.Edge.LeftData;
// eo.Edge.LeftData = eo.Edge.RightData;
// eo.Edge.RightData = T;
// }
// 2. Replace eo by new Edge
final VoronoiEdge VE = new VoronoiEdge();
VE.LeftData = a.DataPoint;
VE.RightData = c.DataPoint;
VE.AddVertex(VNew);
edgeList.add(VE);
final EdgeNode VEN = new EdgeNode(VE, false, eo.getLeft(), eo
.getRight());
final Node parent = eo.getParent();
if (parent == null)
return VEN;
parent.Replace(eo, VEN);
return Root;
}
DataNode NodeN, NodeL, NodeR;
Point Center;
public boolean Valid = true;
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + getX() + "," + getY() + "::" + (Valid ? "" : "!!!") + NodeN + "," + Center + ">";
}
}
| 4,534 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DataEvent.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/DataEvent.java |
/**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import java.util.ArrayList;
import java.util.HashSet;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
class DataEvent extends Event {
public DataEvent(Point DP) {
DataPoint = DP;
}
@Override
public double getX() {
return DataPoint.getX();
}
@Override
public double getY() {
return DataPoint.getY();
}
public Point getDatum() {
return DataPoint;
}
/**
* Will return the new root (unchanged except in start-up)
*/
@Override
Node process(Node Root, double ys,
HashSet<Point> vertList,
HashSet<VoronoiEdge> edgeList,
ArrayList<DataNode> CircleCheckList)
{
if (Root == null) {
Root = new DataNode(DataPoint);
CircleCheckList.add((DataNode) Root);
return Root;
}
// 1. Find the node to be replaced
final Node C = Node.FindDataNode(Root, ys, DataPoint.getX());
// 2. Create the subtree (ONE Edge, but two VEdgeNodes)
final VoronoiEdge VE = new VoronoiEdge();
VE.LeftData = ((DataNode) C).DataPoint;
VE.RightData = DataPoint;
VE.VVertexA = Point.UNKNOWN;
VE.VVertexB = Point.UNKNOWN;
edgeList.add(VE);
Node SubRoot;
if (MathTools.eq(VE.LeftData.getY(), VE.RightData.getY())) {
DataNode l, r;
if (VE.LeftData.getX() < VE.RightData.getX()) {
l = new DataNode(VE.LeftData);
r = new DataNode(VE.RightData);
SubRoot = new EdgeNode(VE, false, l, r);
} else {
l = new DataNode(VE.RightData);
r = new DataNode(VE.LeftData);
SubRoot = new EdgeNode(VE, true, l, r);
}
CircleCheckList.add(l);
CircleCheckList.add(r);
} else {
DataNode l = new DataNode(VE.LeftData);
DataNode rl = new DataNode(VE.RightData);
DataNode rr = new DataNode(VE.LeftData);
EdgeNode r = new EdgeNode(VE, true, rl, rr);
SubRoot = new EdgeNode(VE, false, l, r);
CircleCheckList.add(l);
CircleCheckList.add(rl);
CircleCheckList.add(rr);
}
// 3. Apply subtree
Node parent = C.getParent();
if (parent == null)
return SubRoot;
parent.Replace(C, SubRoot);
return Root;
}
// ******************************************************************** //
// Sorting Support.
// ******************************************************************** //
/**
* Indicates whether some other object is "equal to" this one.
* This method implements an equivalence relation
* on non-null object references.
*
* <p>This method simply compares the co-ordinates of the two points,
* with a limited precision.
*
* <p>Note that the precision of the test is limited by the precision
* set in {@link MathTools#setPrecision(double)}. That is, only as
* many fractional digits are compared as configured there; hence,
* two very close points will be considered equal.
*
* @param obj The reference object with which to compare.
* @return true if this object is the same as the obj
* argument, to within the given precision;
* false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof DataEvent))
return false;
final DataEvent o = (DataEvent) obj;
return DataPoint.equals(o.DataPoint);
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return "<" + getX() + "," + getY() + ">";
}
private Point DataPoint;
}
| 4,810 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
EdgeNode.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/EdgeNode.java | /**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import org.hermit.geometry.MathTools;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
class EdgeNode extends Node {
EdgeNode(VoronoiEdge E, boolean Flipped, Node left, Node right) {
super(left, right);
Edge = E;
this.Flipped = Flipped;
}
double Cut(double ys, double x) {
final double l0 = Edge.LeftData.getX();
final double l1 = Edge.LeftData.getY();
final double r0 = Edge.RightData.getX();
final double r1 = Edge.RightData.getY();
double delta;
if (!Flipped)
delta = ParabolicCut(l0, l1, r0, r1, ys);
else
delta = ParabolicCut(r0, r1, l0, l1, ys);
return MathTools.round(x - delta);
}
private static double ParabolicCut(double x1, double y1, double x2, double y2,
double ys) {
// y1=-y1;
// y2=-y2;
// ys=-ys;
//
if (MathTools.eq(x1, x2) && MathTools.eq(y1, y2))
// if(y1>y2)
// return double.PositiveInfinity;
// if(y1<y2)
// return double.NegativeInfinity;
// return x;
throw new IllegalArgumentException(
"Identical datapoints are not allowed!");
if (MathTools.eq(y1, ys) && MathTools.eq(y2, ys))
return (x1 + x2) / 2;
if (MathTools.eq(y1, ys))
return x1;
if (MathTools.eq(y2, ys))
return x2;
final double a1 = 1 / (2 * (y1 - ys));
final double a2 = 1 / (2 * (y2 - ys));
if (MathTools.eq(a1, a2))
return (x1 + x2) / 2;
double xs1 = 0.5
/ (2 * a1 - 2 * a2)
* (4 * a1 * x1 - 4 * a2 * x2 + 2 * Math.sqrt(-8 * a1 * x1 * a2
* x2 - 2 * a1 * y1 + 2 * a1 * y2 + 4 * a1 * a2 * x2
* x2 + 2 * a2 * y1 + 4 * a2 * a1 * x1 * x1 - 2 * a2
* y2));
double xs2 = 0.5
/ (2 * a1 - 2 * a2)
* (4 * a1 * x1 - 4 * a2 * x2 - 2 * Math.sqrt(-8 * a1 * x1 * a2
* x2 - 2 * a1 * y1 + 2 * a1 * y2 + 4 * a1 * a2 * x2
* x2 + 2 * a2 * y1 + 4 * a2 * a1 * x1 * x1 - 2 * a2
* y2));
xs1 = MathTools.round(xs1);
xs2 = MathTools.round(xs2);
if (xs1 > xs2) {
final double h = xs1;
xs1 = xs2;
xs2 = h;
}
if (y1 >= y2)
return xs2;
return xs1;
}
void cleanupEdge() {
while (Edge.VVertexB == Point.UNKNOWN)
Edge.AddVertex(Point.INFINITE);
// VE.Flipped = !VE.Flipped;
if (Flipped) {
final Point T = Edge.LeftData;
Edge.LeftData = Edge.RightData;
Edge.RightData = T;
}
Edge.Done = true;
}
VoronoiEdge Edge;
private boolean Flipped;
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return super.toString() + (Flipped ? "!" : "") + Edge;
}
}
| 3,952 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DataNode.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geometry/voronoi/DataNode.java |
/**
* bentools: Voronoi diagram generator. This is Benjamin Dittes'
* C# implementation of Fortune's algorithm, translated to Java
* by Ian Cameron Smith.
*
* <p>The only license info I can see: "If you ever need a voronoi
* clustering in C#, feel free to use my solution here." See
* http://bdittes.googlepages.com/
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.hermit.geometry.voronoi;
import org.hermit.geometry.Point;
/**
* @author clint
*
*/
class DataNode extends Node {
public DataNode(Point DP) {
DataPoint = DP;
}
public DataNode(Event P) {
DataPoint = new Point(P.getX(), P.getY());
}
public Point DataPoint;
CircleEvent CircleCheckDataNode(double ys) {
final DataNode l = Node.LeftDataNode(this);
final DataNode r = Node.RightDataNode(this);
if (l == null || r == null || l.DataPoint == r.DataPoint
|| l.DataPoint == DataPoint || DataPoint == r.DataPoint)
return null;
if (ccw(l.DataPoint, DataPoint, r.DataPoint) <= 0)
return null;
final Point Center = CircumCircleCenter(l.DataPoint,
DataPoint, r.DataPoint);
final CircleEvent VC = new CircleEvent(this, l, r, Center);
if (VC.getY() >= ys)
return VC;
return null;
}
private static int ccw(Point P0, Point P1, Point P2) {
double dx1, dx2, dy1, dy2;
dx1 = P1.getX() - P0.getX();
dy1 = P1.getY() - P0.getY();
dx2 = P2.getX() - P0.getX();
dy2 = P2.getY() - P0.getY();
if (dx1 * dy2 > dy1 * dx2)
return +1;
if (dx1 * dy2 < dy1 * dx2)
return -1;
if (dx1 * dx2 < 0 || dy1 * dy2 < 0)
return -1;
return 0;
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Convert this instance to a String suitable for display.
*
* @return String representation of this instance.
*/
@Override
public String toString() {
return super.toString() + DataPoint;
}
}
| 2,396 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
CharFormatter.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/utils/CharFormatter.java |
/**
* utils: general utility functions.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.utils;
/**
* Utilities for quickly formatting numbers into character buffers, without
* memory allocations. These routines are much faster than using
* String.format, and can be used to avoid GC.
*
* @author Ian Cameron Smith
*/
public class CharFormatter
{
// ******************************************************************** //
// Private Constructors.
// ******************************************************************** //
/**
* No instances of this class.
*/
private CharFormatter() {
}
// ************************************************************************ //
// Static Formatting Utilities.
// ************************************************************************ //
/**
* Fill a field of a given width with spaces.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param field Width of the field to blank. -1 means use
* all available space.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static final void blank(char[] buf, int off, int field)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
for (int i = 0; i < field; ++i)
buf[off + i] = ' ';
}
/**
* Format a string left-aligned into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static final void formatString(char[] buf, int off, String val,
int field)
{
formatString(buf, off, val, field, false);
}
/**
* Format a string into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @param right Iff true, format the text right-aligned; else
* left-aligned.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static final void formatString(char[] buf, int off, String val,
int field, boolean right)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
if (val == null || val.length() == 0) {
blank(buf, off, field);
return;
}
int strlen = val.length();
int len = val.length() < field ? val.length() : field;
int pad = field - len;
if (!right)
val.getChars(0, len, buf, off);
else
val.getChars(strlen - len, strlen, buf, off + pad);
int pads = !right ? off + len : off;
for (int i = 0; i < pad; ++i)
buf[pads + i] = ' ';
}
/**
* Format a single character into a fixed-width field. The remainder
* is filled with spaces. MUCH faster than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @param right Iff true, format the text right-aligned; else
* left-aligned.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static final void formatChar(char[] buf, int off, char val,
int field, boolean right)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
if (val == 0 || field < 1) {
blank(buf, off, field);
return;
}
int pad = field - 1;
if (!right)
buf[off] = val;
else
buf[off + pad] = val;
int pads = !right ? off + 1 : off;
for (int i = 0; i < pad; ++i)
buf[pads + i] = ' ';
}
/**
* Format an integer right-aligned into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space. The value will be padded
* on the left with spaces if smaller than the field.
* @param signed Iff true, add a sign character, space for
* positive, '-' for negative. This takes
* up one place in the given field width.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
* @throws IllegalArgumentException Negative value given and
* signed == false.
*/
public static final void formatInt(char[] buf, int off, int val,
int field, boolean signed)
{
formatInt(buf, off, val, field, signed, false);
}
/**
* Format an integer right-aligned into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @param signed Iff true, add a sign character, space for
* positive, '-' for negative. This takes
* up one place in the given field width.
* @param lz Iff true, pad with leading zeros; otherwise,
* pad on the left with spaces.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
* @throws IllegalArgumentException Negative value given and
* signed == false.
*/
public static final void formatInt(char[] buf, int off, int val,
int field, boolean signed, boolean lz)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
// If the value is negative but field is unsigned, just put in an
// error indicator.
if (!signed && val < 0) {
formatChar(buf, off, '-', field, true);
return;
}
int sign = val >= 0 ? 1 : -1;
val *= sign;
char schar = signed ? (sign < 0 ? '-' : ' ') : 0;
try {
formatInt(buf, off, val, field, schar, lz);
} catch (OverflowException e) {
formatChar(buf, off, '+', field, true);
}
}
/**
* Format an integer left-aligned into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space. If the value is smaller
* than the field, pads on the right with space.
* @param signed Iff true, add a sign character, space for
* positive, '-' for negative. This takes
* up one place in the given field width, so positive
* values will have a space on the left. Iff false,
* no space is taken for the sign; values must
* be positive, and will begin in the first position.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
* @throws IllegalArgumentException Negative value given and
* signed == false.
*/
public static final void formatIntLeft(char[] buf, int off, int val,
int field, boolean signed)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
// If the value is negative but field is unsigned, just put in an
// error indicator.
if (!signed && val < 0) {
formatChar(buf, off, '-', field, false);
return;
}
int sign = val >= 0 ? 1 : -1;
val *= sign;
char schar = signed ? (sign < 0 ? '-' : ' ') : 0;
try {
formatIntLeft(buf, off, val, field, schar);
} catch (OverflowException e) {
formatChar(buf, off, '+', field, false);
}
}
/**
* Format an unsigned integer into a fixed-width field in hexadecimal.
* MUCH faster than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static final void formatHex(char[] buf, int off, int val, int field)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
if (field < 1)
throw new IllegalArgumentException("Field <" + field + "> too small");
for (int i = off + field - 1; i >= off; --i) {
int d = val % 16;
buf[i] = d < 10 ? (char) ('0' + d) : (char) ('a' + d - 10);
val /= 16;
}
// We should have used up all the value. If not, then the value
// doesn't fit; just put in an error indicator.
if (val != 0)
formatChar(buf, off, '+', field, true);
}
/**
* Format a floating-point value into a fixed-width field, with sign.
* MUCH faster than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @param frac Number of digits after the decimal.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
* @throws IllegalArgumentException Negative value given and
* signed == false.
*/
public static final void formatFloat(char[] buf, int off, double val,
int field, int frac)
{
formatFloat(buf, off, val, field, frac, true);
}
/**
* Format a floating-point value into a fixed-width field. MUCH faster
* than String.format.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format.
* @param field Width of the field to format in. -1 means use
* all available space.
* @param frac Number of digits after the decimal.
* @param signed Iff true, add a sign character, space for
* positive, '-' for negative. This takes
* up one place in the given field width.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
* @throws IllegalArgumentException Negative value given and
* signed == false.
*/
public static final void formatFloat(char[] buf, int off, double val,
int field, int frac, boolean signed)
{
if (field < 0)
field = buf.length - off;
if (field < 0)
field = 0;
if (off + field > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + field);
// If the value is negative but field is unsigned, just put in an
// error indicator.
if (!signed && val < 0) {
formatChar(buf, off, '-', field, true);
return;
}
int intDigits = field - frac - 1;
int sign = val >= 0 ? 1 : -1;
val *= sign;
char schar = signed ? (sign < 0 ? '-' : ' ') : 0;
int intPart = (int) val;
double fracPart = val - intPart;
for (int i = 0; i < frac; ++i)
fracPart *= 10;
try {
formatInt(buf, off, intPart, intDigits, schar, false);
buf[off + intDigits] = '.';
formatInt(buf, off + intDigits + 1, (int) fracPart, frac, (char) 0, true);
} catch (OverflowException e) {
formatChar(buf, off, '+', field, true);
}
}
/**
* Internal integer formatter.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format. Must not be negative.
* @param field Width of the field to format in. Must not be
* negative.
* @param schar Iff not zero, add this sign character. This takes
* up one place in the given field width.
* @param leadZero Iff true, pad on the left with leading zeros
* instead of spaces.
* @throws IllegalArgumentException Field width is too small.
* @throws OverflowException Overflow: the value is too big to be
* formatted into the field.
*/
private static final void formatInt(char[] buf, int off, int val,
int field, char schar, boolean leadZero)
throws IllegalArgumentException, OverflowException
{
int intDigits = field - (schar != 0 ? 1 : 0);
if (intDigits < 1)
throw new IllegalArgumentException("Field <" + field + "> too small");
int last = 0;
for (int i = off + field - 1; i >= off + field - intDigits; --i) {
if (val == 0 && !leadZero && i < off + field - 1) {
buf[i] = ' ';
} else {
buf[i] = val == 0 ? '0' : (char) ('0' + val % 10);
val /= 10;
last = i;
}
}
// We should have used up all the value. If not, then the value
// doesn't fit; just put in an error indicator.
if (val != 0) {
formatChar(buf, off, '+', field, true);
throw new OverflowException();
}
if (schar != 0) {
buf[off] = ' ';
buf[last - 1] = schar;
}
}
/**
* Internal integer formatter for left-aligned values.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param val The value to format. Must not be negative.
* @param field Width of the field to format in. Must not be
* negative. If the number is narrower than the
* field, it will be right-padded with space.
* @param schar Iff not zero, add this sign character. This takes
* up one place in the given field width.
* @throws IllegalArgumentException Field width is too small.
* @throws OverflowException Overflow: the value is too big to be
* formatted into the field.
*/
private static final void formatIntLeft(char[] buf, int off, int val,
int field, char schar)
throws IllegalArgumentException, OverflowException
{
// Check that we have space for the sign and at least 1 digit.
int intDigits = field - (schar != 0 ? 1 : 0);
if (intDigits < 1)
throw new IllegalArgumentException("Field <" + field + "> too small");
// Count the digits in the value.
int valDigits = 1;
int v = val / 10;
while (v > 0) {
v /= 10;
++valDigits;
}
// If the value doesn't fit, just put in an error indicator and bail.
if (intDigits < valDigits) {
formatChar(buf, off, '+', field, false);
throw new OverflowException();
}
// First, put in the sign if any.
int index = off;
if (schar != 0)
buf[index++] = schar;
// Now the digits.
for (int i = index + valDigits - 1; i >= index; --i) {
buf[i] = val == 0 ? '0' : (char) ('0' + val % 10);
val /= 10;
}
index += valDigits;
// Now pad out with spaces.
while (index < off + field)
buf[index++] = ' ';
}
/**
* Format an angle for user display in degrees and minutes.
* Negative angles are formatted with a "-" sign, as in
* "-171°15.165'". Place the result in the supplied buffer.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param angle The angle to format.
* @return Number of characters written.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static int formatDegMin(char[] buf, int off, double angle)
{
return formatDegMin(buf, off, angle, ' ', '-', false);
}
/**
* Format an angle as a string in the format
* "W171°15.165'". Place the result in the supplied buffer.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param angle The angle to format.
* @param pos Sign character to use if positive.
* @param neg Sign character to use if negative.
* @param space If true, leave a space after the sign and degrees.
* Otherwise pack them.
* @return Number of characters written.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static int formatDegMin(char[] buf, int off, double angle,
char pos, char neg, boolean space)
{
if (off + (space ? 14 : 12) > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + (space ? 14 : 12));
int p = off;
if (angle < 0) {
buf[p++] = neg;
angle = -angle;
} else
buf[p++] = pos;
if (space)
buf[p++] = ' ';
int deg = (int) angle;
int min = (int) (angle * 60.0 % 60.0);
int frac = (int) (angle * 60000.0 % 1000.0);
try {
formatInt(buf, p, deg, 3, (char) 0, false);
p += 3;
buf[p++] = '°';
if (space)
buf[p++] = ' ';
formatInt(buf, p, min, 2, (char) 0, true);
p += 2;
buf[p++] = '.';
formatInt(buf, p, frac, 3, (char) 0, true);
p += 3;
buf[p++] = '\'';
} catch (OverflowException e) {
formatChar(buf, p, '+', 1, true);
}
return p - off;
}
/**
* Format a latitude and longitude for user display in degrees and
* minutes. Place the result in the supplied buffer.
*
* @param buf Buffer to place the result in.
* @param off Offset within buf to start writing at.
* @param lat The latitude.
* @param lon The longitude.
* @param space If true, leave a space after the sign and degrees.
* Otherwise pack them.
* @return Number of characters written.
* @throws ArrayIndexOutOfBoundsException Buffer is too small.
*/
public static int formatLatLon(char[] buf, int off,
double lat, double lon, boolean space)
{
if (off + (space ? 29 : 25) > buf.length)
throw new ArrayIndexOutOfBoundsException("Buffer [" + buf.length +
"] too small for " +
off + "+" + (space ? 29 : 25));
int p = off;
p += formatDegMin(buf, off, lat, 'N', 'S', space);
buf[p++] = ' ';
p += formatDegMin(buf, off, lon, 'E', 'W', space);
return p - off;
}
// ******************************************************************** //
// Private Classes.
// ******************************************************************** //
private static final class OverflowException extends Exception {
private static final long serialVersionUID = -6009530000597939453L;
}
}
| 24,357 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Bitwise.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/utils/Bitwise.java |
/**
* utils: general utility functions.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.utils;
/**
* A set of bit-twiddling utilities.
*
* @author Ian Cameron Smith
*/
public class Bitwise
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* This class is not constructible.
*/
private Bitwise() {
}
// ******************************************************************** //
// Number Properties.
// ******************************************************************** //
/**
* Returns true if the argument is power of 2.
*
* @param n The number to test.
* @return true if the argument is power of 2.
*/
public static final boolean isPowerOf2(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
// ******************************************************************** //
// Bit Order Reversal.
// ******************************************************************** //
/**
* Reverse the lowest n bits of j. This function is useful in the
* Cooley–Tukey FFT algorithm, for example.
*
* @param j Number to be reversed.
* @param n Number of low-order bits of j which are significant
* and to be reversed.
* @return The lowest n bits of the input value j, reversed.
* The higher-order bits will be zero.
*/
public static final int bitrev(int j, int n) {
int r = 0;
for (int i = 0; i < n; ++i, j >>= 1)
r = (r << 1) | (j & 0x0001);
return r;
}
}
| 2,409 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TimeUtils.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/utils/TimeUtils.java |
/**
* utils: general utility functions.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.utils;
import java.util.TimeZone;
/**
* Utilities for handling and formatting dates and times.
*
* @author Ian Cameron Smith
*/
public class TimeUtils
{
// ************************************************************************ //
// Public Constructors.
// ************************************************************************ //
/**
* Constructor -- disallow instantiation.
*/
private TimeUtils() { }
// ************************************************************************ //
// Formatting.
// ************************************************************************ //
/**
* Format a time of day in ms as hours and minutes, in 24-hour clock format.
*
* @param time The time in ms to format.
* @return The formatted value.
*/
public static String timeMsToHm(long time) {
// Convert to minutes.
time /= 60 * 1000;
int hour = (int) time / 60;
int min = (int) time % 60;
StringBuilder hm = new StringBuilder(5);
hm.setLength(5);
hm.setCharAt(0, (char) ('0' + hour / 10));
hm.setCharAt(1, (char) ('0' + hour % 10));
hm.setCharAt(2, ':');
hm.setCharAt(3, (char) ('0' + min / 10));
hm.setCharAt(4, (char) ('0' + min % 10));
return hm.toString();
}
/**
* Format a time offset as hours, minutes and seconds, only including
* the relevant components. If the offset is less than 60 sec, only
* the seconds will be included; if the offset is an exact number of
* hours, only hours; etc.
*
* @param off The time offset in ms to format.
* @return The formatted value.
*/
public static String intervalMsToHmsShort(long off) {
if (off == 0)
return "";
String hms = "";
off /= 1000;
if (off >= 0) {
hms += "+";
} else {
hms += "-";
off = -off;
}
if (off >= 3600) {
hms += (off / 3600) + "h";
off = off % 3600;
}
if (off >= 60) {
hms += (off / 60) + "m";
off = off % 60;
}
if (off > 0)
hms += off + "s";
return hms;
}
/**
* Produce a string describing the offset of the given time zone from
* UTC, including the DST offset if there is one.
*
* @param zone TimeZone whose offset we want.
* @return Formatted offset.
*/
public static String formatOffset(TimeZone zone) {
String fmt = "";
int base = zone.getRawOffset();
fmt += "UTC" + intervalMsToHmsShort(base);
int dst = zone.getDSTSavings();
if (dst != 0)
fmt += " (UTC" + intervalMsToHmsShort(base + dst) + ")";
return fmt;
}
/**
* Produce a string describing the offset of the given time zone from
* UTC, including the DST offset if there is one.
*
* @param zone TimeZone whose offset we want.
* @return Formatted offset.
*/
public static String formatOffsetFull(TimeZone zone) {
String fmt = zone.getID() + ": ";
int base = zone.getRawOffset();
fmt += zone.getDisplayName(false, TimeZone.LONG) + "=UTC" + intervalMsToHmsShort(base);
int dst = zone.getDSTSavings();
if (dst != 0)
fmt += " (" + zone.getDisplayName(true, TimeZone.LONG) + "=UTC" + intervalMsToHmsShort(base + dst) + ")";
return fmt;
}
}
| 4,115 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Angle.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/utils/Angle.java |
/**
* utils: general utility functions.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.utils;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.round;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
import java.text.NumberFormat;
/**
* Utilities for handling and formatting angles, including latitudes
* and longitudes.
*
* @author Ian Cameron Smith
*/
public class Angle
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Half pi; a quarter circle in radians; same as 90 degrees.
*/
public static final double HALFPI = PI / 2;
/**
* Two times pi; a circle in radians; same as 360 degrees.
*/
public static final double TWOPI = PI * 2;
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create an Angle from an angle given in radians.
*
* @param radians Source angle in radians.
*/
public Angle(double radians) {
angleR = radians;
}
// ******************************************************************** //
// Accessors and Converters.
// ******************************************************************** //
/**
* Create a Angle from an angle given in degrees.
*
* @param degrees Source angle in degrees.
* @return The corresponding Angle.
*/
public static Angle fromDegrees(double degrees) {
return new Angle(toRadians(degrees));
}
/**
* Create a Angle from an angle given in degrees, minutes
* and seconds.
*
* <p>If any of the parameters is negative, the result is negative.
*
* @param d Whole degrees.
* @param m Minutes.
* @param s Seconds.
* @return The corresponding Angle.
*/
public static Angle fromDegrees(int d, int m, double s) {
boolean neg = d < 0 || m < 0 || s < 0;
double df = ((abs(s) / 60.0 + abs(m)) / 60.0 + abs(d));
return new Angle(toRadians(neg ? -df : df));
}
/**
* Create a Angle from a right ascension given in hours, minutes
* and seconds.
*
* <p>If any of the parameters is negative, the result is negative
* (though they really shouldn't be).
*
* @param rh Hours of right ascension.
* @param rm Minutes of right ascension.
* @param rs Seconds of right ascension.
* @return The corresponding Angle.
*/
public static Angle fromRightAscension(int rh, int rm, double rs) {
boolean neg = rh < 0 || rm < 0 || rs < 0;
double ra = ((abs(rs) / 60.0 + abs(rm)) / 60.0 + abs(rh)) * 15.0;
return new Angle(toRadians(neg ? -ra : ra));
}
/**
* Get the angle in radians.
*
* @return The angle in radians.
*/
public final double getRadians() {
return angleR;
}
/**
* Get the azimuth in degrees.
*
* @return The azimuth in degrees, clockwise from north.
* This will be in the range 0 <= degrees < 360.0.
*/
public final double getDegrees() {
return toDegrees(angleR);
}
// ******************************************************************** //
// Azimuth Arithmetic.
// ******************************************************************** //
/**
* Calculate the azimuth which is the given angular offset from this one.
*
* @param radians Offset to add to this Azimuth, in radians;
* positive is clockwise from north, may be
* negative.
* @return Azimuth which is equal to this Azimuth plus
* the given offset. Overflow is taken care of.
*/
public Angle add(double radians) {
return new Angle(angleR + radians);
}
// ******************************************************************** //
// Conversions.
// ******************************************************************** //
/**
* Return the given value mod PI, with negative values made positive --
* in other words, the value put into the range [0 .. PI).
*
* @param v Input value.
* @return v % PI, plus PI if negative.
*/
public static final double modPi(double v) {
v %= PI;
return v < 0 ? v + PI : v;
}
/**
* Return the given value mod 2*PI, with negative values made positive --
* in other words, the value put into the range [0 .. TWOPI).
*
* @param v Input value.
* @return v % TWOPI, plus TWOPI if negative.
*/
public static final double modTwoPi(double v) {
v %= TWOPI;
return v < 0 ? v + TWOPI : v;
}
// ******************************************************************** //
// Formatting.
// ******************************************************************** //
/**
* Format this azimuth for user display in degrees.
*
* @return The formatted azimuth.
*/
public String formatDeg() {
return String.format("%d°", round(toDegrees(angleR)));
}
/**
* Format this azimuth for user display in degrees and minutes.
*
* @return The formatted azimuth.
*/
public String formatDegMin() {
return Angle.formatDegMin(toDegrees(angleR)) + '°';
}
/**
* Format this azimuth for user display in degrees and minutes.
*
* @return The formatted azimuth.
*/
public String formatDegMinSec() {
return Angle.formatDegMinSec(toDegrees(angleR)) + '°';
}
/**
* Format this azimuth as a String.
*
* @return This azimuth as a string, in degrees.
*/
@Override
public String toString() {
return formatDeg();
}
// ************************************************************************ //
// Static Formatting Utilities.
// ************************************************************************ //
/**
* Format a floating-point value.
*
* @param val The value to format.
* @param frac Maximum number of digits after the point.
* @return The formatted value.
*/
public static String formatFloat(double val, int frac) {
floatFormat.setMaximumFractionDigits(frac);
return floatFormat.format(val);
}
/**
* Format an angle as a bearing.
*
* @param val The value to format.
* @return The formatted value.
*/
public static String formatBearing(double val) {
return Math.round(val) + "°";
}
/**
* Format an angle for user display in degrees and minutes.
* Negative angles are formatted with a "-" sign.
*
* @param angle The angle to format.
* @return The formatted angle.
*/
public static String formatDegMin(double angle) {
return formatDegMin(angle, ' ', '-');
}
/**
* Format a latitude or longitude angle as a string in the format
* "W171° 15.165'".
*
* @param angle Angle to format.
* @param pos Sign character to use if positive.
* @param neg Sign character to use if negative.
* @return The formatted angle.
*/
public static String formatDegMin(double angle, char pos, char neg) {
StringBuilder sb = new StringBuilder(12);
formatDegMin(angle, pos, neg, sb);
return sb.toString();
}
/**
* Format a latitude or longitude angle as a string in the format
* "W171°15.165'". Place the result in a supplied StringBuilder.
*
* The StringBuilder will be set to the required length, 12. For
* best efficiency, leave it at that length.
*
* @param angle Angle to format.
* @param pos Sign character to use if positive.
* @param neg Sign character to use if negative.
* @param sb StringBuilder to write the result into.
*/
public static void formatDegMin(double angle,
char pos, char neg, StringBuilder sb)
{
if (sb.length() != 12)
sb.setLength(12);
if (angle < 0) {
sb.setCharAt(0, neg);
angle = -angle;
} else
sb.setCharAt(0, pos);
int deg = (int) angle;
int min = (int) (angle * 60.0 % 60.0);
int frac = (int) (angle * 60000.0 % 1000.0);
sb.setCharAt( 1, deg < 100 ? ' ' : (char) ('0' + deg / 100));
sb.setCharAt( 2, deg < 10 ? ' ' : (char) ('0' + deg / 10 % 10));
sb.setCharAt( 3, (char) ('0' + deg % 10));
sb.setCharAt( 4, '°');
sb.setCharAt( 5, (char) ('0' + min / 10));
sb.setCharAt( 6, (char) ('0' + min % 10));
sb.setCharAt( 7, '.');
sb.setCharAt( 8, (char) ('0' + frac / 100));
sb.setCharAt( 9, (char) ('0' + frac / 10 % 10));
sb.setCharAt(10, (char) ('0' + frac % 10));
sb.setCharAt(11, '\'');
}
/**
* Format an angle for user display in degrees and minutes.
*
* @param angle The angle to format.
* @return The formatted angle.
*/
public static String formatDegMinSec(double angle) {
return formatDegMinSec(angle, ' ', '-');
}
/**
* Format an angle for user display in degrees and minutes.
*
* @param angle The angle to format.
* @param posSign Sign to use for positive values; none if null.
* @param negSign Sign to use for negative values; none if null.
* @return The formatted angle.
*/
public static String formatDegMinSec(double angle, char posSign, char negSign) {
char sign = angle >= 0 ? posSign : negSign;
angle = Math.abs(angle);
int deg = (int) angle;
angle = (angle - deg) * 60.0;
int min = (int) angle;
angle = (angle - min) * 60.0;
double sec = angle;
// Rounding errors?
if (sec >= 60.0) {
sec = 0;
++min;
}
if (min >= 60) {
min -= 60;
++deg;
}
return String.format("%s%3d° %2d' %8.5f\"", sign, deg, min, sec);
//return sign + deg + "° " + min + "' " + angleFormat.format(sec) + "\"";
}
/**
* Format a latitude and longitude for user display in degrees and
* minutes.
*
* @param lat The latitude.
* @param lon The longitude.
* @return The formatted angle.
*/
public static String formatLatLon(double lat, double lon) {
return formatDegMin(lat, 'N', 'S') + " " + formatDegMin(lon, 'E', 'W');
}
/**
* Format an angle for user display as a right ascension.
*
* @param angle The angle to format.
* @return The formatted angle.
* TODO: units!
*/
public static String formatRightAsc(double angle) {
if (angle < 0)
angle += 360.0;
double hours = angle / 15.0;
int h = (int) hours;
hours = (hours - h) * 60.0;
int m = (int) hours;
hours = (hours - m) * 60.0;
double s = hours;
// Rounding errors?
if (s >= 60.0) {
s = 0;
++m;
}
if (m >= 60) {
m -= 60;
++h;
}
if (h >= 24) {
h -= 24;
}
return String.format("%02dh %02d' %08.5f\"", h, m, s);
}
// ************************************************************************ //
// Class Data.
// ************************************************************************ //
// Number formatter for integer values.
private static NumberFormat intFormat = null;
static {
// Set up the number formatter for integer values.
intFormat = NumberFormat.getInstance();
intFormat.setMinimumIntegerDigits(3);
intFormat.setMaximumIntegerDigits(3);
intFormat.setMaximumFractionDigits(0);
}
// Number formatter for floating-point values.
private static NumberFormat floatFormat = null;
static {
// Set up the number formatter for floating-point values.
floatFormat = NumberFormat.getInstance();
floatFormat.setMinimumFractionDigits(0);
floatFormat.setMaximumFractionDigits(7);
}
// Number formatter for formatAngle.
private static NumberFormat angleFormat = null;
static {
// Set up the number formatter for angleFormat.
angleFormat = NumberFormat.getInstance();
angleFormat.setMinimumFractionDigits(0);
angleFormat.setMaximumFractionDigits(3);
}
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
/**
* The azimuth, in radians, clockwise from north.
*/
private double angleR;
}
| 12,592 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
VincentyCalculator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/VincentyCalculator.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import static java.lang.Double.isNaN;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
/**
* A geographic data calculator based on Vincenty's formulae.
*
* <p>The geodetic operations in this class are based on an ellipsoidal
* model of the Earth, using Vincenty's formulae; this is slow, but
* very accurate. Be aware, however, that accuracy is compromised in
* extreme cases, such as nearly-antipodal points.
*
* <p>The user needs to specify the ellipsoid to use for the geodetic
* calculations; this is done in the constructor. The Ellipsoid enum
* defines a range of reference ellipsoids. The default is the widely-used
* WGS-84 standard.
*
* <p>The code in this class was converted from the Fortran implementations
* developed by the National Geodetic Survey. No license is specified for
* this code, but I believe that it is public domain, since it was created
* by an agency of the US Government.
*
* References:
*
* <ul>
* <li><a href="http://www.ngs.noaa.gov/PC_PROD/Inv_Fwd/">Fortran
* implementations of Vincenty's formulae,</a> from the National
* Geodetic Survey</li>
* <li><a href="http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf">Vincenty's
* paper describing his formulae</a>, from NOAA</li>
* <li><a href="http://www.movable-type.co.uk/scripts/latlong-vincenty.html">JS
* implementations of Vincenty's inverse formula</a>, from Movable Type
* Ltd</li>
* <li><a href="http://www.movable-type.co.uk/scripts/latlong-vincenty-direct.html">JS
* implementations of Vincenty's direct formula</a>, from Movable Type
* Ltd</li>
* </ul>
*
* @author Ian Cameron Smith
*/
public class VincentyCalculator
extends GeoCalculator
{
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a calculator using the default ellipsoid.
*/
public VincentyCalculator() {
super();
}
/**
* Create a calculator using a given ellipsoid.
*
* @param ellip The ellipsoid to use for geodetic calculations.
*/
public VincentyCalculator(Ellipsoid ellip) {
super(ellip);
}
// ******************************************************************** //
// Geodetic Methods.
// ******************************************************************** //
/**
* Get the algorithm this calculator uses.
*
* @return The algorithm this calculator uses.
*/
@Override
public Algorithm getAlgorithm() {
return Algorithm.VINCENTY;
}
/**
* Calculate the distance between two positions.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The distance between p1 and p2.
*/
@Override
public Distance distance(Position p1, Position p2) {
// Compute the geodetic inverse. This gets the distance,
// forward azimuth, and back azimuth.
Ellipsoid ellipsoid = getEllipsoid();
double[] ret = gpnhri(ellipsoid.axis, ellipsoid.flat,
p1.getLatRads(), p1.getLonRads(),
p2.getLatRads(), p2.getLonRads());
return new Distance(ret[0]);
}
/**
* Calculate the distance between a position and a given latitude.
*
* @param p1 Position to calculate the distance from.
* @param lat Latitude in radians to calculate the distance to.
* @return The distance of this Position from lat.
*/
@Override
public Distance latDistance(Position p1, double lat) {
// Seems like this could be simplified.
Position p2 = new Position(lat, p1.getLonRads());
return distance(p1, p2);
}
/**
* Calculate the azimuth (bearing) from a position to another.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The azimuth of pos from this Position.
*/
@Override
public Azimuth azimuth(Position p1, Position p2) {
// Compute the geodetic inverse. This gets the distance,
// forward azimuth, and back azimuth.
Ellipsoid ellipsoid = getEllipsoid();
double[] ret = gpnhri(ellipsoid.axis, ellipsoid.flat,
p1.getLatRads(), p1.getLonRads(),
p2.getLatRads(), p2.getLonRads());
return new Azimuth(ret[1]);
}
/**
* Calculate the azimuth and distance from a position to another.
*
* This function is significantly faster than calling azimuth(p1, p2)
* and distance(p1, p2), if both parts are required.
*
* @param p1 Position to calculate the vector from.
* @param p2 Position to calculate the vector to.
* @return The Vector from p1 to p2.
*/
@Override
public Vector vector(Position p1, Position p2) {
// Compute the geodetic inverse. This gets the distance,
// forward azimuth, and back azimuth.
Ellipsoid ellipsoid = getEllipsoid();
double[] ret = gpnhri(ellipsoid.axis, ellipsoid.flat,
p1.getLatRads(), p1.getLonRads(),
p2.getLatRads(), p2.getLonRads());
return new Vector(new Distance(ret[0]), new Azimuth(ret[1]));
}
/**
* Calculate a second position given its offset from a given position.
*
* @param p1 Position to calculate from.
* @param distance The Distance to the desired position.
* @param azimuth The Azimuth to the desired position.
* @return The position given by the azimuth and distance
* from p1. Returns null if the result
* could not be computed.
*/
@Override
public Position offset(Position p1, Distance distance, Azimuth azimuth) {
// Do the calculation.
Ellipsoid ellipsoid = getEllipsoid();
double[] res = dirct1(p1.getLatRads(), p1.getLonRads(),
azimuth.getRadians(),
distance.getMetres(),
ellipsoid.axis, ellipsoid.flat);
// Create a position from the calculated latitudeR and long,
// if we got one. (We really should.)
if (isNaN(res[0]) || isNaN(res[1]))
return null;
return new Position(res[0], res[1]);
}
// ******************************************************************** //
// The Vincenty Direct Solution.
// ******************************************************************** //
/**
* Solution of the geodetic direct problem after T. Vincenty.
* Modified Rainsford's method with Helmert's elliptical terms.
* Effective in any azimuth and at any distance short of antipodal.
*
* Programmed for the CDC-6600 by lcdr L. Pfeifer, NGS Rockville MD,
* 20 Feb 1975.
*
* @param glat1 The latitude of the starting point, in radians,
* positive north.
* @param glon1 The latitude of the starting point, in radians,
* positive east.
* @param azimuth The azimuth to the desired location, in radians
* clockwise from north.
* @param dist The distance to the desired location, in meters.
* @param axis The semi-major axis of the reference ellipsoid,
* in meters.
* @param flat The flattening of the reference ellipsoid.
* @return An array containing the latitude and longitude
* of the desired point, in radians, and the
* azimuth back from that point to the starting
* point, in radians clockwise from north.
*/
private static double[] dirct1(double glat1, double glon1,
double azimuth, double dist,
double axis, double flat)
{
double r = 1.0 - flat;
double tu = r * sin(glat1) / cos(glat1);
double sf = sin(azimuth);
double cf = cos(azimuth);
double baz = 0.0;
if (cf != 0.0)
baz = atan2(tu, cf) * 2.0;
double cu = 1.0 / sqrt(tu * tu + 1.0);
double su = tu * cu;
double sa = cu * sf;
double c2a = -sa * sa + 1.0;
double x = sqrt((1.0 / r / r - 1.0) * c2a + 1.0) + 1.0;
x = (x - 2.0) / x;
double c = 1.0 - x;
c = (x * x / 4.0 + 1) / c;
double d = (0.375 * x * x - 1.0) * x;
tu = dist / r / axis / c;
double y = tu;
double sy, cy, cz, e;
do {
sy = sin(y);
cy = cos(y);
cz = cos(baz + y);
e = cz * cz * 2.0 - 1.0;
c = y;
x = e * cy;
y = e + e - 1.0;
y = (((sy * sy * 4.0 - 3.0) * y * cz * d / 6.0 + x) *
d / 4.0 - cz) * sy * d + tu;
} while (abs(y - c) > PRECISION_LIMIT);
baz = cu * cy * cf - su * sy;
c = r * sqrt(sa * sa + baz * baz);
d = su * cy + cu * sy * cf;
double glat2 = atan2(d, c);
c = cu * cy - su * sy * cf;
x = atan2(sy * sf, c);
c = ((-3.0 * c2a + 4.0) * flat + 4.0) * c2a * flat / 16.0;
d = ((e * cy * c + cz) * sy * c + y) * sa;
double glon2 = glon1 + x - (1.0 - c) * d * flat;
baz = atan2(sa, baz) + PI;
double[] ret = new double[3];
ret[0] = glat2;
ret[1] = glon2;
ret[2] = baz;
return ret;
}
// ******************************************************************** //
// The Vicenty Inverse Solution.
// ******************************************************************** //
/**
* Solution of the geodetic inverse problem after T. Vincenty.
* Modified rainsford's method with helmert's elliptical terms.
* Effective in any azimuth and at any distance short of antipodal;
* from/to stations must not be the geographic pole.
*
* Programmed by Robert (Sid) Safford; released for field use 5 Jul 1975.
*
* @param a Semi-major axis of reference ellipsoid in meters.
* @param f Flattening (0.0033528...).
* @param p1 Lat station 1, in radians, positive north.
* @param e1 Lon station 1, in radians, positive east.
* @param p2 Lat station 2, in radians, positive north.
* @param e2 Lon station 2, in radians, positive east.
* @return An array of doubles, containing: the geodetic
* distance between the stations, in meters; the
* azimuth at station 1 to station 2; and the
* azimuth at station 2 to station 1. Azimuths are
* in radians, clockwise from north, and may not
* be normalized.
*/
private static double[] gpnhri(double a, double f,
double p1, double e1, double p2, double e2)
{
// aa constant from subroutine gpnloa
// alimit equatorial arc distance along the equator (radians)
// arc meridional arc distance latitude p1 to p2 (in meters)
// az1 azimuth forward (in radians)
// az2 azimuth back (in radians)
// bb constant from subroutine gpnloa
// dlon temporary value for difference in longitude (radians)
// equ equatorial distance (in meters)
// r1,r2 temporary variables
// s ellipsoid distance (in meters)
// sms equatorial - geodesic distance (s - s) "sms"
// ss temporary variable
// Calculate the eccentricity squared.
double esq = f * (2.0 - f);
// Normalize the longitudes to be positive.
if (e1 < 0.0)
e1 += TWO_PI;
if (e2 < 0.0)
e2 += TWO_PI;
// Test the longitude difference; if it's next to zero, then we
// have to calculate this as a meridional arc.
double dlon = e2 - e1;
if (abs(dlon) < GEO_TOLERANCE)
return gpnarc(a, f, esq, p1, p2);
// Normalize the longitude difference to -PI .. PI.
if (dlon >= PI && dlon < TWO_PI)
dlon = dlon - TWO_PI;
if (dlon <= -PI && dlon > -TWO_PI)
dlon = dlon + TWO_PI;
// If the longitude difference is over 180 degrees, turn it around.
double absDlon = abs(dlon);
if (absDlon > PI)
absDlon = TWO_PI - absDlon;
// Compute the limit in longitude (alimit): it is equal
// to twice the distance from the equator to the pole,
// as measured along the equator (east/west).
double alimit = PI * (1.0 - f);
// If the longitude difference is beyond the lift-off point, see if
// our points are anti-nodal. If so, we need to use the lift-off
// algorithm.
if (absDlon >= alimit && abs(p1) < NODAL_LIMIT && abs(p2) < NODAL_LIMIT)
return gpnloa(a, f, esq, dlon);
//
//
double f0 = 1.0 - f;
double b = a * f0;
double epsq = esq / (1.0 - esq);
double f2 = f * f;
double f3 = f * f2;
double f4 = f * f3;
//
// the longitude difference
//
dlon = e2 - e1;
double ab = dlon;
//
// the reduced latitudes
//
double u1 = f0 * sin(p1) / cos(p1);
double u2 = f0 * sin(p2) / cos(p2);
//
u1 = atan(u1);
u2 = atan(u2);
//
double su1 = sin(u1);
double cu1 = cos(u1);
//
double su2 = sin(u2);
double cu2 = cos(u2);
//
// counter for the iteration operation
//
double clon = 0, slon = 0, sinalf = 0;
double sig = 0, csig = 0, ssig = 0, w = 0;
double q2 = 0, q4 = 0, q6 = 0, r2 = 0, r3 = 0;
for (int i = 0; i < 8; ++i) {
clon = cos(ab);
slon = sin(ab);
//
csig = su1 * su2 + cu1 * cu2 * clon;
double k1 = slon * cu2;
double k2 = su2 * cu1 - su1 * cu2 * clon;
ssig = sqrt(k1 * k1 + k2 * k2);
//
sig = atan2(ssig, csig);
sinalf = cu1 * cu2 * slon / ssig;
//
w = 1.0 - sinalf * sinalf;
double t4 = w * w;
double t6 = w * t4;
//
// the coefficients of type a
//
double ao = f - f2 * (1.0 + f + f2) * w / 4.0 + 3.0 * f3 *
(1.0 + 9.0 * f / 4.0) * t4 / 16.0 - 25.0 * f4 * t6 / 128.0;
double a2 = f2 * (1 + f + f2) * w / 4.0 - f3 * (1 + 9.0 * f / 4.0) * t4 / 4.0 +
75.0 * f4 * t6 / 256.0;
double a4 = f3 * (1.0 + 9.0 * f / 4.0) * t4 / 32.0 - 15.0 * f4 * t6 / 256.0;
double a6 = 5.0 * f4 * t6 / 768.0;
//
// the multiple angle functions
//
double qo = 0.0;
if (w > FP_TOLERANCE)
qo = -2.0 * su1 * su2 / w;
//
q2 = csig + qo;
q4 = 2.0 * q2 * q2 - 1.0;
q6 = q2 * (4.0 * q2 * q2 - 3.0);
r2 = 2.0 * ssig * csig;
r3 = ssig * (3.0 - 4.0 * ssig * ssig);
//
// the longitude difference
//
double s = sinalf * (ao * sig + a2 * ssig * q2 + a4 * r2 * q4 + a6 * r3 * q6);
double xz = dlon + s;
//
double xy = abs(xz - ab);
ab = dlon + s;
//
if (xy < PRECISION_LIMIT)
break;
}
//
// the coefficients of type b
//
double z = epsq * w;
//
double bo = 1.0 + z * (1.0 / 4.0 + z * (-3.0 / 64.0 + z * (5.0 / 256.0 - z * 175.0 / 16384.0)));
double b2 = z * (-1.0 / 4.0 + z * (1.0 / 16.0 + z * (-15.0 / 512.0 + z * 35.0 / 2048.0)));
double b4 = z * z * (-1.0 / 128.0 + z * (3.0 / 512.0 - z * 35.0 / 8192.0));
double b6 = z * z * z * (-1.0 / 1536.0 + z * 5.0 / 6144.0);
//
// the distance in meters
//
double s = b * (bo * sig + b2 * ssig * q2 + b4 * r2 * q4 + b6 * r3 * q6);
// Check for a non-distance ... p1,e1 & p2,e2 equal zero? If so,
// set the azimuths to zero. Otherwise calculate them.
double az1, az2;
if (s < 0.00005) {
az1 = 0.0;
az2 = 0.0;
} else {
// First compute the az1 & az2 for along the equator.
if (dlon > PI)
dlon -= TWO_PI;
else if (dlon < -PI)
dlon += TWO_PI;
az1 = dlon < 0 ? PI * 3.0 / 2.0 : PI / 2.0;
az2 = dlon < 0 ? PI / 2.0 : PI * 3.0 / 2.0;
// Now compute the az1 & az2 for latitudes not on the equator.
if (!(abs(su1) < FP_TOLERANCE && abs(su2) < FP_TOLERANCE)) {
double tana1 = slon * cu2 / (su2 * cu1 - clon * su1 * cu2);
double tana2 = slon * cu1 / (su1 * cu2 - clon * su2 * cu1);
double sina1 = sinalf / cu1;
double sina2 = -sinalf / cu2;
az1 = atan2(sina1, sina1 / tana1);
az2 = PI - atan2(sina2, sina2 / tana2);
}
}
return new double[] { s, az1, az2 };
}
// ******************************************************************** //
// Utility Functions.
// ******************************************************************** //
/**
* Compute the length of a meridional arc between two latitudes.
*
* Programmed by Robert (Sid) Safford; released for field use 5 Jul 1975.
*
* @param amax The semi-major axis of the reference ellipsoid,
* @param flat The flattening (0.0033528 ... ).
* @param esq Eccentricity squared for reference ellipsoid.
* @param p1 The latitude of station 1.
* @param p2 The latitude of station 2.
* @return An array of doubles, containing: the geodesic
* distance between the stations, in meters;
* the azimuth at station 1 to station 2;
* and the azimuth at station 2 to station 1.
*/
private static double[] gpnarc(double amax, double flat, double esq,
double p1, double p2)
{
// Check for a 90 degree lookup.
boolean ninety = abs(p1) < FP_TOLERANCE &&
abs(abs(p2) - PI / 2) < FP_TOLERANCE;
double da = p2 - p1;
double s1 = 0.0;
double s2 = 0.0;
// Compute the length of a meridional arc between two latitudes.
double e2 = esq;
double e4 = e2 * e2;
double e6 = e4 * e2;
double e8 = e6 * e2;
double ex = e8 * e2;
//
double t1 = e2 * (003.0 / 4.0);
double t2 = e4 * (015.0 / 64.0);
double t3 = e6 * (035.0 / 512.0);
double t4 = e8 * (315.0 / 16384.0);
double t5 = ex * (693.0 / 131072.0);
//
double a = 1.0 + t1 + 3.0 * t2 + 10.0 * t3 + 35.0 * t4 + 126.0 * t5;
//
if (!ninety) {
//
double b = t1 + 4.0 * t2 + 15.0 * t3 + 56.0 * t4 + 210.0 * t5;
double c = t2 + 06.0 * t3 + 28.0 * t4 + 120.0 * t5;
double d = t3 + 08.0 * t4 + 045.0 * t5;
double e = t4 + 010.0 * t5;
double f = t5;
//
double db = sin(p2 * 2.0) - sin(p1 * 2.0);
double dc = sin(p2 * 4.0) - sin(p1 * 4.0);
double dd = sin(p2 * 6.0) - sin(p1 * 6.0);
double de = sin(p2 * 8.0) - sin(p1 * 8.0);
double df = sin(p2 * 10.0) - sin(p1 * 10.0);
//
// compute the s2 part of the series expansion
//
s2 = -db * b / 2 + dc * c / 4 - dd * d / 6 + de * e / 8 - df * f / 10;
}
//
// compute the s1 part of the series expansion
//
s1 = da * a;
//
// compute the arc length
double arc = amax * (1.0 - esq) * (s1 + s2);
// Make the return array.
double[] ret = new double[3];
ret[0] = abs(arc);
// Calculate the forward and back azimuths, which will be
// north and south or vice versa.
if (p2 > p1) {
ret[1] = 0.0;
ret[2] = PI;
} else {
ret[1] = PI;
ret[2] = 0.0;
}
return ret;
}
/**
* Subroutine to compute the lift-off-azimuth constants.
*
* Programmed by Robert (Sid) Safford; released for field use 10 Jun 1985.
*
* @param a The semi-major axis of the reference ellipsoid,
* @param f The flattening (0.0033528 ... ).
* @param esq Eccentricity squared for reference ellipsoid.
* @param dlon The longitude difference.
* @return An array of doubles, containing: the geodesic
* distance between the stations, in meters;
* the azimuth at station 1 to station 2;
* and the azimuth at station 2 to station 1.
*/
private static double[] gpnloa(double a, double f, double esq, double dlon)
{
double absDlon = abs(dlon);
double cons = (PI - absDlon) / (PI * f);
//
// compute an approximate az
//
double az = asin(cons);
//
double t1 = 1.0;
double t2 = (-1.0 / 4.0) * f * (1.0 + f + f * f);
double t4 = 3.0 / 16.0 * f * f * (1.0 + (9.0 / 4.0) * f);
double t6 = (-25.0 / 128.0) * f * f * f;
//
double ao = 0;
double s = 0;
for (int iter = 0; iter < 7; ++iter) {
s = cos(az);
double c2 = s * s;
//
// compute new ao
//
ao = t1 + t2 * c2 + t4 * c2 * c2 + t6 * c2 * c2 * c2;
double cs = cons / ao;
s = asin(cs);
if (abs(s - az) < PRECISION_LIMIT)
break;
//
az = s;
}
//
double az1 = s;
if (dlon < 0.0)
az1 = 2.0 * PI - az1;
//
double az2 = 2.0 * PI - az1;
//
// equatorial - geodesic (s - s) "sms"
//
double esqp = esq / (1.0 - esq);
s = cos(az1);
//
double u2 = esqp * s * s;
double u4 = u2 * u2;
double u6 = u4 * u2;
double u8 = u6 * u2;
//
t1 = 1.0;
t2 = (1.0 / 4.0) * u2;
t4 = (-3.0 / 64.0) * u4;
t6 = (5.0 / 256.0) * u6;
double t8 = (-175.0 / 16384.0) * u8;
//
double bo = t1 + t2 + t4 + t6 + t8;
s = sin(az1);
// Compute s - s: the equatorial - geodesic distance between the
// stations, in meters.
double sms = a * PI * (1.0 - f * abs(s) * ao - bo * (1.0 - f));
// And now compute the geodesic distance, which is the equatorial
// distance (calculated from the axis) minus sms.
double equDist = a * absDlon;
double geoDist = equDist - sms;
return new double[] { geoDist, az1, az2 };
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Two times PI (handy sometimes).
private static final double TWO_PI = 2 * PI;
// Floating-point tolerance. Two values closer than this can be
// considered to be the same.
private static final double FP_TOLERANCE = 5.0e-15;
// Tolerance used when comparing values against meridians or the
// equator.
private static final double GEO_TOLERANCE = 5.0e-14;
// A looser version of FP_TOLERANCE.
private static final double PRECISION_LIMIT = 0.5e-13;
// Points closer to the equator than this are candidates to be
// consider anti-nodal.
private static final double NODAL_LIMIT = 7.0e-03;
}
| 22,299 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Vector.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/Vector.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
/**
* This class represents a vector over the Earth's surface -- ie. a
* distance and azimuth.
*
* @author Ian Cameron Smith
*/
public final class Vector
{
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a Vector from a given distance and azimuth.
*
* @param distance Source distance.
* @param azimuth Source azimuth.
*/
public Vector(Distance distance, Azimuth azimuth) {
this.distance = distance;
this.azimuth = azimuth;
}
// ******************************************************************** //
// Accessors and Converters.
// ******************************************************************** //
/**
* Create a Vector from distance in metres and an azimuth given in radians.
*
* @param metres Source distance in metres.
* @param radians Source azimuth in radians, clockwise from north.
* @return The new Vector.
*/
public static Vector fromMetresRadians(double metres, double radians) {
return new Vector(new Distance(metres), new Azimuth(radians));
}
/**
* Create a Vector from distance in nautical miles and an azimuth
* given in radians.
*
* @param nmiles Source distance in nautical miles.
* @param radians Source azimuth in radians, clockwise from north.
* @return The new Vector.
*/
public static Vector fromNmRadians(double nmiles, double radians) {
return new Vector(Distance.fromNm(nmiles), new Azimuth(radians));
}
/**
* Get the azimuth.
*
* @return The azimuth.
*/
public final Azimuth getAzimuth() {
return azimuth;
}
/**
* Get the azimuth in radians.
*
* @return The azimuth in radians, clockwise from north.
* This will be in the range 0 <= radians < 2 * PI.
*/
public final double getAzimuthRadians() {
return azimuth.getRadians();
}
/**
* Get the azimuth in degrees.
*
* @return The azimuth in degrees, clockwise from north.
* This will be in the range 0 <= degrees < 360.0.
*/
public final double getAzimuthDegrees() {
return azimuth.getDegrees();
}
/**
* Get the distance.
*
* @return The distance.
*/
public final Distance getDistance() {
return distance;
}
/**
* Get the distance in metres.
*
* @return The distance in metres.
*/
public final double getDistanceMetres() {
return distance.getMetres();
}
/**
* Get the distance in nautical miles.
*
* @return The distance in nautical miles.
*/
public final double getDistanceNm() {
return distance.getNm();
}
// ******************************************************************** //
// Formatting.
// ******************************************************************** //
/**
* Format this vector for user display in degrees and minutes.
*
* @return The formatted vector.
*/
public String formatDegMin() {
return distance.formatM() + ' ' + azimuth.formatDegMin();
}
/**
* Format this vector for user display in degrees and minutes.
*
* @return The formatted vector.
*/
public String formatDegMinSec() {
return distance.formatM() + ' ' + azimuth.formatDegMinSec();
}
/**
* Format this vector as a String.
*
* @return This vector as a string, in degrees and minutes.
*/
@Override
public String toString() {
return formatDegMin();
}
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
/**
* The distance.
*/
private Distance distance;
/**
* The azimuth.
*/
private Azimuth azimuth;
}
| 4,614 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Position.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/Position.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
import org.hermit.utils.Angle;
/**
* This class represents a geographic position -- ie. a latitude and
* longitude. It provides utility methods for the common geodetic
* operations of finding distance and azimuth between points, or projecting
* to a point given a distance and azimuth.
*
* The geodetic operations in this class are based on a simple spherical
* model of the Earth, using the haversine formulae; this is fast, and
* provides accuracy of about 0.5%, which will be adequate for many
* purposes. Users desiring greater accuracy should use the
* {@link VincentyCalculator} subclass.
*
* References:
*
* <ul>
* <li><a href="http://www.movable-type.co.uk/scripts/gis-faq-5.1.html">GIS
* FAQ Q5.1: Great circle distance between 2 points</a></li>
* <li><a href="http://www.movable-type.co.uk/scripts/latlong.html">JS
* implementations of the haversine formulae</a>, from Movable
* Type Ltd</li>
* <li><a href="http://williams.best.vwh.net/avform.htm">Aviation
* Formulary</a>, by Ed Williams</li>
* </ul>
*
* @author Ian Cameron Smith
*/
public class Position
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Constant representing an unknown position.
*/
public static final Position UNKNOWN = new Position(Double.NaN,
Double.NaN, true);
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a Position from a geographic latitude and longitude.
*
* @param latRadians Geographic latitude in radians of the desired
* position, positive north.
* @param lonRadians Longitude in radians of the desired position,
* positive east.
*/
public Position(double latRadians, double lonRadians) {
this(latRadians, lonRadians, false);
}
/**
* Create a Position from a geographic latitude and longitude. This
* private constructor allows NaN, in order to create the constant
* UNKNOWN.
*
* @param latRadians Geographic latitude in radians of the desired
* position, positive north.
* @param lonRadians Longitude in radians of the desired position,
* positive east.
* @param allowNan Iff true, allow the lat and long to be NaN.
*/
private Position(double latRadians, double lonRadians, boolean allowNan) {
if (!allowNan) {
if (Double.isNaN(latRadians) || Double.isInfinite(latRadians) ||
Double.isNaN(lonRadians) || Double.isInfinite(lonRadians))
throw new IllegalArgumentException("Components of a Position" +
" must be finite");
}
init(latRadians, lonRadians);
}
// GeoPoint missing in my ROM????
// /**
// * Create a Position from a Google Maps Point. Point represents
// * latitude and longitude in microdegrees (degrees * 1E6).
// *
// * @param mapPoint The Google Maps representation of the
// * desired position.
// */
// public Position(GeoPoint mapPoint) {
// double latR = toRadians(mapPoint.getLatitudeE6() / MILLION);
// double lonR = toRadians(mapPoint.getLongitudeE6() / MILLION);
// init(latR, lonR);
// }
// /**
// * Create a Position from an Android Location.
// *
// * @param loc The Android Location of the desired position.
// */
// public Position(Location loc) {
// double latR = toRadians(loc.getLatitude());
// double lonR = toRadians(loc.getLongitude());
// init(latR, lonR);
// }
/**
* Create a Position from a Position. This is useful for converting
* between subclasses and superclasses.
*
* @param pos The Position to copy.
*/
public Position(Position pos) {
init(pos.latitudeR, pos.longitudeR);
}
/**
* Set this Position up with a given geographic latitude and longitude.
* Carry out any necessary normalization.
*
* This method should be used by all constructors, to make sure that
* the resulting lat and long are normalized.
*
* @param latRadians Geographic latitude in radians of the desired
* position, positive north.
* @param lonRadians Longitude in radians of the desired position,
* positive east.
*/
private void init(double latRadians, double lonRadians) {
if (!Double.isNaN(latRadians) && !Double.isNaN(lonRadians)) {
if (latRadians < -PI / 2)
latRadians = -PI / 2;
else if (latRadians > PI / 2)
latRadians = PI / 2;
// Normalize the longitude to -PI .. +PI.
while (lonRadians < 0)
lonRadians += 2 * PI;
lonRadians = (lonRadians + PI) % (2 * PI) - PI;
}
latitudeR = latRadians;
longitudeR = lonRadians;
}
// ******************************************************************** //
// Accessors and Converters.
// ******************************************************************** //
/**
* Create a Position from a geographic latitude and longitude given
* in degrees.
*
* @param latDegrees Geographic latitude in degrees of the desired
* position, positive north.
* @param lonDegrees Longitude in degrees of the desired position,
* positive east.
* @return The new Position.
*/
public static Position fromDegrees(double latDegrees, double lonDegrees) {
if (Double.isNaN(latDegrees) || Double.isInfinite(latDegrees) ||
Double.isNaN(lonDegrees) || Double.isInfinite(lonDegrees))
throw new IllegalArgumentException("Components of a Position" +
" must be finite");
return new Position(toRadians(latDegrees), toRadians(lonDegrees));
}
/**
* Get the geographic latitude of this Position in radians.
*
* @return The geographic latitude of this Position in radians,
* positive north. NaN if this is UNKNOWN.
*/
public double getLatRads() {
return latitudeR;
}
/**
* Get the geocentric latitude of this Position in radians.
*
* <p>From AA chapter 11.
*
* @return The geocentric latitude of this Position in radians,
* positive north. NaN if this is UNKNOWN.
*/
public double getGeocentricLat() {
if (Double.isNaN(latitudeR))
return Double.NaN;
final double f1 = toRadians(692.73 / 3600.0);
final double f2 = toRadians(1.16 / 3600.0);
double Δφ = f1 * sin(2 * latitudeR) - f2 * sin(4 * latitudeR);
return latitudeR - Δφ;
}
/**
* Get the longitude of this Position in radians.
*
* @return The longitude of this Position in radians,
* positive east. NaN if this is UNKNOWN.
*/
public double getLonRads() {
return longitudeR;
}
/**
* Get the geographic latitude of this Position in degrees.
*
* @return The geographic latitude of this Position in degrees,
* positive north. NaN if this is UNKNOWN.
*/
public double getLatDegs() {
if (Double.isNaN(latitudeR))
return Double.NaN;
return toDegrees(latitudeR);
}
/**
* Get the longitude of this Position in degrees.
*
* @return The longitude of this Position in degrees,
* positive east. NaN if this is UNKNOWN.
*/
public double getLonDegs() {
if (Double.isNaN(longitudeR))
return Double.NaN;
return toDegrees(longitudeR);
}
/**
* Get the distance from the centre of the Earth to this Position.
*
* <p>From AA chapter 11.
*
* @return The distance to the centre of the Earth, in
* units of EQUATORIAL_RADIUS. NaN if this is UNKNOWN.
*/
public double getCentreDistance() {
if (Double.isNaN(latitudeR))
return Double.NaN;
double ρ = 0.9983271 +
0.0016764 * cos(2 * latitudeR) -
0.0000035 * cos(4 * latitudeR);
return ρ;
}
// /**
// * Convert a given lat and long to a Google Maps Point. Point represents
// * latitude and longitude in microdegrees (degrees * 1E6).
// *
// * @param latRadians Geographic latitude in radians of the desired
// * position, positive north.
// * @param lonRadians Longitude in radians of the desired position,
// * positive east.
// */
// public static GeoPoint toGeoPoint(double latRadians, double lonRadians) {
// int latE6 = (int) round(toDegrees(latRadians) * MILLION);
// int lonE6 = (int) round(toDegrees(lonRadians) * MILLION);
// return new GeoPoint(latE6, lonE6);
// }
// /**
// * Convert this Position to a Google Maps Point. Point represents
// * latitude and longitude in microdegrees (degrees * 1E6).
// *
// * @param The Google Maps representation of this Position.
// */
// public GeoPoint toGeoPoint() {
// int latE6 = (int) round(toDegrees(latitudeR) * MILLION);
// int lonE6 = (int) round(toDegrees(longitudeR) * MILLION);
// return new GeoPoint(latE6, lonE6);
// }
// ******************************************************************** //
// Geodetic Methods.
// ******************************************************************** //
/**
* Calculate the distance and azimuth from this position to another,
* using the haversine formula, which is based on a spherical
* approximation of the Earth. This should give an accuracy within
* 0.5% or so.
*
* In some subclasses, this function may be significantly faster
* than calling distance(pos) and azimuth(pos).
*
* @param pos Position to calculate the vector to.
* @return The Vector to the given position. null if either
* position is UNKNOWN.
*/
public Vector vector(Position pos) {
if (this == UNKNOWN || pos == UNKNOWN)
return null;
GeoCalculator calc = GeoCalculator.getCalculator();
Distance dist = calc.distance(this, pos);
Azimuth fwdAz = calc.azimuth(this, pos);
// Azimuth backAz = pos.azimuth(this);
return new Vector(dist, fwdAz);
}
/**
* Calculate the distance between this position and another, using the
* haversine formula, which is based on a spherical approximation of
* the Earth. This should give an accuracy within 0.5% or so.
*
* @param pos Position to calculate the distance to.
* @return The distance of pos from this Position. null
* if either position is UNKNOWN.
*/
public Distance distance(Position pos) {
if (this == UNKNOWN || pos == UNKNOWN)
return null;
GeoCalculator calc = GeoCalculator.getCalculator();
return calc.distance(this, pos);
}
/**
* Calculate the distance between this position and a given latitude,
* based on a spherical approximation of the Earth. This should
* give an accuracy within 0.5% or so.
*
* @param lat Latitude in radians to calculate the distance to.
* @return The distance of this Position from lat. null
* if this position is UNKNOWN.
*/
public Distance latDistance(double lat) {
if (this == UNKNOWN)
return null;
GeoCalculator calc = GeoCalculator.getCalculator();
return calc.latDistance(this, lat);
}
/**
* Calculate the azimuth (bearing) from this position to another, using
* the haversine formula, which is based on a spherical approximation of
* the Earth. This should give an accuracy within 0.5% or so.
*
* @param pos Position to calculate the azimuth to.
* @return The azimuth of pos from this Position. null
* if either position is UNKNOWN.
*/
public Azimuth azimuth(Position pos) {
if (this == UNKNOWN || pos == UNKNOWN)
return null;
GeoCalculator calc = GeoCalculator.getCalculator();
return calc.azimuth(this, pos);
}
/**
* Calculate a second position given its offset from this one, using the
* current geodetic calculator -- see {@link GeoCalculator}.
*
* @param vector The Vector to the desired position.
* @return The position given by the azimuth and distance
* from this one. Returns null if the result
* could not be computed, including if this position
* is UNKNOWN.
*/
public Position offset(Vector vector) {
return offset(vector.getDistance(), vector.getAzimuth());
}
/**
* Calculate a second position given its offset from this one, using the
* current geodetic calculator -- see {@link GeoCalculator}.
*
* @param distance The Distance to the desired position.
* @param azimuth The Azimuth to the desired position.
* @return The position given by the azimuth and distance
* from this one. Returns null if the result
* could not be computed, including if this position
* is UNKNOWN.
*/
public Position offset(Distance distance, Azimuth azimuth) {
if (this == UNKNOWN)
return null;
GeoCalculator calc = GeoCalculator.getCalculator();
return calc.offset(this, distance, azimuth);
}
// ******************************************************************** //
// Formatting.
// ******************************************************************** //
/**
* Format this position for user display in degrees and minutes.
*
* @return The formatted angle.
*/
public String formatDegMin() {
return Angle.formatDegMin(toDegrees(latitudeR), 'N', 'S') + ' ' +
Angle.formatDegMin(toDegrees(longitudeR), 'E', 'W');
}
/**
* Format this position for user display in degrees and minutes.
*
* @return The formatted angle.
*/
public String formatDegMinSec() {
return Angle.formatDegMinSec(toDegrees(latitudeR), 'N', 'S') + ' ' +
Angle.formatDegMinSec(toDegrees(longitudeR), 'E', 'W');
}
/**
* Format this position as a String.
*
* @return This position as a string, in degrees and minutes.
*/
@Override
public String toString() {
return formatDegMin();
}
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
/**
* The latitude, in radians, positive north.
*/
private double latitudeR;
/**
* The longitude, in radians, positive east.
*/
private double longitudeR;
}
| 15,833 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AndoyerCalculator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/AndoyerCalculator.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import static java.lang.Double.isNaN;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
/**
* A geographic data calculator based on the Andoyer formula. This is
* a good algorithm which takes into account the flattening of the Earth.
* Accuracy should be around the flattening squared; however, some extreme
* cases can yield bad results.
*
* <p>Note that currently we only have the Andoyer algorithm for distance;
* other functions use simpler spherical methods. Hence, this class should
* be used for reasonably fast but fairly accurate distance calculations,
* where edge cases (e.g. near-antipodean points) are not encountered.
*
* @author Ian Cameron Smith
*/
public class AndoyerCalculator
extends GeoCalculator
{
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a calculator using the default ellipsoid.
*/
public AndoyerCalculator() {
super();
}
/**
* Create a calculator using a given ellipsoid.
*
* @param ellip The ellipsoid to use for geodetic calculations.
*/
public AndoyerCalculator(Ellipsoid ellip) {
super(ellip);
}
// ******************************************************************** //
// Geodetic Methods.
// ******************************************************************** //
/**
* Get the algorithm this calculator uses.
*
* @return The algorithm this calculator uses.
*/
@Override
public Algorithm getAlgorithm() {
return Algorithm.ANDOYER;
}
/**
* Calculate the distance between two positions.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The distance between p1 and p2.
*/
@Override
public Distance distance(Position p1, Position p2) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
double p2Lat = p2.getLatRads();
double p2Lon = p2.getLonRads();
Ellipsoid ellipsoid = getEllipsoid();
double a = ellipsoid.axis;
double f = ellipsoid.flat;
double F = (p1Lat + p2Lat) / 2;
double sinF = sin(F);
double sin2F = sinF * sinF;
double cosF = cos(F);
double cos2F = cosF * cosF;
double G = (p1Lat - p2Lat) / 2;
double sinG = sin(G);
double sin2G = sinG * sinG;
double cosG = cos(G);
double cos2G = cosG * cosG;
double λ = (p1Lon - p2Lon) / 2;
double sinλ = sin(λ);
double sin2λ = sinλ * sinλ;
double cosλ = cos(λ);
double cos2λ = cosλ * cosλ;
double S = sin2G * cos2λ + cos2F * sin2λ;
double C = cos2G * cos2λ + sin2F * sin2λ;
double ω = atan(sqrt(S / C));
double R = sqrt(S * C) / ω;
double D = 2 * ω * a;
double H1 = (3 * R - 1) / (2 * C);
double H2 = (3 * R + 1) / (2 * S);
double s = D * (1 + f * H1 * sin2F * cos2G - f * H2 * cos2F * sin2G);
return new Distance(s);
}
/**
* Calculate the distance between a position and a given latitude.
*
* @param p1 Position to calculate the distance from.
* @param lat Latitude in radians to calculate the distance to.
* @return The distance of this Position from lat.
*/
@Override
public Distance latDistance(Position p1, double lat) {
// Seems like this could be simplified.
Position p2 = new Position(lat, p1.getLonRads());
return distance(p1, p2);
}
/**
* Calculate the azimuth (bearing) from a position to another.
*
* <p>NOTE: this is the Haversine version of this algorithm.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The azimuth of pos from this Position.
*/
@Override
public Azimuth azimuth(Position p1, Position p2) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
double p2Lat = p2.getLatRads();
double p2Lon = p2.getLonRads();
double dLon = p2Lon - p1Lon;
double y = sin(dLon) * cos(p2Lat);
double x = cos(p1Lat) * sin(p2Lat) - sin(p1Lat) * cos(p2Lat) * cos(dLon);
// Calculate the azimuth.
return new Azimuth(atan2(y, x));
}
/**
* Calculate the azimuth and distance from a position to another.
*
* This function may be faster than calling azimuth(p1, p2)
* and distance(p1, p2), if both parts are required.
*
* <p>NOTE: this is the Haversine version of this algorithm.
*
* @param p1 Position to calculate the vector from.
* @param p2 Position to calculate the vector to.
* @return The Vector from p1 to p2.
*/
@Override
public Vector vector(Position p1, Position p2) {
Distance dist = distance(p1, p2);
Azimuth fwdAz = azimuth(p1, p2);
return new Vector(dist, fwdAz);
}
/**
* Calculate a second position given its offset from a given position.
*
* <p>NOTE: this is the Haversine version of this algorithm.
*
* @param p1 Position to calculate from.
* @param distance The Distance to the desired position.
* @param azimuth The Azimuth to the desired position.
* @return The position given by the azimuth and distance
* from p1. Returns null if the result
* could not be computed.
*/
@Override
public Position offset(Position p1, Distance distance, Azimuth azimuth) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
Ellipsoid ellipsoid = getEllipsoid();
double angDist = distance.getMetres() / ellipsoid.axis;
double azRads = azimuth.getRadians();
// Pre-calculate some sines and cosines to save multiple calls.
double sinLat = sin(p1Lat);
double cosLat = cos(p1Lat);
double sinDist = sin(angDist);
double cosDist = cos(angDist);
// Calculate the result.
double lat2 = asin(sinLat * cosDist + cosLat * sinDist * cos(azRads));
double lon2 = p1Lon + atan2(sin(azRads) * sinDist * cosLat,
cosDist - sinLat * sin(lat2));
// Return the result, if we got one.
if (isNaN(lat2) || isNaN(lon2))
return null;
return new Position(lat2, lon2);
}
}
| 6,916 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Distance.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/Distance.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import java.text.NumberFormat;
/**
* This class represents a geographic distance -- ie. a distance
* from or to a given geographic position.
*
* @author Ian Cameron Smith
*/
public final class Distance
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* A distance equal to zero.
*/
public static final Distance ZERO = new Distance(0);
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a Distance from a value given in metres.
*
* @param metres Source distance in metres.
*/
public Distance(double metres) {
distanceM = metres;
}
// ******************************************************************** //
// Accessors and Converters.
// ******************************************************************** //
/**
* Create a Distance from a distance given in feet.
*
* @param feet Source distance in feet.
* @return The new Distance.
*/
public static Distance fromFeet(double feet) {
return new Distance(feet * FOOT);
}
/**
* Create a Distance from a distance given in nautical miles.
*
* @param nmiles Source distance in nautical miles.
* @return The new Distance.
*/
public static Distance fromNm(double nmiles) {
return new Distance(nmiles * NAUTICAL_MILE);
}
/**
* Get the distance in metres.
*
* @return The distance in metres.
*/
public final double getMetres() {
return distanceM;
}
/**
* Get the distance in feet.
*
* @return The distance in feet.
*/
public final double getFeet() {
return distanceM / FOOT;
}
/**
* Get the distance in nautical miles.
*
* @return The distance in nautical miles.
*/
public final double getNm() {
return distanceM / NAUTICAL_MILE;
}
// ******************************************************************** //
// Arithmetic.
// ******************************************************************** //
/**
* Return the sum of this and another Distance.
*
* @param d Distance to add to this one.
* @return Distance representing the sum of the two
* distances.
*/
public Distance add(Distance d) {
if (d == null || d == ZERO)
return this;
if (this == ZERO)
return d;
return new Distance(distanceM + d.distanceM);
}
// ******************************************************************** //
// Formatting.
// ******************************************************************** //
/**
* Format a distance for user display in metres.
*
* @param m Distance in metres to format.
* @return The formatted distance.
*/
public static final String formatM(double m) {
floatFormat.setMaximumFractionDigits(1);
return floatFormat.format(m) + " m";
}
/**
* Format this distance for user display in metres.
*
* @return The formatted distance.
*/
public final String formatM() {
return formatM(distanceM);
}
/**
* Format a specified distance for user display in nautical miles.
*
* @param m Distance in metres to format.
* @return The formatted distance.
*/
public static final String formatNm(double m) {
floatFormat.setMaximumFractionDigits(1);
return floatFormat.format(m / NAUTICAL_MILE) + " nm";
}
/**
* Format this distance for user display in nautical miles.
*
* @return The formatted distance.
*/
public final String formatNm() {
return formatNm(distanceM);
}
/**
* Convert a specified distance into a descriptive string, using
* nautical measures.
*
* @param m Distance in metres to format.
* @return Description of this distance. Examples:
* "625 feet", "4.9 naut. miles", "252 naut. miles".
*/
public static final String describeNautical(double m) {
final double feet = m / FOOT;
if (feet < 1000)
return "" + (int) Math.round(feet) + " feet";
final double nm = m / NAUTICAL_MILE;
if (nm < 10) {
floatFormat.setMaximumFractionDigits(1);
return floatFormat.format(nm) + " nm";
}
return "" + (int) Math.round(nm) + " nm";
}
/**
* Convert this distance into a descriptive string, using
* nautical measures.
*
* @return Description of this distance. Examples:
* "625 feet", "4.9 naut. miles", "252 naut. miles".
*/
public final String describeNautical() {
return describeNautical(distanceM);
}
/**
* Format this distance as a String.
*
* @return This distance as a string, in nautical miles.
*/
@Override
public String toString() {
return formatNm();
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// The length of an international standard foot, in metres.
private static final double FOOT = 0.3048;
// The length of an international standard nautical mile, in metres.
private static final double NAUTICAL_MILE = 1852;
// ************************************************************************ //
// Class Data.
// ************************************************************************ //
// Number formatter for floating-point values.
private static NumberFormat floatFormat = null;
static {
// Set up the number formatter for floating-point values.
floatFormat = NumberFormat.getInstance();
floatFormat.setMinimumFractionDigits(0);
floatFormat.setMaximumFractionDigits(1);
}
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
/**
* The distance in metres.
*/
private double distanceM;
}
| 6,844 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
PointOfInterest.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/PointOfInterest.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
/**
* This class represents a point or area of interest. Its subclasses define
* specific interest zones, as either points, lines or areas.
*
* @author Ian Cameron Smith
*/
public abstract class PointOfInterest
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
// Half pi = 90 degrees.
private static final double HALFPI = Math.PI / 2.0;
// The Earth's axial tilt in radians. TODO: use correct current value.
private static final double EARTH_TILT = Math.toRadians(23.43944444);
// Interesting places.
private static final double CHALLENGER_LAT = Math.toRadians(11d + 22d/60d);
private static final double CHALLENGER_LON = Math.toRadians(142d + 36d/60d);
private static final double INACC_LAT = -Math.toRadians(48d + 52.6d/60d);
private static final double INACC_LON = -Math.toRadians(123d + 23.6d/60d);
private static final double RLYEH_LAT = -Math.toRadians(47d + 9d/60d);
private static final double RLYEH_LON = -Math.toRadians(126d + 43d/60d);
// Interesting latitudes. Don't expose these as public constants
// because they are not constant; we need to calculate the correct
// axial tilt.
private static final double NPOLE = HALFPI;
private static final double ARCTIC = HALFPI - EARTH_TILT;
private static final double CANCER = EARTH_TILT;
private static final double EQUATOR = 0.0;
private static final double CAPRICORN = -EARTH_TILT;
private static final double ANTARC = -HALFPI + EARTH_TILT;
private static final double SPOLE = -HALFPI;
/**
* List of general global points of interest. The closest point here
* will be taken as our interesting point, if in there is one in
* the range specified by DISTANCE_NEAR.
*/
public static final PointOfInterest[] GLOBAL_POIS = {
// Specific locations are most interesting.
new POS(EQUATOR, 0.0, "The Origin"),
new POS(EQUATOR, Math.PI, "The Anti-Origin"),
new POS(CHALLENGER_LAT, CHALLENGER_LON, "The Challenger Deep"),
new POS(INACC_LAT, INACC_LON, "Pole of Inaccessibility"),
new POS(RLYEH_LAT, RLYEH_LON, "R'lyeh"),
// Specific latitudes are next most interesting.
new LAT(NPOLE, "The North Pole"),
new LAT(ARCTIC, "The Arctic Circle"),
new LAT(CANCER, "The Tropic of Cancer"),
new LAT(EQUATOR, "The Equator"),
new LAT(CAPRICORN, "The Tropic of Capricorn"),
new LAT(ANTARC, "The Antarctic Circle"),
new LAT(SPOLE, "The South Pole"),
// Major meridians are also interesting, but only outside the Arctic
// (otherwise, if we're near the pole, it always tells us how far
// we are from the Greenwich meridian).
new LON(0.0, ANTARC, ARCTIC, "The Greenwich Meridian"),
new LON(Math.PI, ANTARC, ARCTIC, "The Anti-Meridian"),
};
/**
* List of regions of the world.
*
* Area is important in this list -- the first band we're in is the
* one returned. This is significant for overlapping bands (like
* the Antarctic and the Screaming Sixties).
*/
public static final PointOfInterest[] GLOBAL_AREAS = {
// The Arctic and Antarctic are dead exciting, and take precedence.
new BAND(ARCTIC, NPOLE, "The Arctic"),
new BAND(SPOLE, ANTARC, "The Antarctic"),
// The southern ocean is pretty daring.
new BAND(Math.toRadians(-50), Math.toRadians(-40), "The Roaring Forties"),
new BAND(Math.toRadians(-60), Math.toRadians(-50), "The Furious Fifties"),
new BAND(Math.toRadians(-70), Math.toRadians(-60), "The Screaming Sixties"),
// Moderate latitude bands are fairly boring.
new BAND(EQUATOR, CANCER, "The Northern Tropics"),
new BAND(CAPRICORN, EQUATOR, "The Southern Tropics"),
// Temperate climes are just too boring. I'd rather know my distance
// from the tropics.
// new BAND(CANCER, ARCTIC, "Temperate Climes"),
// new BAND(ANTARC, CAPRICORN, "Temperate Climes"),
};
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Class POS represents an interesting position.
*/
public static final class POS extends PointOfInterest {
/**
* Create a position of interest.
*
* @param lat Latitude, in radians.
* @param lon Longitude, in radians.
* @param n Name of this latitude.
*/
POS(double lat, double lon, String n) {
super(n);
position = new Position(lat, lon);
}
/**
* Get the distance of a given point from this point of interest.
*
* @param pos Point to measure from.
* @return The distance.
* @see org.hermit.geo.PointOfInterest#distance(org.hermit.geo.Position)
*/
@Override
public final Distance distance(Position pos) {
return pos.distance(position);
}
// The position.
private final Position position;
}
/**
* Class LAT represents an interesting line of latitude.
*/
public static final class LAT extends PointOfInterest {
/**
* Create a latitude of interest.
*
* @param lat Latitude, in radians.
* @param n Name of this latitude.
*/
LAT(double lat, String n) {
super(n);
latitude = lat;
}
/**
* Get the distance of a given point from this point of interest.
*
* @param pos Point to measure from.
* @return The distance.
* @see org.hermit.geo.PointOfInterest#distance(org.hermit.geo.Position)
*/
@Override
public final Distance distance(Position pos) {
return pos.latDistance(latitude);
}
/**
* Describe the status of the given position relative to this
* point of interest.
*
* @param pos The position to describe.
* @return A string describing where pos is in relation
* to this POI.
*/
@Override
public final String status(Position pos) {
Distance d = distance(pos);
double nm = d.getNm();
if (nm <= DISTANCE_THRESH)
return getName();
else if (pos.getLatRads() > latitude)
return d.describeNautical() + " north of " + getName();
else
return d.describeNautical() + " south of " + getName();
}
// The latitude, in radians, positive north.
private final double latitude;
}
/**
* Class LON represents an interesting meridian, or a segment of
* a meridian.
*/
public static final class LON extends PointOfInterest {
/**
* Create a meridian of interest.
*
* @param lon Longitude, in radians.
* @param n Name of this meridian.
*/
LON(double lon, String n) {
super(n);
longitude = lon;
southLim = -HALFPI;
northLim = HALFPI;
}
/**
* Create a meridian segment of interest.
*
* @param lon Longitude, in radians.
* @param slim Southern limit of the segment, in radians.
* @param nlim Northern limit of the segment, in radians.
* @param n Name of this meridian.
*/
LON(double lon, double slim, double nlim, String n) {
super(n);
longitude = lon;
southLim = Math.min(slim, nlim);
northLim = Math.max(slim, nlim);
}
/**
* Get the distance of a given point from this point of interest.
*
* @param pos Point to measure from.
* @return The distance.
* @see org.hermit.geo.PointOfInterest#distance(org.hermit.geo.Position)
*/
@Override
public final Distance distance(Position pos) {
// See if we're in the latitude band of interest.
double lat = pos.getLatRads();
if (lat < southLim || lat > northLim)
return new Distance(DISTANCE_FAR);
// Create a position that represents the meridian of interest,
// filling in the latitude from the caller's position.
// Note: this is incorrect, but simple, and not too bad over
// short distances except near the poles.
Position i = new Position(lat, longitude);
return pos.distance(i);
}
/**
* Describe the status of the given position relative to this
* point of interest.
*
* @param pos The position to describe.
* @return A string describing where pos is in relation
* to this POI.
*/
@Override
public final String status(Position pos) {
Distance d = distance(pos);
double nm = d.getNm();
if (nm <= DISTANCE_THRESH)
return getName();
else if (pos.getLonRads() > longitude)
return d.describeNautical() + " east of " + getName();
else
return d.describeNautical() + " west of " + getName();
}
// The longitude, positive east, and the south and
// north limits of the segment of interest, all in radians.
private final double longitude;
private final double southLim;
private final double northLim;
}
/**
* Class BAND represents an interesting band of latitudes.
*/
public static final class BAND extends PointOfInterest {
/**
* Create a meridian of interest.
*
* @param south South limit (latitude) of the band, in radians.
* @param north North limit (latitude) of the band, in radians.
* @param n Name of this band.
*/
BAND(double south, double north, String n) {
super(n);
northLimit = Math.max(north, south); // Just in case.
southLimit = Math.min(north, south); // Just in case.
}
/**
* Get the distance of a given point from this point of interest.
*
* @param pos Point to measure from.
* @return The distance.
* @see org.hermit.geo.PointOfInterest#distance(org.hermit.geo.Position)
*/
@Override
public final Distance distance(Position pos) {
double lat = pos.getLatRads();
if (lat < southLimit)
return pos.latDistance(southLimit);
else if (lat > northLimit)
return pos.latDistance(northLimit);
else
return new Distance(0.0);
}
// The north and south limits, in radians, positive north.
private final double northLimit;
private final double southLimit;
}
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a Position from a latitude and longitude.
*
* @param n Name of this point / area..
*/
public PointOfInterest(String n) {
name = n;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the name of this point of interest.
*
* @return The name of this point.
*/
public final String getName() {
return name;
}
/**
* Calculate the distance from the given position to this point
* of interest.
*
* @param pos The position to calculate from.
* @return The distance from pos to here. Note: may be
* inaccurate over larger distances, e.g. for
* distance to a meridian.
*/
public abstract Distance distance(Position pos);
/**
* Describe the status of the given position relative to this
* point of interest.
*
* @param pos The position to describe.
* @return A string describing where pos is in relation
* to this POI.
*/
public String status(Position pos) {
Distance d = distance(pos);
double nm = d.getNm();
if (nm <= DISTANCE_THRESH)
return name;
else
return d.describeNautical() + " from " + name;
}
// ******************************************************************** //
// Static Methods.
// ******************************************************************** //
/**
* Describe the status of the given position relative to global
* points of interest.
*
* @param pos The position to describe.
* @return A string describing where pos is in relation
* to the nearest known global POI.
*/
public static final String describePosition(Position pos) {
// Get the status message for the region we're in, if any.
String area = describeRegion(pos);
// Find the closest point of interest.
PointOfInterest best = null;
double bestDistance = 0;
PointOfInterest anyPoint = null;
double anyDistance = 0;
for (PointOfInterest poi : GLOBAL_POIS) {
Distance d = poi.distance(pos);
double nm = d.getNm();
if (anyPoint == null || nm < anyDistance) {
anyPoint = poi;
anyDistance = nm;
}
if (nm <= DISTANCE_NEAR && (best == null || nm < bestDistance)) {
best = poi;
bestDistance = nm;
}
}
// Get the status message for the closest point. If we're right there,
// kill the area description.
String point = best != null ? best.status(pos) : null;
if (best != null && bestDistance <= DISTANCE_THRESH)
area = null;
// Concatenate the area and point descriptions, if we have both.
// If we have one, just use that. If we have neither -- i.e.
// nothing interesting in range -- then use the nearest point
// we found. This gives us the range to the tropics when in the
// high temperate zones.
if (area == null) {
if (point == null) {
if (anyPoint == null)
return "The World"; // Really shouldn't ever get here.
else
return anyPoint.status(pos);
} else
return point;
} else {
if (point == null)
return area;
else
return area + ", " + point;
}
}
/**
* Describe the status of the given position in terms of any region
* of interest it lies within.
*
* @param pos The position to describe.
* @return A string describing the region, if any, that
* pos is within. Null if we aren't in an
* interesting region.
*/
public static final String describeRegion(Position pos) {
// Find the general region we're in.
for (PointOfInterest poi : GLOBAL_AREAS) {
Distance d = poi.distance(pos);
if (d.getNm() <= 0)
return poi.status(pos);
}
return null;
}
/**
* Describe the status of the given position relative to global
* points of interest.
*
* @param pos The position to describe.
* @return A string describing where pos is in relation
* to the nearest known global POI. Null if we
* aren't close to anywhere interesting.
*/
public static final String describePoint(Position pos) {
PointOfInterest best = null;
double bestDistance = 0;
// Find the closest point or area of interest.
for (PointOfInterest poi : GLOBAL_POIS) {
Distance d = poi.distance(pos);
double nm = d.getNm();
if (best == null || (nm <= DISTANCE_NEAR && nm < bestDistance)) {
best = poi;
bestDistance = nm;
}
}
// Return our status relative to the closest point of interest.
if (best != null)
return best.status(pos);
return null;
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Distance in metres representing a long way away.
private static final double DISTANCE_FAR =
GeoCalculator.MEAN_RADIUS * Math.PI;
// Distance in nautical miles from a "special place" which is considered
// to be within interesting range.
private static final double DISTANCE_NEAR = 200;
// Distance in nautical miles from a "special place" which is considered
// to be there.
private static final double DISTANCE_THRESH = 0.01;
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
// Name of this point of interest.
private final String name;
}
| 16,993 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
GeoConstants.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/GeoConstants.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
/**
* Global constants for geodetic calculations.
*
* @author Ian Cameron Smith
*/
public interface GeoConstants
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* An approximation of the mean radius of the Earth in metres.
* For spherical-Earth formulae, this is good enough.
*/
public static final double MEAN_RADIUS = 6371000.0;
/**
* The equatorial radius of the Earth in metres.
*/
public static final double EQUATORIAL_RADIUS = 6378137.0;
/**
* The polar radius of the Earth in metres.
*/
public static final double POLAR_RADIUS = 6356755.0;
/**
* Selectable ellipsoids, for geodetic calculations.
*/
public enum Ellipsoid {
/** Pseudo-ellipsoid for an assumed spherical Earth. */
SPHERE("Sphere", MEAN_RADIUS, 0.0),
/** WGS 84 ellipsoid. */
WGS84("GRS80 / WGS84 (NAD83)", 6378137, 1.0 / 298.25722210088),
/** Clarke 1866 (NAD27) ellipsoid. */
NAD27("Clarke 1866 (NAD27)", 6378206.4, 1.0 / 294.9786982138),
/** Airy 1858 ellipsoid. */
AIRY1858("Airy 1858", 6377563.396, 1.0 / 299.3249646),
/** Airy Modified ellipsoid. */
AIRYM("Airy Modified", 6377340.189, 1.0 / 299.3249646),
/** NWL-9D (WGS 66) ellipsoid. */
WGS66("NWL-9D (WGS 66)", 6378145, 1.0 / 298.25),
/** WGS 72 ellipsoid. */
WGS72("WGS 72", 6378135, 1.0 / 298.26);
Ellipsoid(String n, double a, double f) {
name = n;
axis = a;
flat = f;
}
/** User-visible name of this ellipsoid. */
public final String name;
/** Equatorial semimajor axis of this ellipsoid (in metres). */
public final double axis;
/** Flattening of this ellipsoid. */
public final double flat;
}
}
| 2,588 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
HaversineCalculator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/HaversineCalculator.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import static java.lang.Double.isNaN;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
/**
* A geographic data calculator based on the Haversine formula. This is
* a fast algorithm which is based on a spherical approximation of the
* Earth. This should give an accuracy within 0.5% or so.
*
* @author Ian Cameron Smith
*/
public class HaversineCalculator
extends GeoCalculator
{
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a calculator using the default ellipsoid.
*/
public HaversineCalculator() {
// Haversine only does spheres.
super(Ellipsoid.SPHERE);
}
/**
* Create a calculator using a given ellipsoid.
*
* @param ellip The ellipsoid to use for geodetic calculations.
*/
public HaversineCalculator(Ellipsoid ellip) {
super(ellip);
if (ellip != Ellipsoid.SPHERE)
throw new IllegalArgumentException("HaversineCalculator can only work on Ellipsoid.SHPERE");
}
// ******************************************************************** //
// Geodetic Methods.
// ******************************************************************** //
/**
* Get the algorithm this calculator uses.
*
* @return The algorithm this calculator uses.
*/
@Override
public Algorithm getAlgorithm() {
return Algorithm.HAVERSINE;
}
/**
* Calculate the distance between two positions.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The distance between p1 and p2.
*/
@Override
public Distance distance(Position p1, Position p2) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
double p2Lat = p2.getLatRads();
double p2Lon = p2.getLonRads();
double halfLat = (p2Lat - p1Lat) / 2;
double halfLon = (p2Lon - p1Lon) / 2;
// Calculate sines squared, without doing sines twice.
double sin2HalfLat = sin(halfLat);
sin2HalfLat = sin2HalfLat * sin2HalfLat;
double sin2HalfLon = sin(halfLon);
sin2HalfLon = sin2HalfLon * sin2HalfLon;
double a = sin2HalfLat + cos(p1Lat) * cos(p2Lat) * sin2HalfLon;
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
// Convert the angular distance to metres.
Ellipsoid ellipsoid = getEllipsoid();
return new Distance(ellipsoid.axis * c);
}
/**
* Calculate the distance between a position and a given latitude.
*
* @param p1 Position to calculate the distance from.
* @param lat Latitude in radians to calculate the distance to.
* @return The distance of this Position from lat.
*/
@Override
public Distance latDistance(Position p1, double lat) {
// In a spherical model, the angular distance is trivial.
double c = lat - p1.getLatRads();
// Convert the angular distance to metres.
Ellipsoid ellipsoid = getEllipsoid();
return new Distance(ellipsoid.axis * Math.abs(c));
}
/**
* Calculate the azimuth (bearing) from a position to another.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The azimuth of pos from this Position.
*/
@Override
public Azimuth azimuth(Position p1, Position p2) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
double p2Lat = p2.getLatRads();
double p2Lon = p2.getLonRads();
double dLon = p2Lon - p1Lon;
double y = sin(dLon) * cos(p2Lat);
double x = cos(p1Lat) * sin(p2Lat) - sin(p1Lat) * cos(p2Lat) * cos(dLon);
// Calculate the azimuth.
return new Azimuth(atan2(y, x));
}
/**
* Calculate the azimuth and distance from a position to another.
*
* This function may be faster than calling azimuth(p1, p2)
* and distance(p1, p2), if both parts are required.
*
* @param p1 Position to calculate the vector from.
* @param p2 Position to calculate the vector to.
* @return The Vector from p1 to p2.
*/
@Override
public Vector vector(Position p1, Position p2) {
Distance dist = distance(p1, p2);
Azimuth fwdAz = azimuth(p1, p2);
return new Vector(dist, fwdAz);
}
/**
* Calculate a second position given its offset from a given position.
*
* @param p1 Position to calculate from.
* @param distance The Distance to the desired position.
* @param azimuth The Azimuth to the desired position.
* @return The position given by the azimuth and distance
* from p1. Returns null if the result
* could not be computed.
*/
@Override
public Position offset(Position p1, Distance distance, Azimuth azimuth) {
double p1Lat = p1.getLatRads();
double p1Lon = p1.getLonRads();
Ellipsoid ellipsoid = getEllipsoid();
double angDist = distance.getMetres() / ellipsoid.axis;
double azRads = azimuth.getRadians();
// Pre-calculate some sines and cosines to save multiple calls.
double sinLat = sin(p1Lat);
double cosLat = cos(p1Lat);
double sinDist = sin(angDist);
double cosDist = cos(angDist);
// Calculate the result.
double lat2 = asin(sinLat * cosDist + cosLat * sinDist * cos(azRads));
double lon2 = p1Lon + atan2(sin(azRads) * sinDist * cosLat,
cosDist - sinLat * sin(lat2));
// Return the result, if we got one.
if (isNaN(lat2) || isNaN(lon2))
return null;
return new Position(lat2, lon2);
}
}
| 6,278 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Azimuth.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/Azimuth.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
import static java.lang.Math.toRadians;
import org.hermit.utils.Angle;
/**
* This class represents a geographic azimuth -- ie. a compass heading
* from or to a given geographic position.
*
* @author Ian Cameron Smith
*/
public final class Azimuth
extends Angle
{
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create an Azimuth from an azimuth given in radians.
*
* @param radians Source azimuth in radians, clockwise from north.
*/
public Azimuth(double radians) {
// Normalize to the range 0 <= radians < 2 * PI.
super(modTwoPi(radians));
}
// ******************************************************************** //
// Accessors and Converters.
// ******************************************************************** //
/**
* Create a Azimuth from an azimuth given in degrees.
*
* @param degrees Source azimuth in degrees, clockwise from north.
* @return The new Azimuth.
*/
public static Azimuth fromDegrees(double degrees) {
return new Azimuth(toRadians(degrees));
}
// ******************************************************************** //
// Azimuth Arithmetic.
// ******************************************************************** //
/**
* Calculate the azimuth which is the given angular offset from this one.
*
* @param radians Offset to add to this Azimuth, in radians;
* positive is clockwise from north, may be
* negative.
* @return Azimuth which is equal to this Azimuth plus
* the given offset. Overflow is taken care of.
*/
@Override
public Azimuth add(double radians) {
// The constructor takes care of normalization.
return new Azimuth(getRadians() + radians);
}
}
| 2,613 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
GeoCalculator.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/geo/GeoCalculator.java |
/**
* geo: geographical utilities.
* <br>Copyright 2004-2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
package org.hermit.geo;
/**
* Base class for geographic data calculators. Subclasses of this class
* provide functions like distance and azimuth calculation; since there are
* multiple algorithms with very different accuracy and complexity, the user
* can select which subclass they wish to use.
*
* @author Ian Cameron Smith
*/
public abstract class GeoCalculator
implements GeoConstants
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Definition of the algorithm to be used.
*/
public enum Algorithm {
/** The Haversine algorithm -- assumes a spherical Earth. */
HAVERSINE,
/** As per Haversine, but uses the better Andoyer method for distance. */
ANDOYER,
/** The very accurate but slow Vincenty method. */
VINCENTY;
// The instantiated calculator for this algorithm, once we have
// created it.
private GeoCalculator calculator = null;
}
// ******************************************************************** //
// Public Constructors.
// ******************************************************************** //
/**
* Create a calculator using the WGS84 ellipsoid.
*/
public GeoCalculator() {
this(Ellipsoid.WGS84);
}
/**
* Create a calculator using a given ellipsoid.
*
* @param ellip The ellipsoid to use for geodetic calculations.
*/
public GeoCalculator(Ellipsoid ellip) {
ellipsoid = ellip;
}
// ******************************************************************** //
// Algorithm Selection.
// ******************************************************************** //
/**
* Get the geodetic calculator in use.
*
* @return The algorithm currently in use.
*/
public static Algorithm getCurrentAlgorithm() {
return defaultCalculator.getAlgorithm();
}
/**
* Set the geodetic calculator to use for future calculations.
* The default is HAVERSINE.
*
* @param algorithm The algorithm to use. If it has a selectable
* ellipsoid, then the WGS84 ellipsoid will
* be used.
*/
public static void setAlgorithm(Algorithm algorithm) {
defaultCalculator = getCalculator(algorithm, Ellipsoid.WGS84);
}
/**
* Set the geodetic calcualtor to use for future calculations.
* The default is HAVERSINE.
*
* @param algorithm The algorithm to use.
* @param ellipsoid If the algorithm has a selectable
* ellipsoid, then this ellipsoid will
* be used.
*/
public static void setAlgorithm(Algorithm algorithm, Ellipsoid ellipsoid) {
defaultCalculator = getCalculator(algorithm, ellipsoid);
}
/**
* Get the default geodetic calcualtor.
*
* @return The default geodetic calcualtor.
*/
public static GeoCalculator getCalculator() {
return defaultCalculator;
}
/**
* Get a geodetic calcualtor based on the indicated algorithm.
*
* @param algorithm The algorithm to use. If it has a selectable
* ellipsoid, then the WGS84 ellipsoid will
* be used.
* @return A calculator for the given algorithm.
*/
private static GeoCalculator getCalculator(Algorithm algorithm) {
return getCalculator(algorithm, Ellipsoid.WGS84);
}
/**
* Get a geodetic calculator based on the indicated algorithm.
*
* @param algorithm The algorithm to use.
* @param ellipsoid If the algorithm has a selectable
* ellipsoid, then this ellipsoid will
* be used.
* @return A calculator for the given algorithm.
*/
private static GeoCalculator getCalculator(Algorithm algorithm,
Ellipsoid ellipsoid)
{
switch (algorithm) {
case HAVERSINE:
algorithm.calculator = new HaversineCalculator(Ellipsoid.SPHERE);
break;
case ANDOYER:
algorithm.calculator = new AndoyerCalculator(ellipsoid);
break;
case VINCENTY:
algorithm.calculator = new VincentyCalculator(ellipsoid);
break;
}
return algorithm.calculator;
}
// ******************************************************************** //
// Geodetic Methods.
// ******************************************************************** //
/**
* Get the algorithm this calculator uses.
*
* @return The algorithm this calculator uses.
*/
public abstract Algorithm getAlgorithm();
/**
* Get the ellipsoid for this calculator.
*
* @return The ellipsoid this calculator was configured
* with.
*/
Ellipsoid getEllipsoid() {
return ellipsoid;
}
/**
* Calculate the distance between two positions.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The distance between p1 and p2.
*/
public abstract Distance distance(Position p1, Position p2);
/**
* Calculate the distance between a position and a given latitude.
*
* @param p1 Position to calculate the distance from.
* @param lat Latitude in radians to calculate the distance to.
* @return The distance of this Position from lat.
*/
public abstract Distance latDistance(Position p1, double lat);
/**
* Calculate the azimuth (bearing) from a position to another.
*
* @param p1 Position to calculate the distance from.
* @param p2 Position to calculate the distance to.
* @return The azimuth of pos from this Position.
*/
public abstract Azimuth azimuth(Position p1, Position p2);
/**
* Calculate the azimuth and distance from a position to another.
*
* This function may be faster than calling azimuth(p1, p2)
* and distance(p1, p2), if both parts are required.
*
* @param p1 Position to calculate the vector from.
* @param p2 Position to calculate the vector to.
* @return The Vector from p1 to p2.
*/
public abstract Vector vector(Position p1, Position p2);
/**
* Calculate a second position given its offset from a given position.
*
* @param p1 Position to calculate from.
* @param distance The Distance to the desired position.
* @param azimuth The Azimuth to the desired position.
* @return The position given by the azimuth and distance
* from p1. Returns null if the result
* could not be computed.
*/
public abstract Position offset(Position p1, Distance distance, Azimuth azimuth);
// ******************************************************************** //
// Private Class Data.
// ******************************************************************** //
// The default GeoCalculator used for geodetic calculations.
private static GeoCalculator defaultCalculator =
getCalculator(Algorithm.HAVERSINE);
// ******************************************************************** //
// Private Member Data.
// ******************************************************************** //
// The ellipsoid to use for the geodetic computations.
private Ellipsoid ellipsoid = null;
}
| 7,711 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Window.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/dsp/Window.java |
/**
* dsp: various digital signal processing algorithms
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.dsp;
/**
* A windowing function for a discrete signal. This is used to
* pre-process a signal prior to FFT, in order to improve the frequency
* response, essentially by eliminating the discontinuities at the ends
* of a block of samples.
*/
public final class Window {
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Definitions of the available window functions.
*/
public enum Function {
/** A simple rectangular window function. This is equivalent to
* doing no windowing. */
RECTANGULAR,
/** The Blackman-Harris window function. */
BLACKMAN_HARRIS,
/** The Gauss window function. */
GAUSS,
/** The Weedon-Gauss window function. */
WEEDON_GAUSS,
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a window function for a given sample size. This preallocates
* resources appropriate to that block size.
*
* @param size The number of samples in a block that we will
* be asked to transform.
*/
public Window(int size) {
this(size, DEFAULT_FUNC);
}
/**
* Create a window function for a given sample size. This preallocates
* resources appropriate to that block size.
*
* @param size The number of samples in a block that we will
* be asked to transform.
* @param function The window function to use. Function.RECTANGULAR
* effectively means no transformation.
*/
public Window(int size, Function function) {
blockSize = size;
// Create the window function as an array, so we do the
// calculations once only. For RECTANGULAR, leave the kernel as
// null, signalling no transformation.
kernel = function == Function.RECTANGULAR ? null : new double[size];
switch (function) {
case RECTANGULAR:
// Nothing to do.
break;
case BLACKMAN_HARRIS:
makeBlackmanHarris(kernel, size);
break;
case GAUSS:
makeGauss(kernel, size);
break;
case WEEDON_GAUSS:
makeWeedonGauss(kernel, size);
break;
}
}
// ******************************************************************** //
// Window Functions.
// ******************************************************************** //
private void makeBlackmanHarris(double[] buf, int len) {
final double n = (double) (len - 1);
for (int i = 0; i < len; ++i) {
final double f = Math.PI * (double) i / n;
buf[i] = BH_A0 -
BH_A1 * Math.cos(2.0 * f) +
BH_A2 * Math.cos(4.0 * f) -
BH_A3 * Math.cos(6.0 * f);
}
}
private void makeGauss(double[] buf, int len) {
final double k = (double) (len - 1) / 2;
for (int i = 0; i < len; ++i) {
final double d = (i - k) / (0.4 * k);
buf[i] = Math.exp(-0.5 * d * d);
}
}
private void makeWeedonGauss(double[] buf, int len) {
final double k = (-250.0 * 0.4605) / (double) (len * len);
final double d = (double) len / 2.0;
for (int i = 0; i < len; ++i) {
final double n = (double) i - d;
buf[i] = Math.exp(n * n * k);
}
}
// ******************************************************************** //
// Data Transformation.
// ******************************************************************** //
/**
* Apply the window function to a given data block. The data in
* the provided buffer will be multiplied by the window function.
*
* @param input The input data buffer. This data will be
* transformed in-place by the window function.
* @throws IllegalArgumentException Invalid data size.
*/
public final void transform(double[] input) {
transform(input, 0, input.length);
}
/**
* Apply the window function to a given data block. The data in
* the provided buffer will be multiplied by the window function.
*
* @param input The input data buffer. This data will be
* transformed in-place by the window function.
* @param off Offset in the buffer at which the data to
* be transformed starts.
* @param count Number of samples in the data to be
* transformed. Must be the same as the size
* parameter that was given to the constructor.
* @throws IllegalArgumentException Invalid data size.
*/
public final void transform(double[] input, int off, int count) {
if (count != blockSize)
throw new IllegalArgumentException("bad input count in Window:" +
" constructed for " + blockSize +
"; given " + input.length);
if (kernel != null)
for (int i = 0; i < blockSize; i++)
input[off + i] *= kernel[i];
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Default window function.
private static final Function DEFAULT_FUNC = Function.BLACKMAN_HARRIS;
// Blackman-Harris coefficients. These sum to 1.0.
private static final double BH_A0 = 0.35875;
private static final double BH_A1 = 0.48829;
private static final double BH_A2 = 0.14128;
private static final double BH_A3 = 0.01168;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The size of an input data block.
private final int blockSize;
// The window function, as a pre-computed array of multiplication factors.
// If null, do no transformation -- this is a unity rectangular window.
private final double[] kernel;
}
| 7,211 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
FFTTransformer.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/dsp/FFTTransformer.java |
/**
* dsp: various digital signal processing algorithms
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.dsp;
import org.hermit.utils.Bitwise;
import ca.uol.aig.fftpack.RealDoubleFFT;
/**
* Implementation of the Cooley–Tukey FFT algorithm by Tsan-Kuang Lee,
* for real-valued data and results:
* http://www.ling.upenn.edu/~tklee/Projects/dsp/
*
* <p>His copyright statement: "Do whatever you want with the code.
* Feedbacks and improvement welcome."
*
* <p>Usage: create an FFTTransformer with a specified block size, to
* pre-allocate the necessary resources. Then, for each block that
* you want to transform:
* <ul>
* <li>Call {@link #setInput(float[], int, int)} to
* supply the input data. The execution of this method is the only
* time your input buffer will be accessed; the data is converted
* to complex and copied to a different buffer.
* <li>Call {@link #transform()} to actually do the FFT. This is the
* time-consuming part.
* <li>Call {@link #getResults(float[])} to get the results into
* your output buffer.
* </ul>
* <p>The flow is broken up like this to allow you to make best use of
* locks. For example, if the input buffer is also accessed by a thread
* which reads from the audio, you only need to lock out that thread during
* {@link #setInput(float[], int, int)}, not the entire FFT process.
*/
public final class FFTTransformer {
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an FFT transformer for a given sample size. This preallocates
* resources appropriate to that block size.
*
* @param size The number of samples in a block that we will
* be asked to transform. Must be a power of 2.
* @throws IllegalArgumentException Invalid parameter.
*/
public FFTTransformer(int size) {
this(size, (Window) null);
}
/**
* Create an FFT transformer for a given sample size. This preallocates
* resources appropriate to that block size. A specified window
* function will be applied to all input data.
*
* @param size The number of samples in a block that we will
* be asked to transform. Must be a power of 2.
* @param winfunc Window function to apply to all input data.
* @throws IllegalArgumentException Invalid parameter.
*/
public FFTTransformer(int size, Window.Function winfunc) {
this(size, new Window(size, winfunc));
}
/**
* Create an FFT transformer for a given sample size. This preallocates
* resources appropriate to that block size. A specified window
* function will be applied to all input data.
*
* @param size The number of samples in a block that we will
* be asked to transform. Must be a power of 2.
* @param window Window function to apply to all input data.
* Its block size must be the same as the size
* parameter.
* @throws IllegalArgumentException Invalid parameter.
*/
public FFTTransformer(int size, Window window) {
if (!Bitwise.isPowerOf2(size))
throw new IllegalArgumentException("size for FFT must" +
" be a power of 2 (was " + size + ")");
windowFunc = window;
transformer = new RealDoubleFFT(size);
blockSize = size;
// Allocate working data arrays.
xre = new double[blockSize];
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set a new windowing function for this analyser.
*
* @param func The desired windowing function.
*/
public void setWindowFunc(Window.Function func) {
windowFunc = new Window(blockSize, func);
}
// ******************************************************************** //
// Data Setup.
// ******************************************************************** //
/**
* Set up a new data block for the FFT algorithm. The data in
* the provided buffer will be copied out, and that buffer
* will not be referenced again. This is separated
* out from the main computation to allow for more efficient use
* of locks.
*
* @param input The input data buffer.
* @param off Offset in the buffer at which the data to
* be transformed starts.
* @param count Number of samples in the data to be
* transformed. Must be the same as the size
* parameter that was given to the constructor.
* @throws IllegalArgumentException Invalid data size.
*/
public final void setInput(float[] input, int off, int count) {
if (count != blockSize)
throw new IllegalArgumentException("bad input count in FFT:" +
" constructed for " + blockSize +
"; given " + input.length);
// Copy and transform the samples into our internal data buffer.
for (int i = 0; i < blockSize; i++)
xre[i] = input[off + i];
}
/**
* Set up a new data block for the FFT algorithm. The data in
* the provided buffer will be copied out, and that buffer
* will not be referenced again. This is separated
* out from the main computation to allow for more efficient use
* of locks.
*
* @param input The input data buffer.
* @param off Offset in the buffer at which the data to
* be transformed starts.
* @param count Number of samples in the data to be
* transformed. Must be the same as the size
* parameter that was given to the constructor.
* @throws IllegalArgumentException Invalid data size.
*/
public final void setInput(short[] input, int off, int count) {
if (count != blockSize)
throw new IllegalArgumentException("bad input count in FFT:" +
" constructed for " + blockSize +
"; given " + input.length);
// Copy and transform the samples into our internal data buffer.
for (int i = 0; i < blockSize; i++)
xre[i] = (double) input[off + i] / 32768.0;
}
// ******************************************************************** //
// Transform.
// ******************************************************************** //
/**
* Transform the data provided in the last call to setInput.
*/
public final void transform() {
// If we have a window function, apply it now.
if (windowFunc != null)
windowFunc.transform(xre);
// Do the FFT.
transformer.ft(xre);
}
// ******************************************************************** //
// Results.
// ******************************************************************** //
/**
* Get the real results of the last transformation.
*
* @param buffer Buffer in which the real part of the results
* will be placed. This buffer must be half the
* length of the input block. If transform() has
* not been called, the results will be garbage.
* @return The parameter buffer.
* @throws IllegalArgumentException Invalid buffer size.
*/
public final float[] getResults(float[] buffer) {
if (buffer.length != blockSize / 2)
throw new IllegalArgumentException("bad output buffer size in FFT:" +
" must be " + (blockSize / 2) +
"; given " + buffer.length);
final float scale = blockSize * FUDGE;
for (int i = 0; i < blockSize / 2; i++) {
double r = xre[i * 2];
double im = i == 0 ? 0.0 : xre[i * 2 - 1];
buffer[i] = (float) (Math.sqrt(r * r + im * im)) / scale;
}
return buffer;
}
/**
* Get the rolling average real results of the last n transformations.
*
* @param average Buffer in which the averaged real part of the
* results will be maintained. This buffer must be
* half the length of the input block. It is
* important that this buffer is kept intact and
* undisturbed between calls, as the average
* calculation for each value depends on the
* previous average.
* @param histories Buffer in which the historical values of the
* results will be kept. This must be a rectangular
* array, the first dimension being the same as
* average. The second dimension determines the
* length of the history, and hence the time over
* which values are averaged. It is
* important that this buffer is kept intact and
* undisturbed between calls.
* @param index Current history index. The caller needs to pass
* in zero initially, and save the return value
* of this method to pass in as index next time.
* @return The updated index value. Pass this in as
* the index parameter next time around.
* @throws IllegalArgumentException Invalid buffer size.
*/
public final int getResults(float[] average, float[][] histories, int index) {
if (average.length != blockSize / 2)
throw new IllegalArgumentException("bad history buffer size in FFT:" +
" must be " + (blockSize / 2) +
"; given " + average.length);
if (histories.length != blockSize / 2)
throw new IllegalArgumentException("bad average buffer size in FFT:" +
" must be " + (blockSize / 2) +
"; given " + histories.length);
// Update the index.
int historyLen = histories[0].length;
if (++index >= historyLen)
index = 0;
// Now do the rolling average of each value.
final float scale = blockSize * FUDGE;
for (int i = 0; i < blockSize / 2; i++) {
double r = xre[i * 2];
double im = i == 0 ? 0.0 : xre[i * 2 - 1];
final float val = (float) (Math.sqrt(r * r + im * im)) / scale;
final float[] hist = histories[i];
final float prev = hist[index];
hist[index] = val;
average[i] = average[i] - prev / historyLen + val / historyLen;
}
return index;
}
// ******************************************************************** //
// Results Analysis.
// ******************************************************************** //
/**
* Given the results of an FFT, identify prominent frequencies
* in the spectrum.
*
* <p><b>Note:</b> this is experimental and not very good.
*
* @param spectrum Audio spectrum data, as returned by
* {@link #getResults(float[])}.
* @param results Buffer into which the results will be placed.
* @return The parameter buffer.
* @throws IllegalArgumentException Invalid buffer size.
*/
public final int findKeyFrequencies(float[] spectrum, float[] results) {
final int len = spectrum.length;
// Find the average strength.
float average = 0f;
for (int i = 0; i < len; ++i) {
average += spectrum[i];
}
average /= len;
// Find all excursions above 2*average. Group adjacent highs
// together.
int count = 0;
for (int i = 0; i < len && count < results.length; ++i) {
if (spectrum[i] > 2 * average) {
// Compute the weighted average frequency of this peak.
float tot = 0f;
float wavg = 0f;
int j;
for (j = i; j < len && spectrum[j] > 3 * average; ++j) {
tot += spectrum[j];
wavg += spectrum[j] * (float) j;
}
wavg /= tot;
results[count++] = wavg;
// Skip past this peak.
i = j;
}
}
return count;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Fudge factor to scale the FFT output to the range 0-1.
private static final float FUDGE = 0.63610f;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Window function to apply to all input data. If null, no windowing.
private Window windowFunc = null;
// The FFT transformer.
private RealDoubleFFT transformer;
// The size of an input data block.
private final int blockSize;
// Working array -- real data being processed.
private final double[] xre;
}
| 14,642 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SignalPower.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/dsp/SignalPower.java |
/**
* dsp: various digital signal processing algorithms
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.dsp;
/**
* A power metering algorithm.
*/
public final class SignalPower {
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Only static methods are provided in this class.
*/
private SignalPower() {
}
// ******************************************************************** //
// Algorithm.
// ******************************************************************** //
/**
* Calculate the bias and range of the given input signal.
*
* @param sdata Buffer containing the input samples to process.
* @param off Offset in sdata of the data of interest.
* @param samples Number of data samples to process.
* @param out A float array in which the results will be placed
* Must have space for two entries, which will be
* set to:
* <ul>
* <li>The bias, i.e. the offset of the average
* signal value from zero.
* <li>The range, i.e. the absolute value of the largest
* departure from the bias level.
* </ul>
* @throws NullPointerException Null output array reference.
* @throws ArrayIndexOutOfBoundsException Output array too small.
*/
public final static void biasAndRange(short[] sdata, int off, int samples,
float[] out)
{
// Find the max and min signal values, and calculate the bias.
short min = 32767;
short max = -32768;
int total = 0;
for (int i = off; i < off + samples; ++i) {
final short val = sdata[i];
total += val;
if (val < min)
min = val;
if (val > max)
max = val;
}
final float bias = (float) total / (float) samples;
final float bmin = min + bias;
final float bmax = max - bias;
final float range = Math.abs(bmax - bmin) / 2f;
out[0] = bias;
out[1] = range;
}
/**
* Calculate the power of the given input signal.
*
* @param sdata Buffer containing the input samples to process.
* @param off Offset in sdata of the data of interest.
* @param samples Number of data samples to process.
* @return The calculated power in dB relative to the maximum
* input level; hence 0dB represents maximum power,
* and minimum power is about -95dB. Particular
* cases of interest:
* <ul>
* <li>A non-clipping full-range sine wave input is
* about -2.41dB.
* <li>Saturated input (heavily clipped) approaches
* 0dB.
* <li>A low-frequency fully saturated input can
* get above 0dB, but this would be pretty
* artificial.
* <li>A really tiny signal, which only occasionally
* deviates from zero, can get below -100dB.
* <li>A completely zero input will produce an
* output of -Infinity.
* </ul>
* <b>You must be prepared to handle this infinite
* result and results greater than zero,</b> although
* clipping them off would be quite acceptable in
* most cases.
*/
public final static double calculatePowerDb(short[] sdata, int off, int samples) {
// Calculate the sum of the values, and the sum of the squared values.
// We need longs to avoid running out of bits.
double sum = 0;
double sqsum = 0;
for (int i = 0; i < samples; i++) {
final long v = sdata[off + i];
sum += v;
sqsum += v * v;
}
// sqsum is the sum of all (signal+bias)², so
// sqsum = sum(signal²) + samples * bias²
// hence
// sum(signal²) = sqsum - samples * bias²
// Bias is simply the average value, i.e.
// bias = sum / samples
// Since power = sum(signal²) / samples, we have
// power = (sqsum - samples * sum² / samples²) / samples
// so
// power = (sqsum - sum² / samples) / samples
double power = (sqsum - sum * sum / samples) / samples;
// Scale to the range 0 - 1.
power /= MAX_16_BIT * MAX_16_BIT;
// Convert to dB, with 0 being max power. Add a fudge factor to make
// a "real" fully saturated input come to 0 dB.
return Math.log10(power) * 10f + FUDGE;
}
// ******************************************************************** //
// Constants.
// ******************************************************************** //
// Maximum signal amplitude for 16-bit data.
private static final float MAX_16_BIT = 32768;
// This fudge factor is added to the output to make a realistically
// fully-saturated signal come to 0dB. Without it, the signal would
// have to be solid samples of -32768 to read zero, which is not
// realistic. This really is a fudge, because the best value depends
// on the input frequency and sampling rate. We optimise here for
// a 1kHz signal at 16,000 samples/sec.
private static final float FUDGE = 0.6f;
}
| 6,459 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AstroConstants.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/AstroConstants.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.PI;
import static java.lang.Math.toRadians;
/**
* Definitions of useful global constants related to astronomical calculations.
*/
public interface AstroConstants
{
/**
* Half pi; a quarter circle in radians; same as 90 degrees.
*/
public static final double HALFPI = PI / 2;
/**
* Two times pi; a circle in radians; same as 360 degrees.
*/
public static final double TWOPI = PI * 2;
/**
* The number of seconds in a day.
*/
public static final double SECS_PER_DAY = 60 * 60 * 24;
/**
* The Julian date of the Unix/Java 1970 Jan 1.0 epoch relative to the
* astronomical epoch of 4713 BC.
*/
public static final double JD_UNIX = 2440587.5;
/**
* The Julian date of the 1900 Jan 0.5 epoch (which is actually noon,
* 31 Dec 1989) relative to the astronomical epoch of 4713 BC.
*/
public static final double J1900 = 2415020.0;
/**
* The Julian date of the 1990 Jan 0.0 epoch (which is actually 31 Dec
* 1989) relative to the astronomical epoch of 4713 BC.
*/
public static final double J1990 = 2447891.5;
/**
* The Julian date of the 2000 Jan 1.5 epoch (which is actually 1 Jan
* 2000 at noon) relative to the astronomical epoch of 4713 BC.
*/
public static final double J2000 = 2451545.0;
/**
* The obliquity of the ecliptic (angle between the ecliptic and the
* equator) at epoch 2000 Jan 1.5, in radians.
*/
public static final double ε_2000 = toRadians(23.4392911);
/**
* The length of the sidereal year in mean solar days.
*/
public static final double SIDEREAL_RATIO = 1.00273790935;
/**
* The length of the sidereal year in mean solar days.
*/
public static final double SIDEREAL_YEAR = 365.2564;
/**
* The length of the tropical year in mean solar days.
*/
public static final double TROPICAL_YEAR = 365.242191;
/**
* The vertical displacement of an object due to atmospheric
* refraction -- 24 arcmins.
*/
public static final double REFRACTION = toRadians(34.0 / 60.0);
/**
* The constant of aberration, κ.
*/
public static final double ABERRATION = toRadians(20.49552 / 3600.0);
/**
* The angle of the Sun below the horizon at the start / end
* of twilight, in radians.
*/
public static final double TWILIGHT = toRadians(18);
/**
* One AU, in km.
*/
public static final double AU = 149597870;
}
| 3,558 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Body.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Body.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.log10;
import static java.lang.Math.round;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
import org.hermit.astro.Observation.OField;
import org.hermit.geo.Position;
/**
* A celestial body in astronomical calculations; this class calculates
* and caches all parameters relating to a specific body. Derived
* classes represent specific bodies or types of body.
*
* <p>The public enum {@link Name} identifies a particular body. It also contains
* all the orbital elements and other static info for each body.
*
* <p>Applications do not create instances of Body; they are obtained by
* calling {@link Observation#getSun()}, {@link Observation#getMoon()} and
* {@link Observation#getPlanet(Body.Name which)}.
*
* <p>The core of this class is a database of all the data we have calculated
* for this body. Fields in the database are identified by enum {@link Field};
* clients ask for a particular field by calling {@link #get(Field)}. All field
* values are doubles. Each member of Field has a pointer to the
* calculation method which calculates the value of that field (and
* maybe others); if a value is requested which is not in the database,
* the calculation method is called automatically. Hence the database
* acts as a cache of computed data for the body.
*
* <p>The cache must be invalidated, by calling invalidate(), if any of the
* circumstances of the current observation (such as time) changes. This
* is generally done by the controlling {@link Observation} automatically.
*
* <p>Since there may be multiple Observations in existence at one time,
* there may well be multiple versions of each Body floating around, since
* a Body -- and its associated cached data -- is associated with the
* set of circumstances in a particular Observation. So be sure you keep
* straight which Sun, for example, is which.
*
* <p>Note that we depart from the usual Java naming conventions here. To
* simplify reference to source materials, variables are named according
* to the original source text, Greek letters included. So, be careful
* when looking at names; "Χ" may be the Greek Chi, rather than Roman.
*
* @author Ian Cameron Smith
*/
public abstract class Body
implements AstroConstants
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* This enumeration defines the celestial bodies we know about. Each
* member of the enum also contains the following information for the body:
* <ul>
* <li>Name
* <li>Symbol (note not all fonts, e.g. on Android, have all the syms)
* <li>Periodic terms, for planets
* <li>Diameter in arcseconds at 1 AU (not semi-diameter!)
* <li>Base factor in the calculation of magnitude; from AA chapter
* 41. Note we use the "since 1984" table.
* </ul>
*
* <p>Note that not all parameters are relevant to all objects. The
* Moon's diameter and magnitude are calculated in a special way.
*
* <p>Note: for Jupiter and Saturn, the apparent diameter and hence
* magnitude depend on the angle at which they present themselves
* to the Earth. We ignore this since we only need a rough magnitude.
*
* <p>NOTE: the angular data in the definitions is presented in the units
* noted. However we convert to RADIANS for the stored values.
*/
public enum Name {
// Name Sym Terms Diam Mag
/** The Sun. */
SUN( "Sun", '☉', null, 1919.26, -26.74),
/** The Moon. */
MOON( "Moon", '☾', null, 0.00, 0.00),
/** Mercury. */
MERCURY("Mercury", '☿', Vsop87.MERCURY, 6.74, -0.42),
/** Venus. */
VENUS( "Venus", '♀', Vsop87.VENUS, 16.82, -4.40),
/** The Earth. */
EARTH( "Earth", '♁', Vsop87.EARTH, 0.00, 0.00),
/** Mars. */
MARS( "Mars", '♂', Vsop87.MARS, 9.36, -1.52),
/** Jupiter. */
JUPITER("Jupiter", '♃', Vsop87.JUPITER, 196.74, -9.40),
/** Saturn. */
SATURN( "Saturn", '♄', Vsop87.SATURN, 165.6, -8.88),
/** Uranus. */
URANUS( "Uranus", '♅', Vsop87.URANUS, 68.56, -7.19),
/** Neptune. */
NEPTUNE("Neptune", '♆', Vsop87.NEPTUNE, 73.12, -6.87);
Name(String n, char sym, Vsop87 v, double d, double m) {
name = n;
symbol = sym;
terms = v;
θ_o = toRadians(d / 60 / 60);
V_o = m;
}
/** Name of this body. */
public final String name;
/** Symbol of this body. */
public final char symbol;
/** VSOP Periodic terms; null for the Sun and Moon. */
public final Vsop87 terms;
/** Apparent diameter in radians at 1 AU (not semi-diameter!). */
public final double θ_o;
/** Base factor for magnitude, from AA chapter 41. */
public final double V_o;
}
/**
* The names of all the celestial bodies we have information on.
*/
public static final Name[] ALL_BODIES = Name.values();
/**
* The number of celestial bodies we have information on.
*/
public static final int NUM_BODIES = ALL_BODIES.length;
// Class embodying a calculate method which works out one or more fields.
private abstract static class Calc {
abstract void c(Body b) throws AstroError;
}
/**
* This enumeration defines the data fields that are stored for
* each body.
*/
public enum Field {
/** The heliocentric latitude of the body, in radians. */
HE_LATITUDE,
/** The heliocentric longitude of the body, in radians. */
HE_LONGITUDE,
/** The heliocentric radius of the body, in AU. */
HE_RADIUS,
/** The ecliptic longitude of the body, in radians. */
EC_LONGITUDE,
/** The ecliptic latitude of the body, in radians. */
EC_LATITUDE,
/** The right ascension of the body, in radians. */
RIGHT_ASCENSION_AP,
/** The declination of the body, in radians. */
DECLINATION_AP,
/**
* The equatorial horizontal parallax, in radians.
*/
HORIZ_PARALLAX,
/**
* The topocentric right ascension of the body, in radians.
* This is RIGHT_ASCENSION_AP corrected for parallax.
*/
RIGHT_ASCENSION_TOPO,
/**
* The topocentric declination of the body, in radians.
* This is DECLINATION_AP corrected for parallax.
*/
DECLINATION_TOPO,
/**
* The azimuth of the body from the observer, in radians, 0=north.
*/
LOCAL_AZIMUTH,
/**
* The altitude of the body from the observer, in radians.
*/
LOCAL_ALTITUDE,
/** The local hour angle of the body from the observer, in radians. */
LOCAL_HOUR_ANGLE,
/** The distance of the body from the Earth, in AU. */
EARTH_DISTANCE,
/**
* The apparent diameter of the body from the observer's position,
* in radians.
*/
APPARENT_DIAMETER,
/**
* Time at which nautical twilight begins before sunrise (SUN only).
*/
RISE_TWILIGHT,
/**
* Rise time.
*/
RISE_TIME,
/**
* Transit time.
*/
TRANSIT_TIME,
/**
* Set time.
*/
SET_TIME,
/**
* Time at which nautical twilight ends after sunset (SUN only).
*/
SET_TWILIGHT,
/**
* The phase angle, i.e. Sun-Body_Earth angle, in radians.
*/
PHASE_ANGLE,
/**
* The phase, as the fraction (0-1) of the disc which is illuminated.
* This fraction applies to both area and diameter.
*/
PHASE,
/**
* Parallactic angle of this body as seen from the Earth.
*/
PARALLACTIC,
/**
* The position angle of the bright limb of this body from North.
*/
ABS_BRIGHT_LIMB,
/**
* The position angle of the bright limb of this body
* as seen from Earth.
*/
OBS_BRIGHT_LIMB,
/**
* The magnitude of this body as seen from Earth.
*/
MAGNITUDE;
private static void register(Field field, Calc calc) {
if (field.calculator != null)
throw new RuntimeException("Field " + field +
" already has a calculator");
field.calculator = calc;
}
private void calculate(Body b) throws AstroError {
if (calculator == null)
throw new RuntimeException("Field " + this + " has no calculator");
calculator.c(b);
}
private Calc calculator = null;
}
private static final Field[] ALL_FIELDS = Field.values();
private static final int NUM_FIELDS = ALL_FIELDS.length;
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Body. This method is only called from subclasses, and
* then only by {@link Observation}.
*
* @param o The Observation this Body belongs to. This
* contains all global configuration, like the
* current time.
* @param which Which body this is.
*/
protected Body(Observation o, Name which) {
observation = o;
whichBody = which;
// Create the data cache.
dataCache = new Double[NUM_FIELDS];
invalidate();
}
// ******************************************************************** //
// Body Information.
// ******************************************************************** //
/**
* Get this body's identifier.
*
* @return Which body this is.
*/
public Name getId() {
return whichBody;
}
/**
* Get this body's name.
*
* @return The name of this body.
*/
public String getName() {
return whichBody.name;
}
/**
* Get the value of one of the data fields of this body.
*
* @param key The field we want.
* @return The field value.
* @throws AstroError The request was invalid.
*/
public double get(Field key) throws AstroError {
if (dataCache[key.ordinal()] == null)
key.calculate(this);
// Get the value. It has to be there now.
Double val = dataCache[key.ordinal()];
if (val == null)
throw new CalcError("Calculator for field " + key + " failed");
return val;
}
// ******************************************************************** //
// Data Calculation.
// ******************************************************************** //
/**
* Calculate the heliocentric co-ordinates of the body for the currently
* configured time. Result is stored in the cache as HE_LATITUDE,
* HE_LONGITUDE and HE_RADIUS.
*/
static {
Calc calcHe = new Calc() {
@Override void c(Body b) throws AstroError { b.calcHePosition(); }
};
Field.register(Field.HE_LATITUDE, calcHe);
Field.register(Field.HE_LONGITUDE, calcHe);
Field.register(Field.HE_RADIUS, calcHe);
}
abstract void calcHePosition() throws AstroError;
/**
* Calculate the distance in AU, and the ecliptic longitude and
* latitude of the body for the currently configured time.
* Results are stored in the cache as EARTH_DISTANCE, EC_LONGITUDE
* and EC_LATITUDE.
*/
static {
Calc calcEc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcEcPosition(); }
};
Field.register(Field.EARTH_DISTANCE, calcEc);
Field.register(Field.EC_LONGITUDE, calcEc);
Field.register(Field.EC_LATITUDE, calcEc);
}
abstract void calcEcPosition() throws AstroError;
/**
* Calculate the apparent right ascension and
* declination of the body for the currently configured time.
* Results are stored in the cache as RIGHT_ASCENSION_AP
* and DECLINATION_AP.
*/
static {
Calc calc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcEqPosition(); }
};
Field.register(Field.RIGHT_ASCENSION_AP, calc);
Field.register(Field.DECLINATION_AP, calc);
}
void calcEqPosition() throws AstroError {
if (whichBody == Name.EARTH)
throw new AstroError("Cannot calculate RA and Dec of the Earth");
double λ = get(Field.EC_LONGITUDE);
double β = get(Field.EC_LATITUDE);
// Now convert to apparent equatorial co-ordinates -- in other
// words, taking nutation into account.
double[] pos = new double[2];
observation.eclipticToApparentEquatorial(λ, β, pos);
double α = pos[0];
double δ = pos[1];
put(Field.RIGHT_ASCENSION_AP, α);
put(Field.DECLINATION_AP, δ);
}
/**
* Calculate the parallax and topocentric co-ordinates of the
* body for the currently configured time.
* Results are stored in the cache as RIGHT_ASCENSION_AP
* and DECLINATION_AP.
*/
static {
Calc calc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcParallax(); }
};
Field.register(Field.HORIZ_PARALLAX, calc);
Field.register(Field.RIGHT_ASCENSION_TOPO, calc);
Field.register(Field.DECLINATION_TOPO, calc);
}
void calcParallax() throws AstroError {
if (whichBody == Name.EARTH)
throw new AstroError("Cannot calculate topocentric position of the Earth");
double α = get(Field.RIGHT_ASCENSION_AP);
double δ = get(Field.DECLINATION_AP);
double Δ = get(Field.EARTH_DISTANCE);
double H = get(Field.LOCAL_HOUR_ANGLE);
double ρsinφ1 = observation.get(OField.RHO_SIN_PHI1);
double ρcosφ1 = observation.get(OField.RHO_COS_PHI1);
// Calculate the equatorial horizontal parallax in radians.
double sinπ = 0.0000426345 / Δ;
double π = asin(sinπ);
// Calculate the adjusted right ascension.
double y1 = -ρcosφ1 * sinπ * sin(H);
double x = cos(δ) - ρcosφ1 * sinπ * cos(H);
double Δα = atan2(y1, x);
double α1 = α + Δα;
// Calculate the adjusted declination.
double y2 = (sin(δ) - ρsinφ1 * sinπ) * cos(Δα);
double δ1 = atan2(y2, x);
put(Field.HORIZ_PARALLAX, π);
put(Field.RIGHT_ASCENSION_TOPO, α1);
put(Field.DECLINATION_TOPO, δ1);
}
/**
* Calculate the local hour angle of this body for
* the currently configured time. Results are stored
* in the cache as LOCAL_HOUR_ANGLE.
*
* <p>From AA chapter 13.
*/
static {
Field.register(Field.LOCAL_HOUR_ANGLE, new Calc() {
@Override void c(Body b) throws AstroError { b.calcHourAngle(); }
});
}
void calcHourAngle() throws AstroError {
double α = get(Field.RIGHT_ASCENSION_AP);
double θo = observation.get(Observation.OField.GAST_INSTANT);
double L = observation.getObserverPosition().getLonRads();
// Convert the GST to radians.
double θor = toRadians(θo * 15.0);
// Get the local hour angle. Note longitude is positive East,
// contrary to Meeus.
double H = modTwoPi(θor + L - α);
put(Field.LOCAL_HOUR_ANGLE, H);
}
/**
* Calculate the local horizontal co-ordinates -- the altitude and
* azimuth -- of this body for the currently configured time. Results
* are stored in the cache as LOCAL_AZIMUTH and LOCAL_ALTITUDE.
*
* <p>Note that the azimuth is measured eastwards from north.
*/
static {
Calc calcAltAz = new Calc() {
@Override void c(Body b) throws AstroError { b.calcAltAzimuth(); }
};
Field.register(Field.LOCAL_AZIMUTH, calcAltAz);
Field.register(Field.LOCAL_ALTITUDE, calcAltAz);
}
void calcAltAzimuth() throws AstroError {
double δ = get(Field.DECLINATION_AP);
double H = get(Field.LOCAL_HOUR_ANGLE);
double π = get(Field.HORIZ_PARALLAX);
Position pos = observation.getObserverPosition();
double φ = pos.getLatRads();
double Ay = sin(H);
double Ax = cos(H) * sin(φ) - tan(δ) * cos(φ);
double A = atan2(Ay, Ax);
// Make azimuth north-based.
A = (A + PI) % TWOPI;
// Calculate the "local geocentric" altitude.
double sinh = sin(φ) * sin(δ) + cos(φ) * cos(δ) * cos(H);
double h = asin(sinh);
// Calculate the parallax in altitude (the parallax of azimuth is
// very small).
double ρ = pos.getCentreDistance();
double p = asin(ρ * sin(π) * cos(h));
put(Field.LOCAL_AZIMUTH, A);
put(Field.LOCAL_ALTITUDE, h - p);
}
/**
* Calculate the apparent diameter of this body from the Earth for the
* currently configured time. Results are stored in the cache as
* APPARENT_DIAMETER.
*
* <p>Note: the routine here works for the Sun and planets; however,
* for accuracy, we should calculate the angle of the rings of Saturn.
* We don't, because we just want a rough magnitude.
*
* <p>From AA chapter 55.
*/
static {
Field.register(Field.APPARENT_DIAMETER, new Calc() {
@Override void c(Body b) throws AstroError { b.calcApparentSize(); }
});
}
void calcApparentSize() throws AstroError {
if (whichBody == Name.EARTH)
throw new AstroError("Cannot calculate the apparent size of the Earth");
if (whichBody == Name.MOON)
throw new CalcError("calcApparentSize must be overridden for the Moon");
double Δ = get(Field.EARTH_DISTANCE);
// Calculate the angular diameter as seen from Earth.
double θ = whichBody.θ_o / Δ;
put(Field.APPARENT_DIAMETER, θ);
}
/**
* Calculate the rise and set times of this body for
* the currently configured day. The UT rise and set times in decimal
* hours are stored in the cache as RISE_TIME and SET_TIME; the
* azimuths of the rise and set points in radians are stored as
* RISE_AZIMUTH and SET_AZIMUTH.
*
* <p>From AA chapter 15.
*/
static {
Calc calc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcRiseSet(); }
};
Field.register(Field.RISE_TIME, calc);
Field.register(Field.SET_TIME, calc);
Field.register(Field.RISE_TWILIGHT, calc);
Field.register(Field.SET_TWILIGHT, calc);
}
void calcRiseSet() throws AstroError {
if (whichBody == Name.EARTH)
throw new AstroError("Cannot calculate rise/set for the Earth");
// Figure out the standard altitude for this body's rise or set, h_o.
// If this is the Moon, calculate h_o based on parallax. Otherwise,
// h_o is refraction plus the semi-diameter, in radians.
// Note that θ_o is the full diameter.
double h_o;
if (whichBody == Name.MOON) {
double π = get(Field.HORIZ_PARALLAX);
h_o = 0.7275 * π - REFRACTION;
} else
h_o = -(REFRACTION + whichBody.θ_o / 2);
// Get the observer's position. NOTE: my L is positive east,
// the opposite to Astronomical Algorithms.
Position pos = observation.getObserverPosition();
double φ = pos.getLatRads();
double L = pos.getLonRads();
// We need the apparent sidereal time for midnight UT, in radians.
// NOTE: this is midnight Universal Time!
double Θ0 = observation.get(Observation.OField.GAST_MIDNIGHT) * 15.0;
Θ0 = toRadians(Θ0);
// Calculate the Julian day number. We need observations of the
// body's positions for jday-1, jday, and jday+1 at 0h TD.
// NOTE: these times are midnight Dynamical Time!
Instant when = observation.getTime();
double ΔT = when.getΔT();
double jday = round(when.getTd() + 0.5) - 0.5;
Observation o1 = new Observation(Instant.fromTd(jday - 1));
Body b1 = o1.getBody(whichBody);
Observation o2 = new Observation(Instant.fromTd(jday));
Body b2 = o2.getBody(whichBody);
Observation o3 = new Observation(Instant.fromTd(jday + 1));
Body b3 = o3.getBody(whichBody);
// Get this body's position on each day.
double α1 = b1.get(Field.RIGHT_ASCENSION_AP);
double δ1 = b1.get(Field.DECLINATION_AP);
double α2 = b2.get(Field.RIGHT_ASCENSION_AP);
double δ2 = b2.get(Field.DECLINATION_AP);
double α3 = b3.get(Field.RIGHT_ASCENSION_AP);
double δ3 = b3.get(Field.DECLINATION_AP);
double[] αn = { α1, α2, α3 };
double[] δn = { δ1, δ2, δ3 };
// OK! First, calculate approximate time.
double cosH0 = (sin(h_o) - sin(φ) * sin(δ2)) / (cos(φ) * cos(δ2));
if (cosH0 < -1 || cosH0 > 1)
; // FIXME: signal no rise or set!
double H0 = acos(cosH0) % PI;
if (H0 < 0)
H0 += PI;
// Calculate transit, rise and set. These are in fractions of a day.
// Note the reversed sign of L relative to Meeus.
double transit = ((α2 - L - Θ0) / TWOPI) % 1.0;
if (transit < 0)
transit += 1.0;
double rise = (transit - H0 / TWOPI) % 1.0;
if (rise < 0)
rise += 1.0;
double set = (transit + H0 / TWOPI) % 1.0;
if (set < 0)
set += 1.0;
// Refine the values by interpolation.
transit = refineRiseSet(h_o, Θ0, φ, L, ΔT, αn, null, transit) * 24.0;
rise = refineRiseSet(h_o, Θ0, φ, L, ΔT, αn, δn, rise) * 24.0;
set = refineRiseSet(h_o, Θ0, φ, L, ΔT, αn, δn, set) * 24.0;
put(Field.RISE_TIME, rise);
put(Field.TRANSIT_TIME, transit);
put(Field.SET_TIME, set);
// Now, if this is the Sun, calculate the times of twilight.
if (whichBody == Name.SUN) {
// Calculate the duration of twilight.
double t = calculateTwilight(Θ0, φ, L, ΔT, αn, δn,
set / 24.0, HALFPI + TWILIGHT);
put(Field.RISE_TWILIGHT, rise - t);
put(Field.SET_TWILIGHT, set + t);
}
}
private double refineRiseSet(double h_o, double Θ0, double φ, double L,
double ΔT, double[] αn, double[] δn, double m)
{
final double[] args = { -1, 0, 1 };
double Θ0_now = modTwoPi(Θ0 + TWOPI * SIDEREAL_RATIO * m);
double n = m + ΔT / 86400;
// Interpolate for α, and calculate the local hour angle. Note
// the reversed sign of L.
double α = Util.interpolate(args, αn, n);
double H = Θ0_now + L - α;
// Interpolate for δ, if required.
double Δm;
if (δn != null) {
double δ = Util.interpolate(args, δn, n);
double sinh = sin(φ) * sin(δ) + cos(φ) * cos(δ) * cos(H);
double h = asin(sinh);
Δm = (h - h_o) / (TWOPI * cos(δ) * cos(φ) * sin(H));
} else
Δm = -H / TWOPI;
return m + Δm;
}
private double calculateTwilight(double Θ0, double φ, double L, double ΔT,
double[] αn, double[] δn, double m, double z)
{
double Θ0_now = modTwoPi(Θ0 + TWOPI * SIDEREAL_RATIO * m);
double n = m + ΔT / 86400;
// Interpolate for α, and calculate the local hour angle. Note
// the reversed sign of L.
final double[] args = { -1, 0, 1 };
double α = Util.interpolate(args, αn, n);
double δ = Util.interpolate(args, δn, n);
double H = Θ0_now + L - α;
// Convert these to the hour angles of twilight -- TWILIGHT below the
// horizon. Then calculate the duration of twilight in hours.
double cosH1 = (cos(z) - sin(φ) * sin(δ)) / (cos(φ) * cos(δ));
if (cosH1 < -1 || cosH1 > 1)
; // FIXME: signal no twilight!
double H1 = acos(cosH1);
double t = toDegrees(H1 - H) / 15.0;
return t;
}
/**
* Calculate the phase of this body as seen from the Earth for the
* currently configured time. Results are stored in the cache as
* PHASE_ANGLE and PHASE.
*/
static {
Calc calc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcPhase(); }
};
Field.register(Field.PHASE_ANGLE, calc);
Field.register(Field.PHASE, calc);
}
abstract void calcPhase() throws AstroError;
/**
* Calculate the parallactic angle of this body as
* seen from the Earth for the currently configured time. This is
* the angle from the zenith point ("top" of the object as seen by
* us) to the North point (direction from the body to the north
* celestial pole). The result is stored in the cache as
* PARALLACTIC.
*
* <p>If the value is undefined, i.e. if the object is in the
* zenith, then zero will be saved.
*
* <p>From AA chapter 14.
*/
static {
Field.register(Field.PARALLACTIC, new Calc() {
@Override void c(Body b) throws AstroError { b.calcParallactic(); }
});
}
void calcParallactic() throws AstroError {
double H = get(Field.LOCAL_HOUR_ANGLE);
Position pos = observation.getObserverPosition();
double φ = pos.getLatRads();
double δ = get(Field.DECLINATION_AP);
double y = sin(H);
double x = tan(φ) * cos(δ) - sin(δ) * cos(H);
double q = x == 0 ? 0 : atan2(y, x);
put(Field.PARALLACTIC, q);
}
/**
* Calculate the position angle of the bright limb of this body
* from North and as seen from Earth for the currently configured
* time. Results are stored in the cache as ABS_BRIGHT_LIMB and
* OBS_BRIGHT_LIMB.
*
* <p>From AA chapter 48.
*/
static {
Calc calc = new Calc() {
@Override void c(Body b) throws AstroError { b.calcBrightLimb(); }
};
Field.register(Field.ABS_BRIGHT_LIMB, calc);
Field.register(Field.OBS_BRIGHT_LIMB, calc);
}
void calcBrightLimb() throws AstroError {
if (whichBody == Name.EARTH || whichBody == Name.SUN)
throw new AstroError("Cannot calculate rise/set for the " +
whichBody.name);
double α = get(Field.RIGHT_ASCENSION_AP);
double δ = get(Field.DECLINATION_AP);
double q = get(Field.PARALLACTIC);
// We need data for the Sun too.
Sun sun = observation.getSun();
double αo = sun.get(Field.RIGHT_ASCENSION_AP);
double δo = sun.get(Field.DECLINATION_AP);
// Calculate the angle from north of the bright limb.
double Δα = αo - α;
double y = cos(δo) * sin(Δα);
double x = sin(δo) * cos(δ) - cos(δo) * sin(δ) * cos(Δα);
double Χ = modTwoPi(Math.atan2(y, x));
// Calculate the position as seen by the observer.
double obs = modTwoPi(Χ - q);
put(Field.ABS_BRIGHT_LIMB, Χ);
put(Field.OBS_BRIGHT_LIMB, obs);
}
/**
* Calculate the magnitude of this body as
* seen from the Earth for the currently configured time. Results
* are stored in the cache as MAGNITUDE.
*
* From AA chapter 41.
*/
static {
Field.register(Field.MAGNITUDE, new Calc() {
@Override void c(Body b) throws AstroError { b.calcMagnitude(); }
});
}
void calcMagnitude() throws AstroError {
if (whichBody == Name.EARTH)
throw new AstroError("Cannot calculate the magnitude of the Earth");
double Δ = get(Field.EARTH_DISTANCE);
double i = get(Field.PHASE_ANGLE);
// We want i in degrees, and its powers.
i = toDegrees(i);
double i2 = i * i;
double i3 = i2 * i;
// Get the distance from the Sun... for the Moon, I don't know how
// to calculate this, so use the Earth's.
double r;
if (whichBody == Name.SUN)
r = 0.0;
else if (whichBody == Name.MOON) {
Planet earth = observation.getPlanet(Planet.Name.EARTH);
r = earth.get(Field.HE_RADIUS);
} else
r = get(Field.HE_RADIUS);
// Get the base magnitude.
double mag = whichBody.V_o + (r == 0.0 ? 0.0 : 5 * log10(r * Δ));
switch (whichBody) {
case MOON:
break;
case MERCURY:
mag += 0.0380 * i - 0.000273 * i2 + 0.000002 * i3;
break;
case VENUS:
mag += 0.0009 * i + 0.000239 * i2 - 0.00000065 * i3;
break;
case MARS:
mag += 0.016 * i;
break;
case JUPITER:
mag += 0.005 * i;
break;
case SATURN:
// Note: this is a major approximation.
mag += 0.044 * abs(i);
break;
case SUN:
case EARTH:
case URANUS:
case NEPTUNE:
break;
}
put(Field.MAGNITUDE, mag);
}
// ******************************************************************** //
// Global Utilities.
// ******************************************************************** //
/**
* Iterative method to solve Kepler's equation. This will complete in
* a couple of iterations for for values of e <~ 0.1; larger values
* (such as for Pluto, or comets) will take longer.
*
* From section 47, Calculating orbits more precisely, routine R2.
*
* @param M Mean anomaly of the body in radians.
* @param e Eccentricity of the orbit.
* @return The eccentric anomaly in radians.
*/
static double kepler(double M, double e) {
// Solve E - e * sin(E) = M.
// First guess at the value: M.
double E = M;
int iterations = 0;
while (true) {
double δ = E - e * sin(E) - M;
if (abs(δ) <= KEPLER_TOLERANCE)
break;
if (++iterations > KEPLER_MAX_ITER)
throw new CalcError("Too many iterations in kepler, e=" + e);
double ΔE = δ / (1 - e * cos(E));
E -= ΔE;
}
return E;
}
/**
* Calculate the effect of aberration on a body, based on its ecliptical
* co-ordinates.
*
* <p>From AA chapter 23.
*
* @param td The JDE, i.e. JD in TD, for the observation.
* @param λ The ecliptic longitude, in radians.
* @param β The ecliptic latitude, in radians.
* @param Lsun The true (geometric) longitude of the Sun.
* @param pos An array { Δλ, Δβ } in which the adjustments
* for aberration in longitude and latitude in
* radians will be placed.
*/
static void aberrationEc(double td, double λ, double β, double Lsun, double[] pos) {
// Calculate the eccentricity and longitude of the perihelion of
// the Earth's orbit.
double T = (td - J2000) / 36525;
double T2 = T * T;
double e = 0.016708634 - 0.000042037 * T - 0.0000001267 * T2;
double π = 102.93735 + 1.71946 * T + 0.00046 * T2;
π = toRadians(π);
double Δλ = (-ABERRATION * cos(Lsun - λ) + e * ABERRATION * cos(π - λ)) / cos(β);
double Δβ = -ABERRATION * sin(β) * (sin(Lsun - λ) - e * sin(π - λ));
pos[0] = Δλ;
pos[1] = Δβ;
}
/**
* Return the given value mod PI, with negative values made positive --
* in other words, the value put into the range [0 .. PI).
*
* @param v Input value.
* @return v % PI, plus PI if negative.
*/
static final double modPi(double v) {
v %= PI;
return v < 0 ? v + PI : v;
}
/**
* Return the given value mod 2*PI, with negative values made positive --
* in other words, the value put into the range [0 .. TWOPI).
*
* @param v Input value.
* @return v % TWOPI, plus TWOPI if negative.
*/
static final double modTwoPi(double v) {
v %= TWOPI;
return v < 0 ? v + TWOPI : v;
}
/**
* Return the given value 360.0, with negative values made positive --
* in other words, the value put into the range [0 .. 360.0).
*
* @param v Input value.
* @return v % 360.0, plus 360.0 if negative.
*/
static final double mod360(double v) {
v %= 360.0;
return v < 0 ? v + 360.0 : v;
}
/**
* Convert an angle in arcseconds to radians.
*
* @param v An angle in arcseconds.
* @return The same angle converted to radians.
*/
static final double secsToRads(double v) {
return toRadians(v / 3600.0);
}
// ******************************************************************** //
// Cache Management.
// ******************************************************************** //
/**
* Save a specified value in the data cache.
*
* @param key The name of the value to save.
* @param val The value.
*/
protected void put(Field key, Double val) {
dataCache[key.ordinal()] = val;
}
/**
* Invalidate the data cache.
*/
protected void invalidate() {
for (int i = 0; i < NUM_FIELDS; ++i)
dataCache[i] = null;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// The tolerance allowed in the answer when solving Kepler's equation.
private static final double KEPLER_TOLERANCE = 10E-6;
// Maximum number of iterations allowed in the Kepler function.
private static final int KEPLER_MAX_ITER = 10;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The observation this body belongs to.
private Observation observation;
// Which body this is. This gives us access to all its orbital data.
private final Name whichBody;
// Cache of values calculated for this body at the currently
// configured date / time.
private Double[] dataCache;
}
| 32,870 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AstroError.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/AstroError.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
/**
* This exception is used to indicate an invalid request from the caller.
*/
public class AstroError
extends Exception
{
/**
* Create an exception with no message.
*/
public AstroError() {
super();
}
/**
* Create an exception with a message.
*
* @param msg Error message.
*/
public AstroError(String msg) {
super(msg);
}
private static final long serialVersionUID = 7246431317624145407L;
}
| 1,603 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Sun.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Sun.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.toRadians;
/**
* This class represents the Sun, and provides all known information
* about it.
*
* This subclass of {@link Body} basically provides custom calculation
* routines relevant to the Sun.
*
* Note that we depart from the usual Java naming conventions here. To
* simplify reference to source materials, variables are named according
* to the original source text, Greek letters included. So, be careful
* when looking at names; "Χ" may be the Greek Chi, rather than Roman.
*/
public class Sun
extends Body
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Sun. Note that this constructor is non-public; the
* only way to get a Sun is by calling Observation.getSun().
*
* @param o The Observation this Sun belongs to. This contains
* all global configuration, like the current time.
*/
Sun(Observation o) {
super(o, Name.SUN);
observation = o;
}
// ******************************************************************** //
// Data Calculation.
// ******************************************************************** //
/**
* Calculate the heliocentric co-ordinates of the body for the currently
* configured time. Result is stored in the cache as HE_LATITUDE,
* HE_LONGITUDE and HE_RADIUS.
*
* @throws AstroError Invalid request.
*/
@Override
void calcHePosition() throws AstroError {
throw new AstroError("Cannot calculate heliocentric position of the Sun");
}
/**
* Calculate the right ascension and declination of the Sun for
* the currently configured time -- fine method. Results are stored
* in the cache as EC_LONGITUDE and EC_LATITUDE, for ecliptic co-ordinates,
* and RIGHT_ASCENSION and DECLINATION for equatorial co-ordinates.
*
* <p>From AA chapter 25.
*
* @throws AstroError Invalid request.
*/
@Override
void calcEcPosition() throws AstroError {
// We need data for the Earth too.
Planet earth = observation.getPlanet(Planet.Name.EARTH);
// Get the heliocentric co-ordinates of the Earth, and the nutation
// in longitude.
double Lo = earth.get(Field.HE_LONGITUDE);
double Bo = earth.get(Field.HE_LATITUDE);
double Ro = earth.get(Field.HE_RADIUS);
// Calculate the geocentric lon and lat of the Sun.
double λ = Lo < PI ? Lo + PI : Lo - PI;
double β = -Bo;
// Convert to the FK5 system.
double T = (observation.getTd() - J2000) / 36525.0;
double T2 = T * T;
double λ1 = λ - toRadians(1.397) * T - toRadians(0.00031) * T2;
λ += secsToRads(-0.09033);
β += secsToRads(0.03916) * (cos(λ1) - sin(λ1));
// Correct for nutation and aberration.
// NOTE: Meeus says to add Δψ here; but it gets added when we
// convert to equatorial co-ordinates. Which is right?
// Seems doing both nutation bits in the same place makes sense
// (i.e. in eclipticToApparentEquatorial()).
λ = λ - secsToRads(20.4898) / Ro;
put(Field.EARTH_DISTANCE, Ro);
put(Field.EC_LONGITUDE, λ);
put(Field.EC_LATITUDE, β);
}
/**
* Calculate the phase of this body as seen from the Earth for the
* currently configured time. Results are stored in the cache as
* PHASE_ANGLE and PHASE.
*/
@Override
void calcPhase() {
// The Sun is always full.
put(Field.PHASE_ANGLE, PI);
put(Field.PHASE, 1.0);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The observation this Sun belongs to.
private Observation observation;
}
| 4,986 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Planet.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Planet.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.PI;
import static java.lang.Math.acos;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
/**
* This class represents a planet, and provides all known information
* about it.
*
* This subclass of {@link Body} basically provides custom calculation
* routines relevant to planets.
*
* Note that we depart from the usual Java naming conventions here. To
* simplify reference to source materials, variables are named according
* to the original source text, Greek letters included. So, be careful
* when looking at names; "Χ" may be the Greek Chi, rather than Roman.
*/
public class Planet
extends Body
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Planet. Note that this constructor is non-public; the
* only way to get a Planet is by calling Observation.getPlanet().
*
* @param o The Observation this Planet belongs to. This
* contains all global configuration, like the
* current time.
* @param which Which planet this is.
*/
Planet(Observation o, Name which) {
super(o, which);
observation = o;
whichPlanet = which;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Determine whether this is an inner planet (i.e. orbits the Sun inside
* the Earth's orbit).
*
* @return true if this is an inner planet.
*/
public boolean isInner() {
return whichPlanet == Name.MERCURY || whichPlanet == Name.VENUS;
}
// ******************************************************************** //
// Data Calculation.
// ******************************************************************** //
/**
* Calculate the heliocentric co-ordinates of the body for the currently
* configured time. Result is stored in the cache as HE_LATITUDE,
* HE_LONGITUDE and HE_RADIUS.
*
* <p>From AA chapter 32.
*/
@Override
void calcHePosition() {
// Calculate the Julian centuries elapsed since J2000 in
// dynamical time. We also need the time in millenia.
double T = (observation.getTd() - J2000) / 36525;
double Tm = T / 10.0;
// Calculate the heliocentric ecliptical longitude in radians.
double L = whichPlanet.terms.calculateL(Tm) % TWOPI;
if (L < 0)
L += TWOPI;
// Calculate the heliocentric latitude in radians.
double B = whichPlanet.terms.calculateB(Tm) % PI;
if (B < -HALFPI)
B += PI;
// Calculate the radius vector.
double R = whichPlanet.terms.calculateR(Tm);
put(Field.HE_LONGITUDE, L);
put(Field.HE_LATITUDE, B);
put(Field.HE_RADIUS, R);
}
/**
* Calculate the distance in AU, and the ecliptic longitude and
* latitude of the planet for the currently configured time.
* Results are stored in the cache as EARTH_DISTANCE, EC_LONGITUDE
* and EC_LATITUDE.
*
* From AA chapter 33.
*
* @throws AstroError Something went wrong.
*/
@Override
void calcEcPosition() throws AstroError {
if (whichPlanet == Planet.Name.EARTH)
throw new AstroError("Can't calculate the ecliptic position of the Earth");
// We need data for the Earth too.
Planet earth = observation.getPlanet(Planet.Name.EARTH);
// Get the heliocentric co-ordinates of this planet,
// and of the Earth.
double L = get(Field.HE_LONGITUDE);
double B = get(Field.HE_LATITUDE);
double R = get(Field.HE_RADIUS);
double Lo = earth.get(Field.HE_LONGITUDE);
double Bo = earth.get(Field.HE_LATITUDE);
double Ro = earth.get(Field.HE_RADIUS);
double x = R * cos(B) * cos(L) - Ro * cos(Bo) * cos(Lo);
double y = R * cos(B) * sin(L) - Ro * cos(Bo) * sin(Lo);
double z = R * sin(B) - Ro * sin(Bo);
// Calculate the distance to the planet, and its light-time in days.
double Δ = sqrt(x * x + y * y + z * z);
double τ = 0.0057755183 * Δ;
// OK, now correct for light-time. Figure out where the planet
// was at time now - τ.
Instant then = Instant.fromTd(observation.getTd() - τ);
Observation o = new Observation(then);
Planet p = o.getPlanet(whichPlanet);
L = p.get(Field.HE_LONGITUDE);
B = p.get(Field.HE_LATITUDE);
R = p.get(Field.HE_RADIUS);
// Now re-do the rectangular co-ordinates.
x = R * cos(B) * cos(L) - Ro * cos(Bo) * cos(Lo);
y = R * cos(B) * sin(L) - Ro * cos(Bo) * sin(Lo);
z = R * sin(B) - Ro * sin(Bo);
Δ = sqrt(x * x + y * y + z * z);
τ = 0.0057755183 * Δ;
// Note: we could iterate until the change in Δ becomes insignificant,
// but in reality two passes should do.
// Calculate the geometric co-ordinates.
double λ = modTwoPi(atan2(y, x));
double β = atan2(z, sqrt(x * x + y * y));
// Calculate and correct for the aberration.
double[] pos = new double[2];
double Lsun = Lo < PI ? Lo + PI : Lo - PI;
aberrationEc(observation.getTd(), λ, β, Lsun, pos);
λ = modTwoPi(λ + pos[0]);
β += pos[1];
// Now convert to the FK5 system. This is a tiny correction,
// but what the heck.
observation.vsopToFk5(λ, β, pos);
λ = pos[0];
β = pos[1];
put(Field.EARTH_DISTANCE, Δ);
put(Field.EC_LONGITUDE, λ);
put(Field.EC_LATITUDE, β);
}
/**
* Calculate the phase of this body as seen from the Earth for the
* currently configured time. Results are stored in the cache as
* PHASE_ANGLE and PHASE.
*
* <p>From AA chapter 41.
*
* @throws AstroError Invalid request.
*/
@Override
void calcPhase() throws AstroError {
if (whichPlanet == Name.EARTH)
throw new AstroError("Can't calcluate the phase of the Earth");
// We need data for the Sun too.
Sun sun = observation.getSun();
double r = get(Field.HE_RADIUS);
double Δ = get(Field.EARTH_DISTANCE);
double R = sun.get(Field.EARTH_DISTANCE);
// Calculate the phase angle of the planet.
double cosi = (r * r + Δ * Δ - R * R) / (2 * r * Δ);
double i = acos(cosi);
// Calculate the elongation of the Moon.
// double rΔ = r + Δ;
// double k = (rΔ * rΔ - R * R) / (4 * r * Δ);
// And now the phase.
double k = (1 + cosi) / 2;
put(Field.PHASE_ANGLE, i);
put(Field.PHASE, k);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The observation this Planet belongs to.
private Observation observation;
// Which planet this is. This gives us access to all its orbital data.
private final Name whichPlanet;
}
| 7,881 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Util.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Util.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
/**
* This class contains an implementation of Meeus' interpolation methods.
*
* @author Ian Cameron Smith
*/
public class Util
implements AstroConstants
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* No instances allowed.
*/
private Util() {
}
// ******************************************************************** //
// Interpolation Utilities.
// ******************************************************************** //
/**
* Interpolate in a table to find a good interpolated value.
*
* From AA chapter 3.
*
* @param args The arguments of the table. Each element is
* an index in the table (e.g. a time).
* @param values The values of the table. Each element is
* the value for the corresponding argument in args[].
* @param index The argument for which we want the
* interpolated value.
* @return The value of the table at index, interpolated
* from the point values.
*/
public static double interpolate(double[] args, double[] values, double index) {
int tablen = args.length;
if (tablen != values.length)
throw new IllegalArgumentException("Both tables for interpolate()" +
" must be the same length.");
if (tablen != 3)
throw new IllegalArgumentException("interpolate() can only handle" +
" tables of length 3. Sorry.");
// Compute the differences between subsequent elements.
// (This part is generic on the table size.)
double[][] diffTable = new double[tablen - 1][];
for (int col = 0; col < tablen - 1; ++col)
diffTable[col] = makeDiffs(col == 0 ? values : diffTable[col - 1]);
// Calculate the interpolating factor.
double n = index - args[1];
// And interpolate.
double sum = diffTable[0][0] + diffTable[0][1] + n * diffTable[1][0];
return values[1] + n / 2 * sum;
}
/**
* Make a table of differences for the given table.
*
* @param values
* @return
*/
private static double[] makeDiffs(double[] values) {
int n = values.length - 1;
double[] diffs = new double[n];
for (int i = 0; i < n; ++i)
diffs[i] = values[i + 1] - values[i];
return diffs;
}
}
| 3,465 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Instant.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Instant.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.floor;
/**
* A representation of a particular moment in time, with
* methods to convert between the numerous time systems used in astronomy.
*
* @author Ian Cameron Smith
*/
public class Instant
implements AstroConstants
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create an instant representing the current time.
*/
public Instant() {
this(System.currentTimeMillis());
}
/**
* Create an instant from a Julian day number in UT.
*
* @param jd The date to set as a fractional Julian day
* number relative to the astronomical epoch
* of 4713 BC UT.
*/
public Instant(double jd) {
julianDateUt = jd;
double[] ymd = julianToYmd(julianDateUt);
deltaT = calculateDeltaT((int) ymd[0], ymd[1] + ymd[2] / 31.0);
julianDateTd = julianDateUt + deltaT / SECS_PER_DAY;
}
/**
* Create an instant from a Java time in ms since 1 Jan 1970 UTC. This
* is the Unix time * 1000.
*
* @param time Java-style time in milliseconds since 1 Jan,
* 1970 UTC.
*/
public Instant(long time) {
this(javaToJulian(time));
}
/**
* Create an instant from a date / time in UT.
*
* @param y Year number; BC years are in astronomical form,
* so 1 BC = 0, 2 BC = -1, ...
* @param m Month number; January = 1.
* @param d Day of the month, including the fraction of
* the day; e.g. 0.25 = 6 a.m.
*/
public Instant(int y, int m, double d) {
this(ymdToJulian(y, m, d));
}
/**
* Create an instant from a date / time in UT.
*
* @param y Year number; BC years in astronomical form.
* @param m Month number; January = 1.
* @param d Day of the month.
* @param ho Hour.
* @param mn Minute.
* @param se Second.
*/
public Instant(int y, int m, int d, int ho, int mn, int se) {
this(ymdToJulian(y, m, d, ho, mn, se));
}
/**
* Create an instant from a Julian day in TD.
*
* @param td The date to set as a Julian day number relative
* to the astronomical epoch of 4713 BC UT, in
* TD.
* @return The new Instant.
*/
public static Instant fromTd(double td) {
return new Instant(tdToUt(td));
}
/**
* Create an instant from a date / time in TD. THis is mainly useful
* for running test cases, some of which specify time in TD.
*
* @param y Year number; BC years in astronomical form.
* @param m Month number; January = 1.
* @param d Day of the month, including the fraction of
* the day; e.g. 0.25 = 6 a.m.
* @return The new Instant.
*/
public static Instant fromTd(int y, int m, double d) {
double td = ymdToJulian(y, m, d);
return new Instant(tdToUt(td));
}
// ******************************************************************** //
// Getters.
// ******************************************************************** //
/**
* Get the Julian day number in UT represented by this Instant.
*
* @return The Julian day number in UT.
*/
public double getUt() {
return julianDateUt;
}
/**
* Convert this instant to year / month / day.
*
* From AA chapter 7.
*
* @return An array containing year, month, day, where
* the last value includes the fraction of
* the day; e.g. 0.25 = 6 a.m.
*/
public double[] getYmd() {
return julianToYmd(julianDateUt);
}
/**
* Get the Julian date in TD represented by this Instant.
*
* <p>Note that we don't distinguish between TDT(TT) and TDB, which
* are always within 0.0017 seconds.
*
* @return The Julian date in TD, in days.
*/
public double getTd() {
return julianDateTd;
}
/**
* Get the Greenwich mean sideral time represented by this Instant.
*
* @return The Greenwich mean sideral time in decimal hours.
*/
public double getGmst() {
return utToGmst(julianDateUt);
}
/**
* Get the Java time in ms since 1 Jan 1970 UTC represented by this
* Instant. This is the Unix time * 1000.
*
* @return The time in ms since 1 Jan 1970 UTC.
*/
public long getJavaTime() {
return julianToJava(julianDateUt);
}
/**
* Get the ΔT value for this Instant.
*
* @return ΔT in seconds.
*/
public double getΔT() {
return deltaT;
}
// ******************************************************************** //
// Time System Conversions.
// ******************************************************************** //
/**
* Convert a given Julian date from UT to TD.
*
* <p>Note that we don't distinguish between TDT(TT) and TDB, which
* are always within 0.0017 seconds.
*
* <p>From AA chapter 10.
*
* @param jd The Julian date in UT.
* @return The Julian date in TD, based on an
* approximation of ΔT.
*/
public static double utToTd(double jd) {
double[] ymd = julianToYmd(jd);
// ΔT is TDT - UT1 in seconds.
double ΔT = calculateDeltaT((int) ymd[0], ymd[1] + ymd[2] / 31.0);
return jd + ΔT / SECS_PER_DAY;
}
/**
* Convert a given Julian date from TD to UT.
*
* <p>Note that we don't distinguish between TDT(TT) and TDB, which
* are always within 0.0017 seconds.
*
* <p>From AA chapter 10.
*
* @param jd The Julian date in TD.
* @return The Julian date in UT, based on an
* approximation of ΔT.
*/
public static double tdToUt(double jd) {
double[] ymd = julianToYmd(jd);
// ΔT is TDT - UT1 in seconds.
double ΔT = calculateDeltaT((int) ymd[0], ymd[1] + ymd[2] / 31.0);
return jd - ΔT / SECS_PER_DAY;
}
// ******************************************************************** //
// Date and Time Utilities.
// ******************************************************************** //
/**
* Convert a given year / month / day to the Julian day relative
* to the astronomical epoch of 4713 BC.
*
* From AA chapter 7.
*
* @param y Year number; BC years in astronomical form.
* @param m Month number; January = 1.
* @param d Day of the month, including the fraction of
* the day; e.g. 0.25 = 6 a.m.
* @return The Julian date of the given Y/M/D, relative
* to the astronomical epoch of 4713 BC.
*/
public static double ymdToJulian(int y, int m, double d) {
if (m <= 2) {
--y;
m += 12;
}
int a = (int) floor((float) y / 100f);
int b = 2 - a + (int) floor((float) a / 4f);
return (int) floor(365.25 * (y + 4716)) +
(int) floor(30.6001 * (m + 1)) +
d + b - 1524.5;
}
/**
* Convert a given year / month / day to the Julian day relative
* to the astronomical epoch of 4713 BC.
*
* From AA chapter 7.
*
* @param y Year number; BC years in astronomical form.
* @param m Month number; January = 1.
* @param d Day of the month.
* @param ho Hour.
* @param mn Minute.
* @param se Second.
* @return The Julian date of the given Y/M/D, relative
* to the astronomical epoch of 4713 BC.
*/
public static double ymdToJulian(int y, int m, double d,
int ho, int mn, int se)
{
double df = ((double) se / 3600.0 + (double) mn / 60.0 + ho) / 24.0;
return ymdToJulian(y, m, (double) d + df);
}
/**
* Convert a given Julian day relative to the astronomical epoch
* of 4713 BC to year / month / day.
*
* From AA chapter 7.
*
* @param jd The Julian date to convert, relative
* to the astronomical epoch of 4713 BC.
* @return An array containing year, month, day, where
* the last value includes the fraction of
* the day; e.g. 0.25 = 6 a.m.
*/
public static double[] julianToYmd(double jd) {
jd += 0.5;
double z = floor(jd);
double f = jd - z;
double a;
if (z < 2299161)
a = z;
else {
double α = floor((z - 1867216.25) / 36524.25);
a = z + 1 + α - floor(α / 4.0);
}
double b = a + 1524;
double c = floor((b - 122.1) / 365.25);
double d = floor(365.25 * c);
double e = floor((b - d) / 30.6001);
double day = b - d - floor(30.6001 * e) + f;
double month = e < 14 ? e - 1 : e - 13;
double year = month > 2 ? c - 4716 : c - 4715;
return new double[] { year, month, day };
}
/**
* Convert a date/time in Java notation -- milliseconds since 1 Jan,
* 1970 -- to the Julian day relative to the astronomical epoch
* of 4713 BC.
*
* @param time Java-style time in milliseconds since 1 Jan,
* 1970.
* @return The equivalent Julian date relative
* to the astronomical epoch of 4713 BC.
*/
public static double javaToJulian(long time) {
// Convert the time to days since 1 Jan 1970 (with a fractional
// part).
double days = (double) time / 1000.0 / 3600.0 / 24.0;
// And add the julian date of the Unix epoch.
return days + JD_UNIX;
}
/**
* Convert a Julian day relative to the astronomical epoch
* of 4713 BC to the date/time in Java notation -- milliseconds
* since 1 Jan, 1970.
*
* @param julian A Julian date relative to the astronomical
* epoch of 4713 BC.
* @return The equivalent Java-style time in milliseconds
* since 1 Jan, 1970.
*/
public static long julianToJava(double julian) {
// Subtract the julian date of the Unix epoch.
double ubase = julian - JD_UNIX;
// Convert to a time in ms.
return (long) (ubase * 1000 * 3600 * 24);
}
/**
* Convert a UT time to Greenwich mean sideral time.
*
* From AA chapter 12.
*
* @param jd The Julian day number, including fraction.
* @return The Greenwich mean sideral time in decimal hours.
*/
@Deprecated
public static double utToGmst(double jd) {
// Get The Julian date of midnight on the day of the given time.
// This is a day number ending in .5. And get the decimal hour
// since midnight.
double midnight = floor(jd + 0.5) - 0.5;
double hour = (jd - midnight) * 24.0;
double d_u = midnight - J2000;
double T_u = d_u / 36525.0;
double T_u2 = T_u * T_u;
double T_u3 = T_u2 * T_u;
// Calculate the GMST in hours.
double T0 = 24110.54841 + 8640184.812866 * T_u +
0.093104 * T_u2 - 6.2E-6 * T_u3;
T0 /= 3600.0;
double GMST = (hour * 1.00273790935 + T0) % 24;
if (GMST < 0)
GMST += 24;
return GMST;
}
/**
* Convert a Greenwich sideral time to UT.
*
* NOTE: the sidereal day is shorter than the solar day, so some
* sidereal times (about the first 4 minutes) occur twice in a given day.
* This routine assumes that the GST is in the first interval, if
* it is ambiguous.
*
* From PAC section 13, GST to UT.
*
* @param JD The Julian date of midnight on the day of
* the given time.
* @param GST The Greenwich sideral time in decimal hours.
* @return The UT time in decimal hours.
*/
@Deprecated
public static double gstToUt(double JD, double GST) {
double S = JD - J2000;
double T = S / 36525.0;
double T0 = 6.697374558 + 2400.051336 * T + 0.000025862 * T * T;
T0 = T0 % 24;
if (T0 < 0)
T0 += 24;
double UT = (GST - T0) % 24;
if (UT < 0)
UT += 24;
UT *= 0.9972695663;
return UT;
}
/**
* Convert a Greenwich sidereal time to local sideral time.
*
* From PAC section 14, LST.
*
* @param GST The Greenwich sidereal time in decimal hours.
* @param Λ The observer's geographical longitude in radians;
* west longitudes negative, east positive.
* @return The local sideral time in decimal hours.
*/
@Deprecated
public static double gstToLst(double GST, double Λ) {
double H = Math.toDegrees(Λ) / 15;
double L = (GST + H) % 24;
if (L < 0)
L += 24;
return L;
}
/**
* Convert a local sidereal time to Greenwich sideral time.
*
* From PAC section 15, LST to GST.
*
* @param LST The local sidereal time in decimal hours.
* @param Λ The observer's geographical longitude in radians;
* west longitudes negative, east positive.
* @return The Greenwich sideral time in decimal hours.
*/
@Deprecated
public static double lstToGst(double LST, double Λ) {
double H = Math.toDegrees(Λ) / 15;
double G = (LST - H) % 24;
if (G < 0)
G += 24;
return G;
}
// ******************************************************************** //
// Formatting Utilities.
// ******************************************************************** //
/**
* Format a decimal time as a string in hours and minutes.
*
* @param hv The time to format, as fractional hours.
* @return The angle formatted in hours and minutes.
*/
public static String timeAsHm(Double hv) {
if (hv == null)
return "--";
double h = hv % 24.0;
if (h < 0)
h += 24;
int hour = (int) h;
int min = (int) (h * 60.0) % 60;
return String.format("%02d:%02d", hour, min);
}
/**
* Format a decimal time as a string in hours, minutes and seconds.
*
* @param hv The time to format, as decimal hours.
* @return The angle formatted in hours, minutes and seconds.
*/
public static String timeAsHms(Double hv) {
if (hv == null)
return "--";
double h = hv % 24.0;
if (h < 0)
h += 24;
int hour = (int) h;
int min = (int) (h * 60.0) % 60;
float sec = (float) (h * 3600.0) % 60f;
return String.format("%02d:%02d:%04.1f", hour, min, sec);
}
// ******************************************************************** //
// ΔT.
// ******************************************************************** //
/**
* Calculate an estimate of the value of ΔT, ie TD - UT in seconds,
* for a given moment in time.
*
* This method gives a reasonably good value over the period
* -1999 to +3000.
*
* Reference: Polynomial Expressions for Delta T (ΔT)
* Espenak and Meeus
* http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html
*
* @param year The year for which we want ΔT.
* @param month The fractional month; 0.5 = mid-Jan. Does not
* have to be terribly accurate, given the precision
* to which the variation in ΔT is known.
* @return The value of ΔT for the given year and month.
*/
public static double calculateDeltaT(int year, double month) {
double y = (double) year + month / 12.0;
double ΔT;
if (year < -500) {
double u = (y - 1820.0) / 100.0;
ΔT = -20.0 + 32.0 * u * u;
} else if (year < 500) {
// Between years -500 and +500, we use the data from Table 1,
// except that for the year -500 we changed the value 17190 to
// 17203.7 in order to avoid a discontinuity with the previous
// formula at that epoch. The value for ΔT is given by a
// polynomial of the 6th degree, which reproduces the values in
// Table 1 with an error not larger than 4 seconds:
double u = y / 100.0;
double u2 = u * u;
double u3 = u2 * u;
double u4 = u3 * u;
double u5 = u4 * u;
double u6 = u5 * u;
ΔT = 10583.6 - 1014.41 * u + 33.78311 * u2 - 5.952053 * u3
- 0.1798452 * u4 + 0.022174192 * u5 + 0.0090316521 * u6;
} else if (year < 1600) {
// Between years +500 and +1600, we again use the data from Table 1 to derive a polynomial of the 6th degree.
double u = (y - 1000.0) / 100.0;
double u2 = u * u;
double u3 = u2 * u;
double u4 = u3 * u;
double u5 = u4 * u;
double u6 = u5 * u;
ΔT = 1574.2 - 556.01 * u + 71.23472 * u2 + 0.319781 * u3
- 0.8503463 * u4 - 0.005050998 * u5 + 0.0083572073 * u6;
} else if (year < 1700) {
double t = y - 1600.0;
double t2 = t * t;
double t3 = t2 * t;
ΔT = 120.0 - 0.9808 * t - 0.01532 * t2 + t3 / 7129.0;
} else if (year < 1800) {
double t = y - 1700.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
ΔT = 8.83 + 0.1603 * t - 0.0059285 * t2
+ 0.00013336 * t3 - t4 / 1174000.0;
} else if (year < 1860) {
double t = y - 1800.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
double t5 = t4 * t;
double t6 = t5 * t;
double t7 = t6 * t;
ΔT = 13.72 - 0.332447 * t + 0.0068612 * t2 + 0.0041116 * t3
- 0.00037436 * t4 + 0.0000121272 * t5
- 0.0000001699 * t6 + 0.000000000875 * t7;
} else if (year < 1900) {
double t = y - 1860.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
double t5 = t4 * t;
ΔT = 7.62 + 0.5737 * t - 0.251754 * t2 + 0.01680668 * t3
-0.0004473624 * t4 + t5 / 233174.0;
} else if (year < 1920) {
double t = y - 1900.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
ΔT = -2.79 + 1.494119 * t - 0.0598939 * t2
+ 0.0061966 * t3 - 0.000197 * t4;
} else if (year < 1941) {
double t = y - 1920.0;
double t2 = t * t;
double t3 = t2 * t;
ΔT = 21.20 + 0.84493 * t - 0.076100 * t2 + 0.0020936 * t3;
} else if (year < 1961) {
double t = y - 1950.0;
double t2 = t * t;
double t3 = t2 * t;
ΔT = 29.07 + 0.407 * t - t2 / 233.0 + t3 / 2547.0;
} else if (year < 1986) {
double t = y - 1975.0;
double t2 = t * t;
double t3 = t2 * t;
ΔT = 45.45 + 1.067 * t - t2 / 260.0 - t3 / 718.0;
} else if (year < 2005) {
double t = y - 2000.0;
double t2 = t * t;
double t3 = t2 * t;
double t4 = t3 * t;
double t5 = t4 * t;
ΔT = 63.86 + 0.3345 * t - 0.060374 * t2 + 0.0017275 * t3
+ 0.000651814 * t4 + 0.00002373599 * t5;
} else if (year < 2050) {
// This expression is derived from estimated values of ΔT
// in the years 2010 and 2050. The value for 2010 (66.9 seconds)
// is based on a linearly extrapolation from 2005 using 0.39
// seconds/year (average from 1995 to 2005). The value for
// 2050 (93 seconds) is linearly extrapolated from 2010 using
// 0.66 seconds/year (average rate from 1901 to 2000).
double t = y - 2000.0;
double t2 = t * t;
ΔT = 62.92 + 0.32217 * t + 0.005589 * t2;
} else if (year < 2150) {
// The last term is introduced to eliminate the discontinuity
// at 2050.
double u = (y - 1820.0) / 100.0;
double u2 = u * u;
ΔT = -20.0 + 32.0 * u2 - 0.5628 * (2150.0 - y);
} else {
double u = (y - 1820.0) / 100.0;
double u2 = u * u;
ΔT = -20.0 + 32.0 * u2;
}
return ΔT;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "astro";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The Julian date in days of this instant relative to the
// 4713 BC epoch in UT.
private final double julianDateUt;
// The Julian date in days of this instant relative to the
// 4713 BC epoch in TD.
private final double julianDateTd;
// The value for ΔT at this instant, in seconds.
private final double deltaT;
}
| 20,154 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Observation.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Observation.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
import org.hermit.geo.GeoConstants;
import org.hermit.geo.Position;
/**
* This class represents a particular set of circumstances for a
* calculation, for example at a particular location and moment in time.
* It provides methods to access information about all the celestial
* bodies relating to this observation.
*
* <p>There may be multiple Observations in existence at one time,
* each one representing a particular set of circumstances -- for example,
* a particular time of observation. Each Observation has its own set of
* Body objects associated with it.
*/
public class Observation
implements AstroConstants
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
// Class embodying a calculate method which works out one or more fields.
private abstract static class Calc {
abstract void c(Observation o);
}
/**
* This enumeration defines the data fields that are stored for
* each body.
*/
public enum OField {
/**
* The quantity ρ sin φ' is used for the calculation of parallax.
*/
RHO_SIN_PHI1,
/**
* The quantity ρ cos φ' is used for the calculation of parallax.
*/
RHO_COS_PHI1,
/**
* Greenwich mean sidereal time at midnight UT on the day of
* the observation.
*/
GMST_MIDNIGHT,
/**
* Greenwich mean sidereal time at the moment of the observation.
*/
GMST_INSTANT,
/**
* Greenwich apparent sidereal time at midnight UT on the day of
* the observation.
*/
GAST_MIDNIGHT,
/**
* Greenwich apparent sidereal time at the moment of the observation.
*/
GAST_INSTANT,
/**
* Local mean sidereal time at midnight UT on the day of
* the observation.
*/
LMST_MIDNIGHT,
/**
* Local mean sidereal time at the moment of the observation.
*/
LMST_INSTANT,
/**
* Local apparent sidereal time at midnight UT on the day of
* the observation.
*/
LAST_MIDNIGHT,
/**
* Local apparent sidereal time at the moment of the observation.
*/
LAST_INSTANT,
/**
* Nutation in longitude.
*/
NUTATION_IN_LONGITUDE,
/**
* Nutation in obliquity.
*/
NUTATION_IN_OBLIQUITY,
/**
* Mean obliquity.
*/
MEAN_OBLIQUITY,
/**
* True obliquity.
*/
TRUE_OBLIQUITY,
/**
* Apparent LST.
*/
APPARENT_LST;
private static void register(OField field, Calc calc) {
if (field.calculator != null)
throw new RuntimeException("Obs Field " + field +
" already has a calculator");
field.calculator = calc;
}
private void calculate(Observation o) {
if (calculator == null)
throw new RuntimeException("Obs Field " + this + " has no calculator");
calculator.c(o);
}
private Calc calculator = null;
}
private static final OField[] ALL_FIELDS = OField.values();
private static final int NUM_FIELDS = ALL_FIELDS.length;
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create an observation for a given Julian day.
*
* @param i The Instant of time for this observation.
*/
public Observation(Instant i) {
this(i, new Position(0, 0));
}
/**
* Create an observation for a given Julian day.
*
* @param i The Instant of time for this observation.
* @param pos The observer's geographical position.
*/
public Observation(Instant i, Position pos) {
observationTime = i;
observerPos = pos;
// Create the table where we will store bodies as we create them.
celestialBodies = new Body[Body.NUM_BODIES];
// Create the data cache.
dataCache = new Double[NUM_FIELDS];
invalidate();
}
/**
* Create an observation for a given Java time.
*
* @param time Java-style time in milliseconds since 1 Jan,
* 1970.
*/
public Observation(long time) {
this(new Instant(time));
}
/**
* Create an observation for a given Java time.
*
* @param time Java-style time in milliseconds since 1 Jan,
* 1970.
* @param pos The observer's geographical position.
*/
public Observation(long time, Position pos) {
this(new Instant(time), pos);
}
/**
* Create an observation for right now.
*/
public Observation() {
this(System.currentTimeMillis());
}
/**
* Create an observation for a given Julian day.
*
* @param jd The date to set as a Julian date relative
* to the astronomical epoch of 4713 BC UTC.
*/
public Observation(double jd) {
this(new Instant(jd));
}
// ******************************************************************** //
// Time Setup.
// ******************************************************************** //
/**
* Get the time of this Observation.
*
* @return The time of this Observation.
*/
public Instant getTime() {
return observationTime;
}
/**
* Get the UT1 Julian date of this Observation.
*
* @return The configured Julian date relative
* to the astronomical epoch of 4713 BC UT1.
*/
public double getUt() {
return observationTime.getUt();
}
/**
* Get the Julian date in TD of this Observation.
*
* <p>Note that we don't distinguish between TDT(TT) and TDB, which
* are always within 0.0017 seconds.
*
* @return The Julian date in TD, in days.
*/
public double getTd() {
return observationTime.getTd();
}
/**
* Set the time for calculations. This clears out any cached data we
* may have calculated.
*
* @param time The time to use for all calculations on this
* Observation.
*/
public void setTime(Instant time) {
observationTime = time;
// Invalidate the data caches.
invalidate();
}
/**
* Set the date / time of this Observation. This clears out any
* cached data we may have calculated.
*
* @param y Year number; BC years in astronomical form.
* @param m Month number; January = 1.
* @param d Day of the month, including the fraction of
* the day; e.g. 0.25 = 6 a.m.
*/
public void setDate(int y, int m, double d) {
setTime(new Instant(y, m, d));
}
/**
* Set the time of this Observation. This clears out any cached data we
* may have calculated.
*
* @param time Java-style time in milliseconds since 1 Jan,
* 1970.
*/
public void setJavaTime(long time) {
setTime(new Instant(time));
}
/**
* Set the time for calculations as a UTC Julian date. This clears
* out any cached data we may have calculated.
*
* @param jd The date to set as a Julian date relative
* to the astronomical epoch of 4713 BC UTC.
*/
public void setJulian(double jd) {
setTime(new Instant(jd));
}
/**
* Get the number of days since a given epoch.
*
* @param epoch Epoch of interest (e.g. Instant.JD_1990).
* @return The number of days since the 1990 Jan 0.0 epoch.
*/
public double getDaysSince(double epoch) {
return getUt() - epoch;
}
// ******************************************************************** //
// Observer Setup.
// ******************************************************************** //
/**
* Get the observer's geographical position.
*
* @return The observer's geographical position.
*/
public Position getObserverPosition() {
return observerPos;
}
/**
* Set the observer's position for this observation. This clears
* out any cached data we may have calculated.
*
* @param pos The observer's geographical position.
*/
public void setObserverPosition(Position pos) {
observerPos = pos;
// Invalidate the data caches.
invalidate();
}
/**
* Get the observer's altitude.
*
* @return The observer's altitude above sea level in metres.
*/
public double getObserverAltitude() {
return observerAlt;
}
/**
* Set the observer's altitude for this observation. This clears
* out any cached data we may have calculated.
*
* @param alt The observer's altitude above sea level in metres.
*/
public void setObserverAltitude(double alt) {
observerAlt = alt;
// Invalidate the data caches.
invalidate();
}
// ******************************************************************** //
// Celestial Bodies.
// ******************************************************************** //
/**
* Get the named celestial body. There is a single instance of each body
* associated with the set of observing circumstances represented by
* this Observation; we return a handle to that instance.
*
* <p>Bear in mind that there may be multiple Observations in use;
* each one has its own set of associated Body objects.
*
* @param which Which body to get.
* @return A handle on the instance of that body for this
* Observation.
*/
public Body getBody(Body.Name which) {
int ord = which.ordinal();
if (celestialBodies[ord] == null) {
Body bod;
if (which == Body.Name.SUN)
bod = new Sun(this);
else if (which == Body.Name.MOON)
bod = new Moon(this);
else
bod = new Planet(this, which);
celestialBodies[ord] = bod;
}
return celestialBodies[ord];
}
/**
* Get the Sun. There is a single instance of Sun
* associated with the set of observing circumstances represented by
* this Observation; we return a handle to that instance.
*
* <p>This is essentially a convenience routine which calls getBody()
* and casts the return to the correct type.
*
* @return A handle on the instance of the Sun for this
* Observation.
*/
public Sun getSun() {
try {
return (Sun) getBody(Body.Name.SUN);
} catch (ClassCastException e) {
throw new CalcError("SUN object is not an instance of Sun");
}
}
/**
* Get the Moon. There is a single instance of Moon
* associated with the set of observing circumstances represented by
* this Observation; we return a handle to that instance.
*
* <p>This is essentially a convenience routine which calls getBody()
* and casts the return to the correct type.
*
* @return A handle on the instance of the Moon for this
* Observation.
*/
public Moon getMoon() {
try {
return (Moon) getBody(Body.Name.MOON);
} catch (ClassCastException e) {
throw new CalcError("MOON object is not an instance of Moon");
}
}
/**
* Get a planet. There is a single instance of each planet
* associated with the set of observing circumstances represented by
* this Observation; we return a handle to that instance.
*
* <p>This is essentially a convenience routine which calls getBody()
* and casts the return to the correct type.
*
* @param which Which planet to get.
* @return A handle on the instance of the given planet
* for this Observation.
*/
public Planet getPlanet(Body.Name which) {
try {
return (Planet) getBody(which);
} catch (ClassCastException e) {
throw new CalcError(which.toString() +
" object is not an instance of Planet");
}
}
// ******************************************************************** //
// Circumstances Data.
// ******************************************************************** //
/**
* Get the value of one of the data fields of this Observation.
*
* @param key The field we want.
* @return The field value.
*/
public double get(OField key) {
if (dataCache[key.ordinal()] == null)
key.calculate(this);
// Get the value. It has to be there now.
Double val = dataCache[key.ordinal()];
if (val == null)
throw new CalcError("Calculator for observation field " +
key + " failed");
return val;
}
/**
* Save a specified value in the data cache.
*
* @param key The name of the value to save.
* @param val The value.
*/
protected void put(OField key, Double val) {
dataCache[key.ordinal()] = val;
}
/**
* Invalidate all of the data caches associated with this Observation.
*/
protected void invalidate() {
// Clear the data calculated for this Observation.
for (int i = 0; i < NUM_FIELDS; ++i)
dataCache[i] = null;
// Clear the caches in all the bodies.
for (Body b : celestialBodies)
if (b != null)
b.invalidate();
}
// ******************************************************************** //
// Data Calculation.
// ******************************************************************** //
/**
* Calculate the values of ρ sin φ' and ρ cos φ' for the observer on
* the currently configured date.
* The results are stored in the cache as RHO_SIN_PHI1, RHO_COS_PHI1.
*
* <p>From AA chapter 11.
*/
static {
Calc calc = new Calc() {
@Override void c(Observation o) { o.calcRhoPhiPrime(); }
};
OField.register(OField.RHO_SIN_PHI1, calc);
OField.register(OField.RHO_COS_PHI1, calc);
}
private void calcRhoPhiPrime() {
double φ = observerPos.getLatRads();
// Inverse of the Earth's flattening.
double f1 = GeoConstants.POLAR_RADIUS / GeoConstants.EQUATORIAL_RADIUS;
// Observer's altitude as a fraction of the equatorial radius.
double Hf= observerAlt / GeoConstants.EQUATORIAL_RADIUS;
// Compute the results.
double u = atan(f1 * tan(φ));
double ρsinφ1 = f1 * sin(u) + Hf * sin(φ);
double ρcosφ1 = cos(u) + Hf * cos(φ);
put(OField.RHO_SIN_PHI1, ρsinφ1);
put(OField.RHO_COS_PHI1, ρcosφ1);
}
/**
* Calculate the nutation in both longitude and obliquity for
* the currently configured date. The results are stored in the cache
* as NUTATION_IN_LONGITUDE and NUTATION_IN_OBLIQUITY.
*
* From AA chapter 22.
*/
static {
Calc calc = new Calc() {
@Override void c(Observation o) { o.calcNutation(); }
};
OField.register(OField.NUTATION_IN_LONGITUDE, calc);
OField.register(OField.NUTATION_IN_OBLIQUITY, calc);
}
private void calcNutation() {
// Note: we need Dynamical Time here.
double T = (observationTime.getTd() - J2000) / 36525.0;
double T2 = T * T;
double T3 = T2 * T;
// Calculate angles in degrees. Mean elongation of the Moon:
double D = 297.85036 + 445267.111480 * T - 0.0019142 * T2 + T3 / 189474;
// Mean anomaly of the Sun:
double M = 357.52772 + 35999.050340 * T - 0.0001603 * T2 - T3 / 300000;
// Mean anomaly of the Moon:
double M1 = 134.96298 + 477198.867398 * T + 0.0086972 * T2 + T3 / 56250;
// Moon's argument of latitude:
double F = 93.27191 + 483202.017538 * T - 0.0036825 * T2 + T3 / 327270;
// Longitude of the ascending node of the moon's mean orbit:
double Ω = 125.04452 - 1934.136261 * T + 0.0020708 * T2 + T3 / 450000;
// Calculate Δψ and Δε in arcseconds. Convert to radians.
double Δψ = 0;
double Δε = 0;
for (NutationTerm term : nutationTerms) {
double a = term.D * D + term.M * M +
term.M1 * M1 + term.F * F + term.Ω * Ω;
Δψ += (term.Δψ0 + term.Δψ1 * T) * sin(toRadians(a)) * 0.0001;
Δε += (term.Δε0 + term.Δε1 * T) * cos(toRadians(a)) * 0.0001;
}
Δψ = toRadians(Δψ / 3600);
Δε = toRadians(Δε / 3600);
put(OField.NUTATION_IN_LONGITUDE, Δψ);
put(OField.NUTATION_IN_OBLIQUITY, Δε);
}
/**
* Calculate the mean obliquity of the ecliptic (angle between the
* ecliptic and the equator, not including nutation) for the currently
* configured date. The result is stored in the cache as MEAN_OBLIQUITY.
*
* From AA chapter 22.
*/
static {
OField.register(OField.MEAN_OBLIQUITY, new Calc() {
@Override void c(Observation o) { o.calcMeanObliquity(); }
});
}
private void calcMeanObliquity() {
double j = getTd() - J2000;
double T = j / 36525.0;
double T2 = T * T;
double T3 = T2 * T;
// Calculate the delta, and convert to radians.
double delta = 46.8150 * T + 0.00059 * T2 - 0.001813 * T3;
delta = toRadians(delta / 3600.0);
// Get the obliquity.
double ε0 = ε_2000 - delta;
put(OField.MEAN_OBLIQUITY, ε0);
}
/**
* Calculate the true obliquity of the ecliptic (angle between the
* ecliptic and the equator, including the effect of nutation) for
* the currently configured date. The result is stored in the cache
* as TRUE_OBLIQUITY.
*
* From AA chapter 22.
*/
static {
OField.register(OField.TRUE_OBLIQUITY, new Calc() {
@Override void c(Observation o) { o.calcTrueObliquity(); }
});
}
private void calcTrueObliquity() {
double ε0 = get(OField.MEAN_OBLIQUITY);
double Δε = get(OField.NUTATION_IN_OBLIQUITY);
// Now we get the true obliquity.
double ε = ε0 + Δε;
put(OField.TRUE_OBLIQUITY, ε);
}
/**
* Calculate the mean sidereal time for the currently configured date.
* The results are stored in the cache as GMST_MIDNIGHT, GMST_INSTANT.
*
* From AA chapter 12.
*/
static {
Calc calc = new Calc() {
@Override void c(Observation o) { o.calcMeanSidereal(); }
};
OField.register(OField.GMST_MIDNIGHT, calc);
OField.register(OField.GMST_INSTANT, calc);
OField.register(OField.LMST_MIDNIGHT, calc);
OField.register(OField.LMST_INSTANT, calc);
}
private void calcMeanSidereal() {
// Get The Julian date of midnight on the day of the given time.
// This is a day number ending in .5. And get the decimal hour
// since midnight.
double jd = getUt();
double midnight = floor(jd + 0.5) - 0.5;
double hour = (jd - midnight) * 24.0;
double T = (midnight - J2000) / 36525.0;
double T2 = T * T;
double T3 = T2 * T;
// Calculate the GMST in hours.
double GMSTMidnight = 24110.54841 + 8640184.812866 * T +
0.093104 * T2 - 6.2E-6 * T3;
GMSTMidnight = (GMSTMidnight / 3600.0) % 24.0;
if (GMSTMidnight < 0)
GMSTMidnight += 24;
double GMST = (hour * 1.00273790935 + GMSTMidnight) % 24.0;
put(OField.GMST_MIDNIGHT, GMSTMidnight);
put(OField.GMST_INSTANT, GMST);
double offset = observerPos.getLonDegs() / 15.0;
double LMSTMidnight = (GMSTMidnight + offset) % 24.0;
if (LMSTMidnight < 0)
LMSTMidnight += 24;
double LMST = (GMST + offset) % 24.0;
if (LMST < 0)
LMST += 24;
put(OField.LMST_MIDNIGHT, LMSTMidnight);
put(OField.LMST_INSTANT, LMST);
}
/**
* Calculate the apparent sidereal time for the currently configured date.
* The results are stored in the cache as GAST_MIDNIGHT, GAST_INSTANT.
*
* From AA chapter 12.
*/
static {
Calc calc = new Calc() {
@Override void c(Observation o) { o.calcApparentSidereal(); }
};
OField.register(OField.GAST_MIDNIGHT, calc);
OField.register(OField.GAST_INSTANT, calc);
OField.register(OField.LAST_MIDNIGHT, calc);
OField.register(OField.LAST_INSTANT, calc);
}
private void calcApparentSidereal() {
double ε = get(OField.TRUE_OBLIQUITY);
double Δψ = get(OField.NUTATION_IN_LONGITUDE);
double GMSTMidnight = get(OField.GMST_MIDNIGHT);
double GMST = get(OField.GMST_INSTANT);
double LMSTMidnight = get(OField.LMST_MIDNIGHT);
double LMST = get(OField.LMST_INSTANT);
// Calculate the correction as a decimal hour fraction.
double corr = toDegrees(Δψ) * cos(ε) / 15.0;
double GASTMidnight = (GMSTMidnight + corr) % 24.0;
double GAST = (GMST + corr) % 24.0;
double LASTMidnight = (LMSTMidnight + corr) % 24.0;
double LAST = (LMST + corr) % 24.0;
put(OField.GAST_MIDNIGHT, GASTMidnight);
put(OField.GAST_INSTANT, GAST);
put(OField.LAST_MIDNIGHT, LASTMidnight);
put(OField.LAST_INSTANT, LAST);
}
// ******************************************************************** //
// Co-Ordinate Utilities.
// ******************************************************************** //
/**
* Convert ecliptic co-ordinates to mean equatorial co-ordinates
* (right ascension and declination) for the circumstances of this
* Observation. This does not take nutation into account.
*
* <p>Note the returned ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param λ The ecliptic longitude, in radians.
* @param β The ecliptic latitude, in radians.
* @param pos An array { α, δ } in which the right ascension
* in radians and the declination in radians will
* be placed.
*/
public void eclipticToMeanEquatorial(double λ, double β, double[] pos) {
double ε0 = get(OField.MEAN_OBLIQUITY);
ecToEq(ε0, λ, β, pos);
}
/**
* Convert ecliptic co-ordinates to apparent equatorial co-ordinates
* (right ascension and declination) for the circumstances of this
* Observation. This takes nutation into account -- so don't apply
* nutation to the returned values.
*
* <p>Note the returned ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param λ The ecliptic longitude, in radians.
* @param β The ecliptic latitude, in radians.
* @param pos An array { α, δ } in which the right ascension
* in radians and the declination in radians will
* be placed.
*/
public void eclipticToApparentEquatorial(double λ, double β, double[] pos) {
double Δψ = get(OField.NUTATION_IN_LONGITUDE);
double ε = get(OField.TRUE_OBLIQUITY);
ecToEq(ε, λ + Δψ, β, pos);
}
/**
* Convert ecliptic co-ordinates to equatorial co-ordinates
* (right ascension and declination) for a given value of the
* obliquity of the ecliptic.
*
* <p>Note the returned ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param ε The value to use for the obliquity of the ecliptic.
* @param λ The ecliptic longitude, in radians.
* @param β The ecliptic latitude, in radians.
* @param pos An array { α, δ } in which the right ascension
* in radians and the declination in radians will
* be placed.
*/
private static void ecToEq(double ε, double λ, double β, double[] pos) {
double y = sin(λ) * cos(ε) - tan(β) * sin(ε);
double x = cos(λ);
double α = atan2(y, x);
if (α < 0)
α += TWOPI;
double sinδ = sin(β) * cos(ε) + cos(β) * sin(ε) * sin(λ);
double δ = asin(sinδ);
pos[0] = α;
pos[1] = δ;
}
/**
* Convert mean equatorial co-ordinates (right ascension and
* declination) to ecliptic co-ordinates for the circumstances of this
* Observation. This does not take nutation into account.
*
* <p>Note the given ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param α The mean right ascension, in radians.
* @param δ The mean declination, in radians.
* @param pos An array { λ, β } in which the ecliptic longitude
* and the ecliptic latitude in radians will
* be placed.
*/
public void meanEquatorialToEcliptic(double α, double δ, double[] pos) {
double ε0 = get(OField.MEAN_OBLIQUITY);
eqToEc(ε0, α, δ, pos);
}
/**
* Convert apparent equatorial co-ordinates (right ascension and
* declination) to ecliptic co-ordinates for the circumstances of this
* Observation. This takes nutation into account.
*
* <p>Note the given ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param α The mean right ascension, in radians.
* @param δ The mean declination, in radians.
* @param pos An array { λ, β } in which the ecliptic longitude
* and the ecliptic latitude in radians will
* be placed.
*/
public void apparentEquatorialToEcliptic(double α, double δ, double[] pos) {
double Δψ = get(OField.NUTATION_IN_LONGITUDE);
double ε = get(OField.TRUE_OBLIQUITY);
eqToEc(ε, α, δ, pos);
// This is assumed based on eclipticToApparentEquatorial().
pos[0] -= Δψ;
}
/**
* Convert equatorial co-ordinates to ecliptic co-ordinates
* (ecliptic longitude and latitude) for a given value of the
* obliquity of the ecliptic.
*
* <p>Note the given ascension is in radians, not hours, for internal
* consistency.
*
* <p>From AA chapter 13.
*
* @param ε The value to use for the obliquity of the ecliptic.
* @param α The right ascension, in radians.
* @param δ The declination, in radians.
* @param pos An array { λ, β } in which the ecliptic longitude
* and the ecliptic latitude in radians will
* be placed.
*/
private static void eqToEc(double ε, double α, double δ, double[] pos) {
double y = sin(α) * cos(ε) + tan(δ) * sin(ε);
double x = cos(α);
double λ = modTwoPi(atan2(y, x));
double sinβ = sin(δ) * cos(ε) - cos(δ) * sin(ε) * sin(α);
double β = asin(sinβ);
pos[0] = λ;
pos[1] = β;
}
/**
* Convert co-ordinates in the VSOP87 system to the FK5 system.
*
* <p>From AA chapter 32.
*
* @param L The longitude in radians.
* @param B The latitude in radians.
* @param pos An array { L, B } in which the corrected
* longitude and latitude in radians will
* be placed.
*/
void vsopToFk5(double L, double B, double[] pos) {
double T = (getTd() - J2000) / 36525.0;
double T2 = T * T;
double L1 = L - toRadians(1.397) * T - toRadians(0.00031) * T2;
double ΔL = secsToRads(-0.09033) +
secsToRads(0.03916) * (cos(L1) + sin(L1)) * tan(B);
double ΔB = secsToRads(0.03916) * (cos(L1) - sin(L1));
pos[0] = L + ΔL;
pos[1] = B + ΔB;
}
// ******************************************************************** //
// Formatting Utilities.
// ******************************************************************** //
/**
* Format an angle as a string in degrees, minutes and seconds.
*
* From section 21 / 8.
*
* @param ar The angle to format, in radians.
* @return The angle formatted in degrees, minutes and seconds.
*/
@Deprecated
public static String angleAsDms(Double ar) {
if (ar == null)
return "--";
double a = toDegrees(ar);
int s = a < 0 ? -1 : 1;
a *= s;
int deg = (int) a * s;
int min = (int) (a * 60.0) % 60;
float sec = (float) (a * 3600.0) % 60f;
return String.format("%3d°%02d'%04.1f\"", deg, min, sec);
}
/**
* Format an angle as a string in hours, minutes and seconds. This is
* appropriate for a right ascension.
*
* From section 8.
*
* @param ar The angle to format, in radians.
* @return The angle formatted in hours, minutes and seconds.
*/
@Deprecated
public static String angleAsHms(Double ar) {
if (ar == null)
return "--";
double a = toDegrees(ar) % 360.0;
if (a < 0)
a += 360.0;
// Convert to hours.
double h = a / 15.0;
int hour = (int) h;
int min = (int) (h * 60.0) % 60;
float sec = (float) (h * 3600.0) % 60f;
return String.format("%3dh%02d'%04.1f\"", hour, min, sec);
}
/**
* Return the given value mod 2*PI, with negative values made positive --
* in other words, the value put into the range [0 .. TWOPI).
*
* @param v Input value.
* @return v % TWOPI, plus TWOPI if negative.
*/
static final double modTwoPi(double v) {
v %= TWOPI;
return v < 0 ? v + TWOPI : v;
}
/**
* Convert an angle in arcseconds to radians.
*
* @param v An angle in arcseconds.
* @return The same angle converted to radians.
*/
static final double secsToRads(double v) {
return toRadians(v / 3600.0);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "onwatch";
// Monster table of coefficients for the calculation of nutation.
private static final class NutationTerm {
NutationTerm(int D, int M, int M1, int F, int Ω,
double Δψ0, double Δψ1, double Δε0, double Δε1)
{
this.D = D;
this.M = M;
this.M1 = M1;
this.F = F;
this.Ω = Ω;
this.Δψ0 = Δψ0;
this.Δψ1 = Δψ1;
this.Δε0 = Δε0;
this.Δε1 = Δε1;
}
final int D;
final int M;
final int M1;
final int F;
final int Ω;
final double Δψ0;
final double Δψ1;
final double Δε0;
final double Δε1;
};
private static final NutationTerm nutationTerms[] = {
new NutationTerm( 0, 0, 0, 0, 1, -171996, -174.2, 92025, 8.9),
new NutationTerm(-2, 0, 0, 2, 2, -13187, -1.6, 5736, -3.1),
new NutationTerm( 0, 0, 0, 2, 2, -2274, -0.2, 977, -0.5),
new NutationTerm( 0, 0, 0, 0, 2, 2062, 0.2, -895, 0.5),
new NutationTerm( 0, 1, 0, 0, 0, 1426, -3.4, 54, -0.1),
new NutationTerm( 0, 0, 1, 0, 0, 712, 0.1, -7, 0),
new NutationTerm(-2, 1, 0, 2, 2, -517, 1.2, 224, -0.6),
new NutationTerm( 0, 0, 0, 2, 1, -386, -0.4, 200, 0),
new NutationTerm( 0, 0, 1, 2, 2, -301, 0, 129, -0.1),
new NutationTerm(-2, -1, 0, 2, 2, 217, -0.5, -95, 0.3),
new NutationTerm(-2, 0, 1, 0, 0, -158, 0, 0, 0),
new NutationTerm(-2, 0, 0, 2, 1, 129, 0.1, -70, 0),
new NutationTerm( 0, 0, -1, 2, 2, 123, 0, -53, 0),
new NutationTerm( 2, 0, 0, 0, 0, 63, 0, 0, 0),
new NutationTerm( 0, 0, 1, 0, 1, 63, 0.1, -33, 0),
new NutationTerm( 2, 0, -1, 2, 2, -59, 0, 26, 0),
new NutationTerm( 0, 0, -1, 0, 1, -58, -0.1, 32, 0),
new NutationTerm( 0, 0, 1, 2, 1, -51, 0, 27, 0),
new NutationTerm(-2, 0, 2, 0, 0, 48, 0, 0, 0),
new NutationTerm( 0, 0, -2, 2, 1, 46, 0, -24, 0),
new NutationTerm( 2, 0, 0, 2, 2, -38, 0, 16, 0),
new NutationTerm( 0, 0, 2, 2, 2, -31, 0, 13, 0),
new NutationTerm( 0, 0, 2, 0, 0, 29, 0, 0, 0),
new NutationTerm(-2, 0, 1, 2, 2, 29, 0, -12, 0),
new NutationTerm( 0, 0, 0, 2, 0, 26, 0, 0, 0),
new NutationTerm(-2, 0, 0, 2, 0, -22, 0, 0, 0),
new NutationTerm( 0, 0, -1, 2, 1, 21, 0, -10, 0),
new NutationTerm( 0, 2, 0, 0, 0, 17, -0.1, 0, 0),
new NutationTerm( 2, 0, -1, 0, 1, 16, 0, -8, 0),
new NutationTerm(-2, 2, 0, 2, 2, -16, 0.1, 7, 0),
new NutationTerm( 0, 1, 0, 0, 1, -15, 0, 9, 0),
new NutationTerm(-2, 0, 1, 0, 1, -13, 0, 7, 0),
new NutationTerm( 0, -1, 0, 0, 1, -12, 0, 6, 0),
new NutationTerm( 0, 0, 2, -2, 0, 11, 0, 0, 0),
new NutationTerm( 2, 0, -1, 2, 1, -10, 0, 5, 0),
new NutationTerm( 2, 0, 1, 2, 2, -8, 0, 3, 0),
new NutationTerm( 0, 1, 0, 2, 2, 7, 0, -3, 0),
new NutationTerm(-2, 1, 1, 0, 0, -7, 0, 0, 0),
new NutationTerm( 0, -1, 0, 2, 2, -7, 0, 3, 0),
new NutationTerm( 2, 0, 0, 2, 1, -7, 0, 3, 0),
new NutationTerm( 2, 0, 1, 0, 0, 6, 0, 0, 0),
new NutationTerm(-2, 0, 2, 2, 2, 6, 0, -3, 0),
new NutationTerm(-2, 0, 1, 2, 1, 6, 0, -3, 0),
new NutationTerm( 2, 0, -2, 0, 1, -6, 0, 3, 0),
new NutationTerm( 2, 0, 0, 0, 1, -6, 0, 3, 0),
new NutationTerm( 0, -1, 1, 0, 0, 5, 0, 0, 0),
new NutationTerm(-2, -1, 0, 2, 1, -5, 0, 3, 0),
new NutationTerm(-2, 0, 0, 0, 1, -5, 0, 3, 0),
new NutationTerm( 0, 0, 2, 2, 1, -5, 0, 3, 0),
new NutationTerm(-2, 0, 2, 0, 1, 4, 0, 0, 0),
new NutationTerm(-2, 1, 0, 2, 1, 4, 0, 0, 0),
new NutationTerm( 0, 0, 1, -2, 0, 4, 0, 0, 0),
new NutationTerm(-1, 0, 1, 0, 0, -4, 0, 0, 0),
new NutationTerm(-2, 1, 0, 0, 0, -4, 0, 0, 0),
new NutationTerm( 1, 0, 0, 0, 0, -4, 0, 0, 0),
new NutationTerm( 0, 0, 1, 2, 0, 3, 0, 0, 0),
new NutationTerm( 0, 0, -2, 2, 2, -3, 0, 0, 0),
new NutationTerm(-1, -1, 1, 0, 0, -3, 0, 0, 0),
new NutationTerm( 0, 1, 1, 0, 0, -3, 0, 0, 0),
new NutationTerm( 0, -1, 1, 2, 2, -3, 0, 0, 0),
new NutationTerm( 2, -1, -1, 2, 2, -3, 0, 0, 0),
new NutationTerm( 0, 0, 3, 2, 2, -3, 0, 0, 0),
new NutationTerm( 2, -1, 0, 2, 2, -3, 0, 0, 0),
};
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The current Julian date relative to the 4713 BC epoch. Null if
// not yet set.
private Instant observationTime = null;
// The observer's geographical position.
private Position observerPos = null;
// The observer's altitude above sea level in metres.
private double observerAlt = 0.0;
// The celestial bodies in this Universe.
private Body[] celestialBodies;
// Cache of values calculated for this body at the currently
// configured date / time.
private Double[] dataCache;
}
| 35,761 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Vsop87.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Vsop87.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.cos;
/**
* This class contains the tables of periodic terms from the VSOP87
* planetary theory. It also contains a simple method to calculate the
* value of any series for any moment in time.
*
* <p>Each instance of this class embodies the data tables for one planet.
*/
class Vsop87 {
// ******************************************************************** //
// Mercury.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] MERCURY_L = {
{
{ 440250710, 0.0, 0.0 },
{ 40989415, 1.48302034, 26087.90314157 },
{ 5046294, 4.47785449, 52175.8062831 },
{ 855347, 1.165203, 78263.709425 },
{ 165590, 4.119692, 104351.612566 },
{ 34562, 0.77931, 130439.51571 },
{ 7583, 3.7135, 156527.4188 },
{ 3560, 1.5120, 1109.3786 },
{ 1803, 4.1033, 5661.3320 },
{ 1726, 0.3583, 182615.3220 },
{ 1590, 2.9951, 25028.5212 },
{ 1365, 4.5992, 27197.2817 },
{ 1017, 0.8803, 31749.2352 },
{ 714, 1.541, 24978.525 },
{ 644, 5.303, 21535.950 },
{ 451, 6.050, 51116.424 },
{ 404, 3.282, 208703.225 },
{ 352, 5.242, 20426.571 },
{ 345, 2.792, 15874.618 },
{ 343, 5.765, 955.600 },
{ 339, 5.863, 25558.212 },
{ 325, 1.337, 53285.185 },
{ 273, 2.495, 529.691 },
{ 264, 3.917, 57837.138 },
{ 260, 0.987, 4551.953 },
{ 239, 0.113, 1059.382 },
{ 235, 0.267, 11322.664 },
{ 217, 0.660, 13521.751 },
{ 209, 2.092, 47623.853 },
{ 183, 2.629, 27043.503 },
{ 182, 2.434, 25661.305 },
{ 176, 4.536, 51066.428 },
{ 173, 2.452, 24498.830 },
{ 142, 3.360, 37410.567 },
{ 138, 0.291, 10213.286 },
{ 125, 3.721, 39609.655 },
{ 118, 2.781, 77204.327 },
{ 106, 4.206, 19804.827 }
},
{
{ 2608814706223.0, 0, 0 },
{ 1126008, 6.2170397, 26087.9031416 },
{ 303471, 3.055655, 52175.806283 },
{ 80538, 6.10455, 78263.70942 },
{ 21245, 2.83532, 104351.61257 },
{ 5592, 5.8268, 130439.5157 },
{ 1472, 2.5185, 156527.4188 },
{ 388, 5.480, 182615.322 },
{ 352, 3.052, 1109.379 },
{ 103, 2.149, 208703.225 },
{ 94, 6.12, 27197.28 },
{ 91, 0.00, 24978.52 },
{ 52, 5.62, 5661.33 },
{ 44, 4.57, 25028.52 },
{ 28, 3.04, 51066.43 },
{ 27, 5.09, 234791.13 }
},
{
{ 53050, 0, 0 },
{ 16904, 4.69072, 26087.90314 },
{ 7397, 1.3474, 52175.8063 },
{ 3018, 4.4564, 78263.7094 },
{ 1107, 1.264, 104351.6126 },
{ 378, 4.320, 130439.516 },
{ 123, 1.069, 156527.419 },
{ 39, 4.08, 182615.32 },
{ 15, 4.63, 1109.38 },
{ 12, 0.79, 208703.23 }
},
{
{ 188, 0.035, 52175.806 },
{ 142, 3.125, 26087.903 },
{ 97, 3.00, 78263.71 },
{ 44, 6.02, 104351.61 },
{ 35, 0, 0 },
{ 18, 2.78, 130439.52 },
{ 7, 5.82, 156527.42 },
{ 3, 2.57, 182615.32 }
},
{
{ 114, 3.1416, 0 },
{ 2, 2.03, 26087.90 },
{ 2, 1.42, 78263.71 },
{ 2, 4.50, 52175.81 },
{ 1, 4.50, 104351.61 },
{ 1, 1.27, 130439.52 }
},
{
{ 1, 3.14, 0 }
}
};
// Heliocentric latitude.
private static final double[][][] MERCURY_B = {
{
{ 11737529, 1.98357499, 26087.90314157 },
{ 2388077, 5.0373896, 52175.8062831 },
{ 1222840, 3.1415927, 0 },
{ 543252, 1.796444, 78263.709425 },
{ 129779, 4.832325, 104351.612566 },
{ 31867, 1.58088, 130439.51571 },
{ 7963, 4.6097, 156527.4188 },
{ 2014, 1.3532, 182615.3220 },
{ 514, 4.378, 208703.325 },
{ 209, 2.020, 24978.525 },
{ 208, 4.918, 27197.282 },
{ 132, 1.119, 234791.128 },
{ 121, 1.813, 53285.185 },
{ 100, 5.657, 20426.571 }
},
{
{ 429151, 3.501698, 26087.903142 },
{ 146234, 3.141593, 0 },
{ 22675, 0.01515, 52175.80628 },
{ 10895, 0.48540, 78263.70942 },
{ 6353, 3.4294, 104351.6126 },
{ 2496, 0.1605, 130439.5157 },
{ 860, 3.185, 156527.419 },
{ 278, 6.210, 182615.322 },
{ 86, 2.95, 208703.23 },
{ 28, 0.29, 27197.28 },
{ 26, 5.98, 234791.13 }
},
{
{ 11831, 4.79066, 26087.90314 },
{ 1914, 0, 0 },
{ 1045, 1.2122, 52175.8063 },
{ 266, 4.434, 78263.709 },
{ 170, 1.623, 104351.613 },
{ 96, 4.80, 130439.52 },
{ 45, 1.61, 156527.42 },
{ 18, 4.67, 182615.32 },
{ 7, 1.43, 208703.23 }
},
{
{ 235, 0.354, 26087.903 },
{ 161, 0, 0 },
{ 19, 4.36, 52175.81 },
{ 6, 2.51, 78263.71 },
{ 5, 6.14, 104351.61 },
{ 3, 3.12, 130439.52 },
{ 2, 6.27, 156527.42 }
},
{
{ 4, 1.75, 26087.90 },
{ 1, 3.14, 0 }
}
};
// Heliocentric radius vector.
private static final double[][][] MERCURY_R = {
{
{ 39528272, 0, 0 },
{ 7834132, 6.1923372, 26087.9031416 },
{ 795526, 2.959897, 52175.806283 },
{ 121282, 6.010642, 78263.709425 },
{ 21922, 2.77820, 104351.61257 },
{ 4354, 5.8289, 130439.5157 },
{ 918, 2.597, 156527.419 },
{ 290, 1.424, 25028.521 },
{ 260, 3.028, 27197.282 },
{ 202, 5.647, 182615.322 },
{ 201, 5.592, 31749.235 },
{ 142, 6.253, 24978.525 },
{ 100, 3.734, 21535.950 }
},
{
{ 217348, 4.656172, 26087.903142 },
{ 44142, 1.42386, 52175.80628 },
{ 10094, 4.47466, 78263.70942 },
{ 2433, 1.2423, 104351.6126 },
{ 1624, 0, 0 },
{ 604, 4.293, 130439.516 },
{ 153, 1.061, 156527.419 },
{ 39, 4.11, 182615.32 }
},
{
{ 3118, 3.0823, 26087.9031 },
{ 1245, 6.1518, 52175.8063 },
{ 425, 2.926, 78263.709 },
{ 136, 5.980, 104351.613 },
{ 42, 2.75, 130439.52 },
{ 22, 3.14, 0 },
{ 13, 5.80, 156527.42 }
},
{
{ 33, 1.68, 26087.90 },
{ 24, 4.63, 52175.81 },
{ 12, 1.39, 78263.71 },
{ 5, 4.44, 104351.61 },
{ 2, 1.21, 130439.52 }
}
};
/**
* Tables of Vsop87 terms for Mercury.
*/
static Vsop87 MERCURY = new Vsop87(MERCURY_L, MERCURY_B, MERCURY_R);
// ******************************************************************** //
// Venus.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] VENUS_L = {
{
{ 317614667, 0, 0 },
{ 1353968, 5.5931332, 10213.2855462 },
{ 89892, 5.30650, 20426.57109 },
{ 5477, 4.4163, 7860.4194 },
{ 3456, 2.6996, 11790.6291 },
{ 2372, 2.9938, 3930.2097 },
{ 1664, 4.2502, 1577.3435 },
{ 1438, 4.1575, 9683.5946 },
{ 1317, 5.1867, 26.2983 },
{ 1201, 6.1536, 30639.8566 },
{ 769, 0.816, 9437.763 },
{ 761, 1.950, 529.691 },
{ 708, 1.065, 775.523 },
{ 585, 3.998, 191.448 },
{ 500, 4.123, 15720.839 },
{ 429, 3.586, 19367.189 },
{ 327, 5.677, 5507.553 },
{ 326, 4.591, 10404.734 },
{ 232, 3.163, 9153.904 },
{ 180, 4.653, 1109.379 },
{ 155, 5.570, 19651.048 },
{ 128, 4.226, 20.775 },
{ 128, 0.962, 5661.332 },
{ 106, 1.537, 801.821 }
},
{
{ 1021352943053.0, 0, 0 },
{ 95708, 2.46424, 10213.28555 },
{ 14445, 0.51625, 20426.57109 },
{ 213, 1.795, 30639.857 },
{ 174, 2.655, 26.298 },
{ 152, 6.106, 1577.344 },
{ 82, 5.70, 191.45 },
{ 70, 2.68, 9437.76 },
{ 52, 3.60, 775.52 },
{ 38, 1.03, 529.69 },
{ 30, 1.25, 5507.55 },
{ 25, 6.11, 10404.73 }
},
{
{ 54127, 0, 0 },
{ 3891, 0.3451, 10213.2855 },
{ 1338, 2.0201, 20426.5711 },
{ 24, 2.05, 26.30 },
{ 19, 3.54, 30639.86 },
{ 10, 3.97, 775.52 },
{ 7, 1.52, 1577.34 },
{ 6, 1.00, 191.45 }
},
{
{ 136, 4.804, 10213.286 },
{ 78, 3.67, 20426.57},
{ 26, 0, 0 }
},
{
{ 114, 3.1416, 0 },
{ 3, 5.21, 20426.57 },
{ 2, 2.51, 10213.29 }
},
{
{ 1, 3.14, 0 },
}
};
// Heliocentric latitude.
private static final double[][][] VENUS_B = {
{
{ 5923638, 0.2670278, 10213.2855462 },
{ 40108, 1.14737, 20426.57109 },
{ 32815, 3.14737, 0 },
{ 1011, 1.0895, 30639.8566 },
{ 149, 6.254, 18073.705 },
{ 138, 0.860, 1577.344 },
{ 130, 3.672, 9437.763 },
{ 120, 3.705, 2352.866 },
{ 108, 4.539, 22003.915 }
},
{
{ 513348, 1.803643, 10213.285546 },
{ 4380, 3.3862, 20426.5711 },
{ 199, 0, 0 },
{ 197, 2.530, 30639.857 }
},
{
{ 22378, 3.38509, 10213.28555 },
{ 282, 0, 0 },
{ 173, 5.256, 20426.571 },
{ 27, 3.87, 30639.86 }
},
{
{ 647, 4.992, 10213.286 },
{ 20, 3.14, 0 },
{ 6, 0.77, 20426.57 },
{ 3, 5.44, 30639.86 }
},
{
{ 14, 0.32, 10213.29 }
}
};
// Heliocentric radius vector.
private static final double[][][] VENUS_R = {
{
{ 72334821, 0, 0 },
{ 489824, 4.021518, 10213.285546 },
{ 1658, 4.9021, 20426.5711 },
{ 1632, 2.8455, 7860.4194 },
{ 1378, 1.1285, 11790.6291 },
{ 498, 2.587, 9683.595 },
{ 374, 1.423, 3930.210 },
{ 264, 5.529, 9437.763 },
{ 237, 2.551, 15720.839 },
{ 222, 2.013, 19367.189 },
{ 126, 2.728, 1577.344 },
{ 119, 3.020, 10404.734 }
},
{
{ 34551, 0.89199, 10213.28555 },
{ 234, 1.772, 20426.571 },
{ 234, 3.142, 0 }
},
{
{ 1407, 5.0637, 10213.2855 },
{ 16, 5.47, 20426.57 },
{ 13, 0, 0 }
},
{
{ 50, 3.22, 10213.29 }
},
{
{ 1, 0.92, 10213.29 }
}
};
/**
* Tables of Vsop87 terms for Venus.
*/
static Vsop87 VENUS = new Vsop87(VENUS_L, VENUS_B, VENUS_R);
// ******************************************************************** //
// Earth.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] EARTH_L = {
{
{ 175347046, 0, 0 },
{ 3341656, 4.6692568, 6283.0758500 },
{ 34894, 4.62610, 12566.15170 },
{ 3497, 2.7441, 5753.3849 },
{ 3418, 2.8289, 3.5231 },
{ 3136, 3.6277, 77713.7715 },
{ 2676, 4.4181, 7860.4194 },
{ 2343, 6.1352, 3930.2097 },
{ 1324, 0.7425, 11506.7698 },
{ 1273, 2.0371, 529.6910 },
{ 1199, 1.1096, 1577.3435 },
{ 990, 5.233, 5884.927 },
{ 902, 2.045, 26.298 },
{ 857, 3.508, 398.149 },
{ 780, 1.179, 5223.694 },
{ 753, 2.533, 5507.553 },
{ 505, 4.583, 18849.228 },
{ 492, 4.205, 775.523 },
{ 357, 2.920, 0.067 },
{ 317, 5.849, 11790.629 },
{ 284, 1.899, 796.288 },
{ 271, 0.315, 10977.079 },
{ 243, 0.345, 5486.778 },
{ 206, 4.806, 2544.314 },
{ 205, 1.869, 5573.143 },
{ 202, 2.458, 6069.777 },
{ 156, 0.833, 213.299 },
{ 132, 3.411, 2942.463 },
{ 126, 1.083, 20.775 },
{ 115, 0.645, 0.980 },
{ 103, 0.636, 4694.003 },
{ 102, 0.976, 15720.839 },
{ 102, 4.267, 7.114 },
{ 99, 6.21, 2146.17 },
{ 98, 0.68, 155.42 },
{ 86, 5.98, 161000.69 },
{ 85, 1.30, 6275.96 },
{ 85, 3.67, 71430.70 },
{ 80, 1.81, 17260.15 },
{ 79, 3.04, 12036.46 },
{ 75, 1.76, 5088.63 },
{ 74, 3.50, 3154.69 },
{ 74, 4.68, 801.82 },
{ 70, 0.83, 9437.76 },
{ 62, 3.98, 8827.39 },
{ 61, 1.82, 7084.90 },
{ 57, 2.78, 6286.60 },
{ 56, 4.39, 14143.50 },
{ 56, 3.47, 6279.55 },
{ 52, 0.19, 12139.55 },
{ 52, 1.33, 1748.02 },
{ 51, 0.28, 5856.48 },
{ 49, 0.49, 1194.45 },
{ 41, 5.37, 8429.24 },
{ 41, 2.40, 19651.05 },
{ 39, 6.17, 10447.39 },
{ 37, 6.04, 10213.29 },
{ 37, 2.57, 1059.38 },
{ 36, 1.71, 2352.87 },
{ 36, 1.78, 6812.77 },
{ 33, 0.59, 17789.85 },
{ 30, 0.44, 83996.85 },
{ 30, 2.74, 1349.87 },
{ 25, 3.16, 4690.48 }
},
{
{ 628331966747.0, 0, 0 },
{ 206059, 2.678235, 6283.075850 },
{ 4303, 2.6351, 12566.1517 },
{ 425, 1.590, 3.523 },
{ 119, 5.796, 26.298 },
{ 109, 2.966, 1577.344 },
{ 93, 2.59, 18849.23 },
{ 72, 1.14, 529.69 },
{ 68, 1.87, 398.15 },
{ 67, 4.41, 5507.55 },
{ 59, 2.89, 5223.69 },
{ 56, 2.17, 155.42 },
{ 45, 0.40, 796.30 },
{ 36, 0.47, 775.52 },
{ 29, 2.65, 7.11 },
{ 21, 5.43, 0.98 },
{ 19, 1.85, 5486.78 },
{ 19, 4.97, 213.30 },
{ 17, 2.99, 6275.96 },
{ 16, 0.03, 2544.31 },
{ 16, 1.43, 2146.17 },
{ 15, 1.21, 10977.08 },
{ 12, 2.83, 1748.02 },
{ 12, 3.26, 5088.63 },
{ 12, 5.27, 1194.45 },
{ 12, 2.08, 4694.00 },
{ 11, 0.77, 553.57 },
{ 10, 1.30, 6286.60 },
{ 10, 4.24, 1349.87 },
{ 9, 2.70, 242.73 },
{ 9, 5.64, 951.72 },
{ 8, 5.30, 2352.87 },
{ 6, 2.65, 9437.76 },
{ 6, 4.67, 4690.48 }
},
{
{ 52919, 0, 0 },
{ 8720, 1.0721, 6283.0758 },
{ 309, 0.867, 12566.152 },
{ 27, 0.05, 3.52 },
{ 16, 5.19, 26.30 },
{ 16, 3.68, 155.42 },
{ 10, 0.76, 18849.23 },
{ 9, 2.06, 77713.77 },
{ 7, 0.83, 775.52 },
{ 5, 4.66, 1577.34 },
{ 4, 1.03, 7.11 },
{ 4, 3.44, 5573.14 },
{ 3, 5.14, 796.30 },
{ 3, 6.05, 5507.55 },
{ 3, 1.19, 242.73 },
{ 3, 6.12, 529.69 },
{ 3, 0.31, 398.15 },
{ 3, 2.28, 553.57 },
{ 2, 4.38, 5223.69 },
{ 2, 3.75, 0.98 }
},
{
{ 289, 5.844, 6283.076 },
{ 35, 0, 0 },
{ 17, 5.49, 12566.15 },
{ 3, 5.20, 155.42 },
{ 1, 4.72, 3.52 },
{ 1, 5.30, 18849.23 },
{ 1, 5.97, 242.73 }
},
{
{ 114, 3.142, 0 },
{ 8, 4.13, 6283.08 },
{ 1, 3.84, 12566.15 }
},
{
{ 1, 3.14, 0 },
}
};
// Heliocentric latitude.
private static final double[][][] EARTH_B = {
{
{ 280, 3.199, 84334.662 },
{ 102, 5.422, 5507.553 },
{ 80, 3.88, 5223.69},
{ 44, 3.70, 2352.87 },
{ 32, 4.00, 1577.34 }
},
{
{ 9, 3.90, 5507.55 },
{ 6, 1.73, 5223.69}
},
{
{ 22378, 3.38509, 10213.28555 },
{ 282, 0, 0 },
{ 173, 5.256, 20426.571 },
{ 27, 3.87, 30639.86 }
},
{
{ 647, 4.992, 10213.286 },
{ 20, 3.14, 0 },
{ 6, 0.77, 20426.57 },
{ 3, 5.44, 30639.86 }
},
{
{ 14, 0.32, 10213.29 }
}
};
// Heliocentric radius vector.
private static final double[][][] EARTH_R = {
{
{ 100013989, 0, 0 },
{ 1670700, 3.0984635, 6283.0758500 },
{ 13956, 3.05525, 12566.15170 },
{ 3084, 5.1985, 77713.7715 },
{ 1628, 1.1739, 5753.3849 },
{ 1576, 2.8469, 7860.4194 },
{ 925, 5.453, 11506.770 },
{ 542, 4.564, 3930.210 },
{ 472, 3.661, 5884.927 },
{ 346, 0.964, 5507.553 },
{ 329, 5.900, 5223.694 },
{ 307, 0.299, 5573.143 },
{ 243, 4.273, 11790.629 },
{ 212, 5.847, 1577.344 },
{ 186, 5.022, 10977.079 },
{ 175, 3.012, 18849.228 },
{ 110, 5.055, 5486.778 },
{ 98, 0.89, 6069.78 },
{ 86, 5.69, 15720.84 },
{ 86, 1.27, 161000.69},
{ 65, 0.27, 17260.15 },
{ 63, 0.92, 529.69 },
{ 57, 2.01, 83996.85 },
{ 56, 5.24, 71430.70 },
{ 49, 3.25, 2544.31 },
{ 47, 2.58, 775.52 },
{ 45, 5.54, 9437.76 },
{ 43, 6.01, 6275.96 },
{ 39, 5.36, 4694.00 },
{ 38, 2.39, 8827.39 },
{ 37, 0.83, 19651.05 },
{ 37, 4.90, 12139.55 },
{ 36, 1.67, 12036.46 },
{ 35, 1.84, 2942.46 },
{ 33, 0.24, 7084.90 },
{ 32, 0.18, 5088.63 },
{ 32, 1.78, 398.15 },
{ 28, 1.21, 6286.60 },
{ 28, 1.90, 6279.55 },
{ 26, 4.59, 10447.39 }
},
{
{ 103019, 1.107490, 6283.075850 },
{ 1721, 1.0644, 12566.1517 },
{ 702, 3.142, 0 },
{ 32, 1.02, 18849.23 },
{ 31, 2.84, 5507.55 },
{ 25, 1.32, 5223.69 },
{ 18, 1.42, 1577.34 },
{ 10, 5.91, 10977.08 },
{ 9, 1.42, 6275.96 },
{ 9, 0.27, 5486.78 }
},
{
{ 4359, 5.7846, 6283.0758 },
{ 124, 5.579, 12566.152 },
{ 12, 3.14, 0 },
{ 9, 3.63, 77713.77 },
{ 6, 1.87, 5573.14 },
{ 3, 5.47, 18849.23 }
},
{
{ 145, 4.273, 6283.076 },
{ 7, 3.92, 12566.15 }
},
{
{ 4, 2.56, 6283.08 }
}
};
/**
* Tables of Vsop87 terms for the Earth.
*/
static Vsop87 EARTH = new Vsop87(EARTH_L, EARTH_B, EARTH_R);
// ******************************************************************** //
// Mars.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] MARS_L = {
{
{ 620347712, 0, 0 },
{ 18656368, 5.05037100, 3340.61242670 },
{ 1108217, 5.4009984, 6681.2248534 },
{ 91798, 5.75479, 10021.83728 },
{ 27745, 5.97050, 3.52312 },
{ 12316, 0.84956, 2810.92146 },
{ 10610, 2.93959, 2281.23050 },
{ 8927, 4.1570, 0.0173 },
{ 8716, 6.1101, 13362.4497 },
{ 7775, 3.3397, 5621.8429 },
{ 6798, 0.3646, 398.1490 },
{ 4161, 0.2281, 2942.4634 },
{ 3575, 1.6619, 2544.3144 },
{ 3075, 0.8570, 191.4483 },
{ 2938, 6.0789, 0.0673 },
{ 2628, 0.6481, 3337.0893 },
{ 2580, 0.0300, 3344.1355 },
{ 2389, 5.0390, 796.2980 },
{ 1799, 0.6563, 529.6910 },
{ 1546, 2.9158, 1751.5395 },
{ 1528, 1.1498, 6151.5339 },
{ 1286, 3.0680, 2146.1654 },
{ 1264, 3.6228, 5092.1520 },
{ 1025, 3.6933, 8962.4553 },
{ 892, 0.183, 16703.062 },
{ 859, 2.401, 2914.014 },
{ 833, 4.495, 3340.630 },
{ 833, 2.464, 3340.595 },
{ 749, 3.822, 155.420 },
{ 724, 0.675, 3738.761 },
{ 713, 3.663, 1059.382 },
{ 655, 0.489, 3127.313 },
{ 636, 2.922, 8432.764 },
{ 553, 4.475, 1748.016 },
{ 550, 3.810, 0.980 },
{ 472, 3.625, 1194.447 },
{ 426, 0.554, 6283.076 },
{ 415, 0.497, 213.299 },
{ 312, 0.999, 6677.702 },
{ 307, 0.381, 6684.748 },
{ 302, 4.486, 3532.061 },
{ 299, 2.783, 6254.627 },
{ 293, 4.221, 20.775 },
{ 284, 5.769, 3149.164 },
{ 281, 5.882, 1349.867 },
{ 274, 0.542, 3340.545 },
{ 274, 0.134, 3340.680 },
{ 239, 5.372, 4136.910 },
{ 236, 5.755, 3333.499 },
{ 231, 1.282, 3870.303 },
{ 221, 3.505, 382.897 },
{ 204, 2.821, 1221.849 },
{ 193, 3.357, 3.590 },
{ 189, 1.491, 9492.146 },
{ 179, 1.006, 951.718 },
{ 174, 2.414, 553.569 },
{ 172, 0.439, 5486.778 },
{ 160, 3.949, 4562.461 },
{ 144, 1.419, 135.065 },
{ 140, 3.326, 2700.715 },
{ 138, 4.301, 7.114 },
{ 131, 4.045, 12303.068 },
{ 128, 2.208, 1592.596 },
{ 128, 1.807, 5088.629 },
{ 117, 3.128, 7903.073 },
{ 113, 3.701, 1589.073 },
{ 110, 1.052, 242.729 },
{ 105, 0.785, 8827.390 },
{ 100, 3.243, 11773.377 }
},
{
{ 334085627474.0, 0, 0 },
{ 1458227, 3.6042605, 3340.6124267 },
{ 164901, 3.926313, 6681.224853 },
{ 19963, 4.26594, 10021.83728 },
{ 3452, 4.7321, 3.5231 },
{ 2485, 4.6128, 13362.4497 },
{ 842, 4.459, 2281.230 },
{ 538, 5.016, 398.149 },
{ 521, 4.994, 3344.136 },
{ 433, 2.561, 191.448 },
{ 430, 5.316, 155.420 },
{ 382, 3.539, 796.298 },
{ 314, 4.963, 16703.062 },
{ 283, 3.160, 2544.314 },
{ 206, 4.569, 2146.165 },
{ 169, 1.329, 3337.089 },
{ 158, 4.185, 1751.540 },
{ 134, 2.233, 0.980 },
{ 134, 5.974, 1748.016 },
{ 118, 6.024, 6151.534 },
{ 117, 2.213, 1059.382 },
{ 114, 2.129, 1194.447 },
{ 114, 5.428, 3738.761 },
{ 91, 1.10, 1349.87 },
{ 85, 3.91, 553.57 },
{ 83, 5.30, 6684.75 },
{ 81, 4.43, 529.69 },
{ 80, 2.25, 8962.46 },
{ 73, 2.50, 951.72 },
{ 73, 5.84, 242.73 },
{ 71, 3.86, 2914.01 },
{ 68, 5.02, 382.90 },
{ 65, 1.02, 3340.60 },
{ 65, 3.05, 3340.63 },
{ 62, 4.15, 3149.16 },
{ 57, 3.89, 4136.91 },
{ 48, 4.87, 213.30 },
{ 48, 1.18, 3333.50 },
{ 47, 1.31, 3185.19 },
{ 41, 0.71, 1592.60 },
{ 40, 2.73, 7.11 },
{ 40, 5.32, 20043.67 },
{ 33, 5.41, 6283.08 },
{ 28, 0.05, 9492.15 },
{ 27, 3.89, 1221.85 },
{ 27, 5.11, 2700.72 }
},
{
{ 58016, 2.04979, 3340.61243 },
{ 54188, 0, 0 },
{ 13908, 2.45742, 6681.22485 },
{ 2465, 2.8000, 10021.8373 },
{ 398, 3.141, 13362.450 },
{ 222, 3.194, 3.523 },
{ 121, 0.543, 155.420 },
{ 62, 3.49, 16703.06 },
{ 54, 3.54, 3344.14 },
{ 34, 6.00, 2281.23 },
{ 32, 4.14, 191.45 },
{ 30, 2.00, 796.30 },
{ 23, 4.33, 242.73 },
{ 22, 3.45, 398.15 },
{ 20, 5.42, 553.57 },
{ 16, 0.66, 0.98 },
{ 16, 6.11, 2146.17 },
{ 16, 1.22, 1748.02 },
{ 15, 6.10, 3185.19 },
{ 14, 4.02, 951.72 },
{ 14, 2.62, 1349.87 },
{ 13, 0.60, 1194.45 },
{ 12, 3.86, 6684.75 },
{ 11, 4.72, 2544.31 },
{ 10, 0.25, 382.90 },
{ 9, 0.68, 1059.38 },
{ 9, 3.83, 20043.67 },
{ 9, 3.88, 3738.76 },
{ 8, 5.46, 1751.54 },
{ 7, 2.58, 3149.16 },
{ 7, 2.38, 4136.91 },
{ 6, 5.48, 1592.60 },
{ 6, 2.34, 3097.88 }
},
{
{ 1482, 0.4443, 3340.6124 },
{ 662, 0.885, 6681.225 },
{ 188, 1.288, 10021.837 },
{ 41, 1.65, 13362.45 },
{ 26, 0, 0 },
{ 23, 2.05, 155.42 },
{ 10, 1.58, 3.52 },
{ 8, 2.00, 16703.06 },
{ 5, 2.82, 242.73 },
{ 4, 2.02, 3344.14 },
{ 3, 4.59, 3185.19 },
{ 3, 0.65, 553.57 }
},
{
{ 114, 3.1416, 0 },
{ 29, 5.64, 6681.22 },
{ 24, 5.14, 3340.61 },
{ 11, 6.03, 10021.84 },
{ 3, 0.13, 13362.45 },
{ 3, 3.56, 155.42 },
{ 1, 0.49, 16703.06 },
{ 1, 1.32, 242.73 }
},
{
{ 1, 3.14, 0 },
{ 1, 4.04, 6681.22 }
}
};
// Heliocentric latitude.
private static final double[][][] MARS_B = {
{
{ 3197135, 3.7683204, 3340.6124267 },
{ 298033, 4.106170, 6681.224853 },
{ 289105, 0, 0 },
{ 31366, 4.44651, 10021.83728 },
{ 3484, 4.7881, 13362.4497 },
{ 443, 5.026, 3344.136 },
{ 443, 5.652, 3337.089 },
{ 399, 5.131, 16703.062 },
{ 293, 3.793, 2281.230 },
{ 182, 6.136, 6151.534 },
{ 163, 4.264, 529.691 },
{ 160, 2.232, 1059.382 },
{ 149, 2.165, 5621.843 },
{ 143, 1.182, 3340.595},
{ 143, 3.213, 3340.630 },
{ 139, 2.418, 8962.455 }
},
{
{ 350069, 5.368478, 3340.612427 },
{ 14116, 3.14159, 0 },
{ 9671, 5.4788, 6681.2249 },
{ 1472, 3.2021, 10021.8373 },
{ 426, 3.408, 13362.450 },
{ 102, 0.776, 3337.089 },
{ 79, 3.72, 16703.06 },
{ 33, 3.46, 5621.84 },
{ 26, 2.48, 2281.23 }
},
{
{ 16727, 0.60221, 3340.61243 },
{ 4987, 4.1416, 0 },
{ 302, 3.559, 6681.225 },
{ 26, 1.90, 13362.45 },
{ 21, 0.92, 10021.84 },
{ 12, 2.24, 3337.09 },
{ 8, 2.25, 16703.06 }
},
{
{ 607, 1.981, 3340.612 },
{ 43, 0, 0 },
{ 14, 1.80, 6681.22 },
{ 3, 3.45, 10021.84 }
},
{
{ 13, 0, 0 },
{ 11, 3.46, 3340.61 },
{ 1, 0.50, 6681.22 }
}
};
// Heliocentric radius vector.
private static final double[][][] MARS_R = {
{
{ 153033488, 0, 0 },
{ 14184953, 3.47971284, 3340.61242670 },
{ 660776, 3.817834, 6681.224853 },
{ 46179, 4.15595, 10021.83728 },
{ 8110, 5.5596, 2810.9215 },
{ 7485, 1.7724, 5621.8429 },
{ 5523, 1.3644, 2281.2305 },
{ 3825, 4.4941, 13362.4497 },
{ 2484, 4.9255, 2942.4634 },
{ 2307, 0.0908, 2544.3144 },
{ 1999, 5.3606, 3337.0893 },
{ 1960, 4.7425, 3344.1355 },
{ 1167, 2.1126, 5092.1520 },
{ 1103, 5.0091, 398.1490 },
{ 992, 5.839, 6151.534 },
{ 899, 4.408, 529.691 },
{ 807, 2.102, 1059.382 },
{ 798, 3.448, 796.298 },
{ 741, 1.499, 2146.165 },
{ 726, 1.245, 8432.764 },
{ 692, 2.134, 8962.455 },
{ 633, 0.894, 3340.595 },
{ 633, 2.924, 3340.630 },
{ 630, 1.287, 1751.540 },
{ 574, 0.829, 2914.014 },
{ 526, 5.383, 3738.761 },
{ 473, 5.199, 3127.313 },
{ 348, 4.832, 16703.062 },
{ 284, 2.907, 3532.061 },
{ 280, 5.257, 6283.076 },
{ 276, 1.218, 6254.627 },
{ 275, 2.908, 1748.016 },
{ 270, 3.764, 5884.927 },
{ 239, 2.037, 1194.447 },
{ 234, 5.105, 5486.778 },
{ 228, 3.255, 6872.673 },
{ 223, 4.199, 3149.164 },
{ 219, 5.583, 191.448 },
{ 208, 5.255, 3340.545 },
{ 208, 4.846, 3340.680 },
{ 186, 5.699, 6677.702 },
{ 183, 5.081, 6684.748 },
{ 179, 4.184, 3333.499 },
{ 176, 5.953, 3870.303 },
{ 164, 3.799, 4136.910 }
},
{
{ 1107433, 2.0325052, 3340.6124267 },
{ 103176, 2.370718, 6681.224853 },
{ 12877, 0, 0 },
{ 10816, 2.70888, 10021.83728 },
{ 1195, 3.0470, 13362.4497 },
{ 439, 2.888, 2281.230 },
{ 396, 3.423, 3344.136 },
{ 183, 1.584, 2544.314 },
{ 136, 3.385, 16703.062 },
{ 128, 6.043, 3337.089 },
{ 128, 0.630, 1059.382 },
{ 127, 1.954, 796.298 },
{ 118, 2.998, 2146.165 },
{ 88, 3.42, 398.15 },
{ 83, 3.86, 3738.76 },
{ 76, 4.45, 6151.53 },
{ 72, 2.76, 529.69 },
{ 67, 2.55, 1751.54 },
{ 66, 4.41, 1748.02 },
{ 58, 0.54, 1194.45 },
{ 54, 0.68, 8962.46 },
{ 51, 3.73, 6684.75 },
{ 49, 5.73, 3340.60 },
{ 49, 1.48, 3340.63 },
{ 48, 2.58, 3149.16 },
{ 48, 2.29, 2914.01 },
{ 39, 2.32, 4136.91 }
},
{
{ 44242, 0.47931, 3340.61243 },
{ 8138, 0.8700, 6681.2249 },
{ 1275, 1.2259, 10021.8373 },
{ 187, 1.573, 13362.450 },
{ 52, 3.14, 0 },
{ 41, 1.97, 3344.14 },
{ 27, 1.92, 16703.06 },
{ 18, 4.43, 2281.23 },
{ 12, 4.53, 3185.19 },
{ 10, 5.39, 1059.38 },
{ 10, 0.42, 796.30 }
},
{
{ 1113, 5.1499, 3340.6124 },
{ 424, 5.613, 6681.225 },
{ 100, 5.997, 10021.837 },
{ 20, 0.08, 13362.45 },
{ 5, 3.14, 0 },
{ 3, 0.43, 16703.06 }
},
{
{ 20, 3.58, 3340.61 },
{ 16, 4.05, 6681.22 },
{ 6, 4.46, 10021.84 },
{ 2, 4.84, 13362.45 }
}
};
/**
* Tables of Vsop87 terms for Mars.
*/
static Vsop87 MARS = new Vsop87(MARS_L, MARS_B, MARS_R);
// ******************************************************************** //
// Jupiter.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] JUPITER_L = {
{
{ 59954691, 0, 0 },
{ 9695899, 5.0619179, 529.6909651 },
{ 573610, 1.444062, 7.113547 },
{ 306389, 5.417347, 1059.381930 },
{ 97178, 4.14265, 632.78374 },
{ 72903, 3.64043, 522.57742 },
{ 64264, 3.41145, 103.09277 },
{ 39806, 2.29377, 419.48464 },
{ 38858, 1.27232, 316.39187 },
{ 27965, 1.78455, 536.80451 },
{ 13590, 5.77481, 1589.07290 },
{ 8769, 3.6300, 949.1756 },
{ 8246, 3.5823, 206.1855 },
{ 7368, 5.0810, 735.8765 },
{ 6263, 0.0250, 213.2991 },
{ 6114, 4.5132, 1162.4747 },
{ 5305, 4.1863, 1052.2684 },
{ 5305, 1.3067, 14.2271 },
{ 4905, 1.3208, 110.2063 },
{ 4647, 4.6996, 3.9322 },
{ 3045, 4.3168, 426.5982 },
{ 2610, 1.5667, 846.0828 },
{ 2028, 1.0638, 3.1814 },
{ 1921, 0.9717, 639.8973 },
{ 1765, 2.1415, 1066.4955 },
{ 1723, 3.8804, 1265.5675 },
{ 1633, 3.5820, 515.4639 },
{ 1432, 4.2968, 625.6702 },
{ 973, 4.098, 95.979 },
{ 884, 2.437, 412.371 },
{ 733, 6.085, 838.969 },
{ 731, 3.806, 1581.959 },
{ 709, 1.293, 742.990 },
{ 692, 6.134, 2118.764 },
{ 614, 4.109, 1478.867 },
{ 582, 4.540, 309.278 },
{ 495, 3.756, 323.505 },
{ 441, 2.958, 454.909 },
{ 417, 1.036, 2.488 },
{ 390, 4.897, 1692.166 },
{ 376, 4.703, 1368.660 },
{ 341, 5.715, 533.623 },
{ 330, 4.740, 0.048 },
{ 262, 1.877, 0.963 },
{ 261, 0.820, 380.128 },
{ 257, 3.724, 199.072 },
{ 244, 5.220, 728.763 },
{ 235, 1.227, 909.819 },
{ 220, 1.651, 543.918 },
{ 207, 1.855, 525.759 },
{ 202, 1.807, 1375.774 },
{ 197, 5.293, 1155.361 },
{ 175, 3.730, 942.062 },
{ 175, 3.226, 1898.351 },
{ 175, 5.910, 956.289 },
{ 158, 4.365, 1795.258 },
{ 151, 3.906, 74.782 },
{ 149, 4.377, 1685.052 },
{ 141, 3.136, 491.558 },
{ 138, 1.318, 1169.588 },
{ 131, 4.169, 1045.155 },
{ 117, 2.500, 1596.186 },
{ 117, 3.389, 0.521 },
{ 106, 4.554, 526.510 }
},
{
{ 52993480757.0, 0, 0 },
{ 489741, 4.220667, 529.690965 },
{ 228919, 6.026475, 7.113547 },
{ 27655, 4.57266, 1059.38193 },
{ 20721, 5.45939, 522.57742 },
{ 12106, 0.16986, 536.80451 },
{ 6068, 4.4242, 103.0928 },
{ 5434, 3.9848, 419.4846 },
{ 4238, 5.8901, 14.2271 },
{ 2212, 5.2677, 206.1855 },
{ 1746, 4.9267, 1589.0729 },
{ 1296, 5.5513, 3.1814 },
{ 1173, 5.8565, 1052.2684 },
{ 1163, 0.5145, 3.9322 },
{ 1099, 5.3070, 515.4639 },
{ 1007, 0.4648, 735.8765 },
{ 1004, 3.1504, 426.5982 },
{ 848, 5.758, 110.206 },
{ 827, 4.803, 213.299 },
{ 816, 0.586, 1066.495 },
{ 725, 5.518, 639.897 },
{ 568, 5.989, 625.670 },
{ 474, 4.132, 412.371 },
{ 413, 5.737, 95.979 },
{ 345, 4.242, 632.784 },
{ 336, 3.732, 1162.475 },
{ 234, 4.035, 949.176 },
{ 234, 6.243, 309.278 },
{ 199, 1.505, 838.969 },
{ 195, 2.219, 323.505 },
{ 187, 6.086, 742.990 },
{ 184, 6.280, 543.918 },
{ 171, 5.417, 199.072 },
{ 131, 0.626, 728.763 },
{ 115, 0.680, 846.083 },
{ 115, 5.286, 2118.764 },
{ 108, 4.493, 956.289 },
{ 80, 5.82, 1045.15 },
{ 72, 5.34, 942.06 },
{ 70, 5.97, 532.87 },
{ 67, 5.73, 21.34 },
{ 66, 0.13, 526.51 },
{ 65, 6.09, 1581.96 },
{ 59, 0.59, 1155.36 },
{ 58, 0.99, 1596.19 },
{ 57, 5.97, 1169.59 },
{ 57, 1.41, 533.62 },
{ 55, 5.43, 10.29 },
{ 52, 5.73, 117.32 },
{ 52, 0.23, 1368.66 },
{ 50, 6.08, 525.76 },
{ 47, 3.63, 1478.87 },
{ 47, 0.51, 1265.57 },
{ 40, 4.16, 1692.17 },
{ 34, 0.10, 302.16 },
{ 33, 5.04, 220.41 },
{ 32, 5.37, 508.35 },
{ 29, 5.42, 1272.68 },
{ 29, 3.36, 4.67 },
{ 29, 0.76, 88.87 },
{ 25, 1.61, 831.86 }
},
{
{ 47234, 4.32148, 7.11355 },
{ 38966, 0, 0 },
{ 30629, 2.93021, 529.69097 },
{ 3189, 1.0550, 522.5774 },
{ 2729, 4.8455, 536.8045 },
{ 2723, 3.4141, 1059.3819 },
{ 1721, 4.1873, 14.2271 },
{ 383, 5.768, 419.485 },
{ 378, 0.760, 515.464 },
{ 367, 6.055, 103.093 },
{ 337, 3.786, 3.181 },
{ 308, 0.694, 206.186 },
{ 218, 3.814, 1589.073 },
{ 199, 5.340, 1066.495 },
{ 197, 2.484, 3.932 },
{ 156, 1.406, 1052.268 },
{ 146, 3.814, 639.897 },
{ 142, 1.634, 426.598 },
{ 130, 5.837, 412.371 },
{ 117, 1.414, 625.670 },
{ 97, 4.03, 110.21 },
{ 91, 1.11, 95.98 },
{ 87, 2.52, 632.78 },
{ 79, 4.64, 543.92 },
{ 72, 2.22, 735.88 },
{ 58, 0.83, 199.07 },
{ 57, 3.12, 213.30 },
{ 49, 1.67, 309.28 },
{ 40, 4.02, 21.34 },
{ 40, 0.62, 323.51 },
{ 36, 2.33, 728.76 },
{ 29, 3.61, 10.29 },
{ 28, 3.24, 838.97 },
{ 26, 4.50, 742.99 },
{ 26, 2.51, 1162.47 },
{ 25, 1.22, 1045.15 },
{ 24, 3.01, 956.29 },
{ 19, 4.29, 532.87 },
{ 18, 0.81, 508.35 },
{ 17, 4.20, 2118.76 },
{ 17, 1.83, 526.51 },
{ 15, 5.81, 1596.19 },
{ 15, 0.68, 942.06 },
{ 15, 4.00, 117.32 },
{ 14, 5.95, 316.39 },
{ 14, 1.80, 302.16 },
{ 13, 2.52, 88.87 },
{ 13, 4.37, 1169.59 },
{ 11, 4.44, 525.76 },
{ 10, 1.72, 1581.96 },
{ 9, 2.18, 1155.36 },
{ 9, 3.29, 220.41 },
{ 9, 3.32, 831.86 },
{ 8, 5.76, 846.08 },
{ 8, 2.71, 533.62 },
{ 7, 2.18, 1265.57 },
{ 6, 0.50, 949.18 }
},
{
{ 6502, 2.5986, 7.1135 },
{ 1357, 1.3464, 529.6910 },
{ 471, 2.475, 14.227 },
{ 417, 3.245, 536.805 },
{ 353, 2.974, 522.577 },
{ 155, 2.076, 1059.382 },
{ 87, 2.51, 515.46 },
{ 44, 0, 0 },
{ 34, 3.83, 1066.50 },
{ 28, 2.45, 206.19 },
{ 24, 1.28, 412.37 },
{ 23, 2.98, 543.92 },
{ 20, 2.10, 639.90 },
{ 20, 1.40, 419.48 },
{ 19, 1.59, 103.09 },
{ 17, 2.30, 21.34 },
{ 17, 2.60, 1589.07 },
{ 16, 3.15, 625.67 },
{ 16, 3.36, 1052.27 },
{ 13, 2.76, 95.98 },
{ 13, 2.54, 199.07 },
{ 13, 6.27, 426.60 },
{ 9, 1.76, 10.29 },
{ 9, 2.27, 110.21 },
{ 7, 3.43, 309.28 },
{ 7, 4.04, 728.76 },
{ 6, 2.52, 508.35 },
{ 5, 2.91, 1045.15 },
{ 5, 5.25, 323.51 },
{ 4, 4.30, 88.87 },
{ 4, 3.52, 302.16 },
{ 4, 4.09, 735.88 },
{ 3, 1.43, 956.29 },
{ 3, 4.36, 1596.19 },
{ 3, 1.25, 213.30 },
{ 3, 5.02, 838.97 },
{ 3, 2.24, 117.32 },
{ 2, 2.90, 742.99 },
{ 2, 2.36, 942.06 }
},
{
{ 669, 0.853, 7.114 },
{ 114, 3.142, 0 },
{ 100, 0.743, 14.227 },
{ 50, 1.65, 536.80 },
{ 44, 5.82, 529.69 },
{ 32, 4.86, 522.58 },
{ 15, 4.29, 515.46 },
{ 9, 0.71, 1059.38 },
{ 5, 1.30, 543.92 },
{ 4, 2.32, 1066.50 },
{ 4, 0.48, 21.34 },
{ 3, 3.00, 412.37 },
{ 2, 0.40, 639.90 },
{ 2, 4.26, 199.07 },
{ 2, 4.91, 625.67 },
{ 2, 4.26, 206.19 },
{ 1, 5.26, 1052.27 },
{ 1, 4.72, 95.98 },
{ 1, 1.29, 1589.07 }
},
{
{ 50, 5.26, 7.11 },
{ 16, 5.25, 14.23 },
{ 4, 0.01, 536.80 },
{ 2, 1.10, 522.58 },
{ 1, 3.14, 0 }
}
};
// Heliocentric latitude.
private static final double[][][] JUPITER_B = {
{
{ 2268616, 3.5585261, 529.6909651 },
{ 110090, 0, 0 },
{ 109972, 3.908093, 1059.381930 },
{ 8101, 3.6051, 522.5774 },
{ 6438, 0.3063, 536.8045 },
{ 6044, 4.2588, 1589.0729 },
{ 1107, 2.9853, 1162.4747 },
{ 944, 1.675, 426.598 },
{ 942, 2.936, 1052.268 },
{ 894, 1.754, 7.114 },
{ 836, 5.179, 103.093 },
{ 767, 2.155, 632.784 },
{ 684, 3.678, 213.299 },
{ 629, 0.643, 1066.495 },
{ 559, 0.014, 846.083 },
{ 532, 2.703, 110.206 },
{ 464, 1.173, 949.176 },
{ 431, 2.608, 419.485 },
{ 351, 4.611, 2118.764 },
{ 132, 4.778, 742.990 },
{ 123, 3.350, 1692.166 },
{ 116, 1.387, 323.505 },
{ 115, 5.049, 316.392 },
{ 104, 3.701, 515.464 },
{ 103, 2.319, 1478.867 },
{ 102, 3.153, 1581.959 }
},
{
{ 177352, 5.701665, 529.690965 },
{ 3230, 5.7794, 1059.3819 },
{ 3081, 5.4746, 522.5774 },
{ 2212, 4.7348, 536.8045 },
{ 1694, 3.1416, 0 },
{ 346, 4.746, 1052.268 },
{ 234, 5.189, 1066.495 },
{ 196, 6.186, 7.114 },
{ 150, 3.927, 1589.073 },
{ 114, 3.439, 632.784 },
{ 97, 2.91, 949.18 },
{ 82, 5.08, 1162.47 },
{ 77, 2.51, 103.09 },
{ 77, 0.61, 419.48 },
{ 74, 5.50, 515.46 },
{ 61, 5.45, 213.30 },
{ 50, 3.95, 735.88 },
{ 46, 0.54, 110.21 },
{ 45, 1.90, 846.08 },
{ 37, 4.70, 543.92 },
{ 36, 6.11, 316.39 },
{ 32, 4.92, 1581.96 }
},
{
{ 8094, 1.4632, 529.6910 },
{ 813, 3.1416, 0 },
{ 742, 0.957, 522.577 },
{ 399, 2.899, 536.805 },
{ 342, 1.447, 1059.382 },
{ 74, 0.41, 1052.27 },
{ 46, 3.48, 1066.50 },
{ 30, 1.93, 1589.07 },
{ 29, 0.99, 515.46 },
{ 23, 4.27, 7.11 },
{ 14, 2.92, 543.92 },
{ 12, 5.22, 632.78 },
{ 11, 4.88, 949.18 },
{ 6, 6.21, 1045.15 }
},
{
{ 252, 3.381, 529.691 },
{ 122, 2.733, 522.577 },
{ 49, 1.04, 536.80 },
{ 11, 2.31, 1052.27 },
{ 8, 2.77, 515.46 },
{ 7, 4.25, 1059.38 },
{ 6, 1.78, 1066.50 },
{ 4, 1.13, 543.92 },
{ 3, 3.14, 0 }
},
{
{ 15, 4.53, 522.58 },
{ 5, 4.47, 529.69 },
{ 4, 5.44, 536.80 },
{ 3, 0, 0 },
{ 2, 4.52, 515.46 },
{ 1, 4.20, 1052.27 }
},
{
{ 1, 0.09, 522.58 }
}
};
// Heliocentric radius vector.
private static final double[][][] JUPITER_R = {
{
{ 520887429, 0, 0 },
{ 25209327, 3.49108640, 529.69096509 },
{ 610600, 3.841154, 1059.381930 },
{ 282029, 2.574199, 632.783739 },
{ 187647, 2.075904, 522.577418 },
{ 86793, 0.71001, 419.48464 },
{ 72063, 0.21466, 536.80451 },
{ 65517, 5.97996, 316.39187 },
{ 30135, 2.16132, 949.17561 },
{ 29135, 1.67759, 103.09277 },
{ 23947, 0.27458, 7.11355 },
{ 23453, 3.54023, 735.87651 },
{ 22284, 4.19363, 1589.07290 },
{ 13033, 2.96043, 1162.47470 },
{ 12749, 2.71550, 1052.26838 },
{ 9703, 1.9067, 206.1855 },
{ 9161, 4.4135, 213.2991 },
{ 7895, 2.4791, 426.5982 },
{ 7058, 2.1818, 1265.5675 },
{ 6138, 6.2642, 846.0828 },
{ 5477, 5.6573, 639.8973 },
{ 4170, 2.0161, 515.4639 },
{ 4137, 2.7222, 625.6702 },
{ 3503, 0.5653, 1066.4955 },
{ 2617, 2.0099, 1581.9593 },
{ 2500, 4.5518, 838.9693 },
{ 2128, 6.1275, 742.9901 },
{ 1912, 0.8562, 412.3711 },
{ 1611, 3.0887, 1368.6603 },
{ 1479, 2.6803, 1478.8666 },
{ 1231, 1.8904, 323.5054 },
{ 1217, 1.8017, 110.2063 },
{ 1015, 1.3867, 454.9094 },
{ 999, 2.872, 309.278 },
{ 961, 4.549, 2118.764 },
{ 886, 4.148, 533.623 },
{ 821, 1.593, 1898.351 },
{ 812, 5.941, 909.819 },
{ 777, 3.677, 728.763 },
{ 727, 3.988, 1155.361 },
{ 655, 2.791, 1685.052 },
{ 654, 3.382, 1692.166 },
{ 621, 4.823, 956.289 },
{ 615, 2.276, 942.062 },
{ 562, 0.081, 543.918 },
{ 542, 0.284, 525.759 }
},
{
{ 1271802,2.6493751, 529.6909651 },
{ 61662, 3.00076, 1059.38193 },
{ 53444, 3.89718, 522.57742 },
{ 41390, 0, 0 },
{ 31185, 4.88277, 536.80451 },
{ 11847, 2.41330, 419.48464 },
{ 9166, 4.7598, 7.1135 },
{ 3404, 3.3469, 1589.0729 },
{ 3203, 5.2108, 735.8765 },
{ 3176, 2.7930, 103.0928 },
{ 2806, 3.7422, 515.4639 },
{ 2677, 4.3305, 1052.2684 },
{ 2600, 3.6344, 206.1855 },
{ 2412, 1.4695, 426.5982 },
{ 2101, 3.9276, 639.8973 },
{ 1646, 4.4163, 1066.4955 },
{ 1641, 4.4163, 625.6702 },
{ 1050, 3.1611, 213.2991 },
{ 1025, 2.5543, 412.3711 },
{ 806, 2.678, 632.784 },
{ 741, 2.171, 1162.475 },
{ 677, 6.250, 838.969 },
{ 567, 4.577, 742.990 },
{ 485, 2.469, 949.176 },
{ 469, 4.710, 543.918 },
{ 445, 0.403, 323.505 },
{ 416, 5.368, 728.763 },
{ 402, 4.605, 309.278 },
{ 347, 4.681, 14.227 },
{ 338, 3.168, 956.289 },
{ 261, 5.343, 846.083 },
{ 247, 3.923, 942.062 },
{ 220, 4.842, 1368.660 },
{ 203, 5.600, 1155.361 },
{ 200, 4.439, 1045.155 },
{ 197, 3.706, 2118.764 },
{ 196, 3.759, 199.072 },
{ 184, 4.265, 95.979 },
{ 180, 4.402, 532.872 },
{ 170, 4.846, 526.510 },
{ 146, 6.130, 533.623 },
{ 133, 1.322, 110.206 },
{ 132, 4.512, 525.759 }
},
{
{ 79645, 1.35866, 529.69097 },
{ 8252, 5.7777, 522.5774 },
{ 7030, 3.2748, 536.8045 },
{ 5314, 1.8384, 1059.3819 },
{ 1861, 2.9768, 7.1135 },
{ 964, 5.480, 515.464 },
{ 836, 4.199, 419.485 },
{ 498, 3.142, 0 },
{ 427, 2.228, 639.897 },
{ 406, 3.783, 1066.495 },
{ 377, 2.242, 1589.073 },
{ 363, 5.368, 206.186 },
{ 342, 6.099, 1052.268 },
{ 339, 6.127, 625.670 },
{ 333, 0.003, 426.598 },
{ 280, 4.262, 412.371 },
{ 257, 0.963, 632.784 },
{ 230, 0.705, 735.877 },
{ 201, 3.069, 543.918 },
{ 200, 4.429, 103.093 },
{ 139, 2.932, 14.227 },
{ 114, 0.787, 728.763 },
{ 95, 1.70, 838.97 },
{ 86, 5.14, 323.51 },
{ 83, 0.06, 309.28 },
{ 80, 2.98, 742.99 },
{ 75, 1.60, 956.29 },
{ 70, 1.51, 213.30 },
{ 67, 5.47, 199.07 },
{ 62, 6.10, 1045.15 },
{ 56, 0.96, 1162.47 },
{ 52, 5.58, 942.06 },
{ 50, 2.72, 532.87 },
{ 45, 5.52, 508.35 },
{ 44, 0.27, 526.51 },
{ 40, 5.95, 95.98 }
},
{
{ 3519, 6.0580, 529.6910 },
{ 1073, 1.6732, 536.8045 },
{ 916, 1.413, 522.577 },
{ 342, 0.523, 1059.382 },
{ 255, 1.196, 7.114 },
{ 222, 0.952, 515.464 },
{ 90, 3.14, 0 },
{ 69, 2.27, 1066.50 },
{ 58, 1.41, 543.92 },
{ 58, 0.53, 639.90 },
{ 51, 5.98, 412.37 },
{ 47, 1.58, 625.67 },
{ 43, 6.12, 419.48 },
{ 37, 1.18, 14.23 },
{ 34, 1.67, 1052.27 },
{ 34, 0.85, 206.19 },
{ 31, 1.04, 1589.07 },
{ 30, 4.63, 426.60 },
{ 21, 2.50, 728.76 },
{ 15, 0.89, 199.07 },
{ 14, 0.96, 508.35 },
{ 13, 1.50, 1045.15 },
{ 12, 2.61, 735.88 },
{ 12, 3.56, 323.51 },
{ 11, 1.79, 309.28 },
{ 11, 6.28, 956.29 },
{ 10, 6.26, 103.09 },
{ 9, 3.45, 838.97 }
},
{
{ 129, 0.084, 536.805 },
{ 113, 4.249, 529.691 },
{ 83, 3.30, 522.58 },
{ 38, 2.73, 515.46 },
{ 27, 5.69, 7.11 },
{ 18, 5.40, 1059.38 },
{ 13, 6.02, 543.92 },
{ 9, 0.77, 1066.50 },
{ 8, 5.68, 14.23 },
{ 7, 1.43, 412.37 },
{ 6, 5.12, 639.90 },
{ 5, 3.34, 625.67 },
{ 3, 3.40, 1052.27 },
{ 3, 4.16, 728.76 },
{ 3, 2.90, 426.60 }
},
{
{ 11, 4.75, 536.80 },
{ 4, 5.92, 522.58 },
{ 2, 5.57, 515.46 },
{ 2, 4.30, 543.92 },
{ 2, 3.69, 7.11 },
{ 2, 4.13, 1059.38 },
{ 2, 5.49, 1066.50 }
}
};
/**
* Tables of Vsop87 terms for Jupiter.
*/
static Vsop87 JUPITER = new Vsop87(JUPITER_L, JUPITER_B, JUPITER_R);
// ******************************************************************** //
// Saturn.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] SATURN_L = {
{
{ 87401354, 0, 0 },
{ 11107660, 3.96205090, 213.29909544 },
{ 1414151, 4.5858152, 7.1135470 },
{ 398379, 0.521120, 206.185548 },
{ 350769, 3.303299, 426.598191 },
{ 206816, 0.246584, 103.092774 },
{ 79271, 3.84007, 220.41264 },
{ 23990, 4.66977, 110.20632 },
{ 16574, 0.43719, 419.48464 },
{ 15820, 0.93809, 632.78374 },
{ 15054, 2.71670, 639.89729 },
{ 14907, 5.76903, 316.39187 },
{ 14610, 1.56519, 3.93215 },
{ 13160, 4.44891, 14.22709 },
{ 13005, 5.98119, 11.04570 },
{ 10725, 3.12940, 202.25340 },
{ 6126, 1.7633, 277.0350 },
{ 5863, 0.2366, 529.6910 },
{ 5228, 4.2078, 3.1814 },
{ 5020, 3.1779, 433.7117 },
{ 4593, 0.6198, 199.0720 },
{ 4006, 2.2448, 63.7359 },
{ 3874, 3.2228, 138.5175 },
{ 3269, 0.7749, 949.1756 },
{ 2954, 0.9828, 95.9792 },
{ 2461, 2.0316, 735.8765 },
{ 1758, 3.2658, 522.5774 },
{ 1640, 5.5050, 846.0828 },
{ 1581, 4.3727, 309.2783 },
{ 1391, 4.0233, 323.5054 },
{ 1124, 2.8373, 415.5525 },
{ 1087, 4.1834, 2.4477 },
{ 1017, 3.7170, 227.5262 },
{ 957, 0.507, 1265.567 },
{ 853, 3.421, 175.166 },
{ 849, 3.191, 209.367 },
{ 789, 5.007, 0.963 },
{ 749, 2.144, 853.196 },
{ 744, 5.253, 224.345 },
{ 687, 1.747, 1052.268 },
{ 654, 1.599, 0.048 },
{ 634, 2.299, 412.371 },
{ 625, 0.970, 210.118 },
{ 580, 3.093, 74.782 },
{ 546, 2.127, 350.332 },
{ 543, 1.518, 9.561 },
{ 530, 4.449, 117.320 },
{ 478, 2.965, 137.033 },
{ 474, 5.475, 742.990 },
{ 452, 1.044, 490.334 },
{ 449, 1.290, 127.472 },
{ 372, 2.278, 217.231 },
{ 355, 3.013, 838.969 },
{ 347, 1.539, 340.771 },
{ 343, 0.246, 0.521 },
{ 330, 0.247, 1581.959 },
{ 322, 0.961, 203.738 },
{ 322, 2.572, 647.011 },
{ 309, 3.495, 216.480 },
{ 287, 2.370, 351.817 },
{ 278, 0.400, 211.815 },
{ 249, 1.470, 1368.660 },
{ 227, 4.910, 12.530 },
{ 220, 4.204, 200.769 },
{ 209, 1.345, 625.670 },
{ 208, 0.483, 1162.475 },
{ 208, 1.283, 39.357 },
{ 204, 6.011, 265.989 },
{ 185, 3.503, 149.563 },
{ 184, 0.973, 4.193 },
{ 182, 5.491, 2.921 },
{ 174, 1.863, 0.751 },
{ 165, 0.440, 5.417 },
{ 149, 5.736, 52.690 },
{ 148, 1.535, 5.629 },
{ 146, 6.231, 195.140 },
{ 140, 4.295, 21.341 },
{ 131, 4.068, 10.295 },
{ 125, 6.277, 1898.351 },
{ 122, 1.976, 4.666 },
{ 118, 5.341, 554.070 },
{ 117, 2.679, 1155.361 },
{ 114, 5.594, 1059.382 },
{ 112, 1.105, 191.208 },
{ 110, 0.166, 1.484 },
{ 109, 3.438, 536.805 },
{ 107, 4.012, 956.289 },
{ 104, 2.192, 88.866 },
{ 103, 1.197, 1685.052 },
{ 101, 4.965, 269.921 }
},
{
{ 21354295596.0, 0, 0 },
{ 1296855, 1.8282054, 213.2990954 },
{ 564348, 2.885001, 7.113547 },
{ 107679, 2.277699, 206.185548 },
{ 98323, 1.08070, 426.59819 },
{ 40255, 2.04128, 220.41264 },
{ 19942, 1.27955, 103.09277 },
{ 10512, 2.74880, 14.22709 },
{ 6939, 0.4049, 639.8973 },
{ 4803, 2.4419, 419.4846 },
{ 4056, 2.9217, 110.2063 },
{ 3769, 3.6497, 3.9322 },
{ 3385, 2.4169, 3.1814 },
{ 3302, 1.2626, 433.7117 },
{ 3071, 2.3274, 199.0720 },
{ 1953, 3.5639, 11.0457 },
{ 1249, 2.6280, 95.9792 },
{ 922, 1.961, 227.526 },
{ 706, 4.417, 529.691 },
{ 650, 6.174, 202.253 },
{ 628, 6.111, 309.278 },
{ 487, 6.040, 853.196 },
{ 479, 4.988, 522.577 },
{ 468, 4.617, 63.736 },
{ 417, 2.117, 323.505 },
{ 408, 1.299, 209.367 },
{ 352, 2.317, 632.784 },
{ 344, 3.959, 412.371 },
{ 340, 3.634, 316.392 },
{ 336, 3.772, 735.877 },
{ 332, 2.861, 210.118 },
{ 289, 2.733, 117.320 },
{ 281, 5.744, 2.448 },
{ 266, 0.543, 647.011 },
{ 230, 1.644, 216.480 },
{ 192, 2.965, 224.345 },
{ 173, 4.077, 846.083 },
{ 167, 2.597, 21.341 },
{ 136, 2.286, 10.295 },
{ 131, 3.441, 742.990 },
{ 128, 4.095, 217.231 },
{ 109, 6.161, 415.552 },
{ 98, 4.73, 838.97 },
{ 94, 3.48, 1052.27 },
{ 92, 3.95, 88.87 },
{ 87, 1.22, 440.83 },
{ 83, 3.11, 625.67 },
{ 78, 6.24, 302.16 },
{ 67, 0.29, 4.67 },
{ 66, 5.65, 9.56 },
{ 62, 4.29, 127.47 },
{ 62, 1.83, 195.14 },
{ 58, 2.48, 191.96 },
{ 57, 5.02, 137.03 },
{ 55, 0.28, 74.78 },
{ 54, 5.13, 490.33 },
{ 51, 1.46, 536.80 },
{ 47, 1.18, 149.56 },
{ 47, 5.15, 515.46 },
{ 46, 2.23, 956.29 },
{ 44, 2.71, 5.42 },
{ 40, 0.41, 269.92 },
{ 40, 3.89, 728.76 },
{ 38, 0.65, 422.67 },
{ 38, 2.53, 12.53 },
{ 37, 3.78, 2.92 },
{ 35, 6.08, 5.63 },
{ 34, 3.21, 1368.66 },
{ 33, 4.64, 277.03 },
{ 33, 5.43, 1066.50 },
{ 33, 0.30, 351.82 },
{ 32, 4.39, 1155.36 },
{ 31, 2.43, 52.69 },
{ 30, 2.84, 203.00 },
{ 30, 6.19, 284.15 },
{ 30, 3.39, 1059.38 },
{ 29, 2.03, 330.62 },
{ 28, 2.74, 265.99 },
{ 26, 4.51, 340.77 }
},
{
{ 116441, 1.179879, 7.113547 },
{ 91921, 0.07425, 213.29910 },
{ 90592, 0, 0 },
{ 15277, 4.06492, 206.18555 },
{ 10631, 0.25778, 220.41264 },
{ 10605, 5.40964, 426.59819 },
{ 4265, 1.0460, 14.2271 },
{ 1216, 2.9186, 103.0928 },
{ 1165, 4.6094, 639.8973 },
{ 1082, 5.6913, 433.7117 },
{ 1045, 4.0421, 199.0720 },
{ 1020, 0.6337, 3.1814 },
{ 634, 4.388, 419.485 },
{ 549, 5.573, 3.932 },
{ 457, 1.268, 110.206 },
{ 425, 0.209, 227.526 },
{ 274, 4.288, 95.979 },
{ 162, 1.381, 11.046 },
{ 129, 1.566, 309.278 },
{ 117, 3.881, 853.196 },
{ 105, 4.900, 647.011 },
{ 101, 0.893, 21.341 },
{ 96, 2.91, 316.39 },
{ 95, 5.63, 412.37 },
{ 85, 5.73, 209.37 },
{ 83, 6.05, 216.48 },
{ 82, 1.02, 117.32 },
{ 75, 4.76, 210.12 },
{ 67, 0.46, 522.58 },
{ 66, 0.48, 10.29 },
{ 64, 0.35, 323.51 },
{ 61, 4.88, 632.78 },
{ 53, 2.75, 529.69 },
{ 46, 5.69, 440.83 },
{ 45, 1.67, 202.25 },
{ 42, 5.71, 88.87 },
{ 32, 0.07, 63.74 },
{ 32, 1.67, 302.16 },
{ 31, 4.16, 191.96 },
{ 27, 0.83, 224.34 },
{ 25, 5.66, 735.88 },
{ 20, 5.94, 217.23 },
{ 18, 4.90, 625.67 },
{ 17, 1.63, 742.99 },
{ 16, 0.58, 515.46 },
{ 14, 0.21, 838.97 },
{ 14, 3.76, 195.14 },
{ 12, 4.72, 203.00 },
{ 12, 0.13, 234.64 },
{ 12, 3.12, 846.08 },
{ 11, 5.92, 536.80 },
{ 11, 5.60, 728.76 },
{ 11, 3.20, 1066.50 },
{ 10, 4.99, 422.67 },
{ 10, 0.26, 330.62 },
{ 10, 4.15, 860.31 },
{ 9, 0.46, 956.29 },
{ 8, 2.14, 269.92 },
{ 8, 5.25, 429.78 },
{ 8, 4.03, 9.56 },
{ 7, 5.40, 1052.27 },
{ 6, 4.46, 284.15 },
{ 6, 5.93, 405.26 }
},
{
{ 16039, 5.73945, 7.11355 },
{ 4250, 4.5854, 213.2991 },
{ 1907, 4.7608, 220.4126 },
{ 1466, 5.9133, 206.1855 },
{ 1162, 5.6197, 14.2271 },
{ 1067, 3.6082, 426.5982 },
{ 239, 3.861, 433.712 },
{ 237, 5.768, 199.072 },
{ 166, 5.116, 3.181 },
{ 151, 2.736, 639.897 },
{ 131, 4.743, 227.526 },
{ 63, 0.23, 419.48 },
{ 62, 4.74, 103.09 },
{ 40, 5.47, 21.34 },
{ 40, 5.96, 95.98 },
{ 39, 5.83, 110.21 },
{ 28, 3.01, 647.01 },
{ 25, 0.99, 3.93 },
{ 19, 1.92, 853.20 },
{ 18, 4.97, 10.29 },
{ 18, 1.03, 412.37 },
{ 18, 4.20, 216.48 },
{ 18, 3.32, 309.28 },
{ 16, 3.90, 440.83 },
{ 16, 5.62, 117.32 },
{ 13, 1.18, 88.87 },
{ 11, 5.58, 11.05 },
{ 11, 5.93, 191.96 },
{ 10, 3.95, 209.37 },
{ 9, 3.39, 302.16 },
{ 8, 4.88, 323.51 },
{ 7, 0.38, 632.78 },
{ 6, 2.25, 522.58 },
{ 6, 1.06, 210.12 },
{ 5, 4.64, 234.64 },
{ 4, 3.14, 0 },
{ 4, 2.31, 515.46 },
{ 3, 2.20, 860.31 },
{ 3, 0.59, 529.69 },
{ 3, 4.93, 224.34 },
{ 3, 0.42, 625.67 },
{ 2, 4.77, 330.62 },
{ 2, 3.35, 429.78 },
{ 2, 3.20, 202.25 },
{ 2, 1.19, 1066.50 },
{ 2, 1.35, 405.26 },
{ 2, 4.16, 223.59 },
{ 2, 3.07, 654.12 }
},
{
{ 1662, 3.9983, 7.1135 },
{ 257, 2.984, 220.413 },
{ 236, 3.902, 14.227 },
{ 149, 2.741, 213.299 },
{ 114, 3.142, 0 },
{ 110, 1.515, 206.186 },
{ 68, 1.72, 426.60 },
{ 40, 2.05, 433.71 },
{ 38, 1.24, 199.07 },
{ 31, 3.01, 227.53 },
{ 15, 0.83, 639.90 },
{ 9, 3.71, 21.34 },
{ 6, 2.42, 419.48 },
{ 6, 1.16, 647.01 },
{ 4, 1.45, 95.98 },
{ 4, 2.12, 440.83 },
{ 3, 4.09, 110.21 },
{ 3, 2.77, 412.37 },
{ 3, 3.01, 88.87 },
{ 3, 0.00, 853.20 },
{ 3, 0.39, 103.09 },
{ 2, 3.78, 117.32 },
{ 2, 2.83, 234.64 },
{ 2, 5.08, 309.28 },
{ 2, 2.24, 216.48 },
{ 2, 5.19, 302.16 },
{ 1, 1.55, 191.96 }
},
{
{ 124, 2.259, 7.114 },
{ 34, 2.16, 14.23 },
{ 28, 1.20, 220.41 },
{ 6, 1.22, 227.53 },
{ 5, 0.24, 433.71 },
{ 4, 6.23, 426.60 },
{ 3, 2.97, 199.07 },
{ 3, 4.29, 206.19 },
{ 2, 6.25, 213.30 },
{ 1, 5.28, 639.90 },
{ 1, 0.24, 440.83 },
{ 1, 3.14, 0 }
}
};
// Heliocentric latitude.
private static final double[][][] SATURN_B = {
{
{ 4330678, 3.6028443, 213.2990954 },
{ 240348, 2.852385, 426.598191 },
{ 84746, 0, 0 },
{ 34116, 0.57297, 206.18555 },
{ 30863, 3.48442, 220.41264 },
{ 14734, 2.11847, 639.89729 },
{ 9917, 5.7900, 419.4846 },
{ 6994, 4.7360, 7.1135 },
{ 4808, 5.4331, 316.3919 },
{ 4788, 4.9651, 110.2063 },
{ 3432, 2.7326, 433.7117 },
{ 1506, 6.0130, 103.0928 },
{ 1060, 5.6310, 529.6910 },
{ 969, 5.204, 632.784 },
{ 942, 1.396, 853.196 },
{ 708, 3.803, 323.505 },
{ 552, 5.131, 202.253 },
{ 400, 3.359, 227.526 },
{ 319, 3.626, 209.367 },
{ 316, 1.997, 647.011 },
{ 314, 0.465, 217.231 },
{ 284, 4.886, 224.345 },
{ 236, 2.139, 11.046 },
{ 215, 5.950, 846.083 },
{ 209, 2.120, 415.552 },
{ 207, 0.730, 199.072 },
{ 179, 2.954, 63.736 },
{ 141, 0.644, 490.334 },
{ 139, 4.595, 14.227 },
{ 139, 1.998, 735.877 },
{ 135, 5.245, 742.990 },
{ 122, 3.115, 522.577 },
{ 116, 3.109, 216.480 },
{ 114, 0.963, 210.118 }
},
{
{ 397555, 5.332900, 213.299095 },
{ 49479, 3.14159, 0 },
{ 18572, 6.09919, 426.59819 },
{ 14801, 2.30586, 206.18555 },
{ 9644, 1.6967, 220.4126 },
{ 3757, 1.2543, 419.4846 },
{ 2717, 5.9117, 639.8973 },
{ 1455, 0.8516, 433.7117 },
{ 1291, 2.9177, 7.1135 },
{ 853, 0.436, 316.392 },
{ 298, 0.919, 632.784 },
{ 292, 5.316, 853.196 },
{ 284, 1.619, 227.526 },
{ 275, 3.889, 103.093 },
{ 172, 0.052, 647.011 },
{ 166, 2.444, 199.072 },
{ 158, 5.209, 110.206 },
{ 128, 1.207, 529.691 },
{ 110, 2.457, 217.231 },
{ 82, 2.76, 210.12 },
{ 81, 2.86, 14.23 },
{ 69, 1.66, 202.25 },
{ 65, 1.26, 216.48 },
{ 61, 1.25, 209.37 },
{ 59, 1.82, 323.51 },
{ 46, 0.82, 440.83 },
{ 36, 1.82, 224.34 },
{ 34, 2.84, 117.32 },
{ 33, 1.31, 412.37 },
{ 32, 1.19, 846.08 },
{ 27, 4.65, 1066.50 },
{ 27, 4.44, 11.05 }
},
{
{ 20630, 0.50482, 213.29910 },
{ 3720, 3.9983, 206.1855 },
{ 1627, 6.1819, 220.4126 },
{ 1346, 0, 0 },
{ 706, 3.039, 419.485 },
{ 365, 5.099, 426.598 },
{ 330, 5.279, 433.712 },
{ 219, 3.828, 639.897 },
{ 139, 1.043, 7.114 },
{ 104, 6.157, 227.526 },
{ 93, 1.98, 316.39 },
{ 71, 4.15, 199.07 },
{ 52, 2.88, 632.78 },
{ 49, 4.43, 647.01 },
{ 41, 3.16, 853.20 },
{ 29, 4.53, 210.12 },
{ 24, 1.12, 14.23 },
{ 21, 4.35, 217.23 },
{ 20, 5.31, 440.83 },
{ 18, 0.85, 110.21 },
{ 17, 5.68, 216.48 },
{ 16, 4.26, 103.09 },
{ 14, 3.00, 412.37 },
{ 12, 2.53, 529.69 },
{ 8, 3.32, 202.25 },
{ 7, 5.56, 209.37 },
{ 7, 0.29, 323.51 },
{ 6, 1.16, 117.32 },
{ 6, 3.61, 869.31 }
},
{
{ 666, 1.990, 213.299 },
{ 632, 5.698, 206.186 },
{ 398, 0, 0 },
{ 188, 4.338, 220.413 },
{ 92, 4.84, 419.48 },
{ 52, 3.42, 433.71 },
{ 42, 2.38, 426.60 },
{ 26, 4.40, 227.53 },
{ 21, 5.85, 199.07 },
{ 18, 1.99, 639.90 },
{ 11, 5.37, 7.11 },
{ 10, 2.55, 647.01 },
{ 7, 3.46, 316.39 },
{ 6, 4.80, 632.78 },
{ 6, 0.02, 210.12 },
{ 6, 3.52, 440.83 },
{ 5, 5.64, 14.23 },
{ 5, 1.22, 853.20 },
{ 4, 4.71, 412.37 },
{ 3, 0.63, 103.09 },
{ 2, 3.72, 216.48 }
},
{
{ 80, 1.12, 206.19 },
{ 32, 3.12, 213.30 },
{ 17, 2.48, 220.41 },
{ 12, 3.14, 0 },
{ 9, 0.38, 419.48 },
{ 6, 1.56, 433.71 },
{ 5, 2.63, 227.53 },
{ 5, 1.28, 199.07 },
{ 1, 1.43, 426.60 },
{ 1, 0.67, 647.01 },
{ 1, 1.72, 440.83 },
{ 1, 6.18, 639.90 }
},
{
{ 8, 2.82, 206.19 },
{ 1, 0.51, 220.41 }
}
};
// Heliocentric radius vector.
private static final double[][][] SATURN_R = {
{
{ 955758136, 0, 0 },
{ 52921382, 2.39226220, 213.29909544 },
{ 1873680, 5.2354961, 206.1855484 },
{ 1464664, 1.6476305, 426.5981909 },
{ 821891, 5.935200, 316.391870 },
{ 547507, 5.015326, 103.092774 },
{ 371684, 2.271148, 220.412642 },
{ 361778, 3.139043, 7.113547 },
{ 140618, 5.704067, 632.783739 },
{ 108975, 3.293136, 110.206321 },
{ 69007, 5.94100, 419.48464 },
{ 61053, 0.94038, 639.89729 },
{ 48913, 1.55733, 202.25340 },
{ 34144, 0.19519, 277.03499 },
{ 32402, 5.47085, 949.17561 },
{ 20937, 0.46349, 735.87651 },
{ 20839, 1.52103, 433.71174 },
{ 20747, 5.33256, 199.07200 },
{ 15298, 3.05944, 529.69097 },
{ 14296, 2.60434, 323.50542 },
{ 12884, 1.64892, 138.51750 },
{ 11993, 5.98051, 846.08283 },
{ 11380, 1.73106, 522.57742 },
{ 9796, 5.2048, 1265.5675 },
{ 7753, 5.8519, 95.9792 },
{ 6771, 3.0043, 14.2271 },
{ 6466, 0.1773, 1052.2684 },
{ 5850, 1.4552, 415.5525 },
{ 5307, 0.5974, 63.7359 },
{ 4696, 2.1492, 227.5262 },
{ 4044, 1.6401, 209.3669 },
{ 3688, 0.7802, 412.3711 },
{ 3461, 1.8509, 175.1661 },
{ 3420, 4.9455, 1581.9593 },
{ 3401, 0.5539, 350.3321 },
{ 3376, 3.6953, 224.3448 },
{ 2976, 5.6847, 210.1177 },
{ 2885, 1.3876, 838.9693 },
{ 2881, 0.1796, 853.1964 },
{ 2508, 3.5385, 742.9901 },
{ 2448, 6.1841, 1368.6603 },
{ 2406, 2.9656, 117.3199 },
{ 2174, 0.0151, 340.7709 },
{ 2024, 5.0541, 11.0457 }
},
{
{ 6182981, 0.2584352, 213.2990954 },
{ 506578, 0.711147, 206.185548 },
{ 341394, 5.796358, 426.598191 },
{ 188491, 0.472157, 220.412642 },
{ 186262, 3.141593, 0 },
{ 143891, 1.407449, 7.113547 },
{ 49621, 6.01744, 103.09277 },
{ 20928, 5.09246, 639.89729 },
{ 19953, 1.17560, 419.48464 },
{ 18840, 1.60820, 110.20632 },
{ 13877, 0.75886, 199.07200 },
{ 12893, 5.94330, 433.71174 },
{ 5397, 1.2885, 14.2271 },
{ 4869, 0.8679, 323.5054 },
{ 4247, 0.3930, 227.5262 },
{ 3252, 1.2585, 95.9792 },
{ 3081, 3.4366, 522.5774 },
{ 2909, 4.6068, 202.2534 },
{ 2856, 2.1673, 735.8765 },
{ 1988, 2.4505, 412.3711 },
{ 1941, 6.0239, 209.3669 },
{ 1581, 1.2919, 210.1177 },
{ 1340, 4.3080, 853.1964 },
{ 1316, 1.2530, 117.3199 },
{ 1203, 1.8665, 316.3919 },
{ 1091, 0.0753, 216.4805 },
{ 966, 0.480, 632.784 },
{ 954, 5.152, 647.011 },
{ 898, 0.983, 529.691 },
{ 882, 1.885, 1052.268 },
{ 874, 1.402, 224.345 },
{ 785, 3.064, 838.969 },
{ 740, 1.382, 625.670 },
{ 658, 4.144, 309.278 },
{ 650, 1.725, 742.990 },
{ 613, 3.033, 63.736 },
{ 599, 2.549, 217.231 },
{ 503, 2.130, 3.932 }
},
{
{ 436902, 4.786717, 213.299095 },
{ 71923, 2.50070, 206.18555 },
{ 49767, 4.97168, 220.41264 },
{ 43221, 3.86940, 426.59819 },
{ 29646, 5.96310, 7.11355 },
{ 4721, 2.4753, 199.0720 },
{ 4142, 4.1067, 433.7117 },
{ 3789, 3.0977, 639.8973 },
{ 2964, 1.3721, 103.0928 },
{ 2556, 2.8507, 419.4846 },
{ 2327, 0, 0 },
{ 2208, 6.2759, 110.2063 },
{ 2188, 5.8555, 14.2271 },
{ 1957, 4.9245, 227.5262 },
{ 924, 5.464, 323.505 },
{ 706, 2.971, 95.979 },
{ 546, 4.129, 412.371 },
{ 431, 5.178, 522.577 },
{ 405, 4.173, 209.367 },
{ 391, 4.481, 216.480 },
{ 374, 5.834, 117.320 },
{ 361, 3.277, 647.011 },
{ 356, 3.192, 210.118 },
{ 326, 2.269, 853.196 },
{ 207, 4.022, 735.877 },
{ 204, 0.088, 202.253 },
{ 180, 3.597, 632.784 },
{ 178, 4.097, 440.825 },
{ 154, 3.135, 625.670 },
{ 148, 0.136, 302.165 },
{ 133, 2.594, 191.958 },
{ 132, 5.933, 309.278 }
},
{
{ 20315, 3.02187, 213.29910 },
{ 8924, 3.1914, 220.4126 },
{ 6909, 4.3517, 206.1855 },
{ 4087, 4.2241, 7.1135 },
{ 3879, 2.0106, 426.5982 },
{ 1071, 4.2036, 199.0720 },
{ 907, 2.283, 433.712 },
{ 606, 3.175, 227.526 },
{ 597, 4.135, 14.227 },
{ 483, 1.173, 639.897 },
{ 393, 0, 0 },
{ 229, 4.698, 419.485 },
{ 188, 4.590, 110.206 },
{ 150, 3.202, 103.093 },
{ 121, 3.768, 323.505 },
{ 102, 4.710, 95.979 },
{ 101, 5.819, 412.371 },
{ 93, 1.44, 647.01 },
{ 84, 2.63, 216.48 },
{ 73, 4.15, 117.32 },
{ 62, 2.31, 440.83 },
{ 55, 0.31, 853.20 },
{ 50, 2.39, 209.37 },
{ 45, 4.37, 191.96 },
{ 41, 0.69, 522.58 },
{ 40, 1.84, 302.16 },
{ 38, 5.94, 88.87 },
{ 32, 4.01, 21.34 }
},
{
{ 1202, 1.4150, 220.4126 },
{ 708, 1.162, 213.299 },
{ 516, 6.240, 206.186 },
{ 427, 2.469, 7.114 },
{ 268, 0.187, 426.598 },
{ 170, 5.959, 199.072 },
{ 150, 0.480, 433.712 },
{ 145, 1.442, 227.526 },
{ 121, 2.405, 14.227 },
{ 47, 5.57, 639.90 },
{ 19, 5.86, 647.01 },
{ 17, 0.53, 440.83 },
{ 16, 2.90, 110.21 },
{ 15, 0.30, 419.48 },
{ 14, 1.30, 412.37 },
{ 13, 2.09, 323.51 },
{ 11, 0.22, 95.98 },
{ 11, 2.46, 117.32 },
{ 10, 3.14, 0 },
{ 9, 1.56, 88.87 },
{ 9, 2.28, 21.34 },
{ 9, 0.68, 216.48 },
{ 8, 1.27, 234.64 }
},
{
{ 129, 5.913, 220.413 },
{ 32, 0.69, 7.11 },
{ 27, 5.91, 227.53 },
{ 20, 4.95, 433.71 },
{ 20, 0.67, 14.23 },
{ 14, 2.67, 206.19 },
{ 14, 1.46, 199.07 },
{ 13, 4.59, 426.60 },
{ 7, 4.63, 213.30 },
{ 5, 3.61, 639.90 },
{ 4, 4.90, 440.83 },
{ 3, 4.07, 647.01 },
{ 3, 4.66, 191.96 },
{ 3, 0.49, 323.51 },
{ 3, 3.18, 419.48 },
{ 2, 3.70, 88.87 },
{ 2, 3.32, 95.98 },
{ 2, 0.56, 117.32 }
}
};
/**
* Tables of Vsop87 terms for Saturn.
*/
static Vsop87 SATURN = new Vsop87(SATURN_L, SATURN_B, SATURN_R);
// ******************************************************************** //
// Uranus.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] URANUS_L = {
{
{ 548129294, 0, 0 },
{ 9260408, 0.8910642, 74.7815986 },
{ 1504248, 3.6271926, 1.4844727 },
{ 365982, 1.899622, 73.297126 },
{ 272328, 3.358237, 149.563197 },
{ 70328, 5.39254, 63.73590 },
{ 68893, 6.09292, 76.26607 },
{ 61999, 2.26952, 2.96895 },
{ 61951, 2.85099, 11.04570 },
{ 26469, 3.14152, 71.81265 },
{ 25711, 6.11380, 454.90937 },
{ 21079, 4.36059, 148.07872 },
{ 17819, 1.74437, 36.64856 },
{ 14613, 4.73732, 3.93215 },
{ 11163, 5.82682, 224.34480 },
{ 10998, 0.48865, 138.51750 },
{ 9527, 2.9552, 35.1641 },
{ 7546, 5.2363, 109.9457 },
{ 4220, 3.2333, 70.8494 },
{ 4052, 2.2775, 151.0477 },
{ 3490, 5.4831, 146.5943 },
{ 3355, 1.0655, 4.4534 },
{ 3144, 4.7520, 77.7505 },
{ 2927, 4.6290, 9.5612 },
{ 2922, 5.3524, 85.8273 },
{ 2273, 4.3660, 70.3282 },
{ 2149, 0.6075, 38.1330 },
{ 2051, 1.5177, 0.1119 },
{ 1992, 4.9244, 277.0350 },
{ 1667, 3.6274, 380.1278 },
{ 1533, 2.5859, 52.6902 },
{ 1376, 2.0428, 65.2204 },
{ 1372, 4.1964, 111.4302 },
{ 1284, 3.1135, 202.2534 },
{ 1282, 0.5427, 222.8603 },
{ 1244, 0.9161, 2.4477 },
{ 1221, 0.1990, 108.4612 },
{ 1151, 4.1790, 33.6796 },
{ 1150, 0.9334, 3.1814 },
{ 1090, 1.7750, 12.5302 },
{ 1072, 0.2356, 62.2514 },
{ 946, 1.192, 127.472 },
{ 708, 5.183, 213.299 },
{ 653, 0.966, 78.714 },
{ 628, 0.182, 984.600 },
{ 607, 5.432, 529.691 },
{ 559, 3.358, 0.521 },
{ 524, 2.013, 299.126 },
{ 483, 2.106, 0.963 },
{ 471, 1.407, 184.727 },
{ 467, 0.415, 145.110 },
{ 434, 5.521, 183.243 },
{ 405, 5.987, 8.077 },
{ 399, 0.338, 415.552 },
{ 396, 5.870, 351.817 },
{ 379, 2.350, 56.622 },
{ 310, 5.833, 145.631 },
{ 300, 5.644, 22.091 },
{ 294, 5.839, 39.618 },
{ 252, 1.637, 221.376 },
{ 249, 4.746, 225.829 },
{ 239, 2.350, 137.033 },
{ 224, 0.516, 84.343 },
{ 223, 2.843, 0.261 },
{ 220, 1.922, 67.668 },
{ 217, 6.142, 5.938 },
{ 216, 4.778, 340.771 },
{ 208, 5.580, 68.844 },
{ 202, 1.297, 0.048 },
{ 199, 0.956, 152.532 },
{ 194, 1.888, 456.394 },
{ 193, 0.916, 453.425 } ,
{ 187, 1.319, 0.160 },
{ 182, 3.536, 79.235 },
{ 173, 1.539, 160.609 },
{ 172, 5.680, 219.891 },
{ 170, 3.677, 5.417 },
{ 169, 5.879, 18.159 },
{ 165, 1.424, 106.977 },
{ 163, 3.050, 112.915 },
{ 158, 0.738, 54.175 },
{ 147, 1.263, 59.804 },
{ 143, 1.300, 35.425 },
{ 139, 5.386, 32.195 },
{ 139, 4.260, 909.819 },
{ 124, 1.374, 7.114 },
{ 110, 2.027, 554.070 },
{ 109, 5.706, 77.963 },
{ 104, 5.028, 0.751 },
{ 104, 1.458, 24.379 },
{ 103, 0.681, 14.978 }
},
{
{ 7502543122.0, 0, 0 },
{ 154458, 5.242017, 74.781599 },
{ 24456, 1.71256, 1.48447 },
{ 9258, 0.4284, 11.0457 },
{ 8266, 1.5022, 63.7359 },
{ 7842, 1.3198, 149.5632 },
{ 3899, 0.4648, 3.9322 },
{ 2284, 4.1737, 76.2661 },
{ 1927, 0.5301, 2.9689 },
{ 1233, 1.5863, 70.8494 },
{ 791, 5.436, 3.181 },
{ 767, 1.996, 73.297 },
{ 482, 2.984, 85.827 },
{ 450, 4.138, 138.517 },
{ 446, 3.723, 224.345 },
{ 427, 4.731, 71.813 },
{ 354, 2.583, 148.079 },
{ 348, 2.454, 9.561 },
{ 317, 5.579, 52.690 },
{ 206, 2.363, 2.448 },
{ 189, 4.202, 56.622 },
{ 184, 0.284, 151.048 },
{ 180, 5.684, 12.530 },
{ 171, 3.001, 78.714 },
{ 158, 2.909, 0.963 },
{ 155, 5.591, 4.453 },
{ 154, 4.652, 35.164 },
{ 152, 2.942, 77.751 },
{ 143, 2.590, 62.251 },
{ 121, 4.148, 127.472 },
{ 116, 3.732, 65.220 },
{ 102, 4.188, 145.631 },
{ 102, 6.034, 0.112 },
{ 88, 3.99, 18.16 },
{ 88, 6.16, 202.25 },
{ 81, 2.64, 22.09 },
{ 72, 6.05, 70.33 },
{ 69, 4.05, 77.96 },
{ 59, 3.70, 67.67 },
{ 47, 3.54, 351.82 },
{ 44, 5.91, 7.11 },
{ 43, 5.72, 5.42 },
{ 39, 4.92, 222.86 },
{ 36, 5.90, 33.68 },
{ 36, 3.29, 8.08 },
{ 36, 3.33, 71.60 },
{ 35, 5.08, 38.13 },
{ 31, 5.62, 984.60 },
{ 31, 5.50, 59.80 },
{ 31, 5.46, 160.61 },
{ 30, 1.66, 447.80 },
{ 29, 1.15, 462.02 },
{ 29, 4.52, 84.34 },
{ 27, 5.54, 131.40 },
{ 27, 6.15, 299.13 },
{ 26, 4.99, 137.03 },
{ 25, 5.74, 380.13 }
},
{
{ 53033, 0, 0 },
{ 2358, 2.2601, 74.7816 },
{ 769, 4.526, 11.046 },
{ 552, 3.258, 63.736 },
{ 542, 2.276, 3.932 },
{ 529, 4.923, 1.484 },
{ 258, 3.691, 3.181 },
{ 239, 5.858, 149.563 },
{ 182, 6.218, 70.849 },
{ 54, 1.44, 76.27 },
{ 49, 6.03, 56.62 },
{ 45, 3.91, 2.45 },
{ 45, 0.81, 85.83 },
{ 38, 1.78, 52.69 },
{ 37, 4.46, 2.97 },
{ 33, 0.86, 9.56 },
{ 29, 5.10, 73.30 },
{ 24, 2.11, 18.16 },
{ 22, 5.99, 138.52 },
{ 22, 4.82, 78.71 },
{ 21, 2.40, 77.96 },
{ 21, 2.17, 224.34 },
{ 17, 2.54, 145.63 },
{ 17, 3.47, 12.53 },
{ 12, 0.02, 22.09 },
{ 11, 0.08, 127.47 },
{ 10, 5.16, 71.60 },
{ 10, 4.46, 62.25 },
{ 9, 4.26, 7.11 },
{ 8, 5.50, 67.67 },
{ 7, 1.25, 5.42 },
{ 6, 3.36, 447.80 },
{ 6, 5.45, 65.22 },
{ 6, 4.52, 151.05 },
{ 6, 5.73, 462.02 }
},
{
{ 121, 0.024, 74.782 },
{ 68, 4.12, 3.93 },
{ 53, 2.39, 11.05 },
{ 46, 0, 0 },
{ 45, 2.04, 3.18 },
{ 44, 2.96, 1.48 },
{ 25, 4.89, 63.74 },
{ 21, 4.55, 70.85 },
{ 20, 2.31, 149.56 },
{ 9, 1.58, 56.62 },
{ 4, 0.23, 18.16 },
{ 4, 5.39, 76.27 },
{ 4, 0.95, 77.96 },
{ 3, 4.98, 85.83 },
{ 3, 4.13, 52.69 },
{ 3, 0.37, 78.71 },
{ 2, 0.86, 145.63 },
{ 2, 5.66, 9.56 }
},
{
{ 114, 3.142, 0 },
{ 6, 4.58, 74.78 },
{ 3, 0.35, 11.05 },
{ 1, 3.42, 56.62 }
}
};
// Heliocentric latitude.
private static final double[][][] URANUS_B = {
{
{ 1346278, 2.6187781, 74.7815986 },
{ 62341, 5.08111, 149.56320 },
{ 61601, 3.14159, 0 },
{ 9964, 1.6160, 76.2661 },
{ 9926, 0.5763, 73.2971 },
{ 3259, 1.2612, 224.3448 },
{ 2972, 2.2437, 1.4845 },
{ 2010, 6.0555, 148.0787 },
{ 1522, 0.2796, 63.7359 },
{ 924, 4.038, 151.048 },
{ 761, 6.140, 71.813 },
{ 522, 3.321, 138.517 },
{ 463, 0.743, 85.827 },
{ 437, 3.381, 529.691 },
{ 435, 0.341, 77.751 },
{ 431, 3.554, 213.299 },
{ 420, 5.213, 11.046 },
{ 245, 0.788, 2.969 },
{ 233, 2.257, 222.860 },
{ 216, 1.591, 38.133 },
{ 180, 3.725, 299.126 },
{ 175, 1.236, 146.594 },
{ 174, 1.937, 380.128 },
{ 160, 5.336, 111.430 },
{ 144, 5.962, 35.164 },
{ 116, 5.739, 70.849 },
{ 106, 0.941, 70.328 },
{ 102, 2.619, 78.714 }
},
{
{ 206366, 4.123943, 74.781599 },
{ 8563, 0.3382, 149.5632 },
{ 1726, 2.1219, 73.2971 },
{ 1374, 0, 0 },
{ 1369, 3.0686, 76.2661 },
{ 451, 3.777, 1.484 },
{ 400, 2.848, 224.345 },
{ 307, 1.255, 148.079 },
{ 154, 3.786, 63.736 },
{ 112, 5.573, 151.048 },
{ 111, 5.329, 138.517 },
{ 83, 3.59, 71.81 },
{ 56, 3.40, 85.83 },
{ 54, 1.70, 77.75 },
{ 42, 1.21, 11.05 },
{ 41, 4.45, 78.71 },
{ 32, 3.77, 222.86 },
{ 30, 2.56, 2.97 },
{ 27, 5.34, 213.30 },
{ 26, 0.42, 380.13 }
},
{
{ 9212, 5.8004, 74.7816 },
{ 557, 0, 0},
{ 286, 2.177, 149.563 },
{ 95, 3.84, 73.30 },
{ 45, 4.88, 76.27 },
{ 20, 5.46, 1.48 },
{ 15, 0.88, 138.52 },
{ 14, 2.85, 148.08 },
{ 14, 5.07, 63.74 },
{ 10, 5.00, 224.34 },
{ 8, 6.27, 78.71 }
},
{
{ 268, 1.251, 74.782 },
{ 11, 3.14, 0 },
{ 6, 4.01, 149.56 },
{ 3, 5.78, 73.30 }
},
{
{ 6, 2.85, 74.78 }
}
};
// Heliocentric radius vector.
private static final double[][][] URANUS_R = {
{
{ 1921264848, 0, 0 },
{ 88784984, 5.60377527, 74.78159857 },
{ 3440836, 0.3283610, 73.2971259 },
{ 2055653, 1.7829517, 149.5631971 },
{ 649322, 4.522473, 76.266071 },
{ 602248, 3.860038, 63.735898 },
{ 496404, 1.401399, 454.909367 },
{ 338526, 1.580027, 138.517497 },
{ 243508, 1.570866, 71.812653 },
{ 190522, 1.998094, 1.484473 },
{ 161858, 2.791379, 148.078724 },
{ 143706, 1.383686, 11.045700 },
{ 93192, 0.17437, 36.64856 },
{ 89806, 3.66105, 109.94569 },
{ 71424, 4.24509, 224.34480 },
{ 46677, 1.39977, 35.16409 },
{ 39026, 3.36235, 277.03499 },
{ 39010, 1.66971, 70.84945 },
{ 36755, 3.88649, 146.59425 },
{ 30349, 0.70100, 151.04767 },
{ 29156, 3.18056, 77.75054 },
{ 25786, 3.78538, 85.82730 },
{ 25620, 5.25656, 380.12777 },
{ 22637, 0.72519, 529.69097 },
{ 20473, 2.79640, 70.32818 },
{ 20472, 1.55589, 202.25340 },
{ 17901, 0.55455, 2.96895 },
{ 15503, 5.35405, 38.13304 },
{ 14702, 4.90434, 108.46122 },
{ 12897, 2.62154, 111.43016 },
{ 12328, 5.96039, 127.47180 },
{ 11959, 1.75044, 984.60033 },
{ 11853, 0.99343, 52.69020 },
{ 11696, 3.29826, 3.93215 },
{ 11495, 0.43774, 65.22037 },
{ 10793, 1.42105, 213.29910 },
{ 9111, 4.9964, 62.2514 },
{ 8421, 5.2535, 222.8603 },
{ 8402, 5.0388, 415.5525 },
{ 7449, 0.7949, 351.8166 },
{ 7329, 3.9728, 183.2428 },
{ 6046, 5.6796, 78.7138 },
{ 5524, 3.1150, 9.5612 },
{ 5445, 5.1058, 145.1098 },
{ 5238, 2.6296, 33.6796 },
{ 4079, 3.2206, 340.7709 },
{ 3919, 4.2502, 39.6175 },
{ 3802, 6.1099, 184.7273 },
{ 3781, 3.4584, 456.3938 },
{ 3687, 2.4872, 453.4249 },
{ 3102, 4.1403, 219.8914 },
{ 2963, 0.8298, 56.6224 },
{ 2942, 0.4239, 299.1264 },
{ 2940, 2.1464, 137.0330 },
{ 2938, 3.6766, 140.0020 },
{ 2865, 0.3100, 12.5302 },
{ 2538, 4.8546, 131.4039 },
{ 2364, 0.4425, 554.0700 },
{ 2183, 2.9404, 305.3462 }
},
{
{ 1479896, 3.6720571, 74.7815986 },
{ 71212, 6.22601, 63.73590 },
{ 68627, 6.13411, 149.56320 },
{ 24060, 3.14159, 0 },
{ 21468, 2.60177, 76.26607 },
{ 20857, 5.24625, 11.04570 },
{ 11405, 0.01848, 70.84945 },
{ 7497, 0.4236, 73.2971 },
{ 4244, 1.4169, 85.8273 },
{ 3927, 3.1551, 71.8127 },
{ 3578, 2.3116, 224.3448 },
{ 3506, 2.5835, 138.5175 },
{ 3229, 5.2550, 3.9322 },
{ 3060, 0.1532, 1.4845 },
{ 2564, 0.9808, 148.0787 },
{ 2429, 3.9944, 52.6902 },
{ 1645, 2.6535, 127.4718 },
{ 1584, 1.4305, 78.7138 },
{ 1508, 5.0600, 151.0477 },
{ 1490, 2.6756, 56.6224 },
{ 1413, 4.5746, 202.2534 },
{ 1403, 1.3699, 77.7505 },
{ 1228, 1.0470, 62.2514 },
{ 1033, 0.2646, 131.4039 },
{ 992, 2.172, 65.220 },
{ 862, 5.055, 351.817 },
{ 744, 3.076, 35.164 },
{ 687, 2.499, 77.963 },
{ 647, 4.473, 70.328 },
{ 624, 0.863, 9.561 },
{ 604, 0.907, 984.600 },
{ 575, 3.231, 447.796 },
{ 562, 2.718, 462.023 },
{ 530, 5.917, 213.299 },
{ 528, 5.151, 2.969 }
},
{
{ 22440, 0.69953, 74.78160 },
{ 4727, 1.6990, 63.7359 },
{ 1682, 4.6483, 70.8494 },
{ 1650, 3.0966, 11.0457 },
{ 1434, 3.5212, 149.5632 },
{ 770, 0, 0 },
{ 500, 6.172, 76.266 },
{ 461, 0.767, 3.932 },
{ 390, 4.496, 56.622 },
{ 390, 5.527, 85.827 },
{ 292, 0.204, 52.690 },
{ 287, 3.534, 73.297 },
{ 273, 3.847, 138.517 },
{ 220, 1.964, 131.404 },
{ 216, 0.848, 77.963 },
{ 205, 3.248, 78.714 },
{ 149, 4.898, 127.472 },
{ 129, 2.081, 3.181 }
},
{
{ 1164, 4.7345, 74.7816 },
{ 212, 3.343, 63.736 },
{ 196, 2.980, 70.849 },
{ 105, 0.958, 11.046 },
{ 73, 1.00, 149.56 },
{ 72, 0.03, 56.62 },
{ 55, 2.59, 3.93 },
{ 36, 5.65, 77.96 },
{ 34, 3.82, 76.27 },
{ 32, 3.60, 131.40 }
},
{
{ 53, 3.01, 74.78 },
{ 10, 1.91, 56.62 }
}
};
/**
* Tables of Vsop87 terms for Uranus.
*/
static Vsop87 URANUS = new Vsop87(URANUS_L, URANUS_B, URANUS_R);
// ******************************************************************** //
// Neptune.
// ******************************************************************** //
// Heliocentric ecliptical longitude.
private static final double[][][] NEPTUNE_L = {
{
{ 531188633, 0, 0 },
{ 1798476, 2.9010127, 38.1330356 },
{ 1019728, 0.4858092, 1.4844727 },
{ 124532, 4.830081, 36.648563 },
{ 42064, 5.41055, 2.96895 },
{ 37715, 6.09222, 35.16409 },
{ 33785, 1.24489, 76.26607 },
{ 16483, 0.00008, 491.55793 },
{ 9199, 4.9375, 39.6175 },
{ 8994, 0.2746, 175.1661 },
{ 4216, 1.9871, 73.2971 },
{ 3365, 1.0359, 33.6796 },
{ 2285, 4.2061, 4.4534 },
{ 1434, 2.7834, 74.7816 },
{ 900, 2.076, 109.946 },
{ 745, 3.190, 71.813 },
{ 506, 5.748, 114.399 },
{ 400, 0.350, 1021.249 },
{ 345, 3.462, 41.102 },
{ 340, 3.304, 77.751 },
{ 323, 2.248, 32.195 },
{ 306, 0.497, 0.521 },
{ 287, 4.505, 0.048 },
{ 282, 2.246, 146.594 },
{ 267, 4.889, 0.963 },
{ 252, 5.782, 388.465 },
{ 245, 1.247, 9.561 },
{ 233, 2.505, 137.033 },
{ 227, 1.797, 453.425 },
{ 170, 3.324, 108.461 },
{ 151, 2.192, 33.940 },
{ 150, 2.997, 5.938 },
{ 148, 0.859, 111.430 },
{ 119, 3.677, 2.448 },
{ 109, 2.416, 183.243 },
{ 103, 0.041, 0.261 },
{ 103, 4.404, 70.328 },
{ 102, 5.705, 0.112 }
},
{
{ 3837687717.0, 0, 0 },
{ 16604, 4.86319, 1.48447 },
{ 15807, 2.27923, 38.13304 },
{ 3335, 3.6820, 76.2661 },
{ 1306, 3.6732, 2.9689 },
{ 605, 1.505, 35.164 },
{ 179, 3.453, 39.618 },
{ 107, 2.451, 4.453 },
{ 106, 2.755, 33.680 },
{ 73, 5.49, 36.65 },
{ 57, 1.86, 114.40 },
{ 57, 5.22, 0.52 },
{ 35, 4.52, 74.78 },
{ 32, 5.90, 77.75 },
{ 30, 3.67, 388.47 },
{ 29, 5.17, 9.56 },
{ 29, 5.17, 2.45 },
{ 26, 5.25, 168.05 }
},
{
{ 53893, 0, 0 },
{ 296, 1.855, 1.484 },
{ 281, 1.191, 38.133 },
{ 270, 5.721, 76.266 },
{ 23, 1.21, 2.97 },
{ 9, 4.43, 35.16 },
{ 7, 0.54, 2.45 }
},
{
{ 31, 0, 0 },
{ 15, 1.35, 76.27 },
{ 12, 6.04, 1.48 },
{ 12, 6.11, 38.13 }
},
{
{ 114, 3.142, 0 }
}
};
// Heliocentric latitude.
private static final double[][][] NEPTUNE_B = {
{
{ 3088623, 1.4410437, 38.1330356 },
{ 27789, 5.91272, 76.26607 },
{ 27624, 0, 0 },
{ 15448, 3.50877, 39.61751 },
{ 15355, 2.52124, 36.64856 },
{ 2000, 1.5100, 74.7816 },
{ 1968, 4.3778, 1.4845 },
{ 1015, 3.2156, 35.1641 },
{ 606, 2.802, 73.297 },
{ 595, 2.129, 41.102 },
{ 589, 3.187, 2.969 },
{ 402, 4.169, 114.399 },
{ 280, 1.682, 77.751 },
{ 262, 3.767, 213.299 },
{ 254, 3.271, 453.425 },
{ 206, 4.257, 529.691 },
{ 140, 3.530, 137.033 }
},
{
{ 227279, 3.807931, 38.133036 },
{ 1803, 1.9758, 76.2661 },
{ 1433, 3.1416, 0 },
{ 1386, 4.8256, 36.6486 },
{ 1073, 6.0805, 39.6175 },
{ 148, 3.858, 74.782 },
{ 136, 0.478, 1.484 },
{ 70, 6.19, 35.16 },
{ 52, 5.05, 73.30 },
{ 43, 0.31, 114.40 },
{ 37, 4.89, 41.10 },
{ 37, 5.76, 2.97 },
{ 26, 5.22, 213.30 }
},
{
{ 9691, 5.5712, 38.1330 },
{ 79, 3.63, 76.27 },
{ 72, 0.45, 36.65 },
{ 59, 3.14, 0 },
{ 30, 1.61, 39.62 },
{ 6, 5.61, 74.78 }
},
{
{ 273, 1.017, 38.133 },
{ 2, 0, 0 },
{ 2, 2.37, 36.65 },
{ 2, 5.33, 76.27 }
},
{
{ 6, 2.67, 38.13 }
}
};
// Heliocentric radius vector.
private static final double[][][] NEPTUNE_R = {
{
{ 3007013206.0, 0, 0 },
{ 27062259, 1.32999459, 38.13303564 },
{ 1691764, 3.2518614, 36.6485629 },
{ 807831, 5.185928, 1.484473 },
{ 537761, 4.521139, 35.164090 },
{ 495726, 1.571057, 491.557929 },
{ 274572, 1.845523, 175.166060 },
{ 135134, 3.372206, 39.617508 },
{ 121802, 5.797544, 76.266071 },
{ 100895, 0.377027, 73.297126 },
{ 69792, 3.79617, 2.96895 },
{ 46688, 5.74938, 33.67962 },
{ 24594, 0.50802, 109.94569 },
{ 16939, 1.59422, 71.81265 },
{ 14230, 1.07786, 74.78160 },
{ 12012, 1.92062, 1021.24889 },
{ 8395, 0.6782, 146.5943 },
{ 7572, 1.0715, 388.4652 },
{ 5721, 2.5906, 4.4534 },
{ 4840, 1.9069, 41.1020 },
{ 4483, 2.9057, 529.6910 },
{ 4421, 1.7499, 108.4612 },
{ 4354, 0.6799, 32.1951 },
{ 4270, 3.4134, 453.4249 },
{ 3381, 0.8481, 183.2428 },
{ 2881, 1.9860, 137.0330 },
{ 2879, 3.6742, 350.3321 },
{ 2636, 3.0976, 213.2991 },
{ 2530, 5.7984, 490.0735 },
{ 2523, 0.4863, 493.0424 },
{ 2306, 2.8096, 70.3282 },
{ 2087, 0.6186, 33.9402 }
},
{
{ 236339, 0.704980, 38.133036 },
{ 13220, 3.32015, 1.48447 },
{ 8622, 6.2163, 35.1641 },
{ 2702, 1.8814, 39.6175 },
{ 2155, 2.0943, 2.9689 },
{ 2153, 5.1687, 76.2661 },
{ 1603, 0, 0 },
{ 1464, 1.1842, 33.6796 },
{ 1136, 3.9189, 36.6486 },
{ 898, 5.241, 388.465 },
{ 790, 0.533, 168.053 },
{ 760, 0.021, 182.280 },
{ 607, 1.077, 1021.249 },
{ 572, 3.401, 484.444 },
{ 561, 2.887, 498.671 }
},
{
{ 4247, 5.8991, 38.1330 },
{ 218, 0.346, 1.484 },
{ 163, 2.239, 168.053 },
{ 156, 4.594, 182.280 },
{ 127, 2.848, 35.164 }
},
{
{ 166, 4.552, 38.133 }
}
};
/**
* Tables of Vsop87 terms for Neptune.
*/
static Vsop87 NEPTUNE = new Vsop87(NEPTUNE_L, NEPTUNE_B, NEPTUNE_R);
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Construct the table of terms for one planet.
*
* <p>The constructor is private. The only way to get instances is
* with the static members created for each planet.
*/
private Vsop87(double[][][] L, double[][][] B, double[][][] R) {
this.L = L;
this.B = B;
this.R = R;
}
// ******************************************************************** //
// Computation Methods.
// ******************************************************************** //
/**
* Calculate the value of L for this body for the given
* time.
*
* @param Tm The time, in Julian millennia elapsed since
* J2000 in dynamical time.
* @return The calculated value of L in radians.
*/
double calculateL(double Tm) {
return calculateSeries(L, Tm);
}
/**
* Calculate the value of B for this body for the given
* time.
*
* @param Tm The time, in Julian millennia elapsed since
* J2000 in dynamical time.
* @return The calculated value of B in radians.
*/
double calculateB(double Tm) {
return calculateSeries(B, Tm);
}
/**
* Calculate the value of R for this body for the given
* time.
*
* @param Tm The time, in Julian millennia elapsed since
* J2000 in dynamical time.
* @return The calculated value of R in AU.
*/
double calculateR(double Tm) {
return calculateSeries(R, Tm);
}
// ******************************************************************** //
// Utility Methods.
// ******************************************************************** //
/**
* Calculate the value of an orbital term for a given time.
*
* @param series The table of periodic terms to calculate over;
* for example, EarthB.
* @param T The time, in Julian millennia elapsed since
* J2000 in dynamical time.
* @return The calculated value.
*/
static final double calculateSeries(double[][][] series, double T) {
int order = series.length;
double Tn = 1;
double value = 0;
for (int o = 0; o < order; ++o) {
double sum = 0;
for (double[] term : series[o])
sum += term[0] * cos(term[1] + term[2] * T);
value += sum * Tn;
Tn *= T;
}
// The first column of terms in the table is in units of 1E-8.
return value / 100000000;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The tables for L, B and R for this body.
private double[][][] L;
private double[][][] B;
private double[][][] R;
}
| 97,773 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Moon.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/Moon.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
import static java.lang.Math.acos;
import static java.lang.Math.atan;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.toRadians;
/**
* This class represents the Moon, and provides all known information
* about it.
*
* This subclass of {@link Body} basically provides custom calculation
* routines relevant to the Moon.
*
* Note that we depart from the usual Java naming conventions here. To
* simplify reference to source materials, variables are named according
* to the original source text, Greek letters included. So, be careful
* when looking at names; "Χ" may be the Greek Chi, rather than Roman.
*/
public class Moon
extends Body
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a Moon. Note that this constructor is non-public; the
* only way to get a Moon is by calling Observation.getSun().
*
* @param o The Observation this Moon belongs to. This contains
* all global configuration, like the current time.
*/
Moon(Observation o) {
super(o, Name.MOON);
observation = o;
}
// ******************************************************************** //
// Data Calculation.
// ******************************************************************** //
/**
* Calculate the heliocentric co-ordinates of the body for the currently
* configured time. Result is stored in the cache as HE_LATITUDE,
* HE_LONGITUDE and HE_RADIUS.
*
* @throws AstroError Invalid request.
*/
@Override
void calcHePosition() throws AstroError {
throw new AstroError("Cannot calculate heliocentric position of the Moon");
}
/**
* Calculate the distance in AU, and the ecliptic longitude and
* latitude of the planet for the currently configured time.
* Results are stored in the cache as EARTH_DISTANCE, EC_LONGITUDE
* and EC_LATITUDE.
*
* <p>From AA chapter 47.
*/
@Override
void calcEcPosition() {
// Calculate the Julian centuries elapsed since J2000 in
// dynamical time. We also need the time in millenia.
double T = (observation.getTd() - J2000) / 36525;
double T2 = T * T;
double T3 = T2 * T;
double T4 = T3 * T;
// Moon's mean longitude, including the effect of light-time:
double L1 = 218.3164477 + 481267.88123421 * T -
0.0015786 * T2 + T3 / 538841 - T4 / 65194000;
L1 = mod360(L1);
// Mean elongation of the Moon:
double D = 297.8501921 + 445267.1114034 * T -
0.0018819 * T2 + T3 / 545868 - T4 / 113065000;
D = mod360(D);
// Sun's mean anomaly:
double M = 357.5291092 + 35999.0502909 * T -
0.0001536 * T2 + T3 / 24490000;
M = mod360(M);
// Moon's mean anomaly:
double M1 = 134.9633964 + 477198.8675055 * T +
0.0087414 * T2 + T3 / 69699 - T4 / 14712000;
M1 = mod360(M1);
// Moon's argument of latitude:
double F = 93.2720950 + 483202.0175233 * T -
0.0036539 * T2 - T3 / 3526000 + T4 / 863310000;
F = mod360(F);
// Auxiliary terms:
double A1 = 119.75 + 131.849 * T;
double A2 = 53.09 + 479264.290 * T;
double A3 = 313.45 + 481266.484 * T;
double E = 1 - 0.002516 * T - 0.0000074 * T2;
double E2 = E * E;
// Calculate the sums of the periodic terms for longitude and distance.
double Σl = 0;
double Σr = 0;
for (int[] term : longDistTerms) {
double a = term[0] * D + term[1] * M +
term[2] * M1 + term[3] * F;
if (term[1] == 2 || term[1] == -2) {
Σl += E2 * term[4] * sin(toRadians(a));
Σr += E2 * term[5] * cos(toRadians(a));
} else if (term[1] == 1 || term[1] == -1) {
Σl += E * term[4] * sin(toRadians(a));
Σr += E * term[5] * cos(toRadians(a));
} else {
Σl += term[4] * sin(toRadians(a));
Σr += term[5] * cos(toRadians(a));
}
}
// Do the same for latitude.
double Σb = 0;
for (int[] term : latitudeTerms) {
double a = term[0] * D + term[1] * M +
term[2] * M1 + term[3] * F;
if (term[1] == 2 || term[1] == -2)
Σb += E2 * term[4] * sin(toRadians(a));
else if (term[1] == 1 || term[1] == -1)
Σb += E * term[4] * sin(toRadians(a));
else
Σb += term[4] * sin(toRadians(a));
}
// Now the additive terms for Jupiter, Venus, and the Earth's
// flattening.
Σl += 3958 * sin(toRadians(A1)) +
1962 * sin(toRadians(L1 - F)) +
318 * sin(toRadians(A2));
Σb += -2235 * sin(toRadians(L1)) +
382 * sin(toRadians(A3)) +
175 * sin(toRadians(A1 - F)) +
175 * sin(toRadians(A1 + F)) +
127 * sin(toRadians(L1 - M1)) -
115 * sin(toRadians(L1 + M1));
// And finally, calculate the co-ordinates.
double Δ = (385000.56 + Σr / 1000.0) / AU;
double λ = modTwoPi(toRadians(L1 + Σl / 1000000.0));
double β = toRadians(Σb / 1000000.0);
put(Field.EARTH_DISTANCE, Δ);
put(Field.EC_LONGITUDE, λ);
put(Field.EC_LATITUDE, β);
}
/**
* Calculate the apparent diameter of this body from the Earth for the
* currently configured time. Results are stored in the cache as
* APPARENT_DIAMETER.
*
* <p>From AA chapter 55.
*/
@Override
void calcApparentSize() throws AstroError {
double Δ = get(Field.EARTH_DISTANCE);
double h = get(Field.LOCAL_ALTITUDE);
double Δkm = Δ * AU;
// Calculate the geocentric semidiameter in arcseconds.
double s = 358473400.0 / Δkm;
// Calculate the equatorial horizontal parallax, and
// use this to get the topocentric semidiameter.
double sinπ = 6378.14 / Δkm;
double s1 = s * (1 + sin(h) * sinπ);
// Convert to radians.
s1 = toRadians(s1 / 3600.0);
put(Field.APPARENT_DIAMETER, s1 * 2);
}
/**
* Calculate the phase of this body as seen from the Earth for the
* currently configured time. Results are stored in the cache as
* PHASE_ANGLE and PHASE.
*
* <p>From AA chapter 48.
*
* @throws AstroError Invalid request.
*/
@Override
void calcPhase() throws AstroError {
// We need data for the Sun too.
Sun sun = observation.getSun();
double λ = get(Field.EC_LONGITUDE);
double β = get(Field.EC_LATITUDE);
double Δ = get(Field.EARTH_DISTANCE);
double λo = sun.get(Field.EC_LONGITUDE);
double R = sun.get(Field.EARTH_DISTANCE);
// Calculate the elongation of the Moon.
double cosψ = cos(β) * cos(λ - λo);
double ψ = modPi(acos(cosψ));
// Calculate the phase angle of the moon.
double tani = (R * sin(ψ)) / (Δ - R * cosψ);
double i = modPi(atan(tani));
// And now the phase.
double k = (1 + cos(i)) / 2;
put(Field.PHASE_ANGLE, i);
put(Field.PHASE, k);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "onwatch";
// Monster table of coefficients for the calculation of the longitude
// and distance.
private static final int[][] longDistTerms = {
{ 0, 0, 1, 0, 6288774, -20905355 },
{ 2, 0, -1, 0, 1274027, -3699111 },
{ 2, 0, 0, 0, 658314, -2955968 },
{ 0, 0, 2, 0, 213618, -569925 },
{ 0, 1, 0, 0, -185116, 48888 },
{ 0, 0, 0, 2, -114332, -3149 },
{ 2, 0, -2, 0, 58793, 246158 },
{ 2, -1, -1, 0, 57066, -152138 },
{ 2, 0, 1, 0, 53322, -170733 },
{ 2, -1, 0, 0, 45758, -204586 },
{ 0, 1, -1, 0, -40923, -129620 },
{ 1, 0, 0, 0, -34720, 108743 },
{ 0, 1, 1, 0, -30383, 104755 },
{ 2, 0, 0, -2, 15327, 10321 },
{ 0, 0, 1, 2, -12528, 0 },
{ 0, 0, 1, -2, 10980, 79661 },
{ 4, 0, -1, 0, 10675, -34782 },
{ 0, 0, 3, 0, 10034, -23210 },
{ 4, 0, -2, 0, 8548, -21636 },
{ 2, 1, -1, 0, -7888, 24208 },
{ 2, 1, 0, 0, -6766, 30824 },
{ 1, 0, -1, 0, -5163, -8379 },
{ 1, 1, 0, 0, 4987, -16675 },
{ 2, -1, 1, 0, 4036, -12831 },
{ 2, 0, 2, 0, 3994, -10445 },
{ 4, 0, 0, 0, 3861, -11650 },
{ 2, 0, -3, 0, 3665, 14403 },
{ 0, 1, -2, 0, -2689, -7003 },
{ 2, 0, -1, 2, -2602, 0 },
{ 2, -1, -2, 0, 2390, 10056 },
{ 1, 0, 1, 0, -2348, 6322 },
{ 2, -2, 0, 0, 2236, -9884 },
{ 0, 1, 2, 0, -2120, 5751 },
{ 0, 2, 0, 0, -2069, 0 },
{ 2, -2, -1, 0, 2048, -4950 },
{ 2, 0, 1, -2, -1773, 4130 },
{ 2, 0, 0, 2, -1595, 0 },
{ 4, -1, -1, 0, 1215, -3958 },
{ 0, 0, 2, 2, -1110, 0 },
{ 3, 0, -1, 0, -892, 3258 },
{ 2, 1, 1, 0, -810, 2616 },
{ 4, -1, -2, 0, 759, -1897 },
{ 0, 2, -1, 0, -713, -2117 },
{ 2, 2, -1, 0, -700, 2354 },
{ 2, 1, -2, 0, 691, 0 },
{ 2, -1, 0, -2, 596, 0 },
{ 4, 0, 1, 0, 549, -1423 },
{ 0, 0, 4, 0, 537, -1117 },
{ 4, -1, 0, 0, 520, -1571 },
{ 1, 0, -2, 0, -487, -1739 },
{ 2, 1, 0, -2, -399, 0 },
{ 0, 0, 2, -2, -381, -4421 },
{ 1, 1, 1, 0, 351, 0 },
{ 3, 0, -2, 0, -340, 0 },
{ 4, 0, -3, 0, 330, 0 } ,
{ 2, -1, 2, 0, 327, 0 },
{ 0, 2, 1, 0, -323, 1165 },
{ 1, 1, -1, 0, 299, 0 },
{ 2, 0, 3, 0, 294, 0 },
{ 2, 0, -1, -2, 0, 8752 },
};
// Monster table of coefficients for the calculation of the latitude.
private static final int[][] latitudeTerms = {
{ 0, 0, 0, 1, 5128122 },
{ 0, 0, 1, 1, 280602 },
{ 0, 0, 1, -1, 277693 },
{ 2, 0, 0, -1, 173237 },
{ 2, 0, -1, 1, 55413 },
{ 2, 0, -1, -1, 46271 },
{ 2, 0, 0, 1, 32573 },
{ 0, 0, 2, 1, 17198 },
{ 2, 0, 1, -1, 9266 },
{ 0, 0, 2, -1, 8822 },
{ 2, -1, 0, -1, 8216 },
{ 2, 0, -2, -1, 4324 },
{ 2, 0, 1, 1, 4200 },
{ 2, 1, 0, -1, -3359 },
{ 2, -1, -1, 1, 2463 },
{ 2, -1, 0, 1, 2211 },
{ 2, -1, -1, -1, 2065 },
{ 0, 1, -1, -1, -1870 },
{ 4, 0, -1, -1, 1828 },
{ 0, 1, 0, 1, -1794 },
{ 0, 0, 0, 3, -1749 },
{ 0, 1, -1, 1, -1565 },
{ 1, 0, 0, 1, -1491 },
{ 0, 1, 1, 1, -1475 },
{ 0, 1, 1, -1, -1410 },
{ 0, 1, 0, -1, -1344 },
{ 1, 0, 0, -1, -1335 },
{ 0, 0, 3, 1, 1107 },
{ 4, 0, 0, -1, 1021 },
{ 4, 0, -1, 1, 833 },
{ 0, 0, 1, -3, 777 },
{ 4, 0, -2, 1, 671 },
{ 2, 0, 0, -3, 607 },
{ 2, 0, 2, -1, 596 },
{ 2, -1, 1, -1, 491 },
{ 2, 0, -2, 1, -451 },
{ 0, 0, 3, -1, 439 },
{ 2, 0, 2, 1, 422 },
{ 2, 0, -3, -1, 421 },
{ 2, 1, -1, 1, -366 },
{ 2, 1, 0, 1, -351 },
{ 4, 0, 0, 1, 331 },
{ 2, -1, 1, 1, 315 },
{ 2, -2, 0, -1, 302 },
{ 0, 0, 1, 3, -283 },
{ 2, 1, 1, -1, -229 },
{ 1, 1, 0, -1, 223 },
{ 1, 1, 0, 1, 223 },
{ 0, 1, -2, -1, -220 },
{ 2, 1, -1, -1, -220 },
{ 1, 0, 1, 1, -185 },
{ 2, -1, -2, -1, 181 },
{ 0, 1, 2, 1, -177 },
{ 4, 0, -2, -1, 176 },
{ 4, -1, -1, -1, 166 },
{ 1, 0, 1, -1, -164 },
{ 4, 0, 1, -1, 132 },
{ 1, 0, -1, -1, -119 },
{ 4, -1, 0, -1, 115 },
{ 2, -2, 0, 1, 107 },
};
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The observation this Moon belongs to.
private Observation observation;
}
| 13,621 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
CalcError.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/org/hermit/astro/CalcError.java |
/**
* astro: astronomical functions, utilities and data
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>References:
* <dl>
* <dt>PAC</dt>
* <dd>"Practical Astronomy with your Calculator", by Peter Duffett-Smith,
* ISBN-10: 0521356997.</dd>
* <dt>ESAA</dt>
* <dd>"Explanatory Supplement to the Astronomical Almanac", edited
* by Kenneth Seidelmann, ISBN-13: 978-1-891389-45-0.</dd>
* <dt>AA</dt>
* <dd>"Astronomical Algorithms", by Jean Meeus, ISBN-10: 0-943396-61-1.</dd>
* </dl>
* The primary reference for this version of the software is AA.
*
* <p>Note that the formulae have been converted to work in radians, to
* make it easier to work with java.lang.Math.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.astro;
/**
* This exception represents an error within the Astro package; i.e.
* something that shouldn't happen.
*/
public class CalcError
extends RuntimeException
{
/**
* Create an exception with no message.
*/
public CalcError() {
super();
}
/**
* Create an exception with a message.
*
* @param msg Error message.
*/
public CalcError(String msg) {
super(msg);
}
private static final long serialVersionUID = 7246431317624145407L;
}
| 1,638 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
MTRandom.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitLibrary/src/net/goui/util/MTRandom.java | /*
* MTRandom : A Java implementation of the MT19937 (Mersenne Twister)
* pseudo random number generator algorithm based upon the
* original C code by Makoto Matsumoto and Takuji Nishimura.
* Author : David Beaumont
* Email : mersenne-at-www.goui.net
*
* For the original C code, see:
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
*
* This version, Copyright (C) 2005, David Beaumont.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.goui.util;
import java.util.Random;
/**
* A Java implementation of the MT19937 (Mersenne Twister) pseudo
* random number generator algorithm based upon the original C code
* by Makoto Matsumoto and Takuji Nishimura (see
* <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html">
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html</a> for
* more information.
* <p>
* As a subclass of java.util.Random this class provides a single
* canonical method next() for generating bits in the pseudo random
* number sequence. Anyone using this class should invoke the public
* inherited methods (nextInt(), nextFloat etc.) to obtain values as
* normal. This class should provide a drop-in replacement for the
* standard implementation of java.util.Random with the additional
* advantage of having a far longer period and the ability to use a
* far larger seed value.
* <p>
* This is <b>not</b> a cryptographically strong source of randomness
* and should <b>not</b> be used for cryptographic systems or in any
* other situation where true random numbers are required.
* <p>
* <!-- Creative Commons License -->
* <a href="http://creativecommons.org/licenses/LGPL/2.1/"><img alt="CC-GNU LGPL" border="0" src="http://creativecommons.org/images/public/cc-LGPL-a.png" /></a><br />
* This software is licensed under the <a href="http://creativecommons.org/licenses/LGPL/2.1/">CC-GNU LGPL</a>.
* <!-- /Creative Commons License -->
*
* <!--
* <rdf:RDF xmlns="http://web.resource.org/cc/"
* xmlns:dc="http://purl.org/dc/elements/1.1/"
* xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
*
* <Work rdf:about="">
* <license rdf:resource="http://creativecommons.org/licenses/LGPL/2.1/" />
* <dc:type rdf:resource="http://purl.org/dc/dcmitype/Software" />
* </Work>
*
* <License rdf:about="http://creativecommons.org/licenses/LGPL/2.1/">
* <permits rdf:resource="http://web.resource.org/cc/Reproduction" />
* <permits rdf:resource="http://web.resource.org/cc/Distribution" />
* <requires rdf:resource="http://web.resource.org/cc/Notice" />
* <permits rdf:resource="http://web.resource.org/cc/DerivativeWorks" />
* <requires rdf:resource="http://web.resource.org/cc/ShareAlike" />
* <requires rdf:resource="http://web.resource.org/cc/SourceCode" />
* </License>
*
* </rdf:RDF>
* -->
*
* @version 1.0
* @author David Beaumont, Copyright 2005
*/
public class MTRandom extends Random {
/**
* Auto-generated serial version UID. Note that MTRandom does NOT
* support serialisation of its internal state and it may even be
* necessary to implement read/write methods to re-seed it properly.
* This is only here to make Eclipse shut up about it being missing.
*/
private static final long serialVersionUID = -515082678588212038L;
// Constants used in the original C implementation
private final static int UPPER_MASK = 0x80000000;
private final static int LOWER_MASK = 0x7fffffff;
private final static int N = 624;
private final static int M = 397;
private final static int MAGIC[] = { 0x0, 0x9908b0df };
private final static int MAGIC_FACTOR1 = 1812433253;
private final static int MAGIC_FACTOR2 = 1664525;
private final static int MAGIC_FACTOR3 = 1566083941;
private final static int MAGIC_MASK1 = 0x9d2c5680;
private final static int MAGIC_MASK2 = 0xefc60000;
private final static int MAGIC_SEED = 19650218;
private final static long DEFAULT_SEED = 5489L;
// Internal state
private transient int[] mt;
private transient int mti;
private transient boolean compat = false;
// Temporary buffer used during setSeed(long)
private transient int[] ibuf;
/**
* The default constructor for an instance of MTRandom. This invokes
* the no-argument constructor for java.util.Random which will result
* in the class being initialised with a seed value obtained by calling
* System.currentTimeMillis().
*/
public MTRandom() { }
/**
* This version of the constructor can be used to implement identical
* behaviour to the original C code version of this algorithm including
* exactly replicating the case where the seed value had not been set
* prior to calling genrand_int32.
* <p>
* If the compatibility flag is set to true, then the algorithm will be
* seeded with the same default value as was used in the original C
* code. Furthermore the setSeed() method, which must take a 64 bit
* long value, will be limited to using only the lower 32 bits of the
* seed to facilitate seamless migration of existing C code into Java
* where identical behaviour is required.
* <p>
* Whilst useful for ensuring backwards compatibility, it is advised
* that this feature not be used unless specifically required, due to
* the reduction in strength of the seed value.
*
* @param compatible Compatibility flag for replicating original
* behaviour.
*/
public MTRandom(boolean compatible) {
super(0L);
compat = compatible;
setSeed(compat?DEFAULT_SEED:System.currentTimeMillis());
}
/**
* This version of the constructor simply initialises the class with
* the given 64 bit seed value. For a better random number sequence
* this seed value should contain as much entropy as possible.
*
* @param seed The seed value with which to initialise this class.
*/
public MTRandom(long seed) {
super(seed);
}
/**
* This version of the constructor initialises the class with the
* given byte array. All the data will be used to initialise this
* instance.
*
* @param buf The non-empty byte array of seed information.
* @throws NullPointerException if the buffer is null.
* @throws IllegalArgumentException if the buffer has zero length.
*/
public MTRandom(byte[] buf) {
super(0L);
setSeed(buf);
}
/**
* This version of the constructor initialises the class with the
* given integer array. All the data will be used to initialise
* this instance.
*
* @param buf The non-empty integer array of seed information.
* @throws NullPointerException if the buffer is null.
* @throws IllegalArgumentException if the buffer has zero length.
*/
public MTRandom(int[] buf) {
super(0L);
setSeed(buf);
}
// Initializes mt[N] with a simple integer seed. This method is
// required as part of the Mersenne Twister algorithm but need
// not be made public.
private final void setSeed(int seed) {
// Annoying runtime check for initialisation of internal data
// caused by java.util.Random invoking setSeed() during init.
// This is unavoidable because no fields in our instance will
// have been initialised at this point, not even if the code
// were placed at the declaration of the member variable.
if (mt == null) mt = new int[N];
// ---- Begin Mersenne Twister Algorithm ----
mt[0] = seed;
for (mti = 1; mti < N; mti++) {
mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti);
}
// ---- End Mersenne Twister Algorithm ----
}
/**
* This method resets the state of this instance using the 64
* bits of seed data provided. Note that if the same seed data
* is passed to two different instances of MTRandom (both of
* which share the same compatibility state) then the sequence
* of numbers generated by both instances will be identical.
* <p>
* If this instance was initialised in 'compatibility' mode then
* this method will only use the lower 32 bits of any seed value
* passed in and will match the behaviour of the original C code
* exactly with respect to state initialisation.
*
* @param seed The 64 bit value used to initialise the random
* number generator state.
*/
@Override
public final synchronized void setSeed(long seed) {
if (compat) {
setSeed((int)seed);
} else {
// Annoying runtime check for initialisation of internal data
// caused by java.util.Random invoking setSeed() during init.
// This is unavoidable because no fields in our instance will
// have been initialised at this point, not even if the code
// were placed at the declaration of the member variable.
if (ibuf == null) ibuf = new int[2];
ibuf[0] = (int)seed;
ibuf[1] = (int)(seed >>> 32);
setSeed(ibuf);
}
}
/**
* This method resets the state of this instance using the byte
* array of seed data provided. Note that calling this method
* is equivalent to calling "setSeed(pack(buf))" and in particular
* will result in a new integer array being generated during the
* call. If you wish to retain this seed data to allow the pseudo
* random sequence to be restarted then it would be more efficient
* to use the "pack()" method to convert it into an integer array
* first and then use that to re-seed the instance. The behaviour
* of the class will be the same in both cases but it will be more
* efficient.
*
* @param buf The non-empty byte array of seed information.
* @throws NullPointerException if the buffer is null.
* @throws IllegalArgumentException if the buffer has zero length.
*/
public final void setSeed(byte[] buf) {
setSeed(pack(buf));
}
/**
* This method resets the state of this instance using the integer
* array of seed data provided. This is the canonical way of
* resetting the pseudo random number sequence.
*
* @param buf The non-empty integer array of seed information.
* @throws NullPointerException if the buffer is null.
* @throws IllegalArgumentException if the buffer has zero length.
*/
public final synchronized void setSeed(int[] buf) {
int length = buf.length;
if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty");
// ---- Begin Mersenne Twister Algorithm ----
int i = 1, j = 0, k = (N > length ? N : length);
setSeed(MAGIC_SEED);
for (; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j;
i++; j++;
if (i >= N) { mt[0] = mt[N-1]; i = 1; }
if (j >= length) j = 0;
}
for (k = N-1; k > 0; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR3)) - i;
i++;
if (i >= N) { mt[0] = mt[N-1]; i = 1; }
}
mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array
// ---- End Mersenne Twister Algorithm ----
}
/**
* This method forms the basis for generating a pseudo random number
* sequence from this class. If given a value of 32, this method
* behaves identically to the genrand_int32 function in the original
* C code and ensures that using the standard nextInt() function
* (inherited from Random) we are able to replicate behaviour exactly.
* <p>
* Note that where the number of bits requested is not equal to 32
* then bits will simply be masked out from the top of the returned
* integer value. That is to say that:
* <pre>
* mt.setSeed(12345);
* int foo = mt.nextInt(16) + (mt.nextInt(16) << 16);</pre>
* will not give the same result as
* <pre>
* mt.setSeed(12345);
* int foo = mt.nextInt(32);</pre>
*
* @param bits The number of significant bits desired in the output.
* @return The next value in the pseudo random sequence with the
* specified number of bits in the lower part of the integer.
*/
@Override
protected final synchronized int next(int bits) {
// ---- Begin Mersenne Twister Algorithm ----
int y, kk;
if (mti >= N) { // generate N words at one time
// In the original C implementation, mti is checked here
// to determine if initialisation has occurred; if not
// it initialises this instance with DEFAULT_SEED (5489).
// This is no longer necessary as initialisation of the
// Java instance must result in initialisation occurring
// Use the constructor MTRandom(true) to enable backwards
// compatible behaviour.
for (kk = 0; kk < N-M; kk++) {
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >>> 1) ^ MAGIC[y & 0x1];
}
for (;kk < N-1; kk++) {
y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ MAGIC[y & 0x1];
}
y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >>> 1) ^ MAGIC[y & 0x1];
mti = 0;
}
y = mt[mti++];
// Tempering
y ^= (y >>> 11);
y ^= (y << 7) & MAGIC_MASK1;
y ^= (y << 15) & MAGIC_MASK2;
y ^= (y >>> 18);
// ---- End Mersenne Twister Algorithm ----
return (y >>> (32-bits));
}
// This is a fairly obscure little code section to pack a
// byte[] into an int[] in little endian ordering.
/**
* This simply utility method can be used in cases where a byte
* array of seed data is to be used to repeatedly re-seed the
* random number sequence. By packing the byte array into an
* integer array first, using this method, and then invoking
* setSeed() with that; it removes the need to re-pack the byte
* array each time setSeed() is called.
* <p>
* If the length of the byte array is not a multiple of 4 then
* it is implicitly padded with zeros as necessary. For example:
* <pre> byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }</pre>
* becomes
* <pre> int[] { 0x04030201, 0x00000605 }</pre>
* <p>
* Note that this method will not complain if the given byte array
* is empty and will produce an empty integer array, but the
* setSeed() method will throw an exception if the empty integer
* array is passed to it.
*
* @param buf The non-null byte array to be packed.
* @return A non-null integer array of the packed bytes.
* @throws NullPointerException if the given byte array is null.
*/
public static int[] pack(byte[] buf) {
int k, blen = buf.length, ilen = ((buf.length+3) >>> 2);
int[] ibuf = new int[ilen];
for (int n = 0; n < ilen; n++) {
int m = (n+1) << 2;
if (m > blen) m = blen;
for (k = buf[--m]&0xff; (m & 0x3) != 0; k = (k << 8) | buf[--m]&0xff);
ibuf[n] = k;
}
return ibuf;
}
} | 15,093 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
CachedFile.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/net/CachedFile.java |
/**
* org.hermit.android.net: Android utilities for accessing network data.
*
* These classes provide some basic utilities for accessing and cacheing
* various forms of data from network servers.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.net;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Observable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* This class manages a set of web-based files and caches them locally.
* Data about the files is held in a local database.
*/
public class CachedFile
extends Observable
implements WebFetcher.Listener
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Class describing an entry in the cache; i.e. a cached file.
*/
public static final class Entry {
/**
* Create an entry.
*
* @param url The URL of the file that was loaded.
* @param name The name of the file.
*/
private Entry(URL url, String name) {
this.url = url;
this.name = name;
}
/**
* The URL of the file that was loaded.
*/
public final URL url;
/**
* The local name of the file.
*/
public String name;
/**
* The path of the local copy of the file.
*/
public File path = null;
/**
* The last modified time of the file, as reported by the server,
* in ms UTC.
*/
public long date = 0;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a cache of web-based files. This is private, as only one
* instance exists.
*
* @param name The name of this source, and its database table.
* @param urls The list of URLs to cache.
*/
public CachedFile(String name, URL[] urls) {
sourceName = name;
targetFiles = new HashMap<URL, Entry>();
// For each URL, make up an initial entry for it, containing
// the URL and a suitable local filename.
for (URL url : urls) {
String fn = url.getPath().substring(1);
fn = fn.replace('/', '-');
Entry file = new Entry(url, fn);
Log.i(TAG, "Caching file: " + url.getPath() + " -> " + fn);
targetFiles.put(url, file);
}
}
// ******************************************************************** //
// Database Management.
// ******************************************************************** //
/**
* Create our table in the database.
*
* @param db The database.
*/
public void createTable(SQLiteDatabase db) {
// Create our data table.
String create = "CREATE TABLE " + sourceName + " (" +
"url TEXT PRIMARY KEY UNIQUE ON CONFLICT REPLACE";
create += ", name TEXT";
create += ", path TEXT";
create += ", date INTEGER";
create += ");";
db.execSQL(create);
}
/**
* Upgrade or table in the database to a new version.
*
* @param db The database.
* @param oldV Version we're upgrading from.
* @param newV Version we're upgrading to.
*/
public void upgradeTable(SQLiteDatabase db, int oldV, int newV) {
// We can simply dump all the old data, since the DB is just
// a cache of web data.
db.execSQL("DROP TABLE IF EXISTS " + sourceName);
createTable(db);
}
/**
* Set the database we use for storing our data.
*
* @param db The database. Will be null if the database is
* being closed.
*/
public void setDatabase(SQLiteDatabase db) {
synchronized (this) {
database = db;
// If we have a database, make sure all the URLs are in it.
if (database != null)
for (Entry file : targetFiles.values())
syncDatabase(file);
}
}
/**
* Sync the database info for the given file with the given Entry.
* If the target is missing from the database, add it with path=null
* indicating the file is not loaded. If we have a file that is already
* loaded, notify the observers that it's here.
*
* @param file An Entry which contains our current guess
* at the file's state.
*/
private void syncDatabase(Entry file) {
// Get the database info on the file.
Cursor c = database.query(sourceName, null,
"url=\'" + file.url.toString() + "\'",
null, null, null, null, null);
// If there's no record for the file, add one. Don't set the path.
// If there is a record, load it into file.
if (!c.moveToFirst()) {
Log.i(TAG, "New file: " + file.url.toString());
ContentValues vals = new ContentValues();
vals.put("url", file.url.toString());
vals.put("name", file.name);
vals.put("date", 0);
database.insert(sourceName, "path", vals);
} else {
// If the database has a different local name, use that.
int nameIndex = c.getColumnIndex("name");
String n = c.getString(nameIndex);
if (n != null)
file.name = n;
// Get the path where it's stored, if any.
int pathIndex = c.getColumnIndex("path");
String p = c.getString(pathIndex);
// If it's loaded, fill in our copy of the data and notify
// all clients that we have the file.
if (p != null) {
Log.i(TAG, "Existing file loaded: " + file.url.toString());
file.path = new File(p);
// Get the date loaded, if any.
int dateIndex = c.getColumnIndex("date");
Long d = c.getLong(dateIndex);
file.date = d != null ? d : 0;
// Notify the clients. Note that if one client calls
// invalidate(), the others will see an entry with no data.
setChanged();
notifyObservers(file.url);
} else {
Log.i(TAG, "Existing file not here: " + file.url.toString());
file.path = null;
file.date = 0;
}
}
c.close();
}
// ******************************************************************** //
// Data Access.
// ******************************************************************** //
/**
* Query for a given file in the cache.
*
* @param url The URL of the file we want.
* @return null if the URL is not being cached at all.
* Otherwise, an Entry containing info on the file;
* path will be non-null if the file has been loaded,
* and date will be its reported last mod time.
*/
public synchronized Entry getFile(URL url) {
return targetFiles.get(url);
}
/**
* Invalidate the given file in the cache (perhaps it was corrupted).
*
* @param url The URL of the file to invalidate.
*/
public synchronized void invalidate(URL url) {
// Get our local record.
Entry entry = targetFiles.get(url);
if (entry == null)
return;
// Clear it out.
entry.path = null;
entry.date = 0;
// Write the change to the database.
if (database != null) {
ContentValues vals = new ContentValues();
vals.put("url", url.toString());
vals.put("name", entry.name);
database.replace(sourceName, "path", vals);
}
}
// ******************************************************************** //
// Update.
// ******************************************************************** //
/**
* Check to see whether we need to update our cached copies of the
* files. If so, kick off a web fetch.
*
* The observers will be notified for each file that we load.
*
* @param context The application context. Used for
* determining where the local files are kept.
* @param now The current time in millis.
*/
public synchronized void update(Context context, long now) {
if (database == null)
return;
// If it's too soon since the last check, don't even try.
if (now - lastDataCheck < MIN_CHECK_INTERVAL)
return;
// Check all the files we're caching, and see if any of them
// is absent or old enough to need refreshing. If so, kick
// off a load.
boolean checking = false;
for (Entry entry : targetFiles.values()) {
if (entry.path == null || now - entry.date > REFRESH_INTERVAL) {
FileFetcher ff =
new FileFetcher(context, entry.url, entry.name,
this, FETCH_TIMEOUT, entry.date);
WebFetcher.queue(ff);
checking = true;
}
}
if (checking)
lastDataCheck = now;
}
// ******************************************************************** //
// Fetched Data Handling.
// ******************************************************************** //
/**
* This method is invoked when a data item is retrieved from
* the URL we were invoked on.
*
* @param url The URL of the source being loaded.
* @param obj The object that was loaded; the type
* depends on the fetcher class used.
* @param date The last modified time of the source file,
* as reported by the server, in ms UTC.
*/
@Override
public void onWebData(URL url, Object obj, long date) {
if (database == null)
return;
if (!(obj instanceof File)) {
onWebError("Loaded object for " + url + " not a File!");
return;
}
File path = (File) obj;
Log.i(TAG, "Loaded " + url.toString());
// Add it to the database with its new date.
synchronized (this) {
ContentValues vals = new ContentValues();
vals.put("url", url.toString());
vals.put("name", path.getName());
vals.put("path", path.getPath());
vals.put("date", date);
database.replace(sourceName, "path", vals);
// Update the Entry as well.
Entry file = targetFiles.get(url);
file.path = path;
file.date = date;
}
// Inform the clients that we have data. Note that if one client
// calls invalidate(), the others will see an entry with no data.
setChanged();
notifyObservers(url);
}
/**
* This method is invoked when the given URL has been fully fetched.
*/
@Override
public void onWebDone() {
}
/**
* Handle an error while fetching web data.
*
* @param msg The error message.
*/
@Override
public synchronized void onWebError(String msg) {
Log.e(TAG, msg);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "CachedFile";
// Minimum interval in ms between checks for file updates.
private static final long MIN_CHECK_INTERVAL = 60 * 60 * 1000;
// The age of a file in ms at which we will look for a newer version.
private static final long REFRESH_INTERVAL = 240 * 60 * 1000;
// The timeout in ms for fetching a file.
private static final long FETCH_TIMEOUT = 15 * 60 * 1000;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The name of this source, and its database table.
private final String sourceName;
// The files to cache.
private HashMap<URL, Entry> targetFiles;
// The database we use for storing our data.
private SQLiteDatabase database = null;
// Time in ms UTC at which we last checked for data. 0 means
// never.
private long lastDataCheck = 0;
}
| 12,192 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TableFetcher.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/net/TableFetcher.java |
/**
* org.hermit.android.net: Android utilities for accessing network data.
*
* These classes provide some basic utilities for accessing and cacheing
* various forms of data from network servers.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.TimeZone;
import android.content.ContentValues;
/**
* Concrete instance of WebFetcher which fetches tabular data from the web.
* Lines in the file are parsed into fields and passed to the caller
* in a ContentValues object.
*/
public class TableFetcher
extends WebFetcher
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Fetch tabular data from a file on the web.
*
* @param url The URL to fetch data from.
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param ldate If true, parse dates in long format,
* else false.
* @param fields Names to give to the fields in the results.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* Also, any records with timestamps older than
* this are ignored.
* If zero, fetch without this condition.
*/
TableFetcher(URL url, Listener client, long timeout,
boolean ldate, String[] fields, long newer)
{
super(url, client, timeout, newer);
init(client, timeout, ldate, fields, newer);
}
/**
* Fetch tabular data from several files on the web.
*
* @param urls The URLs to fetch data from.
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param ldate If true, parse dates in long format,
* else false.
* @param fields Names to give to the fields in the results.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* Also, any records with timestamps older than
* this are ignored.
* If zero, fetch without this condition.
*/
TableFetcher(URL[] urls, Listener client, long timeout,
boolean ldate, String[] fields, long newer)
{
super(urls, client, timeout, newer);
init(client, timeout, ldate, fields, newer);
}
/**
* Set up this instance.
*
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param ldate If true, parse dates in long format,
* else false.
* @param fields Names to give to the fields in the results.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* Also, any records with timestamps older than
* this are ignored.
* If zero, fetch without this condition.
*/
private final void init(Listener client, long timeout,
boolean ldate, String[] fields, long newer)
{
longDates = ldate;
fieldNames = fields;
TimeZone utc = TimeZone.getTimeZone("UTC");
dateCal = Calendar.getInstance(utc);
dateCal.clear();
dateFields = new int[6];
}
// ******************************************************************** //
// Data Fetching.
// ******************************************************************** //
/**
* Fetch a page of data from the given BufferedReader.
*
* @param url The URL we're reading.
* @param conn The current connection to the URL.
* @param readc The BufferedReader to read from.
* @throws FetchException Some problem was detected.
* @throws IOException An I/O error occurred.
*/
@Override
protected void handle(URL url, URLConnection conn, BufferedReader readc)
throws FetchException, IOException
{
// Get the date of the file.
long date = conn.getLastModified();
ContentValues rec = new ContentValues();
int stat;
int count = 0;
while ((stat = parse(readc, rec)) >= 0) {
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
if (stat >= 1)
dataClient.onWebData(url, rec, date);
if (++count % 20 == 0) {
// Just don't hog the CPU.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new FetchException("interrupted");
}
}
}
}
/**
* Parse a line from a data file.
*
* The files we're interested in have lines with space-separated fields.
* * If longDates == false, the first three are year, month, day,
* and the rest are float values.
* * If longDates == true, the first five are year, month, day,
* julian, dayseconds, and the rest are float values.
* Lines starting with ':' or '#' are comments.
*
* @param readc The BufferedReader to read from.
* @param values The buffer to put the data in. This is the
* parsed record, with a "date" field added,
* containing the timestamp of the record in ms
* UTC.
* @return -1 on EOF; 0 on no data (e.g. end of line); 1
* if got data, which is now in values.
*/
private int parse(BufferedReader readc, ContentValues values) throws IOException {
// Get the date and time (UTC). Note that for long dates we
// need to skip 2 extra fields.
int nDate = longDates ? 6 : 3;
int nread = parseInts(readc, nDate, dateFields);
if (nread < 0)
return -1;
else if (nread < nDate)
return 0;
dateCal.set(Calendar.YEAR, dateFields[0]);
dateCal.set(Calendar.MONTH, dateFields[1] - 1);
dateCal.set(Calendar.DAY_OF_MONTH, dateFields[2]);
if (longDates) {
final int time = dateFields[3];
dateCal.set(Calendar.HOUR_OF_DAY, time / 100);
dateCal.set(Calendar.MINUTE, time % 100);
} else {
dateCal.set(Calendar.HOUR_OF_DAY, 0);
dateCal.set(Calendar.MINUTE, 0);
}
long time = dateCal.getTimeInMillis();
// If this record is too old, forget it.
if (time < newerThanDate)
return 0;
// Get the remaining parameters. Add the timestamp.
values.clear();
nread = parseFloats(readc, values, fieldNames);
if (nread < 0)
return -1;
values.put("date", time);
return 1;
}
/**
* Parse some integer values from a data file.
*
* @param readc The BufferedReader to read from.
* @param count The number of ints to read.
* @param results Array to place the results in.
* @return The number of ints read. 0 on a blank
* line; -1 on EOF.
* @throws IOException
*/
private int parseInts(BufferedReader readc, int count, int[] results)
throws IOException
{
int c;
boolean first = true;
boolean inNum = false;
int index = 0;
int val = 0;
int sign = 1;
while ((c = readc.read()) >= 0) {
// Look for a comment. Skip to the newline.
if (first && (c == ':' || c == '#')) {
while ((c = readc.read()) >= 0)
if (c == '\n' || c == '\r')
break;
return 0;
}
first = false;
if (c == '\n' || c == '\r') {
if (inNum)
results[index++] = val * sign;
return index;
} else if (c == '-') {
if (inNum) {
results[index++] = val * sign;
if (index >= count)
return index;
}
inNum = true;
val = 0;
sign = -1;
} else if (c >= '0' && c <= '9') {
if (!inNum) {
inNum = true;
val = 0;
sign = 1;
}
val = val * 10 + (c - '0');
} else {
if (inNum) {
inNum = false;
results[index++] = val * sign;
if (index >= count)
return index;
}
}
}
if (inNum) {
inNum = false;
results[index++] = val * sign;
}
return index;
}
/**
* Parse some float values from a data file.
*
* @param readc The BufferedReader to read from.
* @param values The values map to place the results in.
* @param results Names of the fields to save in values.
* @return -1 on EOF; 0 on EOL; 1 if got a float and EOL;
* 2 if just got a float.
* @throws IOException
*/
private int parseFloats(BufferedReader readc, ContentValues values, String[] fields)
throws IOException
{
int index = 0;
State state = State.SPACE;
int intv = 0;
int sign = 1;
int fracv = 0;
int fracDiv = 1;
int expv = 0;
int esign = 1;
int c;
while ((c = readc.read()) >= 0) {
if (c == '\n' || c == '\r') {
if (state != State.SPACE) {
if (index < fieldNames.length) {
float val = (intv +
((float) fracv / (float) fracDiv)) *
(float) Math.pow(10, expv * esign) *
sign;
values.put(fields[index++], val);
}
}
return index;
} else if (c == '+' || c == '-') {
if (state == State.SPACE) {
state = State.MAN;
intv = 0;
sign = c == '-' ? -1 : 1;
fracv = 0;
fracDiv = 1;
expv = 0;
esign = 1;
} else if (state == State.MAN)
sign = c == '-' ? -1 : 1;
else if (state == State.EXP)
esign = c == '-' ? -1 : 1;
} else if (c >= '0' && c <= '9') {
if (state == State.SPACE) {
state = State.MAN;
intv = 0;
sign = 1;
fracv = 0;
fracDiv = 1;
expv = 0;
esign = 1;
}
if (state == State.MAN)
intv = intv * 10 + (c - '0');
else if (state == State.FRAC) {
fracv = fracv * 10 + (c - '0');
fracDiv *= 10;
} else if (state == State.EXP)
expv = expv * 10 + (c - '0');
} else if (c == '.') {
if (state == State.SPACE) {
state = State.FRAC;
intv = 0;
sign = 1;
fracv = 0;
fracDiv = 1;
expv = 0;
esign = 1;
} else if (state == State.MAN)
state = State.FRAC;
} else if (c == 'e' || c == 'E') {
if (state == State.MAN || state == State.FRAC)
state = State.EXP;
} else if (c == ' ' || c == '\t' || true) {
if (state != State.SPACE) {
if (index < fieldNames.length) {
float val = (intv + ((float) fracv / (float) fracDiv)) *
(float) Math.pow(10, expv * esign) *
sign;
values.put(fields[index++], val);
}
state = State.SPACE;
}
}
}
return -1;
}
// ******************************************************************** //
// Private Types.
// ******************************************************************** //
// Float parsing state.
private static enum State { SPACE, MAN, FRAC, EXP };
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "CachedFile";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// True if the source uses long dates.
private boolean longDates;
// Names of the fields to parse and return.
private String[] fieldNames;
// Calendar used for date processing.
private Calendar dateCal;
// Int array used for date processing.
private int[] dateFields;
}
| 12,638 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
WebFetcher.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/net/WebFetcher.java |
/**
* org.hermit.android.net: Android utilities for accessing network data.
*
* These classes provide some basic utilities for accessing and cacheing
* various forms of data from network servers.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedList;
import android.os.Process;
import android.util.Log;
/**
* This class fetches data from the web without blocking the main app.
*/
public abstract class WebFetcher
extends Thread
{
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* Web fetching exception. Used to signal a problem while fetching data.
*/
public static class FetchException extends Exception {
/**
* Create a FetchException with a message.
* @param s The exception message.
*/
public FetchException(String s) {
super("Web fetch error: " + s);
}
/**
* Create a FetchException based on another exception.
* @param s The exception message.
* @param e The root exception.
*/
public FetchException(String s, Exception e) {
super("Web fetch error: " + s +
(e.getMessage() == null ? "" : " (" + e.getMessage() + ")"), e);
}
private static final long serialVersionUID = 4699577452411347104L;
}
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Listener for incoming web data.
*/
public static interface Listener {
/**
* This method is invoked when a data item is retrieved from
* one of the URLs we were invoked on.
*
* @param url The URL that this record came from.
* @param obj The object that was loaded; the type
* depends on the fetcher class used.
* @param date The last modified time of the source file,
* as reported by the server, in ms UTC.
*/
public void onWebData(URL url, Object obj, long date);
/**
* This method is invoked when the URLs have been fully fetched.
*/
public void onWebDone();
/**
* This method is invoked if an error occurs when fetching web data.
*
* @param msg The error message.
*/
public void onWebError(String msg);
}
// ******************************************************************** //
// Fetch Queue.
// ******************************************************************** //
/**
* Queue a web fetch. It will be executed when the current fetches
* are done.
*
* @param fetcher The web fetcher to queue.
*/
public static void queue(WebFetcher fetcher) {
synchronized (fetchQueue) {
if (queueRunner == null)
queueRunner = new Runner();
fetchQueue.addLast(fetcher);
fetchQueue.notify();
}
}
/**
* Stop all fetch operations.
*/
public static void killAll() {
// Stop the queue.
synchronized (fetchQueue) {
if (queueRunner != null)
queueRunner.interrupt();
fetchQueue.clear();
}
// Stop all extant fetchers.
synchronized (allFetchers) {
for (WebFetcher f : allFetchers)
f.kill();
}
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a fetcher to get data from a given URL. Data will
* be fetched asynchronously from the URL, and passed as
* it arrives to the given client.
*
* You can start the fetch when you want by calling start(); or you can
* pass it to queue() to be executed when other fetches are done.
*
* @param url The URL to fetch data from.
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
*/
public WebFetcher(URL url, Listener client, long timeout) {
this(new URL[] { url }, client, timeout, 0);
}
/**
* Create a fetcher to get data from a given URL. Data will
* be fetched asynchronously from the URL, and passed as
* it arrives to the given client.
*
* You can start the fetch when you want by calling start(); or you can
* pass it to queue() to be executed when other fetches are done.
*
* @param url The URL to fetch data from.
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* If zero, fetch without this condition.
*/
public WebFetcher(URL url, Listener client, long timeout, long newer) {
this(new URL[] { url }, client, timeout, newer);
}
/**
* Create a fetcher to get data from a given list of URLs. Data will
* be fetched asynchronously from each URL in sequence, and passed as
* it arrives to the given client. If any URL fails, the whole fetch
* will be aborted. If all URLs succeed, onWebDone() will be called
* in the listener.
*
* You can start the fetch when you want by calling start(); or you can
* pass it to queue() to be executed when other fetches are done.
*
* @param urls The URLs to fetch data from.
* @param client Client to pass the data to.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* If zero, fetch without this condition.
*/
public WebFetcher(URL[] urls, Listener client, long timeout, long newer) {
dataUrls = urls;
dataClient = client;
this.timeout = timeout;
newerThanDate = newer;
// Register on the list of all fetchers.
synchronized (allFetchers) {
allFetchers.add(this);
}
}
// ******************************************************************** //
// Thread control.
// ******************************************************************** //
/**
* Kill this fetcher. Don't start it, don't do any more callbacks.
*/
public void kill() {
synchronized (this) {
killed = true;
if (isAlive())
interrupt();
}
}
/**
* Thread's main method. Just fetch the URLs in sequence. If one
* fails, stop there.
*/
@Override
public void run() {
synchronized (this) {
if (killed)
return;
}
// Run this fetch.
URL current = null;
try {
// Fetch each URL in sequence. If one fails, stop there.
for (URL url : dataUrls) {
// Sleep a wee bit, to ensure our client gets some running in first.
sleep(500);
if (isInterrupted())
throw new InterruptedException();
current = url;
Log.i(TAG, "R: start " + url);
fetch(url, newerThanDate);
if (isInterrupted())
throw new InterruptedException();
}
// Tell the client that all URLs are done.
Log.i(TAG, "R: finished all " + current);
dataClient.onWebDone();
} catch (IOException e) {
Log.e(TAG, "R: IOException: " + current);
String msg = e.getClass().getName() + ": " + e.getMessage();
dataClient.onWebError(msg);
} catch (FetchException e) {
Log.e(TAG, "R: FetchException: " + current);
String msg = e.getClass().getName() + ": " + e.getMessage();
dataClient.onWebError(msg);
} catch (InterruptedException e) {
Log.e(TAG, "R: InterruptedException: " + current);
String msg = "Interrupted";
dataClient.onWebError(msg);
} finally {
// We're done; de-register from the list of all fetchers.
synchronized (allFetchers) {
allFetchers.remove(this);
}
}
}
// ******************************************************************** //
// Data Fetching.
// ******************************************************************** //
/**
* Fetch an object from the given URL.
*
* @param url The URL to fetch.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* If zero, fetch without this condition.
* @throws FetchException Some problem was detected, such as a timeout.
* @throws IOException An I/O error occurred.
*/
protected void fetch(URL url, long newer)
throws FetchException, IOException
{
// Attempt to connect to the URL. If we fail, just bomb out.
InputStream stream = null;
try {
// Set up the connection parameters.
URLConnection conn = url.openConnection();
if (newer != 0)
conn.setIfModifiedSince(newer);
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
// Open the connection.
conn.connect();
stream = conn.getInputStream();
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
// Fetch from the stream.
handle(url, conn, stream);
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
} finally {
// Clean up the streams etc. Other than that, we just bomb.
try {
if (stream != null)
stream.close();
} catch (IOException e1) { }
}
}
/**
* Handle data from the given stream.
*
* @param url The URL we're reading.
* @param conn The current connection to the URL.
* @param stream The InputStream to read from.
* @throws FetchException Some problem was detected, such as a timeout.
* @throws IOException An I/O error occurred.
*/
protected void handle(URL url, URLConnection conn, InputStream stream)
throws FetchException, IOException
{
InputStreamReader reads = null;
BufferedReader readc = null;
try {
// Open a buffered reader on the connection. What a chore...
reads = new InputStreamReader(stream);
readc = new BufferedReader(reads, 4096);
// Get the input.
handle(url, conn, readc);
} finally {
// Clean up the streams etc. Other than that, we just bomb.
try {
if (readc != null)
readc.close();
} catch (IOException e1) { }
try {
if (reads != null)
reads.close();
} catch (IOException e1) { }
}
}
/**
* Handle data from the given BufferedReader.
*
* @param url The URL we're reading.
* @param conn The current connection to the URL.
* @param stream The BufferedReader to read from.
* @throws FetchException Some problem was detected, such as a timeout.
* @throws IOException An I/O error occurred.
*/
protected void handle(URL url, URLConnection conn, BufferedReader stream)
throws FetchException, IOException
{
}
// ******************************************************************** //
// Private Class.
// ******************************************************************** //
/**
* This class runs the queue of fetch operations, if we're using
* a queue. It also takes care of timeouts on queue items.
*/
private static final class Runner
extends Thread
{
Runner() {
start();
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true) {
if (isInterrupted())
break;
WebFetcher job;
// Get the next job from the queue. If there isn't one,
// wait until there is.
synchronized (fetchQueue) {
job = fetchQueue.poll();
if (job == null) {
try {
fetchQueue.wait();
} catch (InterruptedException e) { }
if (isInterrupted())
break;
continue;
}
}
if (isInterrupted())
break;
// Kick off the job.
job.start();
// Now wait for it to finish, but only up to the timeout.
try {
job.join(job.timeout);
} catch (InterruptedException e) { }
if (isInterrupted())
break;
// If it didn't finish, kill it.
if (job.isAlive())
job.interrupt();
}
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "WebFetcher";
// List of all WebFetchers in operation.
private static ArrayList<WebFetcher> allFetchers =
new ArrayList<WebFetcher>();
// This is the queue of items to be fetched.
private static final LinkedList<WebFetcher> fetchQueue =
new LinkedList<WebFetcher>();
// Queue runner.
private static Runner queueRunner = null;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The timeout in ms for this fetcher to complete.
protected final long timeout;
// Set to true to kill this thread.
protected boolean killed = false;
// The URLs we're fetching.
protected final URL[] dataUrls;
// If this is zero, it has no effect. If non-zero, it is taken as a
// time in ms UTC; the remote resource will only be fetched if it has
// been modified since that time.
protected final long newerThanDate;
// The client to pass the data to.
protected final Listener dataClient;
}
| 14,789 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
WebBasedData.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/net/WebBasedData.java |
/**
* org.hermit.android.net: Android utilities for accessing network data.
*
* These classes provide some basic utilities for accessing and cacheing
* various forms of data from network servers.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.net;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Observable;
import java.util.TimeZone;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* This class implements a web-based source of data, which is cached
* in a local database. The data is assumed to be timestamped records.
*/
public class WebBasedData
extends Observable
implements WebFetcher.Listener
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a web-based data source.
*
* @param name The name of this source, and its database table.
* @param base The base URL for this source; this is the
* whole URL if urlSuff is null.
* @param suff The URL suffix. If not null, the URL is
* urlBase + date + urlSuff, where date is in
* the format "20091231".
* @param interval Interval in ms between records in the source.
* @param ldate If true, the source uses long-format dates.
* @param fields Names for the fields in the source.
*/
public WebBasedData(String name, String base, String suff,
long interval, boolean ldate, String[] fields)
{
sourceName = name;
urlBase = base;
urlSuff = suff;
dataInterval = interval;
longDate = ldate;
fieldNames = fields;
}
// ******************************************************************** //
// Database Management.
// ******************************************************************** //
/**
* Create our table in the database.
*
* @param db The database.
*/
public void createTable(SQLiteDatabase db) {
Log.i(TAG, "WBD: create table " + sourceName);
String create = "CREATE TABLE " + sourceName + " (" +
"date INTEGER PRIMARY KEY UNIQUE ON CONFLICT IGNORE";
for (String f : fieldNames)
create += "," + f + " REAL";
create += ");";
db.execSQL(create);
}
/**
* Upgrade or table in the database to a new version.
*
* @param db The database.
* @param oldV Version we're upgrading from.
* @param newV Version we're upgrading to.
*/
public void upgradeTable(SQLiteDatabase db, int oldV, int newV) {
Log.i(TAG, "WBD: upgrade table " + sourceName);
// We can simply dump all the old data, since the DB is just
// a cache of web data.
db.execSQL("DROP TABLE IF EXISTS " + sourceName);
createTable(db);
}
/**
* Set the database we use for storing our data.
*
* @param db The database. Will be null if the database
* is being closed.
*/
public void setDatabase(SQLiteDatabase db) {
long date = 0;
synchronized (this) {
database = db;
if (database != null)
date = findLatestDate();
}
// If we have any records, inform the client that we have data.
if (date != 0) {
setChanged();
notifyObservers(latestDate);
}
}
// ******************************************************************** //
// Data Access.
// ******************************************************************** //
/**
* Get the name of this source.
*
* @return The name of this source.
*/
public synchronized String getName() {
return sourceName;
}
/**
* Query for all records we have stored.
*
* It is the caller's responsibility to call close() on the cursor
* when done.
*
* @return A Cursor over all the records, sorted in
* ascending date order. The Cursor is positioned
* before the first record.
*/
public synchronized Cursor allRecords() {
return database.query(sourceName, fieldNames, null, null,
null, null, "date ASC", null);
}
/**
* Query for all records we have stored timstamped AFTER a given date.
*
* It is the caller's responsibility to call close() on the cursor
* when done.
*
* @param date Cut-off date -- only return records newer
* than this date (not equal).
* @return A Cursor over all the records, sorted in
* ascending date order. The Cursor is positioned
* before the first record.
*/
public synchronized Cursor allRecordsSince(long date) {
return database.query(sourceName, fieldNames,
"date>" + date, null,
null, null, "date ASC", null);
}
/**
* Query for the newest record we have stored.
*
* @return The contents of the last record we have.
* Returns null if there are no records.
*/
public synchronized ContentValues lastRecord() {
Cursor c = database.query(sourceName, fieldNames, null, null,
null, null, "date DESC", "1");
if (!c.moveToFirst()) {
c.close();
return null;
}
ContentValues data = new ContentValues();
DatabaseUtils.cursorRowToContentValues(c, data);
c.close();
return data;
}
// ******************************************************************** //
// Update.
// ******************************************************************** //
/**
* Check to see whether we need to update our stored data. If so,
* kick off a web fetch.
*
* The observers will be notified for any new data that we load.
*
* @param now The current time in millis.
*/
public void update(long now) {
if (database == null)
return;
URL[] urls = null;
String name = null;
long earliest = 0;
synchronized (this) {
// If it's too soon since the last check, don't even try.
if (now - lastDataCheck < MIN_CHECK_INTERVAL) {
Log.i(TAG, "WBD " + sourceName + ": update reject: too soon since last");
return;
}
// Find the date of the newest data we have. If it is less than
// REFRESH_INTERVAL old, then do nothing.
long latest = findLatestDate();
if (now - latest < REFRESH_INTERVAL) {
Log.i(TAG, "WBD " + sourceName + ": update reject: have fresh data");
return;
}
// See how far back we need to go. The earliest data we want is
// the most recent we have plus DATA_INTERVAL; maximum
// MAX_DATA_AGE old.
earliest = latest + dataInterval;
if (earliest < now - MAX_SAMPLES * dataInterval)
earliest = now - MAX_SAMPLES * dataInterval;
// Add the URL(s) to fetch. If the URL for this source is
// date-dependent, figure out which URLs to get. Otherwise just
// fetch the URL.
try {
if (urlSuff != null) {
String last = ymNameForDate(earliest);
String curr = ymNameForDate(now);
if (!last.equals(curr)) {
urls = new URL[] { new URL(urlBase + last + urlSuff),
new URL(urlBase + curr + urlSuff) };
name = last + "," + curr;
} else {
urls = new URL[] { new URL(urlBase + curr + urlSuff) };
name = curr;
}
} else {
urls = new URL[] { new URL(urlBase) };
name = "fixed";
}
} catch (MalformedURLException e) {
// Should never really happen.
String msg = e.getClass().getName() + ": " + e.getMessage();
Log.e(TAG, msg);
}
}
Log.i(TAG, "WBD " + sourceName + ": update: kick off " + name);
TableFetcher wf = new TableFetcher(urls, this, FETCH_TIMEOUT,
longDate, fieldNames, earliest);
wf.start();
lastDataCheck = now;
}
/**
* Find the date of the newest record in the database for this
* source.
*
* @return The timestamp of the newest record in
* our table, in ms UTC.
*/
private long findLatestDate() {
String[] fields = new String[] { "date" };
Cursor c = database.query(sourceName, fields, null, null,
null, null, "date DESC", "1");
if (!c.moveToFirst())
latestDate = 0;
else {
int cind = c.getColumnIndexOrThrow(fields[0]);
latestDate = c.getLong(cind);
}
c.close();
return latestDate;
}
/**
* Get the year and month name for a given date.
*
* @param date The date in ms UTC.
* @return Date year-month name, as in "20091231".
*/
private static String ymNameForDate(long date) {
if (calendar == null)
calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(date);
// The URLs we're after contain the date, so we have to construct them.
// Each file is a calendar month of data -- of course we may be at
// the start of a month. So get this month's and last month's,
// to guarantee 30 days * 24 hours.
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
return String.format("%04d%02d", year, month);
}
// ******************************************************************** //
// Fetched Data Handling.
// ******************************************************************** //
/**
* Optional processing step -- this is called for each record we read.
* It can be used to add synthesized values.
*
* @param rec The record to process.
*/
protected void process(ContentValues rec) {
}
/**
* This method is invoked when a data record is retrieved from
* the URL we were invoked on.
*
* @param url The URL of the source being loaded.
* @param obj The object that was loaded; the type
* depends on the fetcher class used.
* @param fileDate The last modified time of the source file,
* as reported by the server, in ms UTC.
*/
@Override
public void onWebData(URL url, Object obj, long fileDate) {
if (database == null)
return;
if (!(obj instanceof ContentValues)) {
onWebError("Loaded object for " + url + " not a ContentValues!");
return;
}
ContentValues rec = (ContentValues) obj;
long rdate = rec.getAsLong("date");
// Do any required processing.
process(rec);
// Add it to the database.
synchronized (this) {
// Update the latest date if this is a newer record.
if (rdate > latestDate) {
database.insert(sourceName, fieldNames[0], rec);
latestDate = rdate;
}
}
}
/**
* This method is invoked when the given URL has been fully fetched.
*/
@Override
public void onWebDone() {
synchronized(this) {
if (database != null) {
// Trim off any old unwanted values.
long earliest = System.currentTimeMillis() - MAX_SAMPLES * dataInterval;
database.delete(sourceName, "date<" + earliest, null);
}
}
// Inform the client that we have data.
setChanged();
notifyObservers(latestDate);
}
/**
* Handle an error while fetching web data.
*/
@Override
public synchronized void onWebError(String msg) {
Log.e(TAG, msg);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "WebBasedData";
// Calendar used for date manipulations.
private static Calendar calendar = null;
// Minimum interval in ms between checks for file updates.
private static final long MIN_CHECK_INTERVAL = 30 * 60 * 1000;
// The interval in ms after which we will look for updated data.
private static final long REFRESH_INTERVAL = 120 * 60 * 1000;
// The maximum number of samples we will store.
private static final long MAX_SAMPLES = 400;
// The timeout in ms for fetching a file.
private static final long FETCH_TIMEOUT = 15 * 60 * 1000;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The name of this source, and its database table.
private final String sourceName;
// The base URL for this source, and the suffix. If urlSuff is null,
// then urlBase is the whole URL; else, the URL is
// urlBase + ymNameForDate(long date) + urlSuff.
private final String urlBase;
private final String urlSuff;
// Interval in ms between records in the source.
private long dataInterval;
// If true, the source uses long date format.
private final boolean longDate;
// The names to assign to the fields from the source.
private final String[] fieldNames;
// The database we use for storing our data.
private SQLiteDatabase database = null;
// Date in ms UTC of the latest record in the DB for this source.
// 0 means no data.
private long latestDate = 0;
// Date in ms UTC at which we last checked for data. 0 means
// never.
private long lastDataCheck = 0;
}
| 14,157 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
FileFetcher.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/net/FileFetcher.java |
/**
* org.hermit.android.net: Android utilities for accessing network data.
*
* These classes provide some basic utilities for accessing and cacheing
* various forms of data from network servers.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.net;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
/**
* Concrete instance of WebFetcher which gets a file and stores it locally.
* The value passed back to the listener is the local file name as a File.
*/
public class FileFetcher
extends WebFetcher
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Fetch a file from the web.
*
* @param context Application context.
* @param url The URL to fetch data from.
* @param name Local name to save the file as.
* @param client Client to pass the data to. It will be given
* the local file name as a File object.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
*/
public FileFetcher(Context context, URL url, String name,
Listener client, long timeout)
{
this(context, url, name, client, timeout, 0);
}
/**
* Fetch a file from the web.
*
* @param context Application context.
* @param url The URL to fetch data from.
* @param name Local name to save the file as.
* @param client Client to pass the data to. It will be given
* the local file name as a File object.
* @param timeout Maximum time in ms for which the job will be
* allowed to run.
* @param newer If-modified-since time in ms UTC. The
* fetch will only be carried out if the remote
* resource has been modified since this time.
* If zero, fetch without this condition.
*/
public FileFetcher(Context context, URL url, String name,
Listener client, long timeout, long newer)
{
super(url, client, timeout, newer);
this.context = context;
this.fileName = name;
filePath = context.getFileStreamPath(fileName);
tempName = fileName + ".part";
tempPath = new File(filePath.getParent(), tempName);
}
// ******************************************************************** //
// Data Fetching.
// ******************************************************************** //
/**
* Fetch a page of data from the given stream.
*
* @param url The URL we're reading.
* @param conn The current connection to the URL.
* @param stream The InputStream to read from.
* @throws FetchException Some problem was detected.
* @throws IOException An I/O error occurred.
*/
@Override
protected void handle(URL url, URLConnection conn, InputStream stream)
throws FetchException, IOException
{
// Get the date of the file.
long date = conn.getLastModified();
try {
// Read the file down and copy it to local storage. If it fails,
// it throws.
fetchFile(url, conn, stream);
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
// OK, it worked. Move the temp. file over the real file.
filePath.delete();
tempPath.renameTo(filePath);
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
// Notify the client that we're done.
dataClient.onWebData(url, filePath, date);
}
finally {
// Delete the temp. if it was left around.
if (tempPath.exists())
tempPath.delete();
}
}
/**
* Fetch a page of data from the given stream.
*
* @param url The URL we're reading.
* @param conn The current connection to the URL.
* @param stream The InputStream to read from.
* @throws IOException
*/
private void fetchFile(URL url, URLConnection conn, InputStream stream)
throws FetchException, IOException
{
// Read the file down and copy it to local storage.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(tempName, Context.MODE_PRIVATE);
byte[] buf = new byte[8192];
int count;
while ((count = stream.read(buf)) >= 0) {
// If we were killed, bomb out.
if (isInterrupted())
throw new FetchException("timed out");
fos.write(buf, 0, count);
// Just don't hog the CPU.
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new FetchException("interrupted");
}
}
} finally {
// On error, kill the file and bail.
try {
if (fos != null)
fos.close();
} catch (IOException e1) { }
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "FileFetcher";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application context.
private Context context;
// Local name for the fetched file.
private String fileName;
// Full path of the downloaded file.
private File filePath;
// Name and full path of the temp copy of the file as its downloading.
private String tempName;
private File tempPath;
}
| 6,072 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AudioReader.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/io/AudioReader.java |
/**
* org.hermit.android.io: Android utilities for accessing peripherals.
*
* These classes provide some basic utilities for accessing the audio
* interface, at present.
*
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.io;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
/**
* A class which reads audio input from the mic in a background thread and
* passes it to the caller when ready.
*
* <p>To use this class, your application must have permission RECORD_AUDIO.
*/
public class AudioReader
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Listener for audio reads.
*/
public static abstract class Listener {
/**
* Audio read error code: no error.
*/
public static final int ERR_OK = 0;
/**
* Audio read error code: the audio reader failed to initialise.
*/
public static final int ERR_INIT_FAILED = 1;
/**
* Audio read error code: an audio read failed.
*/
public static final int ERR_READ_FAILED = 2;
/**
* An audio read has completed.
* @param buffer Buffer containing the data.
*/
public abstract void onReadComplete(short[] buffer);
/**
* An error has occurred. The reader has been terminated.
* @param error ERR_XXX code describing the error.
*/
public abstract void onReadError(int error);
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an AudioReader instance.
*/
public AudioReader() {
// audioManager = (AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* Start this reader.
*
* @param rate The audio sampling rate, in samples / sec.
* @param block Number of samples of input to read at a time.
* This is different from the system audio
* buffer size.
* @param listener Listener to be notified on each completed read.
*/
public void startReader(int rate, int block, Listener listener) {
Log.i(TAG, "Reader: Start Thread");
synchronized (this) {
// Calculate the required I/O buffer size.
int audioBuf = AudioRecord.getMinBufferSize(rate,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT) * 2;
// Set up the audio input.
audioInput = new AudioRecord(MediaRecorder.AudioSource.MIC,
rate,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
audioBuf);
inputBlockSize = block;
sleepTime = (long) (1000f / ((float) rate / (float) block));
inputBuffer = new short[2][inputBlockSize];
inputBufferWhich = 0;
inputBufferIndex = 0;
inputListener = listener;
running = true;
readerThread = new Thread(new Runnable() {
@Override
public void run() { readerRun(); }
}, "Audio Reader");
readerThread.start();
}
}
/**
* Stop this reader.
*/
public void stopReader() {
Log.i(TAG, "Reader: Signal Stop");
synchronized (this) {
running = false;
}
try {
if (readerThread != null)
readerThread.join();
} catch (InterruptedException e) {
;
}
readerThread = null;
// Kill the audio input.
synchronized (this) {
if (audioInput != null) {
audioInput.release();
audioInput = null;
}
}
Log.i(TAG, "Reader: Thread Stopped");
}
// ******************************************************************** //
// Main Loop.
// ******************************************************************** //
/**
* Main loop of the audio reader. This runs in our own thread.
*/
private void readerRun() {
short[] buffer;
int index, readSize;
int timeout = 200;
try {
while (timeout > 0 && audioInput.getState() != AudioRecord.STATE_INITIALIZED) {
Thread.sleep(50);
timeout -= 50;
}
} catch (InterruptedException e) { }
if (audioInput.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG, "Audio reader failed to initialize");
readError(Listener.ERR_INIT_FAILED);
running = false;
return;
}
try {
Log.i(TAG, "Reader: Start Recording");
audioInput.startRecording();
while (running) {
long stime = System.currentTimeMillis();
if (!running)
break;
readSize = inputBlockSize;
int space = inputBlockSize - inputBufferIndex;
if (readSize > space)
readSize = space;
buffer = inputBuffer[inputBufferWhich];
index = inputBufferIndex;
synchronized (buffer) {
int nread = audioInput.read(buffer, index, readSize);
boolean done = false;
if (!running)
break;
if (nread < 0) {
Log.e(TAG, "Audio read failed: error " + nread);
readError(Listener.ERR_READ_FAILED);
running = false;
break;
}
int end = inputBufferIndex + nread;
if (end >= inputBlockSize) {
inputBufferWhich = (inputBufferWhich + 1) % 2;
inputBufferIndex = 0;
done = true;
} else
inputBufferIndex = end;
if (done) {
readDone(buffer);
// Because our block size is way smaller than the audio
// buffer, we get blocks in bursts, which messes up
// the audio analyzer. We don't want to be forced to
// wait until the analysis is done, because if
// the analysis is slow, lag will build up. Instead
// wait, but with a timeout which lets us keep the
// input serviced.
long etime = System.currentTimeMillis();
long sleep = sleepTime - (etime - stime);
if (sleep < 5)
sleep = 5;
try {
buffer.wait(sleep);
} catch (InterruptedException e) { }
}
}
}
} finally {
Log.i(TAG, "Reader: Stop Recording");
if (audioInput.getState() == AudioRecord.RECORDSTATE_RECORDING)
audioInput.stop();
}
}
/**
* Notify the client that a read has completed.
*
* @param buffer Buffer containing the data.
*/
private void readDone(short[] buffer) {
inputListener.onReadComplete(buffer);
}
/**
* Notify the client that an error has occurred. The reader has been
* terminated.
*
* @param error ERR_XXX code describing the error.
*/
private void readError(int code) {
inputListener.onReadError(code);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "WindMeter";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Our audio input device.
private AudioRecord audioInput;
// Our audio input buffer, and the index of the next item to go in.
private short[][] inputBuffer = null;
private int inputBufferWhich = 0;
private int inputBufferIndex = 0;
// Size of the block to read each time.
private int inputBlockSize = 0;
// Time in ms to sleep between blocks, to meter the supply rate.
private long sleepTime = 0;
// Listener for input.
private Listener inputListener = null;
// Flag whether the thread should be running.
private boolean running = false;
// The thread, if any, which is currently reading. Null if not running.
private Thread readerThread = null;
}
| 10,123 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
NumberPickerButton.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/NumberPickerButton.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import org.hermit.android.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageButton;
/**
* This class exists purely to cancel long click events, that got
* started in NumberPicker
*/
class NumberPickerButton extends ImageButton {
private NumberPicker mNumberPicker;
public NumberPickerButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public NumberPickerButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumberPickerButton(Context context) {
super(context);
}
public void setNumberPicker(NumberPicker picker) {
mNumberPicker = picker;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTouchEvent(event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTrackballEvent(event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
|| (keyCode == KeyEvent.KEYCODE_ENTER)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}
private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}
private void cancelLongpress() {
if (R.id.increment == getId()) {
mNumberPicker.cancelIncrement();
} else if (R.id.decrement == getId()) {
mNumberPicker.cancelDecrement();
}
}
}
| 2,451 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TimeoutPicker.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/TimeoutPicker.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import java.util.Calendar;
import org.hermit.android.R;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import org.hermit.android.widgets.NumberPicker;
/**
* A view for selecting an elapsed time, in hours, minutes, and seconds.
* The hour, minutes, and seconds are controlled by vertical spinners.
*
* The hour can be entered by keyboard input. Entering in two digit hours
* can be accomplished by hitting two digits within a timeout of about a
* second (e.g. '1' then '2' to select 12).
*
* The minutes can be entered by entering single digits.
*/
public class TimeoutPicker
extends FrameLayout
{
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* The callback interface used to indicate the time has been adjusted.
*/
public interface OnTimeChangedListener {
/**
* @param view The view associated with this listener.
* @param millis The currently set time interval in milliseconds.
*/
void onTimeChanged(TimeoutPicker view, long millis);
}
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
public TimeoutPicker(Context context) {
this(context, null);
}
public TimeoutPicker(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimeoutPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.timeout_picker, this, true);
// Configure the hour picker.
hourPicker = (NumberPicker) findViewById(R.id.hour);
hourPicker.setMinValue(0);
hourPicker.setMaxValue(99);
hourPicker.setOnLongPressUpdateInterval(100);
hourPicker.setFormatter(TWO_DIGIT_FORMATTER);
hourPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
currentHour = newVal;
onTimeChanged();
}
});
// Configure the minutes picker.
minutePicker = (NumberPicker) findViewById(R.id.minute);
minutePicker.setMinValue(0);
minutePicker.setMaxValue(59);
minutePicker.setOnLongPressUpdateInterval(100);
minutePicker.setFormatter(TWO_DIGIT_FORMATTER);
minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
currentMinute = newVal;
onTimeChanged();
}
});
// Configure the seconds picker.
secondPicker = (NumberPicker) findViewById(R.id.second);
secondPicker.setMinValue(0);
secondPicker.setMaxValue(59);
secondPicker.setOnLongPressUpdateInterval(100);
secondPicker.setFormatter(TWO_DIGIT_FORMATTER);
secondPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
currentSecond = newVal;
onTimeChanged();
}
});
// initialize to current time
Calendar cal = Calendar.getInstance();
// by default we're not in 24 hour mode
setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
setCurrentMinute(cal.get(Calendar.MINUTE));
if (!isEnabled())
setEnabled(false);
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
secondPicker.setEnabled(enabled);
minutePicker.setEnabled(enabled);
hourPicker.setEnabled(enabled);
}
/**
* Set the callback that indicates the time has been adjusted by the user.
* @param onTimeChangedListener the callback, should not be null.
*/
public void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener) {
changeListener = onTimeChangedListener;
}
/**
* @return The current time value in ms.
*/
public long getMillis() {
int secs = currentHour * 3600 + currentMinute * 60 + currentSecond;
return (long) (secs * 1000);
}
/**
* Set the current time value.
*
* @param millis Time value to set, in ms.
*/
public void setMillis(long millis) {
currentSecond = (int) ((millis / 1000) % 60);
currentMinute = (int) ((millis / 60000) % 60);
currentHour = (int) ((millis / 3600000) % 100);
secondPicker.setValue(currentSecond);
minutePicker.setValue(currentMinute);
hourPicker.setValue(currentHour);
onTimeChanged();
}
/**
* @return The current hour (0-99).
*/
public int getCurrentHour() {
return currentHour;
}
/**
* Set the current hour (0-99).
*/
public void setCurrentHour(int hour) {
currentHour = hour;
hourPicker.setValue(currentHour);
onTimeChanged();
}
/**
* @return The current minute.
*/
public int getCurrentMinute() {
return currentMinute;
}
/**
* Set the current minute (0-59).
*/
public void setCurrentMinute(int min) {
currentMinute = min;
minutePicker.setValue(currentMinute);
onTimeChanged();
}
/**
* @return The current second.
*/
public int getCurrentSecond() {
return currentSecond;
}
/**
* Set the current second (0-59).
*/
public void setCurrentSecond(int sec) {
currentSecond = sec;
secondPicker.setValue(currentSecond);
onTimeChanged();
}
/**
* Return the offset of the widget's text baseline from the
* widget's top boundary.
*/
@Override
public int getBaseline() {
return hourPicker.getBaseline();
}
// ******************************************************************** //
// Updating.
// ******************************************************************** //
private void onTimeChanged() {
if (changeListener != null)
changeListener.onTimeChanged(this, getMillis());
}
// ******************************************************************** //
// Save and Restore.
// ******************************************************************** //
/**
* Used to save / restore the state of the timeout picker.
*/
private static class SavedState extends BaseSavedState {
private SavedState(Parcelable superState, int hour, int minute, int sec) {
super(superState);
mHour = hour;
mMinute = minute;
mSecond = sec;
}
private SavedState(Parcel in) {
super(in);
mHour = in.readInt();
mMinute = in.readInt();
mSecond = in.readInt();
}
public int getHour() {
return mHour;
}
public int getMinute() {
return mMinute;
}
public int getSecond() {
return mSecond;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(mHour);
dest.writeInt(mMinute);
dest.writeInt(mSecond);
}
// public static final Parcelable.Creator<SavedState> CREATOR =
// new Creator<SavedState>() {
// public SavedState createFromParcel(Parcel in) {
// return new SavedState(in);
// }
//
// public SavedState[] newArray(int size) {
// return new SavedState[size];
// }
// };
private final int mHour;
private final int mMinute;
private final int mSecond;
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState, currentHour, currentMinute, currentSecond);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setCurrentHour(ss.getHour());
setCurrentMinute(ss.getMinute());
setCurrentSecond(ss.getSecond());
}
// ******************************************************************** //
// Private Types.
// ******************************************************************** //
/*
* Use a custom NumberPicker formatting callback to use two-digit
* minutes strings like "01". Keeping a static formatter etc. is the
* most efficient way to do this; it avoids creating temporary objects
* on every call to format().
*/
private static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
new NumberPicker.Formatter() {
@Override
public String format(int value) {
charBuf[0] = (char) ('0' + value / 10 % 10);
charBuf[1] = (char) ('0' + value % 10);
return new String(charBuf);
}
private final char[] charBuf = new char[2];
};
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// state
private int currentHour = 0; // 0-99
private int currentMinute = 0; // 0-59
private int currentSecond = 0; // 0-59
// ui components
private final NumberPicker hourPicker;
private final NumberPicker minutePicker;
private final NumberPicker secondPicker;
// Listener for time changes. null if not set.
private OnTimeChangedListener changeListener;
}
| 11,060 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
LinedEditText.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/LinedEditText.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;
/**
* A custom EditText that draws lines between each line of text
* that is displayed.
*/
public class LinedEditText extends EditText {
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Construct a widget from a given attribute set. This is required to
* allow this widget to be used from XML layouts.
*
* @param context Context we're running in.
* @param attrs Attributes for this widget.
*/
public LinedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
drawRect = new Rect();
// Initialise the painter with the drawing attributes for the lines.
drawPaint = new Paint();
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setColor(LINE_COLOUR);
}
// ******************************************************************** //
// Drawing.
// ******************************************************************** //
/**
* Overridden onDraw method. Draw the text, with lines.
*
* @param canvas Canvas to draw into.
*/
@Override
protected void onDraw(Canvas canvas) {
Rect r = drawRect;
Paint paint = drawPaint;
// Draw a line under each text line.
int count = getLineCount();
for (int i = 0; i < count; i++) {
// Get the bounds for this text line, and draw a line under it.
int baseline = getLineBounds(i, r);
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
}
super.onDraw(canvas);
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Colour for the text lines.
private static final int LINE_COLOUR = 0x600000ff;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Rect used for storing bounds.
private Rect drawRect;
// Paint used for drawing the lines.
private Paint drawPaint;
}
| 3,072 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TimeoutPickerDialog.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/TimeoutPickerDialog.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import org.hermit.android.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TimePicker;
/**
* A dialog that prompts the user for the time of day using a {@link TimePicker}.
*
* <p>See the <a href="{@docRoot}resources/tutorials/views/hello-timepicker.html">Time Picker
* tutorial</a>.</p>
*/
public class TimeoutPickerDialog extends AlertDialog implements OnClickListener,
TimeoutPicker.OnTimeChangedListener {
/**
* The callback interface used to indicate the user is done filling in
* the time (they clicked on the 'Set' button).
*/
public interface OnTimeSetListener {
/**
* @param view The view associated with this listener.
* @param hourOfDay The hour that was set.
* @param minute The minute that was set.
*/
void onTimeSet(TimeoutPicker view, long millis);
}
private static final String MILLIS = "millis";
private final TimeoutPicker mTimePicker;
private final OnTimeSetListener mCallback;
private long mInitialMillis;
/**
* @param context Parent.
* @param callBack How parent is notified.
* @param timeoutMillis The initial tiume in ms.
*/
public TimeoutPickerDialog(Context context,
OnTimeSetListener callBack,
long timeoutMillis) {
super(context);
mCallback = callBack;
mInitialMillis = timeoutMillis;
updateTitle(mInitialMillis);
setButton(context.getText(R.string.timeout_set), this);
setButton2(context.getText(R.string.timeout_cancel), (OnClickListener) null);
setIcon(android.R.drawable.ic_dialog_info);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.timeout_picker_dialog, null);
setView(view);
mTimePicker = (TimeoutPicker) view.findViewById(R.id.timeoutPicker);
// initialize state
mTimePicker.setMillis(mInitialMillis);
mTimePicker.setOnTimeChangedListener(this);
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (mCallback != null) {
mTimePicker.clearFocus();
mCallback.onTimeSet(mTimePicker, mTimePicker.getMillis());
}
}
@Override
public void onTimeChanged(TimeoutPicker view, long millis) {
updateTitle(millis);
}
public void updateTime(long millis) {
mTimePicker.setMillis(millis);
}
private void updateTitle(long millis) {
int secs = (int) millis / 1000;
int mins = secs / 60 % 60;
int hours = secs / 3600 % 100;
secs %= 60;
setTitle(String.format("%02d:%02d:%02d", hours, mins, secs));
}
@Override
public Bundle onSaveInstanceState() {
Bundle state = super.onSaveInstanceState();
state.putLong(MILLIS, mTimePicker.getMillis());
return state;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long millis = savedInstanceState.getLong(MILLIS);
mTimePicker.setMillis(millis);
mTimePicker.setOnTimeChangedListener(this);
updateTitle(millis);
}
}
| 4,111 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TimeZoneActivity.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/TimeZoneActivity.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.TimeZone;
import org.hermit.utils.TimeUtils;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
/**
* This class displays a picker which can be used to select a timezone.
* Options are provided to add app-specific zones, such as "local",
* "nautical", etc.
*/
public class TimeZoneActivity
extends ListActivity
{
// ******************************************************************** //
// Activity Lifecycle.
// ******************************************************************** //
/**
* Called when the activity is starting. This is where most
* initialization should go: calling setContentView(int) to inflate
* the activity's UI, etc.
*
* @param icicle If the activity is being re-initialized
* after previously being shut down then this
* Bundle contains the data it most recently
* supplied in onSaveInstanceState(Bundle).
* Note: Otherwise it is null.
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Get our passed-in intent.
Intent intent = getIntent();
// Build the master list of timezones, if we haven't yet.
if (zoneList == null)
listZones(intent);
// Create the adapter for the zone list. Map the required fields
// into the list item view.
String[] from = { "name", "offset" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter =
new SimpleAdapter(this, zoneList,
android.R.layout.two_line_list_item,
from, to);
// Bind to our new adapter.
setListAdapter(adapter);
}
// ******************************************************************** //
// Zone Data Management.
// ******************************************************************** //
/**
* Build the global list of timezones.
*
* @param intent Intent containing parameters for this picker.
*/
private static void listZones(Intent intent) {
// Create the list. This is a mapping of time zone offsets
// to timezones which have that raw offset.
zoneMap = new HashMap<Integer, ArrayList<TimeZone>>();
// Build the offset to zone mapping, by scanning all existing zones.
// TODO: due to a stupid bug, TimeZone reports the wrong zone
// name (not zone ID) for many zones. E.g. there are at least
// two different zones reported as "Pacific Standard Time". So
// this algorithm to winnow down the zone list by using the zone
// name doesn't work.
// String[] znames = TimeZone.getAvailableIDs();
// for (int i = 0; i < znames.length; ++i) {
// // Get the zone and its offset.
// TimeZone zone = TimeZone.getTimeZone(znames[i]);
// String name = zone.getDisplayName();
// int offset = zone.getRawOffset();
for (String[] zoneNames : HARD_ZONES) {
// Get the zone and its offset.
String id = zoneNames[0];
String name = zoneNames[1];
TimeZone zone = TimeZone.getTimeZone(id);
int offset = zone.getRawOffset();
// Skip all the "GMT+x" zones.
if (name.startsWith("GMT"))
continue;
// If we don't have any zones for this offset, create the list
// and add it to the hash map. Else, add this zone to the list
// for the offset, but only if there isn't an equivalent zone
// already there.
if (!zoneMap.containsKey(offset)) {
ArrayList<TimeZone> list = new ArrayList<TimeZone>();
list.add(zone);
zoneMap.put(offset, list);
} else {
ArrayList<TimeZone> list = zoneMap.get(offset);
// TODO: So this doesn't work...
// boolean got = false;
// for (TimeZone other : list) {
// String oname = other.getDisplayName();
// if (other.hasSameRules(zone) && oname.equals(name)) {
// got = true;
// break;
// }
// }
// if (!got)
// list.add(zone);
list.add(zone);
}
}
// Create a sorted list of all the offsets.
Set<Integer> keySet = zoneMap.keySet();
Integer[] keys = new Integer[keySet.size()];
keySet.toArray(keys);
java.util.Arrays.sort(keys);
// Now build the key-value list of timezones.
zoneList = new ArrayList<HashMap<String, String>>();
// Add an extra zone if requested.
if (intent != null) {
String id = intent.getStringExtra("addZoneId");
String off = intent.getStringExtra("addZoneOff");
if (off == null)
off = "";
if (id != null) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", id);
map.put("offset", off);
zoneList.add(map);
}
}
// Add system zones.
for (int offset : keys) {
ArrayList<TimeZone> list = zoneMap.get(offset);
for (TimeZone zone : list) {
HashMap<String, String> map = new HashMap<String, String>();
// TODO: we really want the display name, when it works.
// map.put("name", zone.getDisplayName());
map.put("id", zone.getID());
map.put("name", zone.getID());
map.put("offset", TimeUtils.formatOffset(zone));
zoneList.add(map);
}
}
}
// ******************************************************************** //
// Listener.
// ******************************************************************** //
/**
* This method will be called when an item in the list is selected.
* Subclasses can call getListView().getItemAtPosition(position) if
* they need to access the data associated with the selected item.
*
* @param l The ListView where the click happened.
* @param v The view that was clicked within the ListView.
* @param position The position of the view in the list.
* @param id The row id of the item that was clicked.
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Get the zone that was clicked.
HashMap<String, String> item = zoneList.get(position);
// Create an intent containing the return data.
Intent data = new Intent();
data.putExtra("zoneId", item.get("id"));
// And return to the calling activity.
setResult(RESULT_OK, data);
finish();
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Crappy hardwired list of timezones and their user-visible names.
// See the note in listZones().
private static final String[][] HARD_ZONES = {
{ "Pacific/Majuro", "Marshall Islands" },
{ "Pacific/Midway", "Midway Island" },
{ "Pacific/Honolulu", "Hawaii" },
{ "America/Anchorage", "Alaska" },
{ "America/Los_Angeles", "Pacific Time" },
{ "America/Tijuana", "Tijuana" },
{ "America/Phoenix", "Arizona" },
{ "America/Chihuahua", "Chihuahua" },
{ "America/Denver", "Mountain Time" },
{ "America/Costa_Rica", "Central America" },
{ "America/Chicago", "Central Time" },
{ "America/Mexico_City", "Mexico City" },
{ "America/Regina", "Saskatchewan" },
{ "America/Bogota", "Bogota" },
{ "America/New_York", "Eastern Time" },
{ "America/Caracas", "Venezuela" },
{ "America/Barbados", "Atlantic Time" },
{ "America/Manaus", "Manaus" },
{ "America/Santiago", "Santiago" },
{ "America/St_Johns", "Newfoundland" },
{ "America/Araguaina", "Brasilia" },
{ "America/Argentina/Buenos_Aires", "Buenos Aires" },
{ "America/Godthab", "Greenland" },
{ "America/Montevideo", "Montevideo" },
{ "Atlantic/South_Georgia", "Mid-Atlantic" },
{ "Atlantic/Azores", "Azores" },
{ "Atlantic/Cape_Verde", "Cape Verde Islands" },
{ "Africa/Casablanca", "Casablanca" },
{ "Europe/London", "London, Dublin" },
{ "Europe/Amsterdam", "Amsterdam, Berlin" },
{ "Europe/Belgrade", "Belgrade" },
{ "Europe/Brussels", "Brussels" },
{ "Europe/Sarajevo", "Sarajevo" },
{ "Africa/Windhoek", "Windhoek" },
{ "Africa/Brazzaville", "W. Africa Time" },
{ "Asia/Amman", "Amman, Jordan" },
{ "Europe/Athens", "Athens, Istanbul" },
{ "Asia/Beirut", "Beirut, Lebanon" },
{ "Africa/Cairo", "Cairo" },
{ "Europe/Helsinki", "Helsinki" },
{ "Asia/Jerusalem", "Jerusalem" },
{ "Europe/Minsk", "Minsk" },
{ "Africa/Harare", "Harare" },
{ "Asia/Baghdad", "Baghdad" },
{ "Europe/Moscow", "Moscow" },
{ "Asia/Kuwait", "Kuwait" },
{ "Africa/Nairobi", "Nairobi" },
{ "Asia/Tehran", "Tehran" },
{ "Asia/Baku", "Baku" },
{ "Asia/Tbilisi", "Tbilisi" },
{ "Asia/Yerevan", "Yerevan" },
{ "Asia/Dubai", "Dubai" },
{ "Asia/Kabul", "Kabul" },
{ "Asia/Karachi", "Islamabad, Karachi" },
{ "Asia/Oral", "Ural'sk" },
{ "Asia/Yekaterinburg", "Yekaterinburg" },
{ "Asia/Calcutta", "Kolkata" },
{ "Asia/Colombo", "Sri Lanka" },
{ "Asia/Katmandu", "Kathmandu" },
{ "Asia/Almaty", "Astana" },
{ "Asia/Rangoon", "Yangon" },
{ "Asia/Krasnoyarsk", "Krasnoyarsk" },
{ "Asia/Bangkok", "Bangkok" },
{ "Asia/Hong_Kong", "Beijing, Hong Kong" },
{ "Asia/Irkutsk", "Irkutsk" },
{ "Asia/Kuala_Lumpur", "Kuala Lumpur" },
{ "Australia/Perth", "Perth" },
{ "Asia/Taipei", "Taipei" },
{ "Asia/Seoul", "Seoul" },
{ "Asia/Tokyo", "Tokyo, Osaka" },
{ "Asia/Yakutsk", "Yakutsk" },
{ "Australia/Adelaide", "Adelaide" },
{ "Australia/Darwin", "Darwin" },
{ "Australia/Brisbane", "Brisbane" },
{ "Australia/Hobart", "Hobart" },
{ "Australia/Sydney", "Sydney, Canberra" },
{ "Asia/Vladivostok", "Vladivostok" },
{ "Pacific/Guam", "Guam" },
{ "Asia/Magadan", "Magadan" },
{ "Pacific/Auckland", "Auckland" },
{ "Pacific/Fiji", "Fiji" },
{ "Pacific/Tongatapu", "Tonga" },
};
// Mapping of all the timezones we're interested in. This is a mapping
// of time zone offsets to timezones which have that raw offset.
private static HashMap<Integer, ArrayList<TimeZone>> zoneMap = null;
// Listing of all the timezones we're interested in. This is a list
// of maps, each of which represents one zone. Each mapping maps
// field names to values.
private static ArrayList<HashMap<String, String>> zoneList = null;
}
| 11,427 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
MultistateImageButton.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/MultistateImageButton.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;
/**
* This class displays an image button which toggles or cycles through
* multiple states when clicked.
*/
public class MultistateImageButton
extends ImageButton
{
// ******************************************************************** //
// Constructors.
// ******************************************************************** //
/**
* Create a multistate image button with a specified set of image
* resource IDs.
*
* @param context Parent application.
* @param images Resource IDs of the images to use for each
* state.
*/
public MultistateImageButton(Context context, int[] images) {
super(context);
init(images);
}
/**
* Create a multistate image button with a specified set of image
* resource IDs.
*
* @param context Parent application.
* @param attrs Layout attributes.
* @param images Resource IDs of the images to use for each
* state.
*/
public MultistateImageButton(Context context, AttributeSet attrs, int[] images) {
super(context, attrs);
init(images);
}
private void init(int[] images) {
imageIds = images;
setClickable(true);
setState(0);
// Register ourselves as the listener for clicks.
super.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
setState((currentState + 1) % imageIds.length);
if (clientListener != null)
clientListener.onClick(arg0);
}
});
}
// ******************************************************************** //
// Listener.
// ******************************************************************** //
/**
* Register a callback to be invoked when this view is clicked.
* If this view is not clickable, it becomes clickable.
*
* We override this here because we are using the parent class's
* listener slot for our own purposes.
*
* @param l The callback that will run.
*/
@Override
public void setOnClickListener(OnClickListener l) {
clientListener = l;
setClickable(true);
}
// ******************************************************************** //
// Control.
// ******************************************************************** //
/**
* Get the current state of this button.
*
* @return The current state, as an index into the list
* of images.
*/
public int getState() {
return currentState;
}
/**
* Set the current state of this button.
*
* @param s State to set, as an index into the list of images.
*/
public void setState(int s) {
currentState = s;
setImageResource(imageIds[currentState]);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "onwatch";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The resource IDs of the images for each state.
private int[] imageIds;
// Listener which the client has registered for click events. Null
// if not set.
private OnClickListener clientListener = null;
// The current state, as an index into imageIDs.
private int currentState;
}
| 4,047 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
NumberPicker.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/widgets/NumberPicker.java |
/**
* widgets: useful add-on widgets for Android.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.widgets;
import org.hermit.android.R;
import android.content.Context;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A view for selecting a number
*
* For a dialog using this view, see {@link android.app.TimePickerDialog}.
* @hide
*/
public class NumberPicker
extends LinearLayout
{
/**
* The callback interface used to indicate the number value has been adjusted.
*/
public interface OnValueChangeListener {
/**
* @param picker The NumberPicker associated with this listener.
* @param oldVal The previous value.
* @param newVal The new value.
*/
void onValueChange(NumberPicker picker, int oldVal, int newVal);
}
/**
* Interface used to format the number into a string for presentation
*/
public interface Formatter {
public String format(int value);
}
private final Handler mHandler;
private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (mIncrement) {
changeCurrent(mCurrent + 1);
mHandler.postDelayed(this, mSpeed);
} else if (mDecrement) {
changeCurrent(mCurrent - 1);
mHandler.postDelayed(this, mSpeed);
}
}
};
private final EditText mText;
private final InputFilter mNumberInputFilter;
/**
* Lower value of the range of numbers allowed for the NumberPicker
*/
private int mStart;
/**
* Upper value of the range of numbers allowed for the NumberPicker
*/
private int mEnd;
/**
* Current value of this NumberPicker
*/
private int mCurrent;
/**
* Previous value of this NumberPicker.
*/
private int mPrevious;
private OnValueChangeListener mListener;
private Formatter mFormatter;
private long mSpeed = 300;
private boolean mIncrement;
private boolean mDecrement;
/**
* Create a new number picker
* @param context the application environment
*/
public NumberPicker(Context context) {
this(context, null);
}
/**
* Create a new number picker
* @param context the application environment
* @param attrs a collection of attributes
*/
public NumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(LinearLayout.VERTICAL);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.number_picker, this, true);
mHandler = new Handler();
OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
validateInput(mText);
if (!mText.hasFocus()) mText.requestFocus();
// now perform the increment/decrement
if (R.id.increment == v.getId()) {
changeCurrent(mCurrent + 1);
} else if (R.id.decrement == v.getId()) {
changeCurrent(mCurrent - 1);
}
}
};
OnFocusChangeListener focusListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (!hasFocus) {
validateInput(v);
}
}
};
OnLongClickListener longClickListener = new OnLongClickListener() {
/**
* We start the long click here but rely on the {@link NumberPickerButton}
* to inform us when the long click has ended.
*/
@Override
public boolean onLongClick(View v) {
/* The text view may still have focus so clear it's focus which will
* trigger the on focus changed and any typed values to be pulled.
*/
mText.clearFocus();
if (R.id.increment == v.getId()) {
mIncrement = true;
mHandler.post(mRunnable);
} else if (R.id.decrement == v.getId()) {
mDecrement = true;
mHandler.post(mRunnable);
}
return true;
}
};
InputFilter inputFilter = new NumberPickerInputFilter();
mNumberInputFilter = new NumberRangeKeyListener();
mIncrementButton = (NumberPickerButton) findViewById(R.id.increment);
mIncrementButton.setOnClickListener(clickListener);
mIncrementButton.setOnLongClickListener(longClickListener);
mIncrementButton.setNumberPicker(this);
mDecrementButton = (NumberPickerButton) findViewById(R.id.decrement);
mDecrementButton.setOnClickListener(clickListener);
mDecrementButton.setOnLongClickListener(longClickListener);
mDecrementButton.setNumberPicker(this);
mText = (EditText) findViewById(R.id.timepicker_input);
mText.setOnFocusChangeListener(focusListener);
mText.setFilters(new InputFilter[] {inputFilter});
mText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
if (!isEnabled()) {
setEnabled(false);
}
}
/**
* Set the enabled state of this view. The interpretation of the enabled
* state varies by subclass.
*
* @param enabled True if this view is enabled, false otherwise.
*/
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mIncrementButton.setEnabled(enabled);
mDecrementButton.setEnabled(enabled);
mText.setEnabled(enabled);
}
/**
* Set the callback that indicates the number has been adjusted by the user.
* @param listener the callback, should not be null.
*/
public void setOnValueChangedListener(OnValueChangeListener listener) {
mListener = listener;
}
/**
* Set the formatter that will be used to format the number for presentation
* @param formatter the formatter object. If formatter is null, String.valueOf()
* will be used
*/
public void setFormatter(Formatter formatter) {
mFormatter = formatter;
}
public void setMinValue(int start) {
mStart = start;
mCurrent = start;
updateView();
}
public void setMaxValue(int end) {
mEnd = end;
updateView();
}
/**
* Set the current value for the number picker.
*
* @param current the current value the start of the range (inclusive)
* @throws IllegalArgumentException when current is not within the range
* of of the number picker
*/
public void setValue(int current) {
if (current < mStart || current > mEnd) {
throw new IllegalArgumentException(
"current should be >= start and <= end");
}
mCurrent = current;
updateView();
}
/**
* Sets the speed at which the numbers will scroll when the +/-
* buttons are longpressed
*
* @param speed The speed (in milliseconds) at which the numbers will scroll
* default 300ms
*/
public void setOnLongPressUpdateInterval(long speed) {
mSpeed = speed;
}
private String formatNumber(int value) {
return mFormatter != null ? mFormatter.format(value) : String.valueOf(value);
}
/**
* Sets the current value of this NumberPicker, and sets mPrevious to the previous
* value. If current is greater than mEnd less than mStart, the value of mCurrent
* is wrapped around.
*
* Subclasses can override this to change the wrapping behavior
*
* @param current the new value of the NumberPicker
*/
protected void changeCurrent(int current) {
// Wrap around the values if we go past the start or end
if (current > mEnd) {
current = mStart;
} else if (current < mStart) {
current = mEnd;
}
mPrevious = mCurrent;
mCurrent = current;
notifyChange();
updateView();
}
/**
* Notifies the listener, if registered, of a change of the value of this
* NumberPicker.
*/
private void notifyChange() {
if (mListener != null) {
mListener.onValueChange(this, mPrevious, mCurrent);
}
}
/**
* Updates the view of this NumberPicker. If displayValues were specified
* in {@link #setRange}, the string corresponding to the index specified by
* the current value will be returned. Otherwise, the formatter specified
* in {@link setFormatter} will be used to format the number.
*/
private void updateView() {
/* If we don't have displayed values then use the
* current number else find the correct value in the
* displayed values for the current number.
*/
mText.setText(formatNumber(mCurrent));
mText.setSelection(mText.getText().length());
}
private void validateCurrentView(CharSequence str) {
int val = getSelectedPos(str.toString());
if ((val >= mStart) && (val <= mEnd)) {
if (mCurrent != val) {
mPrevious = mCurrent;
mCurrent = val;
notifyChange();
}
}
updateView();
}
private void validateInput(View v) {
String str = String.valueOf(((TextView) v).getText());
if ("".equals(str)) {
// Restore to the old value as we don't allow empty values
updateView();
} else {
// Check the new value and ensure it's in range
validateCurrentView(str);
}
}
/**
* @hide
*/
public void cancelIncrement() {
mIncrement = false;
}
/**
* @hide
*/
public void cancelDecrement() {
mDecrement = false;
}
private static final char[] DIGIT_CHARACTERS = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private NumberPickerButton mIncrementButton;
private NumberPickerButton mDecrementButton;
private class NumberPickerInputFilter implements InputFilter {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
return mNumberInputFilter.filter(source, start, end, dest, dstart, dend);
}
}
private class NumberRangeKeyListener extends NumberKeyListener {
// XXX This doesn't allow for range limits when controlled by a
// soft input method!
@Override
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER;
}
@Override
protected char[] getAcceptedChars() {
return DIGIT_CHARACTERS;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
CharSequence filtered = super.filter(source, start, end, dest, dstart, dend);
if (filtered == null) {
filtered = source.subSequence(start, end);
}
String result = String.valueOf(dest.subSequence(0, dstart))
+ filtered
+ dest.subSequence(dend, dest.length());
if ("".equals(result)) {
return result;
}
int val = getSelectedPos(result);
/* Ensure the user can't type in a value greater
* than the max allowed. We have to allow less than min
* as the user might want to delete some numbers
* and then type a new number.
*/
if (val > mEnd) {
return "";
} else {
return filtered;
}
}
}
private int getSelectedPos(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
/* Ignore as if it's not a number we don't care */
}
return mStart;
}
/**
* Returns the current value of the NumberPicker
* @return the current value.
*/
public int getCurrent() {
return mCurrent;
}
/**
* Returns the upper value of the range of the NumberPicker
* @return the uppper number of the range.
*/
protected int getEndRange() {
return mEnd;
}
/**
* Returns the lower value of the range of the NumberPicker
* @return the lower number of the range.
*/
protected int getBeginRange() {
return mStart;
}
}
| 13,755 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SonagramGauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/SonagramGauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
/**
* A graphical display which displays the audio sonarum from an
* {@link AudioAnalyser} instrument. This class cannot be instantiated
* directly; get an instance by calling
* {@link AudioAnalyser#getSpectrumGauge(SurfaceRunner)}.
*/
public class SonagramGauge
extends Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a SpectrumGauge. This constructor is package-local, as
* public users get these from an {@link AudioAnalyser} instrument.
*
* @param parent Parent surface.
* @param rate The input sample rate, in samples/sec.
*/
SonagramGauge(SurfaceRunner parent, int rate,int inputBlockSize) {
super(parent);
blockSize=inputBlockSize;
setSampleRate(rate);
//Colors for Sonagram
for (int i=0;i<50;i++)
paintColors[i]= Color.rgb(0, i , i*5);
for (int i=50;i<100;i++)
paintColors[i]= Color.rgb(0, i , (100-i)*5);
for (int i=100;i<150;i++)
paintColors[i]= Color.rgb((i-100)*3, (i-50)*2 , 0);
for (int i=150;i<=250;i++)
paintColors[i]= Color.rgb(i, 550-i*2 , 0);
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set the sample rate for this instrument.
*
* @param rate The desired rate, in samples/sec.
*/
public void setSampleRate(int rate) {
period=(float)(1f / rate)*blockSize*2;
nyquistFreq = rate / 2;
// If we have a size, then we have a background. Re-draw it
// to show the new frequency scale.
if (haveBounds())
drawBg(bgCanvas, getPaint());
}
/**
* Set the size for the label text.
*
* @param size Label text size for the gauge.
*/
public void setLabelSize(float size) {
labelSize = size;
}
/**
* Get the size for the label text.
*
* @return Label text size for the gauge.
*/
public float getLabelSize() {
return labelSize;
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
dispX = bounds.left;
dispY = bounds.top;
dispWidth = bounds.width();
dispHeight = bounds.height();
// Do some layout within the meter.
int mw = dispWidth;
int mh = dispHeight;
if (labelSize == 0f)
labelSize = mw / 24f;
sonaGraphX = 0;
sonaGraphY = 3;
sonaGraphWidth = mw - labelSize * 2;
sonaGraphHeight = mh - labelSize - 6 ;
// Create the bitmap for the sonagram display,
// and the Canvas for drawing into it.
finalBitmap = getSurface().getBitmap(dispWidth, dispHeight);
finalCanvas = new Canvas(finalBitmap);
// Create the bitmap for the sonagram display,
// and the Canvas for drawing into it.
sonaBitmap = getSurface().getBitmap((int) sonaGraphWidth, (int) sonaGraphHeight);
sonaCanvas = new Canvas(sonaBitmap);
// Create the bitmap for the background,
// and the Canvas for drawing into it.
bgBitmap = getSurface().getBitmap(dispWidth, dispHeight);
bgCanvas = new Canvas(bgBitmap);
drawBg(bgCanvas, getPaint());
}
// ******************************************************************** //
// Background Drawing.
// ******************************************************************** //
/**
* Do the subclass-sonaific parts of drawing the background
* for this element. Subclasses should override
* this if they have significant background content which they would
* like to draw once only. Whatever is drawn here will be saved in
* a bitmap, which will be rendered to the screen before the
* dynamic content is drawn.
*
* <p>Obviously, if implementing this method, don't clear the screen when
* drawing the dynamic part.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
*/
private void drawBg(Canvas canvas, Paint paint) {
float lx;
float ly;
canvas.drawColor(0xff000000);
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
// Draw the grid.
final float sx = sonaGraphX;
final float sy = sonaGraphY;
final float bw = sonaGraphWidth - 1;
final float bh = sonaGraphHeight - 1;
// Draw freq.
lx = sx + bw + 1;
for (int i = 0; i <= 10; i += 1) {
int f = nyquistFreq * i / 10;
String text = f >= 10000 ? "" + (f / 1000) + "k" :
f >= 1000 ? "" + (f / 1000) + "." + (f / 100 % 10) + "k" :
"" + f;
ly = sy + bh - i * (float) bh / 10f + 1;
canvas.drawText(text, lx + 7, ly + labelSize/3, paint);
canvas.drawLine(lx, ly, lx+3, ly, paint);
}
// Draw time.
ly = sy + bh + labelSize + 1;
float totaltime=(float)Math.floor(bw*period);
for (int i = 0; i <= 9; i += 1) {
float time = totaltime * i / 10;
String text = "" + time + "s";
float tw = paint.measureText(text);
lx = sx + i * (float) bw / 10f + 1;
canvas.drawText(text, lx - (tw / 2), ly, paint);
canvas.drawLine(lx, sy + bh-1, lx, sy + bh + 2, paint);
}
}
// ******************************************************************** //
// Data Updates.
// ******************************************************************** //
/**
* New data from the instrument has arrived. This method is called
* on the thread of the instrument.
*
* @param data An array of floats defining the signal power
* at each frequency in the sonagram.
*/
final void update(float[] data) {
final Canvas canvas = finalCanvas;
final Paint paint = getPaint();
// Now actually do the drawing.
synchronized (this) {
//Background
canvas.drawBitmap(bgBitmap, 0, 0, paint);
//Scroll
sonaCanvas.drawBitmap(sonaBitmap, 1, 0, paint);
//Add Current Data
linearGraph(data, sonaCanvas, paint);
canvas.drawBitmap(sonaBitmap, sonaGraphX, sonaGraphY, paint);
}
}
/**
* Draw a linear sonagram graph.
*
* @param data An array of floats defining the signal power
* at each frequency in the sonagram.
* @param canvas Canvas to draw into.
* @param paint Paint to draw with.
*/
private void linearGraph(float[] data, Canvas canvas, Paint paint) {
paint.setStyle(Style.FILL);
final int len = data.length;
final float bh = (float) sonaGraphHeight / (float) len;
// Element 0 isn't a frequency bucket; skip it.
for (int i = 1; i < len; ++i) {
// Draw the new line.
final float y = sonaGraphHeight- i * bh + 1;
// Cycle the hue angle from 0° to 300°; i.e. red to purple.
float v = (float) (Math.log10(data[i]) / RANGE_BELS + 2f);
int colorIndex=(int)(v*maxColors);
if (colorIndex<0)
colorIndex=0;
if (colorIndex>maxColors)
colorIndex=maxColors;
paint.setColor(paintColors[colorIndex]);
if (bh <= 1.0f)
canvas.drawPoint(0, y, paint);
else
canvas.drawLine(0, y, 0, y - bh, paint);
}
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* Do the subclass-sonaific parts of drawing for this element.
* This method is called on the thread of the containing SuraceView.
*
* <p>Subclasses should override this to do their drawing.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected final void drawBody(Canvas canvas, Paint paint, long now) {
// Since drawBody may be called more often than we get audio
// data, it makes sense to just draw the buffered image here.
synchronized (this) {
canvas.drawBitmap(finalBitmap, dispX, dispY, null);
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// Vertical range of the graph in bels.
private static final float RANGE_BELS = 2f;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The Nyquist frequency -- the highest frequency
// represented in the sonarum data we will be plotting.
private int nyquistFreq = 0;
private int blockSize = 0;
private float period = 0;
// Display position and size within the parent view.
private int dispX = 0;
private int dispY = 0;
private int dispWidth = 0;
private int dispHeight = 0;
// Label text size for the gauge. Zero means not set yet.
private float labelSize = 0f;
// Layout parameters for the VU meter. Position and size for the
// bar itself; position and size for the bar labels; position
// and size for the main readout text.
private float sonaGraphX = 0;
private float sonaGraphY = 0;
private float sonaGraphWidth = 0;
private float sonaGraphHeight = 0;
// Bitmap in which we draw the gauge background,
// and the Canvas and Paint for drawing into it.
private Bitmap bgBitmap = null;
private Canvas bgCanvas = null;
// Bitmap in which we draw the audio sonagram display,
// and the Canvas and Paint for drawing into it.
private Bitmap sonaBitmap = null;
private Canvas sonaCanvas = null;
// Bitmap in which we draw the audio sonagram display,
// and the Canvas and Paint for drawing into it.
private Bitmap finalBitmap = null;
private Canvas finalCanvas = null;
// Buffer for calculating the draw colour from H,S,V values.
private final int[] paintColors= new int[251];
private final int maxColors=250;
}
| 12,387 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
InstrumentSurface.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/InstrumentSurface.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import java.util.ArrayList;
import org.hermit.android.core.SurfaceRunner;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* Common base for applications which display instruments. This class is
* an extension of {@link SurfaceRunner} which provides additional
* functions to manage the instruments embedded in it.
*
* <p>When using this class in an app, the app context <b>must</b> call
* these methods (usually from its corresponding Activity methods):
*
* <ul>
* <li>{@link #onStart()}
* <li>{@link #onResume()}
* <li>{@link #onPause()}
* <li>{@link #onStop()}
* </ul>
*
* <p>The surface is enabled once it is created and sized, and
* {@link #onStart()} and {@link #onResume()} have been called. You then
* start and stop it by calling {@link #surfaceStart()} and
* {@link #surfaceStop()}.
*/
public abstract class InstrumentSurface
extends SurfaceRunner
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Instrument Surface runner option: cache a background bitmap. If set,
* we will ask all the gauges to draw their backgrounds into a full-
* screen bitmap; this bitmap will then be drawn prior to drawing the
* gauge contents each frame.
*/
public static final int SURFACE_CACHE_BG = 0x0100;
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a SurfaceRunner instance.
*
* @param app The application context we're running in.
*/
public InstrumentSurface(Activity app) {
super(app);
init();
}
/**
* Create a SurfaceRunner instance.
*
* @param app The application context we're running in.
* @param options Options for this SurfaceRunner. A bitwise OR of
* SURFACE_XXX constants.
*/
public InstrumentSurface(Activity app, int options) {
super(app, options);
init();
}
/**
* Do initialisation of this class.
*/
private void init() {
instruments = new ArrayList<Instrument>();
gauges = new ArrayList<Gauge>();
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Add an instrument to the system, associated with this surface.
* Is is presumed that the app will create one or more {@link Gauge}s
* for this instrument and add them to the surface with
* {@link #addGauge(Gauge)}.
*
* <p>All instruments added here will be started and stopped when the
* application starts and stops, and will have their measurement turned
* on when the app is visible and running. Their
* {@link Instrument#doUpdate(long)} method will be called each
* time round the main animation loop.
*
* <p>All instruments must be added before the application starts running.
*
* @param i The instrument to add.
*/
public void addInstrument(Instrument i) {
instruments.add(i);
}
/**
* Add a gauge to this surface. If this gauge has an associated
* {@link Instrument}, it should be attached to the surface with
* {@link #addInstrument(Instrument)}.
*
* <p>All gauges added here will have their
* {@link Gauge#draw(Canvas, long, boolean)} method called each
* time round the main animation loop.
*
* <p>All gauges must be added before the application starts running.
*
* @param i The gauge to add.
*/
public void addGauge(Gauge i) {
gauges.add(i);
}
/**
* Remove all gauges from this surface.
*/
public void clearGauges() {
gauges.clear();
}
// ******************************************************************** //
// Layout Processing.
// ******************************************************************** //
/**
* Lay out the display for a given screen size. Subclasses must
* implement this, and should use it to lay out the gauges.
*
* @param width The new width of the surface.
* @param height The new height of the surface.
*/
protected abstract void layout(int width, int height);
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* The application is starting. Perform any initial set-up prior to
* starting the application. We may not have a screen size yet,
* so this is not a good place to allocate resources which depend on
* that.
*
* <p>If subclasses override this, they must call through to this method.
*/
@Override
protected void appStart() {
for (Instrument i : instruments)
i.appStart();
}
/**
* Set the screen size. This is guaranteed to be called before
* animStart(), but perhaps not before appStart().
*
* <p>We call the layout() method here, so subclasses generally don't
* need to override this. If subclasses do override this,
* they must call through to this method.
*
* @param width The new width of the surface.
* @param height The new height of the surface.
* @param config The pixel format of the surface.
*/
@Override
protected void appSize(int width, int height, Bitmap.Config config) {
layout(width, height);
// Set up our background bitmap.
setBackground(width, height);
}
/**
* We are starting the animation loop. The screen size is known.
*
* <p>doUpdate() and doDraw() may be called from this point on.
*
* <p>If subclasses override this, they must call through to this method.
*/
@Override
protected void animStart() {
// Make arrays of the instruments and gauges for faster access.
instrumentArray = new Instrument[instruments.size()];
instruments.toArray(instrumentArray);
gaugeArray = new Gauge[gauges.size()];
gauges.toArray(gaugeArray);
// Start measurement on all the instruments.
for (int i = 0; i < instrumentArray.length; ++i)
instrumentArray[i].measureStart();
}
/**
* We are stopping the animation loop, for example to pause the app.
*
* <p>doUpdate() and doDraw() will not be called from this point on.
*
* <p>If subclasses override this, they must call through to this method.
*/
@Override
protected void animStop() {
// Stop measurement on all the instruments.
for (int i = 0; i < instrumentArray.length; ++i)
instrumentArray[i].measureStop();
}
/**
* The application is closing down. Clean up any resources.
*/
@Override
protected void appStop() {
for (Instrument i : instruments)
i.appStop();
}
// ******************************************************************** //
// Graphics Setup.
// ******************************************************************** //
/**
* Set up our background bitmap.
*
* @param width The width of the surface.
* @param height The height of the surface.
*/
private void setBackground(int width, int height) {
if (optionSet(SURFACE_CACHE_BG)) {
// Create the bitmap for the background,
// and the Canvas for drawing into it.
backgroundBitmap = getBitmap(width, height);
backgroundCanvas = new Canvas(backgroundBitmap);
// Get the gauges to draw their backgrounds in to the bitmap.
backgroundCanvas.drawColor(0xff000000);
for (Gauge g : gauges)
g.drawBackground(backgroundCanvas);
} else {
backgroundBitmap = null;
backgroundCanvas = null;
}
}
// ******************************************************************** //
// Main Processing Loop.
// ******************************************************************** //
/**
* Update the state of the application for the current frame.
*
* <p>Applications must override this, and can use it to update
* for example the physics of a game. This may be a no-op in some cases.
*
* <p>doDraw() will always be called after this method is called;
* however, the converse is not true, as we sometimes need to draw
* just to update the screen. Hence this method is useful for
* updates which are dependent on time rather than frames.
*
* @param now Nominal time of the current frame in ms.
*/
@Override
protected void doUpdate(long now) {
final int il = instrumentArray.length;
for (int i = 0; i < il; ++i)
instrumentArray[i].doUpdate(now);
}
/**
* Draw the current frame of the application.
*
* <p>Applications must override this, and are expected to draw the
* entire screen into the provided canvas.
*
* <p>This method will always be called after a call to doUpdate(),
* and also when the screen needs to be re-drawn.
*
* @param canvas The Canvas to draw into.
* @param now Nominal time of the current frame in ms.
*/
@Override
protected void doDraw(Canvas canvas, long now) {
// Draw the background on to the screen.
if (backgroundBitmap != null)
canvas.drawBitmap(backgroundBitmap, 0, 0, null);
else
canvas.drawColor(0xff000000);
final boolean needBg = backgroundBitmap == null;
// Draw the gauges over the background.
final int gl = gaugeArray.length;
for (int g = 0; g < gl; ++g)
gaugeArray[g].draw(canvas, now, needBg);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The instruments and gauges associated with this surface.
private ArrayList<Instrument> instruments = null;
private ArrayList<Gauge> gauges = null;
// The lists of instruments and gauges in array form for fast access.
private Instrument[] instrumentArray = null;
private Gauge[] gaugeArray = null;
// Bitmap in which we draw the audio waveform display,
// and the Canvas and Paint for drawing into it. Only used if
// OPTION_CACHE_BG is set; otherwise null.
private Bitmap backgroundBitmap = null;
private Canvas backgroundCanvas = null;
}
| 12,157 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SpectrumGauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/SpectrumGauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
/**
* A graphical display which displays the audio spectrum from an
* {@link AudioAnalyser} instrument. This class cannot be instantiated
* directly; get an instance by calling
* {@link AudioAnalyser#getSpectrumGauge(SurfaceRunner)}.
*/
public class SpectrumGauge
extends Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a SpectrumGauge. This constructor is package-local, as
* public users get these from an {@link AudioAnalyser} instrument.
*
* @param parent Parent surface.
* @param rate The input sample rate, in samples/sec.
*/
SpectrumGauge(SurfaceRunner parent, int rate) {
super(parent);
nyquistFreq = rate / 2;
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set the sample rate for this instrument.
*
* @param rate The desired rate, in samples/sec.
*/
public void setSampleRate(int rate) {
nyquistFreq = rate / 2;
// If we have a size, then we have a background. Re-draw it
// to show the new frequency scale.
if (haveBounds())
drawBg(bgCanvas, getPaint());
}
/**
* Set the size for the label text.
*
* @param size Label text size for the gauge.
*/
public void setLabelSize(float size) {
labelSize = size;
}
/**
* Get the size for the label text.
*
* @return Label text size for the gauge.
*/
public float getLabelSize() {
return labelSize;
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
dispX = bounds.left;
dispY = bounds.top;
dispWidth = bounds.width();
dispHeight = bounds.height();
// Do some layout within the meter.
int mw = dispWidth;
int mh = dispHeight;
if (labelSize == 0f)
labelSize = mw / 24f;
spectLabY = mh - 4;
spectGraphMargin = labelSize;
spectGraphX = spectGraphMargin;
spectGraphY = 0;
spectGraphWidth = mw - spectGraphMargin * 2;
spectGraphHeight = mh - labelSize - 6;
// Create the bitmap for the spectrum display,
// and the Canvas for drawing into it.
specBitmap = getSurface().getBitmap(dispWidth, dispHeight);
specCanvas = new Canvas(specBitmap);
// Create the bitmap for the background,
// and the Canvas for drawing into it.
bgBitmap = getSurface().getBitmap(dispWidth, dispHeight);
bgCanvas = new Canvas(bgBitmap);
drawBg(bgCanvas, getPaint());
}
// ******************************************************************** //
// Background Drawing.
// ******************************************************************** //
/**
* Do the subclass-specific parts of drawing the background
* for this element. Subclasses should override
* this if they have significant background content which they would
* like to draw once only. Whatever is drawn here will be saved in
* a bitmap, which will be rendered to the screen before the
* dynamic content is drawn.
*
* <p>Obviously, if implementing this method, don't clear the screen when
* drawing the dynamic part.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
*/
private void drawBg(Canvas canvas, Paint paint) {
canvas.drawColor(0xff000000);
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
// Draw the grid.
final float sx = 0 + spectGraphX;
final float sy = 0 + spectGraphY;
final float ex = sx + spectGraphWidth - 1;
final float ey = sy + spectGraphHeight - 1;
final float bw = spectGraphWidth - 1;
final float bh = spectGraphHeight - 1;
canvas.drawRect(sx, sy, ex, ey, paint);
for (int i = 1; i < 10; ++i) {
final float x = (float) i * (float) bw / 10f;
canvas.drawLine(sx + x, sy, sx + x, sy + bh, paint);
}
for (int i = 1; i < RANGE_BELS; ++i) {
final float y = (float) i * (float) bh / RANGE_BELS;
canvas.drawLine(sx, sy + y, sx + bw, sy + y, paint);
}
// Draw the labels below the grid.
final float ly = 0 + spectLabY;
paint.setTextSize(labelSize);
int step = paint.measureText("8.8k") > bw / 10f - 1 ? 2 : 1;
for (int i = 0; i <= 10; i += step) {
int f = nyquistFreq * i / 10;
String text = f >= 10000 ? "" + (f / 1000) + "k" :
f >= 1000 ? "" + (f / 1000) + "." + (f / 100 % 10) + "k" :
"" + f;
float tw = paint.measureText(text);
float lx = sx + i * (float) bw / 10f + 1 - (tw / 2);
canvas.drawText(text, lx, ly, paint);
}
}
// ******************************************************************** //
// Data Updates.
// ******************************************************************** //
/**
* New data from the instrument has arrived. This method is called
* on the thread of the instrument.
*
* @param data An array of floats defining the signal power
* at each frequency in the spectrum.
*/
final void update(float[] data) {
final Canvas canvas = specCanvas;
final Paint paint = getPaint();
// Now actually do the drawing.
synchronized (this) {
canvas.drawBitmap(bgBitmap, 0, 0, paint);
if (logFreqScale)
logGraph(data, canvas, paint);
else
linearGraph(data, canvas, paint);
}
}
/**
* Draw a linear spectrum graph.
*
* @param data An array of floats defining the signal power
* at each frequency in the spectrum.
* @param canvas Canvas to draw into.
* @param paint Paint to draw with.
*/
private void logGraph(float[] data, Canvas canvas, Paint paint) {
paint.setStyle(Style.FILL);
paintColor[1] = 1f;
paintColor[2] = 1f;
final int len = data.length;
final float bw = (float) (spectGraphWidth - 2) / (float) len;
final float bh = spectGraphHeight - 2;
final float be = spectGraphY + spectGraphHeight - 1;
// Determine the first and last frequencies we have.
final float lf = nyquistFreq / len;
final float rf = nyquistFreq;
// Now, how many octaves is that. Round down. Calculate pixels/oct.
final int octaves = (int) Math.floor(log2(rf / lf)) - 2;
final float octWidth = (float) (spectGraphWidth - 2) / (float) octaves;
// Calculate the base frequency for the graph, which isn't lf.
final float bf = rf / (float) Math.pow(2, octaves);
// Element 0 isn't a frequency bucket; skip it.
for (int i = 1; i < len; ++i) {
// Cycle the hue angle from 0° to 300°; i.e. red to purple.
paintColor[0] = (float) i / (float) len * 300f;
paint.setColor(Color.HSVToColor(paintColor));
// What frequency bucket are we in.
final float f = lf * i;
// For freq f, calculate x.
final float x = spectGraphX + (float) (log2(f) - log2(bf)) * octWidth;
// Draw the bar.
float y = be - (float) (Math.log10(data[i]) / RANGE_BELS + 1f) * bh;
if (y > be)
y = be;
else if (y < spectGraphY)
y = spectGraphY;
if (bw <= 1.0f)
canvas.drawLine(x, y, x, be, paint);
else
canvas.drawRect(x, y, x + bw, be, paint);
}
}
private final double log2(double x) {
return Math.log(x) / LOG2;
}
/**
* Draw a linear spectrum graph.
*
* @param data An array of floats defining the signal power
* at each frequency in the spectrum.
* @param canvas Canvas to draw into.
* @param paint Paint to draw with.
*/
private void linearGraph(float[] data, Canvas canvas, Paint paint) {
paint.setStyle(Style.FILL);
paintColor[1] = 1f;
paintColor[2] = 1f;
final int len = data.length;
final float bw = (float) (spectGraphWidth - 2) / (float) len;
final float bh = spectGraphHeight - 2;
final float be = spectGraphY + spectGraphHeight - 1;
// Element 0 isn't a frequency bucket; skip it.
for (int i = 1; i < len; ++i) {
// Cycle the hue angle from 0° to 300°; i.e. red to purple.
paintColor[0] = (float) i / (float) len * 300f;
paint.setColor(Color.HSVToColor(paintColor));
// Draw the bar.
final float x = spectGraphX + i * bw + 1;
float y = be - (float) (Math.log10(data[i]) / RANGE_BELS + 1f) * bh;
if (y > be)
y = be;
else if (y < spectGraphY)
y = spectGraphY;
if (bw <= 1.0f)
canvas.drawLine(x, y, x, be, paint);
else
canvas.drawRect(x, y, x + bw, be, paint);
}
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* Do the subclass-specific parts of drawing for this element.
* This method is called on the thread of the containing SuraceView.
*
* <p>Subclasses should override this to do their drawing.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected final void drawBody(Canvas canvas, Paint paint, long now) {
// Since drawBody may be called more often than we get audio
// data, it makes sense to just draw the buffered image here.
synchronized (this) {
canvas.drawBitmap(specBitmap, dispX, dispY, null);
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// Log of 2.
private static final double LOG2 = Math.log(2);
// Vertical range of the graph in bels.
private static final float RANGE_BELS = 6f;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The Nyquist frequency -- the highest frequency
// represented in the spectrum data we will be plotting.
private int nyquistFreq = 0;
// If true, draw a logarithmic frequency scale. Otherwise linear.
private static final boolean logFreqScale = false;
// Display position and size within the parent view.
private int dispX = 0;
private int dispY = 0;
private int dispWidth = 0;
private int dispHeight = 0;
// Label text size for the gauge. Zero means not set yet.
private float labelSize = 0f;
// Layout parameters for the VU meter. Position and size for the
// bar itself; position and size for the bar labels; position
// and size for the main readout text.
private float spectGraphX = 0;
private float spectGraphY = 0;
private float spectGraphWidth = 0;
private float spectGraphHeight = 0;
private float spectLabY = 0;
private float spectGraphMargin = 0;
// Bitmap in which we draw the gauge background,
// and the Canvas and Paint for drawing into it.
private Bitmap bgBitmap = null;
private Canvas bgCanvas = null;
// Bitmap in which we draw the audio spectrum display,
// and the Canvas and Paint for drawing into it.
private Bitmap specBitmap = null;
private Canvas specCanvas = null;
// Buffer for calculating the draw colour from H,S,V values.
private float[] paintColor = { 0, 1, 1 };
}
| 14,083 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Instrument.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/Instrument.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.os.Bundle;
/**
* An instrument which measures some quantity, or accesses or produces some
* data, which can be displayed on one or more {@link Gauge} objects.
*/
public class Instrument
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up this view.
*
* @param parent Parent surface.
*/
public Instrument(SurfaceRunner parent) {
parentSurface = parent;
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* The application is starting. Perform any initial set-up prior to
* starting the application.
*/
public void appStart() {
}
/**
* We are starting the main run; start measurements.
*/
public void measureStart() {
}
/**
* We are stopping / pausing the run; stop measurements.
*/
public void measureStop() {
}
/**
* The application is closing down. Clean up any resources.
*/
public void appStop() {
}
// ******************************************************************** //
// Main Loop.
// ******************************************************************** //
/**
* Update the state of the instrument for the current frame.
*
* <p>Instruments may override this, and can use it to read the
* current input state. This method is invoked in the main animation
* loop -- i.e. frequently.
*
* @param now Nominal time of the current frame in ms.
*/
protected void doUpdate(long now) {
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Get the app context of this Element.
*
* @return The app context we're running in.
*/
protected SurfaceRunner getSurface() {
return parentSurface;
}
// ******************************************************************** //
// Save and Restore.
// ******************************************************************** //
/**
* Save the state of the game in the provided Bundle.
*
* @param icicle The Bundle in which we should save our state.
*/
protected void saveState(Bundle icicle) {
// gameTable.saveState(icicle);
}
/**
* Restore the game state from the given Bundle.
*
* @param icicle The Bundle containing the saved state.
*/
protected void restoreState(Bundle icicle) {
// gameTable.pause();
// gameTable.restoreState(icicle);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The SurfaceRunner we're attached to.
private final SurfaceRunner parentSurface;
}
| 4,173 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AudioAnalyser.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/AudioAnalyser.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import org.hermit.android.io.AudioReader;
import org.hermit.dsp.FFTTransformer;
import org.hermit.dsp.SignalPower;
import org.hermit.dsp.Window;
import android.os.Bundle;
/**
* An {@link Instrument} which analyses an audio stream in various ways.
*
* <p>To use this class, your application must have permission RECORD_AUDIO.
*/
public class AudioAnalyser
extends Instrument
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a WindMeter instance.
*
* @param parent Parent surface.
*/
public AudioAnalyser(SurfaceRunner parent) {
super(parent);
parentSurface = parent;
audioReader = new AudioReader();
spectrumAnalyser = new FFTTransformer(inputBlockSize, windowFunction);
// Allocate the spectrum data.
spectrumData = new float[inputBlockSize / 2];
spectrumHist = new float[inputBlockSize / 2][historyLen];
spectrumIndex = 0;
biasRange = new float[2];
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set the sample rate for this instrument.
*
* @param rate The desired rate, in samples/sec.
*/
public void setSampleRate(int rate) {
sampleRate = rate;
// The spectrum gauge needs to know this.
if (spectrumGauge != null)
spectrumGauge.setSampleRate(sampleRate);
// The sonagram gauge needs to know this.
if (sonagramGauge != null)
sonagramGauge.setSampleRate(sampleRate);
}
/**
* Set the input block size for this instrument.
*
* @param size The desired block size, in samples. Typical
* values would be 256, 512, or 1024. Larger block
* sizes will mean more work to analyse the spectrum.
*/
public void setBlockSize(int size) {
inputBlockSize = size;
spectrumAnalyser = new FFTTransformer(inputBlockSize, windowFunction);
// Allocate the spectrum data.
spectrumData = new float[inputBlockSize / 2];
spectrumHist = new float[inputBlockSize / 2][historyLen];
}
/**
* Set the spectrum analyser windowing function for this instrument.
*
* @param func The desired windowing function.
* Window.Function.BLACKMAN_HARRIS is a good option.
* Window.Function.RECTANGULAR turns off windowing.
*/
public void setWindowFunc(Window.Function func) {
windowFunction = func;
spectrumAnalyser.setWindowFunc(func);
}
/**
* Set the decimation rate for this instrument.
*
* @param rate The desired decimation. Only 1 in rate blocks
* will actually be processed.
*/
public void setDecimation(int rate) {
sampleDecimate = rate;
}
/**
* Set the histogram averaging window for this instrument.
*
* @param len The averaging interval. 1 means no averaging.
*/
public void setAverageLen(int len) {
historyLen = len;
// Set up the history buffer.
spectrumHist = new float[inputBlockSize / 2][historyLen];
spectrumIndex = 0;
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* The application is starting. Perform any initial set-up prior to
* starting the application. We may not have a screen size yet,
* so this is not a good place to allocate resources which depend on
* that.
*/
@Override
public void appStart() {
}
/**
* We are starting the main run; start measurements.
*/
@Override
public void measureStart() {
audioProcessed = audioSequence = 0;
readError = AudioReader.Listener.ERR_OK;
audioReader.startReader(sampleRate, inputBlockSize * sampleDecimate, new AudioReader.Listener() {
@Override
public final void onReadComplete(short[] buffer) {
receiveAudio(buffer);
}
@Override
public void onReadError(int error) {
handleError(error);
}
});
}
/**
* We are stopping / pausing the run; stop measurements.
*/
@Override
public void measureStop() {
audioReader.stopReader();
}
/**
* The application is closing down. Clean up any resources.
*/
@Override
public void appStop() {
}
// ******************************************************************** //
// Gauges.
// ******************************************************************** //
/**
* Get a waveform gauge for this audio analyser.
*
* @param surface The surface in which the gauge will be displayed.
* @return A gauge which will display the audio waveform.
*/
public WaveformGauge getWaveformGauge(SurfaceRunner surface) {
if (waveformGauge != null)
throw new RuntimeException("Already have a WaveformGauge" +
" for this AudioAnalyser");
waveformGauge = new WaveformGauge(surface);
return waveformGauge;
}
/**
* Get a spectrum analyser gauge for this audio analyser.
*
* @param surface The surface in which the gauge will be displayed.
* @return A gauge which will display the audio waveform.
*/
public SpectrumGauge getSpectrumGauge(SurfaceRunner surface) {
if (spectrumGauge != null)
throw new RuntimeException("Already have a SpectrumGauge" +
" for this AudioAnalyser");
spectrumGauge = new SpectrumGauge(surface, sampleRate);
return spectrumGauge;
}
/**
* Get a sonagram analyser gauge for this audio analyser.
*
* @param surface The surface in which the gauge will be displayed.
* @return A gauge which will display the audio waveform
* as a sonogram.
*/
public SonagramGauge getSonagramGauge(SurfaceRunner surface) {
if (sonagramGauge != null)
throw new RuntimeException("Already have a SonagramGauge" +
" for this AudioAnalyser");
sonagramGauge = new SonagramGauge(surface, sampleRate, inputBlockSize);
return sonagramGauge;
}
/**
* Get a signal power gauge for this audio analyser.
*
* @param surface The surface in which the gauge will be displayed.
* @return A gauge which will display the signal power in
* a dB meter.
*/
public PowerGauge getPowerGauge(SurfaceRunner surface) {
if (powerGauge != null)
throw new RuntimeException("Already have a PowerGauge" +
" for this AudioAnalyser");
powerGauge = new PowerGauge(surface);
return powerGauge;
}
/**
* Reset all Gauges before choosing new ones.
*/
public void resetGauge() {
synchronized (this) {
waveformGauge=null;
spectrumGauge=null;
sonagramGauge=null;
powerGauge=null;
}
}
// ******************************************************************** //
// Audio Processing.
// ******************************************************************** //
/**
* Handle audio input. This is called on the thread of the audio
* reader.
*
* @param buffer Audio data that was just read.
*/
private final void receiveAudio(short[] buffer) {
// Lock to protect updates to these local variables. See run().
synchronized (this) {
audioData = buffer;
++audioSequence;
}
}
/**
* An error has occurred. The reader has been terminated.
*
* @param error ERR_XXX code describing the error.
*/
private void handleError(int error) {
synchronized (this) {
readError = error;
}
}
// ******************************************************************** //
// Main Loop.
// ******************************************************************** //
/**
* Update the state of the instrument for the current frame.
* This method must be invoked from the doUpdate() method of the
* application's {@link SurfaceRunner}.
*
* <p>Since this is called frequently, we first check whether new
* audio data has actually arrived.
*
* @param now Nominal time of the current frame in ms.
*/
@Override
public final void doUpdate(long now) {
short[] buffer = null;
synchronized (this) {
if (audioData != null && audioSequence > audioProcessed) {
parentSurface.statsCount(1, (int) (audioSequence - audioProcessed - 1));
audioProcessed = audioSequence;
buffer = audioData;
}
}
// If we got data, process it without the lock.
if (buffer != null)
processAudio(buffer);
if (readError != AudioReader.Listener.ERR_OK)
processError(readError);
}
/**
* Handle audio input. This is called on the thread of the
* parent surface.
*
* @param buffer Audio data that was just read.
*/
private final void processAudio(short[] buffer) {
// Process the buffer. While reading it, it needs to be locked.
synchronized (buffer) {
// Calculate the power now, while we have the input
// buffer; this is pretty cheap.
final int len = buffer.length;
// Draw the waveform now, while we have the raw data.
if (waveformGauge != null) {
SignalPower.biasAndRange(buffer, len - inputBlockSize, inputBlockSize, biasRange);
final float bias = biasRange[0];
float range = biasRange[1];
if (range < 1f)
range = 1f;
// long wavStart = System.currentTimeMillis();
waveformGauge.update(buffer, len - inputBlockSize, inputBlockSize, bias, range);
// long wavEnd = System.currentTimeMillis();
// parentSurface.statsTime(1, (wavEnd - wavStart) * 1000);
}
// If we have a power gauge, calculate the signal power.
if (powerGauge != null)
currentPower = SignalPower.calculatePowerDb(buffer, 0, len);
// If we have a spectrum or sonagram analyser, set up the FFT input data.
if (spectrumGauge != null || sonagramGauge != null)
spectrumAnalyser.setInput(buffer, len - inputBlockSize, inputBlockSize);
// Tell the reader we're done with the buffer.
buffer.notify();
}
// If we have a spectrum or sonagram analyser, perform the FFT.
if (spectrumGauge != null || sonagramGauge != null) {
// Do the (expensive) transformation.
// The transformer has its own state, no need to lock here.
long specStart = System.currentTimeMillis();
spectrumAnalyser.transform();
long specEnd = System.currentTimeMillis();
parentSurface.statsTime(0, (specEnd - specStart) * 1000);
// Get the FFT output.
if (historyLen <= 1)
spectrumAnalyser.getResults(spectrumData);
else
spectrumIndex = spectrumAnalyser.getResults(spectrumData,
spectrumHist,
spectrumIndex);
}
// If we have a spectrum gauge, update data and draw.
if (spectrumGauge != null)
spectrumGauge.update(spectrumData);
// If we have a sonagram gauge, update data and draw.
if (sonagramGauge != null)
sonagramGauge.update(spectrumData);
// If we have a power gauge, display the signal power.
if (powerGauge != null)
powerGauge.update(currentPower);
}
/**
* Handle an audio input error.
*
* @param error ERR_XXX code describing the error.
*/
private final void processError(int error) {
// Pass the error to all the gauges we have.
if (waveformGauge != null)
waveformGauge.error(error);
if (spectrumGauge != null)
spectrumGauge.error(error);
if (sonagramGauge != null)
sonagramGauge.error(error);
if (powerGauge != null)
powerGauge.error(error);
}
// ******************************************************************** //
// Save and Restore.
// ******************************************************************** //
/**
* Save the state of the system in the provided Bundle.
*
* @param icicle The Bundle in which we should save our state.
*/
@Override
protected void saveState(Bundle icicle) {
// gameTable.saveState(icicle);
}
/**
* Restore the system state from the given Bundle.
*
* @param icicle The Bundle containing the saved state.
*/
@Override
protected void restoreState(Bundle icicle) {
// gameTable.pause();
// gameTable.restoreState(icicle);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Our parent surface.
private SurfaceRunner parentSurface;
// The desired sampling rate for this analyser, in samples/sec.
private int sampleRate = 8000;
// Audio input block size, in samples.
private int inputBlockSize = 256;
// The selected windowing function.
private Window.Function windowFunction = Window.Function.BLACKMAN_HARRIS;
// The desired decimation rate for this analyser. Only 1 in
// sampleDecimate blocks will actually be processed.
private int sampleDecimate = 1;
// The desired histogram averaging window. 1 means no averaging.
private int historyLen = 4;
// Our audio input device.
private final AudioReader audioReader;
// Fourier Transform calculator we use for calculating the spectrum
// and sonagram.
private FFTTransformer spectrumAnalyser;
// The gauges associated with this instrument. Any may be null if not
// in use.
private WaveformGauge waveformGauge = null;
private SpectrumGauge spectrumGauge = null;
private SonagramGauge sonagramGauge = null;
private PowerGauge powerGauge = null;
// Buffered audio data, and sequence number of the latest block.
private short[] audioData;
private long audioSequence = 0;
// If we got a read error, the error code.
private int readError = AudioReader.Listener.ERR_OK;
// Sequence number of the last block we processed.
private long audioProcessed = 0;
// Analysed audio spectrum data; history data for each frequency
// in the spectrum; index into the history data; and buffer for
// peak frequencies.
private float[] spectrumData;
private float[][] spectrumHist;
private int spectrumIndex;
// Current signal power level, in dB relative to max. input power.
private double currentPower = 0f;
// Temp. buffer for calculated bias and range.
private float[] biasRange = null;
}
| 17,342 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TextGauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/TextGauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
/**
* A {@link Gauge} which displays data in textual form, generally as
* a grid of numeric values.
*/
public class TextGauge
extends Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up this view, and configure the text fields to be displayed in
* this element. This is equivalent to calling setTextFields()
* after the basic constructor.
*
* We support display of a single field, or a rectangular table
* of fields. The caller must call
* {@link #setTextFields(String[] template, int rows)} to set the
* table format.
*
* @param parent Parent surface.
*/
public TextGauge(SurfaceRunner parent) {
super(parent);
textSize = getBaseTextSize();
}
/**
* Set up this view, and configure the text fields to be displayed in
* this element. This is equivalent to calling setTextFields()
* after the basic constructor.
*
* We support display of a single field, or a rectangular table
* of fields. The fields are specified by passing in sample text
* values to be measured; we then allocate the space automatically.
*
* @param parent Parent surface.
* @param template Strings representing the columns to display.
* Each one should be a sample piece of text
* which will be measured to determine the
* required space for each column. Must be provided.
* @param rows Number of rows of text to display.
*/
public TextGauge(SurfaceRunner parent, String[] template, int rows) {
super(parent);
textSize = getBaseTextSize();
// Set up the text fields.
setTextFields(template, rows);
}
/**
* Set up the paint for this element. This is called during
* initialisation. Subclasses can override this to do class-specific
* one-time initialisation.
*
* @param paint The paint to initialise.
*/
@Override
protected void initializePaint(Paint paint) {
float scaleX = getTextScaleX();
if (scaleX != 1f)
paint.setTextScaleX(scaleX);
paint.setTypeface(getTextTypeface());
paint.setAntiAlias(true);
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
// Position our text based on our actual geometry. If setTextFields()
// hasn't been called this does nothing.
positionText();
}
/**
* Set the margins around the displayed text. This the total space
* between the edges of the element and the outside bounds of the text.
*
* @param left The left margin.
* @param top The top margin.
* @param right The right margin.
* @param bottom The bottom margin.
*/
public void setMargins(int left, int top, int right, int bottom) {
marginLeft = left;
marginTop = top;
marginRight = right;
marginBottom = bottom;
// Position our text based on these new margins. If setTextFields()
// hasn't been called this does nothing.
positionText();
}
/**
* Set up the text fields to be displayed in this element.
* If this is never called, there will be no text.
*
* We support display of a single field, or a rectangular table
* of fields. The fields are specified by passing in sample text
* values to be measured; we then allocate the space automatically.
*
* This must be called before setText() can be called.
*
* @param template Strings representing the columns to display.
* Each one should be a sample piece of text
* which will be measured to determine the
* required space for each column.
* @param rows Number of rows of text to display.
*/
public void setTextFields(String[] template, int rows) {
fieldTemplate = template;
numRows = rows;
// Make the field buffers based on the template.
char[][][] buffers = new char[numRows][][];
for (int r = 0; r < numRows; ++r) {
int cols = template.length;
buffers[r] = new char[cols][];
for (int c = 0; c < cols; ++c) {
int l = template[c].length();
char[] buf = new char[l];
for (int i = 0; i < l; ++i)
buf[i] = ' ';
buffers[r][c] = buf;
}
}
fieldBuffers = buffers;
// Position our text based on the template. If setGeometry()
// hasn't been called yet, then the positions will not be final,
// but getTextWidth() and getTextHeight() will return sensible
// values.
positionText();
}
/**
* Get the text buffers for the field values. The caller can change
* a field's content by writing to the appropriate member of the
* array, as in "buffer[row][col][0] = 'X';".
*
* @return Text buffers for the field values.
*/
public char[][][] getBuffer() {
return fieldBuffers;
}
/**
* Get the minimum width needed to fit all the text.
*
* @return The minimum width needed to fit all the text.
* Returns zero if setTextFields() hasn't been called.
*/
@Override
public int getPreferredWidth() {
return textWidth;
}
/**
* Get the minimum height needed to fit all the text.
*
* @return The minimum height needed to fit all the text.
* Returns zero if setTextFields() hasn't been called.
*/
@Override
public int getPreferredHeight() {
return textHeight;
}
/**
* Position the text based on the current template and geometry.
* If If setTextFields() hasn't been called this does nothing.
* If setGeometry() hasn't been called yet, then the positions will
* not be final, but getTextWidth() and getTextHeight() will return
* sensible values.
*/
private void positionText() {
if (fieldTemplate == null)
return;
final int nf = fieldTemplate.length;
colsX = new int[nf];
rowsY = new int[numRows];
Rect bounds = getBounds();
Paint paint = getPaint();
paint.setTextSize(textSize);
// Assign all the column positions based on minimum width.
int x = bounds.left;
for (int i = 0; i < nf; ++i) {
int len = (int) Math.ceil(paint.measureText(fieldTemplate[i]));
int lp = i > 0 ? textPadLeft : marginLeft;
int rp = i < nf - 1 ? textPadRight : marginRight;
colsX[i] = x + lp;
x += len + lp + rp;
}
textWidth = x - bounds.left;
// If we have excess width, distribute it into the inter-column gaps.
// Don't adjust textWidth because it is the minimum.
if (nf > 1) {
int excess = (bounds.right - x) / (nf - 1);
if (excess > 0) {
for (int i = 1; i < nf; ++i)
colsX[i] += excess * i;
}
}
// Assign all the row positions based on minimum height.
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
int y = bounds.top;
for (int i = 0; i < numRows; ++i) {
int tp = i > 0 ? textPadTop : marginTop;
int bp = i < numRows - 1 ? textPadBottom : marginBottom;
rowsY[i] = y + tp - fm.ascent - 2;
y += -fm.ascent - 2 + fm.descent + tp + bp;
}
textHeight = y - bounds.top;
}
// ******************************************************************** //
// Appearance.
// ******************************************************************** //
/**
* Set the text colour of this element.
*
* @param col The new text colour, in ARGB format.
*/
public void setTextColor(int col) {
setPlotColor(col);
}
/**
* Get the text colour of this element.
*
* @return The text colour, in ARGB format.
*/
public int getTextColor() {
return getPlotColor();
}
/**
* Set the text size of this element.
*
* @param size The new text size.
*/
public void setTextSize(float size) {
textSize = size;
// Position our text based on the new size. If setTextFields()
// hasn't been called this does nothing.
positionText();
}
/**
* Get the text size of this element.
*
* @return The text size.
*/
public float getTextSize() {
return textSize;
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* This method is called to ask the element to draw itself.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected void drawBody(Canvas canvas, Paint paint, long now) {
// Set up the display style.
paint.setColor(getPlotColor());
paint.setTextSize(textSize);
final char[][][] tv = fieldBuffers;
// If we have any text to show, draw it.
if (tv != null) {
for (int row = 0; row < rowsY.length && row < tv.length; ++row) {
char[][] fields = tv[row];
int y = rowsY[row];
for (int col = 0; col < colsX.length && col < fields.length; ++col) {
char[] field = fields[col];
int x = colsX[col];
canvas.drawText(field, 0, field.length, x, y, paint);
}
}
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Template for the text fields we're displaying.
private String[] fieldTemplate = null;
private int numRows = 0;
// Buffers where the values of the fields will be stored.
private char[][][] fieldBuffers;
// Horizontal positions of the text columns, and vertical positions
// of the rows. These are the actual text base positions. These
// will be null if we have no defined text fields.
private int[] colsX = null;
private int[] rowsY = null;
// The width and height we would need to display all the text at minimum,
// including padding and margins. Set after a call to setTextFields().
private int textWidth = 0;
private int textHeight = 0;
// Current text size.
private float textSize;
// Margins. These are applied around the outside of the text.
private int marginLeft = 0;
private int marginRight = 0;
private int marginTop = 0;
private int marginBottom = 0;
// Text padding. This is applied between all pairs of text fields.
private int textPadLeft = 2;
private int textPadRight = 2;
private int textPadTop = 0;
private int textPadBottom = 0;
}
| 12,109 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
PowerGauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/PowerGauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import org.hermit.utils.CharFormatter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
/**
* A graphical display which displays the signal power in dB from an
* {@link AudioAnalyser} instrument. This class cannot be instantiated
* directly; get an instance by calling
* {@link AudioAnalyser#getPowerGauge(SurfaceRunner)}.
*/
public class PowerGauge
extends Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a PowerGauge. This constructor is package-local, as
* public users get these from an {@link AudioAnalyser} instrument.
*
* @param parent Parent surface.
*/
PowerGauge(SurfaceRunner parent) {
super(parent);
meterPeaks = new float[METER_PEAKS];
meterPeakTimes = new long[METER_PEAKS];
// Create and initialize the history buffer.
powerHistory = new float[METER_AVERAGE_COUNT];
for (int i = 0; i < METER_AVERAGE_COUNT; ++i)
powerHistory[i] = -100.0f;
averagePower = -100.0f;
// Create the buffers where the text labels are formatted.
dbBuffer = "-100.0dB".toCharArray();
pkBuffer = "-100.0dB peak".toCharArray();
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set the overall thickness of the bar.
*
* @param width Overall width in pixels of the bar.
*/
public void setBarWidth(int width) {
barWidth = width;
}
/**
* Set the size for the label text.
*
* @param size Label text size for the gauge.
*/
public void setLabelSize(float size) {
labelSize = size;
}
/**
* Get the size for the label text.
*
* @return Label text size for the gauge.
*/
public float getLabelSize() {
return labelSize;
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
Paint paint = getPaint();
dispX = bounds.left;
dispY = bounds.top;
dispWidth = bounds.width();
dispHeight = bounds.height();
// Do some layout within the meter.
int mw = dispWidth;
int mh = dispHeight;
if (labelSize == 0f)
labelSize = mw / 24f;
// The bar and labels.
meterBarTop = 0;
meterBarGap = barWidth / 4;
meterLabY = meterBarTop + barWidth + labelSize;
// Horizontal margins.
meterBarMargin = labelSize;
// Text readouts. First try putting them side by side.
float th = mh - meterLabY;
float subWidth = (mw - meterBarMargin * 2) / 2;
meterTextSize = findTextSize(subWidth, th, "-100.0dB", paint);
paint.setTextSize(meterTextSize);
meterTextX = meterBarMargin;
meterTextY = mh - paint.descent();
meterSubTextSize = findTextSize(subWidth, th, "-100.0dB peak", paint);
paint.setTextSize(meterSubTextSize);
meterSubTextX = meterTextX + subWidth;
meterSubTextY = mh - paint.descent();
// If we have tons of empty space, stack the text readouts vertically.
if (meterTextSize <= th / 2) {
float split = th * 1f / 3f;
meterTextSize = (th - split) * 0.9f;
paint.setTextSize(meterTextSize);
float tw = paint.measureText("-100.0dB");
meterTextX = (mw - tw) / 2f;
meterTextY = mh - split - paint.descent();
meterSubTextSize = (th - meterTextSize) * 0.9f;
paint.setTextSize(meterSubTextSize);
float pw = paint.measureText("-100.0dB peak");
meterSubTextX = (mw - pw) / 2f;
meterSubTextY = mh - paint.descent();
}
// Cache our background image.
cacheBackground();
}
private float findTextSize(float w, float h, String template, Paint paint) {
float size = h;
do {
paint.setTextSize(size);
int sw = (int) paint.measureText(template);
if (sw <= w)
break;
--size;
} while (size > 12);
return size;
}
// ******************************************************************** //
// Background Drawing.
// ******************************************************************** //
/**
* Do the subclass-specific parts of drawing the background
* for this element. Subclasses should override
* this if they have significant background content which they would
* like to draw once only. Whatever is drawn here will be saved in
* a bitmap, which will be rendered to the screen before the
* dynamic content is drawn.
*
* <p>Obviously, if implementing this method, don't clear the screen when
* drawing the dynamic part.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
*/
@Override
protected void drawBackgroundBody(Canvas canvas, Paint paint) {
canvas.drawColor(0xff000000);
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
// Draw the grid.
final float mx = dispX + meterBarMargin;
final float mw = dispWidth - meterBarMargin * 2;
final float by = dispY + meterBarTop;
final float bw = mw - 1;
final float bh = barWidth - 1;
final float gw = bw / 10f;
canvas.drawRect(mx, by, mx + bw, by + bh, paint);
for (int i = 1; i < 10; ++i) {
final float x = (float) i * (float) bw / 10f;
canvas.drawLine(mx + x, by, mx + x, by + bh, paint);
}
// Draw the labels below the grid.
final float ly = dispY + meterLabY;
final float ls = labelSize;
paint.setTextSize(ls);
int step = paint.measureText("-99") > bw / 10f - 1 ? 2 : 1;
for (int i = 0; i <= 10; i += step) {
String text = "" + (i * 10 - 100);
float tw = paint.measureText(text);
float lx = mx + i * gw + 1 - (tw / 2);
canvas.drawText(text, lx, ly, paint);
}
}
// ******************************************************************** //
// Data Updates.
// ******************************************************************** //
/**
* New data from the instrument has arrived. This method is called
* on the thread of the instrument.
*
* @param power The current instantaneous signal power level
* in dB, from -Inf to 0+. Typical range is
* -100dB to 0dB, 0dB representing max. input power.
*/
final void update(double power) {
synchronized (this) {
// Save the current level. Clip it to a reasonable range.
if (power < -100.0)
power = -100.0;
else if (power > 0.0)
power = 0.0;
currentPower = (float) power;
// Get the previous power value, and add the new value into the
// history buffer. Re-calculate the rolling average power value.
if (++historyIndex >= powerHistory.length)
historyIndex = 0;
prevPower = powerHistory[historyIndex];
powerHistory[historyIndex] = (float) power;
averagePower -= prevPower / METER_AVERAGE_COUNT;
averagePower += (float) power / METER_AVERAGE_COUNT;
}
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* Do the subclass-specific parts of drawing for this element.
* This method is called on the thread of the containing SuraceView.
*
* <p>Subclasses should override this to do their drawing.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected final void drawBody(Canvas canvas, Paint paint, long now) {
synchronized (this) {
// Re-calculate the peak markers.
calculatePeaks(now, currentPower, prevPower);
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
// Position parameters.
final float mx = dispX + meterBarMargin;
final float mw = dispWidth - meterBarMargin * 2;
final float by = dispY + meterBarTop;
final float bh = barWidth;
final float gap = meterBarGap;
final float bw = mw - 2f;
// Draw the average bar.
final float pa = (averagePower / 100f + 1f) * bw;
paint.setStyle(Style.FILL);
paint.setColor(METER_AVERAGE_COL);
canvas.drawRect(mx + 1, by + 1, mx + pa + 1, by + bh - 1, paint);
// Draw the power bar.
final float p = (currentPower / 100f + 1f) * bw;
paint.setStyle(Style.FILL);
paint.setColor(METER_POWER_COL);
canvas.drawRect(mx + 1, by + gap, mx + p + 1, by + bh - gap, paint);
// Now, draw in the peaks.
paint.setStyle(Style.FILL);
for (int i = 0; i < METER_PEAKS; ++i) {
if (meterPeakTimes[i] != 0) {
// Fade the peak according to its age.
long age = now - meterPeakTimes[i];
float fac = 1f - ((float) age / (float) METER_PEAK_TIME);
int alpha = (int) (fac * 255f);
paint.setColor(METER_PEAK_COL | (alpha << 24));
// Draw it in.
final float pp = (meterPeaks[i] / 100f + 1f) * bw;
canvas.drawRect(mx + pp - 1, by + gap,
mx + pp + 3, by + bh - gap, paint);
}
}
// Draw the text below the meter.
final float tx = dispX + meterTextX;
final float ty = dispY + meterTextY;
CharFormatter.formatFloat(dbBuffer, 0, averagePower, 6, 1);
paint.setStyle(Style.STROKE);
paint.setColor(0xff00ffff);
paint.setTextSize(meterTextSize);
canvas.drawText(dbBuffer, 0, dbBuffer.length, tx, ty, paint);
final float px = dispX + meterSubTextX;
final float py = dispY + meterSubTextY;
CharFormatter.formatFloat(pkBuffer, 0, meterPeakMax, 6, 1);
paint.setTextSize(meterSubTextSize);
canvas.drawText(pkBuffer, 0, pkBuffer.length, px, py, paint);
}
}
/**
* Re-calculate the positions of the peak markers in the VU meter.
*/
private final void calculatePeaks(long now, float power, float prev) {
// First, delete any that have been passed or have timed out.
for (int i = 0; i < METER_PEAKS; ++i) {
if (meterPeakTimes[i] != 0 &&
(meterPeaks[i] < power ||
now - meterPeakTimes[i] > METER_PEAK_TIME))
meterPeakTimes[i] = 0;
}
// If the meter has gone up, set a new peak, if there's an empty
// slot. If there isn't, don't bother, because we would be kicking
// out a higher peak, which we don't want.
if (power > prev) {
boolean done = false;
// First, check for a slightly-higher existing peak. If there
// is one, just bump its time.
for (int i = 0; i < METER_PEAKS; ++i) {
if (meterPeakTimes[i] != 0 && meterPeaks[i] - power < 2.5) {
meterPeakTimes[i] = now;
done = true;
break;
}
}
if (!done) {
// Now scan for an empty slot.
for (int i = 0; i < METER_PEAKS; ++i) {
if (meterPeakTimes[i] == 0) {
meterPeaks[i] = power;
meterPeakTimes[i] = now;
break;
}
}
}
}
// Find the highest peak value.
meterPeakMax = -100f;
for (int i = 0; i < METER_PEAKS; ++i)
if (meterPeakTimes[i] != 0 && meterPeaks[i] > meterPeakMax)
meterPeakMax = meterPeaks[i];
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// Number of peaks we will track in the VU meter.
private static final int METER_PEAKS = 4;
// Time in ms over which peaks in the VU meter fade out.
private static final int METER_PEAK_TIME = 4000;
// Number of updates over which we average the VU meter to get
// a rolling average. 32 is about 2 seconds.
private static final int METER_AVERAGE_COUNT = 32;
// Colours for the meter power bar and average bar and peak marks.
// In METER_PEAK_COL, alpha is set dynamically in the code.
private static final int METER_POWER_COL = 0xff0000ff;
private static final int METER_AVERAGE_COL = 0xa0ff9000;
private static final int METER_PEAK_COL = 0x00ff0000;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Configured meter bar thickness.
private int barWidth = 32;
// Display position and size within the parent view.
private int dispX = 0;
private int dispY = 0;
private int dispWidth = 0;
private int dispHeight = 0;
// Label text size for the gauge. Zero if not set yet.
private float labelSize = 0f;
// Layout parameters for the VU meter. Position and size for the
// bar itself; position and size for the bar labels; position
// and size for the main readout text.
private float meterBarTop = 0;
private float meterBarGap = 0;
private float meterLabY = 0;
private float meterTextX = 0;
private float meterTextY = 0;
private float meterTextSize = 0;
private float meterSubTextX = 0;
private float meterSubTextY = 0;
private float meterSubTextSize = 0;
private float meterBarMargin = 0;
// Current and previous power levels.
private float currentPower = 0f;
private float prevPower = 0f;
// Buffered old meter levels, used to calculate the rolling average.
// Index of the most recent value.
private float[] powerHistory = null;
private int historyIndex = 0;
// Rolling average power value, calculated from the history buffer.
private float averagePower = -100.0f;
// Peak markers in the VU meter, and the times for each one. A zero
// time indicates a peak not set.
private float[] meterPeaks = null;
private long[] meterPeakTimes = null;
private float meterPeakMax = 0f;
// Buffer for displayed average and peak dB value texts.
private char[] dbBuffer = null;
private char[] pkBuffer = null;
}
| 16,786 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Gauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/Gauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
/**
* A graphical display which shows some data in a region
* within a view. The data may come from an {@link Instrument} or
* some other source.
*
* <h2>Configuration</h2>
*
* <p>Your gauge will be notified of its geometry by a call to
* {@link #setGeometry(Rect)}. This is where you should note your position
* and size and perform any internal layout you need to do.
*
* <p>Note that if you are running in an app which handles screen
* configuration changes, {@link #setGeometry(Rect)} will be called any
* time the screen changes size or shape (e.g. on an orientation change).
* You should be prepared to handle these subsequent calls by re-creating
* data structures, re-doing layout, etc., as required.
*
* <h2>Data Updating</h2>
*
* <p>It is assumed that your gauge has some kind of data source, but
* how this works is up to you.
*
* <h2>Drawing Sequence -- User</h2>
*
* <p>A gauge may have a background which is rendered separately from
* its content, for performance reasons. Hence, a Gauge user must request
* the background to be drawn, and then the gauge content to be drawn. If
* the caller is going to cache the background, the background need be
* requested only when the geometry changes.
*
* <p>There are two options. In the non-caching case, the caller may
* simply call {@link #draw(Canvas, long, boolean)}, passing true
* as the last argument. This asks the Gauge to draw its background and
* its content.
*
* <p>In the caching case, the caller should call
* {@link #drawBackground(Canvas)} to ask the gauge to draw its
* background into the given canvas. Since the gauge will use the same
* co-ordinates that it uses to draw to the screen, the canvas will need
* to be the size of the screen (or you can translate the co-ordinates).
* Then, to draw the gauge, the caller should render the stored background
* and then call {@link #draw(Canvas, long, boolean)}.
*
* <h2>Drawing Sequence -- Implementor</h2>
*
* <p>From the Gauge implementor's point of view, there are two routines
* to implement: {@link #drawBackgroundBody(Canvas, Paint)} (optional), and
* {@link #drawBody(Canvas, Paint, long)}.
*
* <p>If your implementation of {@link #drawBody(Canvas, Paint, long)}
* draws a complete, opaque rendition of the gauge, that's all you need;
* there's no need to provide an implementation of drawBackgroundBody().
* But if your gauge has a separate, persistent background appearance,
* you may reap a performance benefit by separating out its drawing.
* Do this by implementing {@link #drawBackgroundBody(Canvas, Paint)}.
* This routine should draw the gauge background at the gauge's
* configured position in the specified Canvas.
*
* <p>A facility is provided for caching background images. To use this,
* call {@link #cacheBackground()} once your layout is set up -- for example
* at the end of {@link #setGeometry(Rect)}. At that point, your background
* will be fetched (by calling your implementation of drawBackgroundBody())
* and stored; then when someone asks us to draw our background, the request
* will be satisfied using the stored bitmap, without calling your
* drawBackgroundBody() again.
*/
public class Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up this view.
*
* @param parent Parent surface.
*/
public Gauge(SurfaceRunner parent) {
this(parent, 0);
}
/**
* Set up this view.
*
* @param parent Parent surface.
* @param options Options for this SurfaceRunner. A bitwise OR of
* GAUGE_XXX constants.
*/
public Gauge(SurfaceRunner parent, int options) {
parentSurface = parent;
gaugeOptions = options;
// Set up our paint.
drawPaint = new Paint();
initializePaint(drawPaint);
}
/**
* Set up this view.
*
* @param parent Parent surface.
* @param grid Colour for drawing a data scale / grid.
* @param plot Colour for drawing data plots.
*/
public Gauge(SurfaceRunner parent, int grid, int plot) {
this(parent, 0, grid, plot);
}
/**
* Set up this view.
*
* @param parent Parent surface.
* @param options Options for this SurfaceRunner. A bitwise OR of
* GAUGE_XXX constants.
* @param grid Colour for drawing a data scale / grid.
* @param plot Colour for drawing data plots.
*/
public Gauge(SurfaceRunner parent, int options, int grid, int plot) {
parentSurface = parent;
gaugeOptions = options;
gridColour = grid;
plotColour = plot;
// Set up our paint.
drawPaint = new Paint();
initializePaint(drawPaint);
}
/**
* Set up the paint for this element. This is called during
* initialization. Subclasses can override this to do class-specific
* one-time initialization.
*
* @param paint The paint to initialize.
*/
protected void initializePaint(Paint paint) { }
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Check whether the given option flag is set on this surface.
*
* @param option The option flag to test; one of GAUGE_XXX.
* @return true iff the option is set.
*/
public boolean optionSet(int option) {
return (gaugeOptions & option) != 0;
}
// ******************************************************************** //
// Global Layout Parameters.
// ******************************************************************** //
/**
* Set the default font for all text.
*
* @param face The default font for all text.
*/
public static void setTextTypeface(Typeface face) {
baseTextFace = face;
}
/**
* Get the default font for all text.
*
* @return The default font for all text.
*/
public static Typeface getTextTypeface() {
return baseTextFace;
}
/**
* Set the base size for text.
*
* @param size Base text size for the app.
*/
public static void setBaseTextSize(float size) {
baseTextSize = size;
headTextSize = baseTextSize * 1.3f;
miniTextSize = baseTextSize * 0.9f;
tinyTextSize = baseTextSize * 0.8f;
}
/**
* Get the base size for text.
*
* @return Base text size for the app.
*/
public static float getBaseTextSize() {
return baseTextSize;
}
/**
* Set the size for header text.
*
* @param size Header text size for the app.
*/
public static void setHeadTextSize(float size) {
headTextSize = size;
}
/**
* Get the size for header text.
*
* @return Header text size for the app.
*/
public static float getHeadTextSize() {
return headTextSize;
}
/**
* Set the size for mini text.
*
* @param size Mini text size for the app.
*/
public static void setMiniTextSize(float size) {
miniTextSize = size;
}
/**
* Get the size for mini text.
*
* @return Mini text size for the app.
*/
public static float getMiniTextSize() {
return miniTextSize;
}
/**
* Set the size for tiny text.
*
* @param size Tiny text size for the app.
*/
public static void setTinyTextSize(float size) {
tinyTextSize = size;
}
/**
* Get the size for tiny text based on this screen's size.
*
* @return Tiny text size for the app.
*/
public static float getTinyTextSize() {
return tinyTextSize;
}
/**
* Set the horizontal scaling of the font; this can be used to
* produce a tall, thin font.
*
* @param scale Horizontal scaling of the font.
*/
public static void setTextScaleX(float scale) {
textScaleX = scale;
}
/**
* Get the base size for text based on this screen's size.
*
* @return Horizontal scaling of the font.
*/
public static float getTextScaleX() {
return textScaleX;
}
/**
* Set the sidebar width.
*
* @param width The sidebar width.
*/
public static void setSidebarWidth(int width) {
viewSidebar = width;
}
/**
* Get the sidebar width.
*
* @return The sidebar width.
*/
public static int getSidebarWidth() {
return viewSidebar;
}
/**
* Set the amount of padding between major elements in a view.
*
* @param pad The amount of padding between major elements in a view.
*/
public static void setInterPadding(int pad) {
interPadding = pad;
}
/**
* Get the amount of padding between major elements in a view.
*
* @return The amount of padding between major elements in a view.
*/
public static int getInterPadding() {
return interPadding;
}
/**
* Set the amount of padding within atoms within an element. Specifically
* the small gaps in side bars.
*
* @param gap The amount of padding within atoms within an element
*/
public static void setInnerGap(int gap) {
innerGap = gap;
}
/**
* Get the amount of padding within atoms within an element. Specifically
* the small gaps in side bars.
*
* @return The amount of padding within atoms within an element
*/
public static int getInnerGap() {
return innerGap;
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
public void setGeometry(Rect bounds) {
elemBounds = bounds;
// Any cached background we may have is now invalid.
backgroundBitmap = null;
backgroundCanvas = null;
}
/**
* Fetch and cache an image of the background now, then use that
* to draw the background on future draw requests. The cached image
* is invalidated the next time the geometry changes.
*
* <p>Implementations should call this method once their layout is
* set -- for example at the end of {@link #setGeometry(Rect)} --
* if they have a significant static background that they wish
* to have cached.
*/
protected void cacheBackground() {
// Create the bitmap for the background,
// and the Canvas for drawing into it.
backgroundBitmap = getSurface().getBitmap(elemBounds.width(),
elemBounds.height());
backgroundCanvas = new Canvas(backgroundBitmap);
// Because the element is going to draw its BG at its proper
// location, and this bitmap is local to the element, we need
// to translate the drawing co-ordinates.
drawBackground(backgroundCanvas, -elemBounds.left, -elemBounds.top);
}
/**
* Get the minimum preferred width for this atom.
*
* @return The minimum preferred width for this atom.
* Returns zero if we don't know yet.
*/
public int getPreferredWidth() {
return 0;
}
/**
* Get the minimum preferred height for this atom.
*
* @return The minimum preferred height for this atom.
* Returns zero if we don't know yet.
*/
public int getPreferredHeight() {
return 0;
}
/**
* Determine whether we have the bounding rect of this Element.
*
* @return True if our geometry has been set up.
*/
public final boolean haveBounds() {
return getWidth() > 0 && getHeight() > 0;
}
/**
* Get the bounding rect of this Element.
*
* @return The bounding rect of this element within
* its parent View. This will be 0, 0, 0, 0 if
* setGeometry() has not been called yet.
*/
public final Rect getBounds() {
return elemBounds;
}
/**
* Get the width of this element -- i.e. the current configured width.
*
* @return The width of this element within
* its parent View. This will be 0 if
* setGeometry() has not been called yet.
*/
public final int getWidth() {
return elemBounds.right - elemBounds.left;
}
/**
* Get the height of this element -- i.e. the current configured height.
*
* @return The height of this element within
* its parent View. This will be 0 if
* setGeometry() has not been called yet.
*/
public final int getHeight() {
return elemBounds.bottom - elemBounds.top;
}
// ******************************************************************** //
// Appearance.
// ******************************************************************** //
/**
* Set the background colour of this element.
*
* @param col The new background colour, in ARGB format.
*/
public void setBackgroundColor(int col) {
colBg = col;
}
/**
* Get the background colour of this element.
*
* @return The background colour, in ARGB format.
*/
public int getBackgroundColor() {
return colBg;
}
/**
* Set the plot colours of this element.
*
* @param grid Colour for drawing a data scale / grid.
* @param plot Colour for drawing data plots.
*/
public void setDataColors(int grid, int plot) {
gridColour = grid;
plotColour = plot;
}
/**
* Set the data scale / grid colour of this element.
*
* @param grid Colour for drawing a data scale / grid.
*/
public void setGridColor(int grid) {
gridColour = grid;
}
/**
* Set the data plot colour of this element.
*
* @param plot Colour for drawing a data plot.
*/
public void setPlotColor(int plot) {
plotColour = plot;
}
/**
* Get the data scale / grid colour of this element.
*
* @return Colour for drawing a data scale / grid.
*/
public int getGridColor() {
return gridColour;
}
/**
* Get the data plot colour of this element.
*
* @return Colour for drawing data plots.
*/
public int getPlotColor() {
return plotColour;
}
// ******************************************************************** //
// Error Handling.
// ******************************************************************** //
/**
* An error has occurred. Notify the user somehow.
*
* <p>Subclasses can override this to do something neat.
*
* @param error ERR_XXX code describing the error.
*/
public void error(int error) {
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* Get this element's Paint.
*
* @return The Paint which was set up in initializePaint().
*/
protected Paint getPaint() {
return drawPaint;
}
/**
* This method is called to ask the element to draw its static
* content; i.e. the background / chrome.
*
* @param canvas Canvas to draw into.
*/
public void drawBackground(Canvas canvas) {
if (backgroundBitmap != null)
canvas.drawBitmap(backgroundBitmap, elemBounds.left, elemBounds.top, null);
else
drawBackground(canvas, 0, 0);
}
/**
* This internal method is used to get the gauge implementation to
* render its background at a specific location.
*
* @param canvas Canvas to draw into.
* @param dx X co-ordinate translation to apply.
* @param dy Y co-ordinate translation to apply.
*/
private void drawBackground(Canvas canvas, int dx, int dy) {
// Clip to our part of the canvas.
canvas.save();
canvas.translate(dx, dy);
canvas.clipRect(getBounds());
drawBackgroundBody(canvas, drawPaint);
canvas.restore();
}
/**
* Do the subclass-specific parts of drawing the background
* for this element. Subclasses should override
* this if they have significant background content which they would
* like to draw once only. Whatever is drawn here will be saved in
* a bitmap, which will be rendered to the screen before the
* dynamic content is drawn.
*
* <p>Obviously, if implementing this method, don't clear the screen when
* drawing the dynamic part.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
*/
protected void drawBackgroundBody(Canvas canvas, Paint paint) {
// If not overridden, we shouldn't need anything, as the overall
// background is cleared each time.
}
/**
* This method is called to ask the element to draw its dynamic content.
*
* @param canvas Canvas to draw into.
* @param now Nominal system time in ms. of this update.
* @param bg Iff true, tell the gauge to draw its background
* first. This is cheaper than calling
* {@link #drawBackground(Canvas)} before
* this method.
*/
public void draw(Canvas canvas, long now, boolean bg) {
drawStart(canvas, drawPaint, now);
if (bg) {
if (backgroundBitmap != null)
canvas.drawBitmap(backgroundBitmap,
elemBounds.left, elemBounds.top, null);
else
drawBackgroundBody(canvas, drawPaint);
}
drawBody(canvas, drawPaint, now);
drawFinish(canvas, drawPaint, now);
}
/**
* Do initial parts of drawing for this element.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
protected void drawStart(Canvas canvas, Paint paint, long now) {
// Clip to our part of the canvas.
canvas.save();
canvas.clipRect(getBounds());
}
/**
* Do the subclass-specific parts of drawing for this element.
*
* Subclasses should override this to do their drawing.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
protected void drawBody(Canvas canvas, Paint paint, long now) {
// If not overridden, just fill with BG colour.
canvas.drawColor(colBg);
}
/**
* Wrap up drawing of this element.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
protected void drawFinish(Canvas canvas, Paint paint, long now) {
canvas.restore();
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* Get the app context of this Element.
*
* @return The app context we're running in.
*/
protected SurfaceRunner getSurface() {
return parentSurface;
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// The minimum happy text size.
private static final float MIN_TEXT = 22f;
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// The default font for all text.
private static Typeface baseTextFace = Typeface.MONOSPACE;
// The base size for all text, based on screen size.
private static float baseTextSize = MIN_TEXT;
// Various other text sizes.
private static float headTextSize = MIN_TEXT * 1.3f;
private static float miniTextSize = MIN_TEXT * 0.9f;
private static float tinyTextSize = MIN_TEXT * 0.8f;
// The horizontal scaling of the font; this can be used to
// produce a tall, thin font.
private static float textScaleX = 1f;
// The thickness of a side bar in a view element.
private static int viewSidebar;
// The amount of padding between major elements in a view.
private static int interPadding;
// The amount of padding within atoms within an element. Specifically
// the small gaps in side bars.
private static int innerGap;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application handle.
private final SurfaceRunner parentSurface;
// Option flags for this instance. A bitwise OR of GAUGE_XXX constants.
private int gaugeOptions = 0;
// The paint we use for drawing.
private Paint drawPaint = null;
// The bounding rect of this element within its parent View.
private Rect elemBounds = new Rect(0, 0, 0, 0);
// Background colour.
private int colBg = 0xff000000;
// Colour of the graph grid and plot.
private int gridColour = 0xff00ff00;
private int plotColour = 0xffff0000;
// Bitmap in which we draw the gauge background, if we're caching it,
// and the Canvas for drawing into it.
private Bitmap backgroundBitmap = null;
private Canvas backgroundCanvas = null;
}
| 23,454 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
WaveformGauge.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/instruments/WaveformGauge.java |
/**
* org.hermit.android.instrument: graphical instruments for Android.
* <br>Copyright 2009 Ian Cameron Smith
*
* <p>These classes provide input and display functions for creating on-screen
* instruments of various kinds in Android apps.
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.instruments;
import org.hermit.android.core.SurfaceRunner;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
/**
* A graphical display which displays the audio waveform from an
* {@link AudioAnalyser} instrument. This class cannot be instantiated
* directly; get an instance by calling
* {@link AudioAnalyser#getWaveformGauge(SurfaceRunner)}.
*/
public class WaveformGauge
extends Gauge
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a WaveformGauge. This constructor is package-local, as
* public users get these from an {@link AudioAnalyser} instrument.
*
* @param parent Parent surface.
*/
WaveformGauge(SurfaceRunner parent) {
super(parent);
}
// ******************************************************************** //
// Geometry.
// ******************************************************************** //
/**
* This is called during layout when the size of this element has
* changed. This is where we first discover our size, so set
* our geometry to match.
*
* @param bounds The bounding rect of this element within
* its parent View.
*/
@Override
public void setGeometry(Rect bounds) {
super.setGeometry(bounds);
dispX = bounds.left;
dispY = bounds.top;
dispWidth = bounds.width();
dispHeight = bounds.height();
// Create the bitmap for the audio waveform display,
// and the Canvas for drawing into it.
waveBitmap = getSurface().getBitmap(dispWidth, dispHeight);
waveCanvas = new Canvas(waveBitmap);
}
// ******************************************************************** //
// Data Updates.
// ******************************************************************** //
/**
* New data from the instrument has arrived. This method is called
* on the thread of the instrument.
*
* @param buffer Audio data that was just read.
* @param off Offset in data of the input data.
* @param len Length of the input data.
* @param bias Bias of the signal -- i.e. the offset of the
* average signal value from zero.
* @param range The range of the signal -- i.e. the absolute
* value of the largest departure from the bias level.
*/
final void update(short[] buffer, int off, int len, float bias, float range) {
final Canvas canvas = waveCanvas;
final Paint paint = getPaint();
// Calculate a scaling factor. We want a degree of AGC, but not
// so much that the waveform is always the same height. Note we have
// to take bias into account, otherwise we could scale the signal
// off the screen.
float scale = (float) Math.pow(1f / (range / 6500f), 0.7) / 16384 * dispHeight;
if (scale < 0.001f || Float.isInfinite(scale))
scale = 0.001f;
else if (scale > 1000f)
scale = 1000f;
final float margin = dispWidth / 24;
final float gwidth = dispWidth - margin * 2;
final float baseY = dispHeight / 2f;
final float uw = gwidth / (float) len;
// Now actually do the drawing.
synchronized (this) {
canvas.drawColor(0xff000000);
// Draw the axes.
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
canvas.drawLine(margin, 0, margin, dispHeight - 1, paint);
// Draw the waveform. Drawing vertical lines up/down to the
// waveform creates a "filled" effect, and is *much* faster
// than drawing the waveform itself with diagonal lines.
paint.setColor(0xffffff00);
paint.setStyle(Style.STROKE);
for (int i = 0; i < len; ++i) {
final float x = margin + i * uw;
final float y = baseY - (buffer[off + i] - bias) * scale;
canvas.drawLine(x, baseY, x, y, paint);
}
}
}
// ******************************************************************** //
// View Drawing.
// ******************************************************************** //
/**
* Do the subclass-specific parts of drawing for this element.
* This method is called on the thread of the containing SuraceView.
*
* <p>Subclasses should override this to do their drawing.
*
* @param canvas Canvas to draw into.
* @param paint The Paint which was set up in initializePaint().
* @param now Nominal system time in ms. of this update.
*/
@Override
protected final void drawBody(Canvas canvas, Paint paint, long now) {
// Since drawBody may be called more often than we get audio
// data, it makes sense to just draw the buffered image here.
synchronized (this) {
canvas.drawBitmap(waveBitmap, dispX, dispY, null);
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
@SuppressWarnings("unused")
private static final String TAG = "instrument";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Display position and size within the parent view.
private int dispX = 0;
private int dispY = 0;
private int dispWidth = 0;
private int dispHeight = 0;
// Bitmap in which we draw the audio waveform display,
// and the Canvas and Paint for drawing into it.
private Bitmap waveBitmap = null;
private Canvas waveCanvas = null;
}
| 6,706 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Ticker.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/utils/Ticker.java |
/**
* org.hermit.android.utils: useful Android utilities.
*
* These classes provide various Android-specific utilities.
*
* <br>Copyright 2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.utils;
import java.util.ArrayList;
import java.util.Calendar;
import android.os.Handler;
import android.util.Log;
/**
* Scheduler for regular callbacks to multiple clients. This class can
* be used to generate callbacks to several listeners, each with their
* own desired callback interval, all from a single thread.
*
* <p>Callbacks are all based on a regular number of seconds within a day,
* and are delivered as closely as possible to the interval boundary.
* For example, if a client asks for a tick every two hours, it will get
* ticks as close as possible to the even hours of the day.</p>
*
* <p>The Ticker can be stopped and started multiple times.</p>
*
* @author Ian Cameron Smith
*/
public class Ticker {
// ******************************************************************** //
// Public Types.
// ******************************************************************** //
/**
* A listener that callers can use to be notified of ticks, along with
* some potentially useful info. You can use this as an alternative
* to using a Handler.
*/
public static abstract class Listener {
/**
* This method is called to notify the client of a tick.
*
* @param time Current system time in ms.
* @param daySecs Number of seconds into the day that this
* tick relates to.
*/
public abstract void tick(long time, int daySecs);
private long time;
private int daySecs;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a ticker. To use it, call {@link #listen(int, Handler)} to
* set one or more listeners; you must also call {@link #start()} to
* set it running.
*/
public Ticker() {
// Get the time in milliseconds of the start of the day.
// This is used for aligning to the configured interval.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
dayStart = cal.getTimeInMillis();
// Create the listeners list.
clients = new ArrayList<ClientData>();
// Set a default interval (so we're always somewhat warm).
tickSecs = 3600;
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* Start this ticker. All callbacks that were previously registered will
* still be in force. To stop this Ticker, call {@link #stop()}.
*/
public void start() {
// Make sure we're not currently running.
stop();
synchronized (this) {
// Re-calculate our tick interval.
tickSecs = calculateInterval();
if (DBG) Log.i(TAG, "start(): tick=" + tickSecs);
enable = true;
tickerThread = new Thread(tickRunner);
tickerThread.start();
}
}
/**
* Stop this ticker. All callbacks will be remembered, so if you start
* the Ticker again (using {@link #start()}), they will begin getting
* notified again.
*/
public void stop() {
synchronized (this) {
enable = false;
if (tickerThread != null) {
if (DBG) Log.i(TAG, "stop()");
tickerThread.interrupt();
tickerThread = null;
}
}
}
// ******************************************************************** //
// Listening.
// ******************************************************************** //
/**
* Schedule a Listener to get callbacks at a regular interval,
* as closely as possible.
*
* <p>Callbacks will be delivered as nearly as possible on the specified
* tick interval, relative to the start of the day. Examples:
*
* <ul>
* <li>if a client asks for a tick every two hours, it will get
* ticks as close as possible to the even hours of the day.</li>
* <li>if a client asks for a tick every seven hours, it will get
* ticks as close as possible to 0:00, 7:00, 14:00, and 21:00;
* then starting over again at 0:00 the next day.</li>
* </ul></p>
*
* <p>Note that the Ticker must be started with {@link #start()} in
* order for the listeners to be called.</p>
*
* @param secs Callback interval, in seconds.
* @param l Listener to invoke, on the caller's thread,
* on the interval.
*/
public void listen(int secs, Listener l) {
listen(secs, new ClientData(secs, new Handler(), l));
}
/**
* Schedule a Handler to get messages at a regular interval,
* as closely as possible.
*
* <p>Messages will be delivered as nearly as possible on the specified
* tick interval, relative to the start of the day. Examples:
*
* <ul>
* <li>if a client asks for a tick every two hours, it will get
* ticks as close as possible to the even hours of the day.</li>
* <li>if a client asks for a tick every seven hours, it will get
* ticks as close as possible to 0:00, 7:00, 14:00, and 21:00;
* then starting over again at 0:00 the next day.</li>
* </ul></p>
*
* <p>Note that the Ticker must be started with {@link #start()} in
* order for the listeners to be called.</p>
*
* @param secs Callback interval, in seconds.
* @param handler Handler to send (empty) callback messages to
* on the interval.
*/
public void listen(int secs, Handler handler) {
listen(secs, new ClientData(secs, handler, null));
}
/**
* Schedule the given listener to get callbacks at a regular interval,
* as closely as possible.
*
* @param secs Callback interval, in seconds.
* @param l Listener to register.
*/
private void listen(int secs, ClientData l) {
synchronized (this) {
clients.add(l);
// Set the overall interval.
if (clients.size() == 1)
tickSecs = secs;
else
tickSecs = gcd(tickSecs, secs);
}
if (DBG) Log.i(TAG, "listen(" + secs + "): tick=" + tickSecs);
// Interrupt the ticker thread, so it can re-schedule.
if (tickerThread != null)
tickerThread.interrupt();
}
/**
* De-register a given handler. All callbacks to this handler will
* be removed.
*
* @param l Runnable to unregister.
*/
public void unlisten(Listener l) {
synchronized (this) {
// Remove all listeners with this handler.
for (int i = 0; i < clients.size(); ) {
ClientData c = clients.get(i);
if (c.listener == l)
clients.remove(i);
else
++i;
}
// Set the new tick interval.
tickSecs = calculateInterval();
}
if (DBG) Log.i(TAG, "unlisten(): tick=" + tickSecs);
// Interrupt the ticker thread, so it can re-schedule.
if (tickerThread != null)
tickerThread.interrupt();
}
/**
* De-register a given handler. All callbacks to this handler will
* be removed.
*
* @param handler Handler to unregister.
*/
public void unlisten(Handler handler) {
synchronized (this) {
// Remove all listeners with this handler.
for (int i = 0; i < clients.size(); ) {
ClientData c = clients.get(i);
if (c.handler == handler)
clients.remove(i);
else
++i;
}
// Set the new tick interval.
tickSecs = calculateInterval();
}
if (DBG) Log.i(TAG, "unlisten(): tick=" + tickSecs);
// Interrupt the ticker thread, so it can re-schedule.
if (tickerThread != null)
tickerThread.interrupt();
}
// ******************************************************************** //
// Implementation.
// ******************************************************************** //
/**
* Determine whether we are still running.
*
* @return true iff we're still enabled.
*/
private boolean isEnabled() {
boolean res;
synchronized (this) {
res = enable;
}
return res;
}
/**
* Re-calculate our tick interval by calculating the gcd of
* all the tick intervals of the remaining listeners.
*
* @return Tick interval which matches all the listeners.
*/
private int calculateInterval() {
int size = clients.size();
if (size == 0)
return 3600;
else {
int iv = clients.get(0).interval;
for (int i = 1; i < size; ++i)
iv = gcd(iv, clients.get(i).interval);
return iv;
}
}
/**
* Run this Ticker. Terminates when we're killed.
*/
private Runnable tickRunner = new Runnable() {
@Override
public void run() {
long dayTime;
while (isEnabled()) {
try {
// Try to sleep up to the next interval boundary, so we
// tick just about on the interval boundary.
long tickMillis = tickSecs * 1000;
dayTime = System.currentTimeMillis() - dayStart;
Thread.sleep(tickMillis - dayTime % tickMillis);
if (!isEnabled())
break;
// OK, now figure out what second boundary we're on. We
// calculate the seconds from some day boundary.
Long time = System.currentTimeMillis();
dayTime = time - dayStart;
int daySec = (int) ((dayTime + 250) / 1000) % DAY_SECS;
// Tell every listener whose tick interval we hit.
synchronized (this) {
for (ClientData c : clients) {
if (daySec % c.interval == 0)
c.tick(time, daySec);
}
}
} catch (InterruptedException e) {
// Do nothing. Interrupts are used to wake us from
// sleep and re-check the configuration.
}
}
}
};
/**
* Calculate the GCD of two integers.
*
* @param a First integer.
* @param b Second integer.
* @return gcd(a, b).
*/
private static final int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
// ******************************************************************** //
// Private Types.
// ******************************************************************** //
// Encapsulate a listener (represented by a Handler) with its
// requested notification interval. If a Listener is also present,
// it is the callback to invoke; otherwise we just send a message to
// the handler. The Handler must be supplied, as it is the handle
// on the thread we need to notify.
private static final class ClientData {
ClientData(int i, Handler h, Listener l) {
interval = i;
handler = h;
listener = l;
if (listener != null) {
poster = new Runnable() {
@Override
public void run() {
listener.tick(listener.time, listener.daySecs);
}
};
}
}
void tick(long time, int daySecs) {
if (listener != null) {
listener.time = time;
listener.daySecs = daySecs;
handler.post(poster);
} else
handler.sendEmptyMessage(1);
}
final int interval;
final Handler handler;
final Listener listener;
Runnable poster = null;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "Ticker";
// Seconds in a day.
private static final int DAY_SECS = 24 * 3600;
private static final boolean DBG = false;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Thread running this ticker.
private Thread tickerThread = null;
// True iff the ticker is enabled. Set to false to stop it.
private boolean enable;
// The time in milliseconds of the start of the day.
private long dayStart;
// The registered listeners.
private ArrayList<ClientData> clients;
// The internal ticker tick interval, in seconds.
private int tickSecs;
}
| 12,242 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
InfoBox.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/notice/InfoBox.java |
/**
* org.hermit.android.notice: various notice dialogs for Android.
*
* These classes are designed to help display notices of various kinds.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.notice;
import org.hermit.android.R;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.text.util.Linkify;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* This class implements a popup info box (a subclass of Dialog)
* which can be used to display help text, about info, license info, etc.
*/
public class InfoBox
extends Dialog
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/** Select configurable button 1 -- the middle button. */
public static final int BUTTON_1 = 1;
/** Select configurable button 2 -- the middle button. */
public static final int BUTTON_2 = 2;
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an info box with a "close" button.
*
* @param parent Parent application context.
*/
public InfoBox(Activity parent) {
this(parent, R.string.button_close);
}
/**
* Create an info box.
*
* @param parent Parent application context.
* @param button Resource ID of the text for the OK button.
*/
public InfoBox(Activity parent, int button) {
super(parent);
parentApp = parent;
resources = parent.getResources();
buttonLabel = button;
buttonLinks = new int[3];
// Build the dialog body.
View content = createDialog();
setContentView(content);
}
/**
* Create the popup dialog UI.
*/
private View createDialog() {
final int WCON = LinearLayout.LayoutParams.WRAP_CONTENT;
final int FPAR = LinearLayout.LayoutParams.FILL_PARENT;
// Create the overall layout.
LinearLayout layout = new LinearLayout(parentApp);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(6, 6, 6, 6);
// Construct the subtitle view, and add it to the layout. Place an
// underline bar below it.
subtitleView = new TextView(parentApp);
subtitleView.setTextSize(18f);
subtitleView.setVisibility(View.GONE);
layout.addView(subtitleView, new LinearLayout.LayoutParams(FPAR, WCON));
subtitleBar = new ImageView(parentApp);
subtitleBar.setImageResource(android.R.drawable.divider_horizontal_dim_dark);
subtitleBar.setVisibility(View.GONE);
layout.addView(subtitleBar, new LinearLayout.LayoutParams(FPAR, WCON));
// Create a ScrollView to put the text in. Shouldn't be necessary,
// but...?
ScrollView tscroll = new ScrollView(parentApp);
tscroll.setVerticalScrollBarEnabled(true);
tscroll.setLayoutParams(new LinearLayout.LayoutParams(WCON, WCON, 1));
layout.addView(tscroll);
// Now create the text view and add it to the scroller. Note: when
// we use Linkify, it's necessary to call setTextColor() to
// avoid all the text blacking out on click.
textView = new TextView(parentApp);
textView.setTextSize(16);
textView.setTextColor(0xffffffff);
textView.setAutoLinkMask(Linkify.WEB_URLS);
textView.setLayoutParams(new LinearLayout.LayoutParams(FPAR, FPAR));
tscroll.addView(textView);
// Add a layout to hold the buttons.
buttonHolder = new LinearLayout(parentApp);
buttonHolder.setBackgroundColor(0xf08080);
buttonHolder.setOrientation(LinearLayout.HORIZONTAL);
buttonHolder.setPadding(6, 3, 3, 3);
layout.addView(buttonHolder,
new LinearLayout.LayoutParams(FPAR, WCON));
// Add the OK button.
Button but = new Button(parentApp);
but.setText(buttonLabel);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
okButtonPressed();
}
});
buttonHolder.addView(but, new LinearLayout.LayoutParams(WCON, WCON, 1));
return layout;
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Set a link button on this dialog. These are buttons that the
* user can click to open a URL, e.g. the project page, license,
* etc.
*
* @param which Which button to set: BUTTON_1 or BUTTON_2.
* @param label The button label as a resource ID.
* @param link Resource ID of the URL for the button.
*/
public void setLinkButton(int which, int label, int link) {
final int WCON = LinearLayout.LayoutParams.WRAP_CONTENT;
// Add the requested button, if not there yet.
int count = buttonHolder.getChildCount();
for (int i = count; i <= which; ++i) {
Button but = new Button(parentApp);
but.setId(i);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b) {
linkButtonPressed(((Button) b).getId());
}
});
LinearLayout.LayoutParams lp;
lp = new LinearLayout.LayoutParams(WCON, WCON);
lp.gravity = Gravity.RIGHT;
buttonHolder.addView(but, lp);
}
// Set up the button as desired.
Button but = (Button) buttonHolder.getChildAt(which);
but.setText(label);
buttonLinks[which] = link;
}
/**
* Set the subtitle for the about box.
*
* @param textId ID of the subtitle to display; if 0, don't show one.
*/
public void setSubtitle(int textId) {
setSubtitle(textId == 0 ? null : resources.getString(textId));
}
/**
* Set the subtitle for the about box.
*
* @param text Subtitle to display; if null, don't show one.
*/
public void setSubtitle(String text) {
if (text == null) {
subtitleView.setVisibility(View.GONE);
subtitleBar.setVisibility(View.GONE);
} else {
subtitleView.setText(text);
subtitleView.setVisibility(View.VISIBLE);
subtitleBar.setVisibility(View.VISIBLE);
}
}
// ******************************************************************** //
// Dialog control.
// ******************************************************************** //
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Text to display in the dialog.
*/
public void show(int title, int text) {
setTitle(title);
textView.setText(text);
show();
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param text Text to display in the dialog.
*/
public void show(int text) {
textView.setText(text);
show();
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param text Text to display in the dialog.
*/
public void show(String text) {
textView.setText(text);
show();
}
// ******************************************************************** //
// Input Handling.
// ******************************************************************** //
/**
* Called when the OK button is clicked.
*/
protected void okButtonPressed() {
dismiss();
}
/**
* Called when a link button is clicked.
*
* @param which The ID of the link button which has been
* clicked, as passed to
* {@link #setLinkButton(int, int, int)}.
*/
protected void linkButtonPressed(int which) {
if (which < 1 || which >= buttonLinks.length)
return;
int URLId = buttonLinks[which];
String URLText = resources.getString(URLId);
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(URLText));
parentApp.startActivity(myIntent);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Parent application context.
private Activity parentApp;
// App's resources.
private Resources resources;
// Text view we use to show the subtitle, and divider bar.
private TextView subtitleView;
private ImageView subtitleBar;
// Text view we use to show the text.
private TextView textView;
// Layout to hold the link buttons.
private LinearLayout buttonHolder;
// OK button label.
private int buttonLabel;
// The URLs associated with the user-specified link buttons.
private int[] buttonLinks;
}
| 9,889 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TextInputDialog.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/notice/TextInputDialog.java |
/**
* org.hermit.android.notice: various notice dialogs for Android.
*
* These classes are designed to help display notices of various kinds.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.notice;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
/**
* This class implements a popup input box (a subclass of AlertDialog)
* which can be used to display a prompt and read a text string from
* the user.
*/
public class TextInputDialog
extends AlertDialog
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Listener invoked when the user clicks the OK button.
*/
public interface OnOkListener {
/**
* The OK button has been clicked.
*
* @param input The input text.
*/
public void onOk(CharSequence input);
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param okBut The resource ID of the text for the OK button.
* @param cancelBut The resource ID of the text for the cancel button.
*/
public TextInputDialog(Context parent, int okBut, int cancelBut) {
this(parent, parent.getText(okBut), parent.getText(cancelBut));
}
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param okBut The text for the OK button.
* @param cancelBut The text for the cancel button.
*/
public TextInputDialog(Context parent, CharSequence okBut, CharSequence cancelBut) {
super(parent);
// Set an appropriate icon.
setIcon(android.R.drawable.ic_dialog_info);
// Set up a custom view for getting the text.
setView(createInputView(parent));
// Set up an OK button and a cancel button.
setButton(BUTTON_POSITIVE, okBut, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
okButtonPressed();
}
});
setButton(BUTTON_NEGATIVE, cancelBut, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
}
/**
* Create the input view for this dialog. This is basically just a prompt
* and input field, both of which can be initialized when the dialog
* is shown.
*
* @param parent Application context.
* @return The input view.
*/
private View createInputView(Context parent) {
LinearLayout view = new LinearLayout(parent);
view.setOrientation(LinearLayout.VERTICAL);
LayoutParams lp;
inputPrompt = new TextView(parent);
inputPrompt.setGravity(Gravity.LEFT);
inputPrompt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
inputPrompt.setTextColor(Color.WHITE);
inputPrompt.setText("Enter text:");
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(20, 20, 20, 10);
view.addView(inputPrompt, lp);
inputField = new EditText(parent);
inputField.setHorizontallyScrolling(true);
inputField.setGravity(Gravity.FILL_HORIZONTAL);
inputField.setTextAppearance(parent, android.R.attr.textAppearanceMedium);
lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(20, 10, 20, 20);
view.addView(inputField, lp);
return view;
}
// ******************************************************************** //
// Dialog control.
// ******************************************************************** //
/**
* Set a listener for the dialog.
*
* @param listener The listener to set.
*/
public void setOnOkListener(OnOkListener listener) {
this.listener = listener;
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
*/
public void show(int title, int text) {
show(title, text, "");
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
* @param dflt Default text to display in the input field.
*/
public void show(int title, int text, String dflt) {
setTitle(title);
inputPrompt.setText(text);
inputField.setText(dflt);
show();
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
*/
public void show(String title, String text) {
show(title, text, "");
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
* @param dflt Default text to display in the input field.
*/
public void show(String title, String text, String dflt) {
setTitle(title);
inputPrompt.setText(text);
inputField.setText(dflt);
show();
}
// ******************************************************************** //
// Input Handling.
// ******************************************************************** //
/**
* Called when the OK button is clicked.
*/
void okButtonPressed() {
dismiss();
if (listener != null)
listener.onOk(inputField.getText());
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Input prompt label.
private TextView inputPrompt;
// Input field.
private EditText inputField;
// User's OK listener. null if not set.
private OnOkListener listener = null;
}
| 6,981 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
YesNoDialog.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/notice/YesNoDialog.java |
/**
* org.hermit.android.notice: various notice dialogs for Android.
*
* These classes are designed to help display notices of various kinds.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.notice;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
/**
* This class implements a popup dialog box (a subclass of AlertDialog)
* which can be used to display a yes / no question.
*/
public class YesNoDialog
extends AlertDialog
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Listener invoked when the user clicks the OK button.
*/
public interface OnOkListener {
/**
* The OK button has been clicked.
*/
public void onOk();
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param okBut The resource ID of the text for the OK button.
* @param cancelBut The resource ID of the text for the cancel button.
*/
public YesNoDialog(Context parent, int okBut, int cancelBut) {
this(parent, parent.getText(okBut), parent.getText(cancelBut));
}
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param okBut The text for the OK button.
* @param cancelBut The text for the cancel button.
*/
public YesNoDialog(Context parent, CharSequence okBut, CharSequence cancelBut) {
super(parent);
appContext = parent;
// Set an appropriate icon.
setIcon(android.R.drawable.ic_dialog_info);
// Set up an OK button and a cancel button.
setButton(BUTTON_POSITIVE, okBut, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
okButtonPressed();
}
});
setButton(BUTTON_NEGATIVE, cancelBut, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
}
// ******************************************************************** //
// Dialog control.
// ******************************************************************** //
/**
* Set a listener for the dialog.
*
* @param listener The listener to set.
*/
public void setOnOkListener(OnOkListener listener) {
this.listener = listener;
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
*/
public void show(int title, int text) {
show(appContext.getText(title), appContext.getText(text));
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Input prompt to display in the dialog.
*/
public void show(CharSequence title, CharSequence text) {
setTitle(title);
setMessage(text);
show();
}
// ******************************************************************** //
// Input Handling.
// ******************************************************************** //
/**
* Called when the OK button is clicked.
*/
void okButtonPressed() {
dismiss();
if (listener != null)
listener.onOk();
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// App context.
private final Context appContext;
// User's OK listener. null if not set.
private OnOkListener listener = null;
}
| 4,442 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
ErrorDialog.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/notice/ErrorDialog.java |
/**
* org.hermit.android.notice: various notice dialogs for Android.
*
* These classes are designed to help display notices of various kinds.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.notice;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
/**
* This class implements a popup error box (a subclass of AlertDialog)
* which can be used to display an error message.
*/
public class ErrorDialog
extends AlertDialog
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param button The resource ID of the text for the OK button.
*/
public ErrorDialog(Context parent, int button) {
this(parent, parent.getText(button));
}
/**
* Create an error dialog.
*
* @param parent Parent application context.
* @param button The text for the OK button.
*/
public ErrorDialog(Context parent, CharSequence button) {
super(parent);
setIcon(android.R.drawable.ic_dialog_alert);
setButton(button, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
okButtonPressed();
}
});
}
// ******************************************************************** //
// Dialog control.
// ******************************************************************** //
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param title Title for the dialog.
* @param text Text to display in the dialog.
*/
public void show(String title, String text) {
setTitle(title);
setMessage(text);
show();
}
/**
* Start the dialog and display it on screen. The window is placed in
* the application layer and opaque.
*
* @param text Text to display in the dialog.
*/
public void show(String text) {
setMessage(text);
show();
}
// ******************************************************************** //
// Input Handling.
// ******************************************************************** //
/**
* Called when the OK button is clicked.
*/
void okButtonPressed() {
dismiss();
}
}
| 2,946 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
AppUtils.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/AppUtils.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
/**
* This class provides some simple application-related utilities.
*/
public class AppUtils
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Version info detail level.
*/
public enum Detail {
/** Do not display. */
NONE,
/** Show basic name and version. */
SIMPLE,
/** Show debug-level detail. */
DEBUG;
}
/**
* Information on an application version.
*/
public class Version {
/** Application's pretty name. null if unknown. */
public CharSequence appName = null;
/** Version code of the app. -1 if unknown. */
public int versionCode = -1;
/** Version name of the app. null if unknown. */
public CharSequence versionName = null;
/** Description either of the app or the version. null if unknown. */
public CharSequence appDesc = null;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Set up an app utils instance for the given activity. This is private;
* users call getInstance() instead.
*
* @param parent Activity for which we want information.
*/
private AppUtils(Activity parent) {
parentApp = parent;
resources = parent.getResources();
}
/**
* Get the app utils instance for this Activity.
*
* @param parent Activity for which we want information.
* @return The application utilities instance for this
* app.
*/
public static AppUtils getInstance(Activity parent) {
if (utilsInstance == null)
utilsInstance = new AppUtils(parent);
return utilsInstance;
}
// ******************************************************************** //
// Current App Info.
// ******************************************************************** //
/**
* Get the version info for the current app.
*
* @return App version info. null if the info could
* not be found.
*/
public Version getAppVersion() {
// If we have the info, just return it.
if (appVersion != null)
return appVersion;
// Get the package manager.
PackageManager pm = parentApp.getPackageManager();
// Get our package name and use it to get our package info. We
// don't need the optional info.
String pname = parentApp.getPackageName();
try {
appVersion = new Version();
PackageInfo pinfo = pm.getPackageInfo(pname, 0);
appVersion.versionCode = pinfo.versionCode;
appVersion.versionName = pinfo.versionName;
// Get the pretty name and description of the app.
ApplicationInfo ainfo = pinfo.applicationInfo;
if (ainfo != null) {
int alabel = ainfo.labelRes;
if (alabel != 0)
appVersion.appName = resources.getText(alabel);
int dlabel = ainfo.descriptionRes;
if (dlabel != 0)
appVersion.appDesc = resources.getText(dlabel);
}
} catch (NameNotFoundException e) {
appVersion = null;
}
return appVersion;
}
/**
* Get a string containing the name and version info for the current
* app's package, in a simple format.
*
* @return Descriptive name / version string.
*/
public String getVersionString() {
return getVersionString(Detail.SIMPLE);
}
/**
* Get a string containing the name and version info for the current
* app's package.
*
* @param detail How much detail we want.
* @return Descriptive name / version string.
*/
public String getVersionString(Detail detail) {
String pname = parentApp.getPackageName();
Version ver = getAppVersion();
if (ver == null)
return String.format("%s (no info)", pname);
CharSequence aname = ver.appName;
if (aname == null)
aname = "?";
int vcode = ver.versionCode;
CharSequence vname = ver.versionName;
if (vname == null)
vname = "?.?";
String res = null;
if (detail == Detail.DEBUG)
res = String.format("%s (%s) %s (%d)", aname, pname, vname, vcode);
else
res = String.format("%s %s", aname, vname);
return res;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// The single instance of this class; null if not set up yet.
private static AppUtils utilsInstance = null;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Parent application context.
private Activity parentApp;
// App's resources.
private Resources resources;
// Version info for this application instance. null if we don't
// have it yet.
private Version appVersion = null;
}
| 5,966 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
OneTimeDialog.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/OneTimeDialog.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import org.hermit.android.notice.InfoBox;
import android.app.Activity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* A class which handles showing one-off notices. This can be used for a
* EULA, or for "new feature" notices which show once per app version.
*
* <p>A benefit of this class is that it doesn't create the notice object
* unless it needs to be shown; most times it doesn't.
*
* @author Ian Cameron Smith
*/
public class OneTimeDialog
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a dialog for showing a notice, or other warnings / disclaimers,
* once only.
*
* <p>When your app starts, call {@link #showFirst()} to display
* the dialog the first time your app runs. This will actually show it
* if it hasn't been seen for the current version of the app.
*
* <p>To display the notice on demand, call {@link #show()}.
*
* @param parent Our parent activity.
* @param name Name for this notice. This should be an internal
* identifier; it will be used to name the preference
* we use.
* @param title Resource ID of the dialog title.
* @param text Resource ID of the notice / warning text.
* @param close Resource ID of the close button.
*/
public OneTimeDialog(Activity parent, String name, int title, int text, int close) {
parentApp = parent;
// Save the notice name and contents.
noticeName = name;
noticeTitle = title;
noticeText = text;
noticeClose = close;
// Create the preference name.
prefName = PREF_PREFIX + noticeName + "Version";
if (appUtils == null)
appUtils = AppUtils.getInstance(parentApp);
if (appPrefs == null)
appPrefs = PreferenceManager.getDefaultSharedPreferences(parentApp);
}
// ******************************************************************** //
// Notice Control.
// ******************************************************************** //
/**
* Show the dialog if this is the first program run.
*/
public void showFirst() {
if (!isAccepted())
show();
}
/**
* Show the dialog unconditionally.
*/
public void show() {
if (noticeDialog == null) {
noticeDialog = new InfoBox(parentApp, noticeClose) {
@Override
protected void okButtonPressed() {
setSeen();
super.okButtonPressed();
}
};
}
noticeDialog.show(noticeTitle, noticeText);
}
/**
* Query whether the dialog has been shown to the user and accepted.
*
* @return True iff the user has seen the dialog and
* clicked "OK".
*/
protected boolean isAccepted() {
AppUtils.Version version = appUtils.getAppVersion();
int seen = -1;
try {
seen = appPrefs.getInt(prefName, seen);
} catch (Exception e) { }
// We consider the EULA accepted if the version seen by the user
// most recently is the current version -- not an earlier or
// later version.
return seen == version.versionCode;
}
/**
* Flag that this dialog has been seen, by setting a preference.
*/
private void setSeen() {
AppUtils.Version version = appUtils.getAppVersion();
SharedPreferences.Editor editor = appPrefs.edit();
editor.putInt(prefName, version.versionCode);
editor.commit();
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Prefix of the preference used to flag that the dialog has been seen
// at a given app version.
private static final String PREF_PREFIX = "org.hermit.android.core.";
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Application utilities instance, used to get app version.
private static AppUtils appUtils = null;
// Application's default shared preferences.
private static SharedPreferences appPrefs = null;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Our parent activity.
private final Activity parentApp;
// Name for this notice. This should be an internal identifier; it
// will be used to name the preference we use.
private final String noticeName;
// Resource IDs of the dialog title, the notice / warning text,
// and the close button label.
private final int noticeTitle;
private final int noticeText;
private final int noticeClose;
// Preference name for this notice. This preference is used to store
// the "accepted" flag.
private final String prefName;
// The EULA dialog.
private InfoBox noticeDialog;
}
| 6,193 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
HelpActivity.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/HelpActivity.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.util.Linkify;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* An activity which displays an application's help, in a structured
* format. Help is supplied via resources arrays; one array contains
* the titles of the help sections, one contains the texts for each
* section. Sub-sections can be added.
*
* <p>To use: subclass this activity, and have the subclass call
* {@link #addHelpFromArrays(int, int)}. Then start this activity when
* you need to display help.
*
* <p>It is recommended that you configure this activity to handle orientation
* and keyboardHidden configuration changes in your app manifest.
*/
public class HelpActivity
extends Activity
{
// ******************************************************************** //
// Activity Lifecycle.
// ******************************************************************** //
/**
* Called when the activity is starting. This is where most
* initialization should go: calling setContentView(int) to inflate
* the activity's UI, etc.
*
* @param icicle Saved application state, if any.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create a scrolling panel as the main view.
mainView = new ScrollView(this);
setContentView(mainView);
}
/**
* This method is called after onStart() when the activity is being
* re-initialized from a previously saved state, given here in state.
* Most implementations will simply use onCreate(Bundle) to restore
* their state, but it is sometimes convenient to do it here after
* all of the initialization has been done or to allow subclasses
* to decide whether to use your default implementation. The default
* implementation of this method performs a restore of any view
* state that had previously been frozen by onSaveInstanceState(Bundle).
*
* This method is called between onStart() and onPostCreate(Bundle).
*
* @param inState The data most recently supplied in
* onSaveInstanceState(Bundle).
*/
@Override
protected void onRestoreInstanceState(Bundle inState) {
super.onRestoreInstanceState(inState);
restoreState(inState);
}
/**
* Called to retrieve per-instance state from an activity before being
* killed so that the state can be restored in onCreate(Bundle) or
* onRestoreInstanceState(Bundle) (the Bundle populated by this method
* will be passed to both).
*
* If called, this method will occur before onStop(). There are no
* guarantees about whether it will occur before or after onPause().
*
* @param outState A Bundle in which to place any state
* information you wish to save.
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState(outState);
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Add help to this help activity.
*
* <p>The parameters are the resource IDs of two arrays; the first
* contains the titles of the help sections, the second contains the
* bodies of the sections. The arrays must be the same length.
*
* <p>A title and the corresponding content may both be resource
* IDs of further arrays. These arrays will be added as sub-sections
* in the most recently-added section. There must be an enclosing
* outer section.
*
* <p>If this method is called more than once, help will be added to the
* top level. (This isn't really recommended.)
*
* @param titlesId Resource ID of the titles array.
* @param textsId Resource ID of the contents array.
*/
protected void addHelpFromArrays(int titlesId, int textsId) {
// Create a new level-0 help view, and add it to the main view.
HelpView hv = new HelpView(0, titlesId, textsId);
mainView.addView(hv);
}
// ******************************************************************** //
// Private Classes.
// ******************************************************************** //
/**
* This class implements a help view, containing structured
* help text.
*/
private final class HelpView
extends LinearLayout
{
/**
* Construct a help view.
*
* @param level Nesting level for this view.
* @param titlesId Resource ID of the titles array.
* @param textsId Resource ID of the contents array.
*/
private HelpView(int level, int titlesId, int textsId) {
super(HelpActivity.this);
setOrientation(VERTICAL);
Resources res = getResources();
// Get the section titles and texts from resources.
TypedArray titles = res.obtainTypedArray(titlesId);
final int nTitles = titles.length();
TypedArray texts = res.obtainTypedArray(textsId);
final int nTexts = texts.length();
if (nTitles != nTexts)
throw new IllegalArgumentException("HelpActivity:" +
" titles and contents arrays" +
" must be the same length");
// Now process all the titles and their corresponding contents.
TypedValue title = new TypedValue();
TypedValue text = new TypedValue();
for (int t = 0; t < nTitles; ++t) {
titles.getValue(t, title);
texts.getValue(t, text);
if (title.type != text.type)
throw new IllegalArgumentException("HelpActivity:" +
" titles and contents values" +
" must be the same type (item " + t + ")");
switch (title.type) {
case TypedValue.TYPE_STRING:
if (title.string.length() == 0)
addSimple(level, text);
else
addSection(level, title, text);
break;
case TypedValue.TYPE_REFERENCE:
addSubs(level, title, text);
break;
default:
throw new IllegalArgumentException("HelpActivity:" +
" invalid item type (item " + t + ")");
}
}
}
private void addSimple(int level, TypedValue text) {
LinearLayout.LayoutParams lp;
ViewGroup body = new BodyView(HelpActivity.this, level, text.string);
lp = new LinearLayout.LayoutParams(FPAR, WCON);
addView(body, lp);
prevBody = body;
}
private void addSection(int level, TypedValue title, TypedValue text) {
LinearLayout.LayoutParams lp;
ViewGroup body = new BodyView(HelpActivity.this, level + 1, text.string);
ViewGroup head = new TitleView(HelpActivity.this, level, title.string, body);
lp = new LinearLayout.LayoutParams(FPAR, WCON);
lp.topMargin = 6;
lp.leftMargin = level * 32;
addView(head, lp);
lp = new LinearLayout.LayoutParams(FPAR, WCON);
addView(body, lp);
prevBody = body;
}
private void addSubs(int level, TypedValue title, TypedValue text) {
if (prevBody == null)
throw new IllegalArgumentException("HelpActivity:" +
" sub-sections must be attached" +
" to an enclosing section");
ViewGroup body = new HelpView(level + 1, title.resourceId, text.resourceId);
prevBody.addView(body, new LinearLayout.LayoutParams(FPAR, WCON));
prevBody = body;
}
// The most recently added section body.
private ViewGroup prevBody = null;
}
/**
* This class implements a title view; it controls the visibility
* of its associated content.
*/
private static final class TitleView
extends LinearLayout
implements View.OnClickListener
{
/**
* Construct a title view.
*
* @param parent Parent activity.
* @param level Nesting level for this view.
* @param title Title string
* @param body The view displaying the content for this
* section. Its visibility will
* be controlled by this TitleView.
*/
private TitleView(Activity parent, int level, CharSequence title, View body) {
super(parent);
setOrientation(HORIZONTAL);
// Store the reference to the body for later.
bodyView = body;
// Set our overall background colour depending on the
// section level.
setBackgroundColor(LEVEL_COLS[level % LEVEL_COLS.length]);
LayoutParams lp;
// Add an expand control. Because Android libraries can't
// have their own resources, we use a text view showing "+"
// and "-".
expandView = new TextView(parent);
expandView.setTextColor(0xff0000ff);
expandView.setTextSize(38 - level * 4);
int s = (int) expandView.getTextSize();
expandView.setPadding(s / 4, 0, 0, 0);
expandView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
lp = new LayoutParams(s, FPAR);
addView(expandView, lp);
// Create the title text view.
textView = new TextView(parent);
textView.setTextColor(0xff000000);
textView.setTextSize(28 - level * 4);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setText(title);
lp = new LayoutParams(FPAR, FPAR);
addView(textView, lp);
setExpanded(false);
setClickable(true);
setOnClickListener(this);
}
@Override
public void onClick(View v) {
setExpanded(!bodyVis);
}
/**
* Set this section to be expanded or not.
*/
private void setExpanded(boolean expanded) {
bodyVis = expanded;
expandView.setText(bodyVis ? "–" : "+");
bodyView.setVisibility(bodyVis ? VISIBLE : GONE);
}
/**
* Check whether this section is expanded or not.
*/
private boolean isExpanded() {
return bodyVis;
}
private TextView expandView = null;
private TextView textView = null;
private View bodyView = null;
private boolean bodyVis = false;
}
/**
* This class implements a section body view. It's basically
* just text, but sub-sections may be added to it, so we use
* LinearLayout.
*/
private static final class BodyView extends LinearLayout {
/**
* Construct a body view.
*
* @param parent Parent activity.
* @param level Nesting level for this view.
* @param text Content text string
*/
private BodyView(Activity parent, int level, CharSequence text) {
super(parent);
setOrientation(VERTICAL);
// Create the body text view, and make URLs active. Note: when
// we use Linkify, it's necessary to call setTextColor() to
// avoid all the text blacking out on click.
TextView bt = new TextView(parent);
bt.setAutoLinkMask(Linkify.WEB_URLS);
bt.setLinksClickable(true);
bt.setTextSize(16);
bt.setTextColor(0xffc0c0ff);
bt.setPadding(level * 32, 0, 0, 0);
bt.setText(text);
LayoutParams lp = new LayoutParams(FPAR, WCON);
addView(bt, lp);
}
}
// ******************************************************************** //
// Save and Restore.
// ******************************************************************** //
/**
* Save our state to the given Bundle.
*
* @param outState A Bundle in which to place any state
* information you wish to save.
*/
private void saveState(Bundle outState) {
saveViewState(mainView, outState, "");
}
/**
* Save the state of a view and its contents to the given Bundle.
*
* @param view The view to save.
* @param outState A Bundle in which to place any state
* information you wish to save.
* @param prefix Prefix for the saved info keys.
*/
private void saveViewState(ViewGroup view, Bundle outState, String prefix) {
if (view instanceof TitleView)
outState.putBoolean(prefix + "expanded", ((TitleView) view).isExpanded());
int nkids = view.getChildCount();
for (int i = 0; i < nkids; ++i) {
View v = view.getChildAt(i);
if (v instanceof HelpView)
saveViewState((HelpView) v, outState, prefix + "H" + i + ".");
else if (v instanceof TitleView)
saveViewState((TitleView) v, outState, prefix + "T" + i + ".");
else if (v instanceof BodyView)
saveViewState((BodyView) v, outState, prefix + "B" + i + ".");
}
}
/**
* Restore our state from the given Bundle.
*
* @param inState The state to restore.
*/
private void restoreState(Bundle inState) {
restoreViewState(mainView, inState, "");
}
/**
* Restore our state from the given Bundle.
*
* @param view The view to restore.
* @param inState The state to restore.
* @param prefix Prefix for the saved info keys.
*/
private void restoreViewState(ViewGroup view, Bundle inState, String prefix) {
if (view instanceof TitleView) {
boolean exp = inState.getBoolean(prefix + "expanded", false);
((TitleView) view).setExpanded(exp);
}
int nkids = view.getChildCount();
for (int i = 0; i < nkids; ++i) {
View v = view.getChildAt(i);
if (v instanceof HelpView)
restoreViewState((HelpView) v, inState, prefix + "H" + i + ".");
else if (v instanceof TitleView)
restoreViewState((TitleView) v, inState, prefix + "T" + i + ".");
else if (v instanceof BodyView)
restoreViewState((BodyView) v, inState, prefix + "B" + i + ".");
}
}
// ******************************************************************** //
// Private Constants.
// ******************************************************************** //
// Colours for the headings at various levels.
private static final int[] LEVEL_COLS = {
0xff008c8c, 0xff8c8c00, 0xff8c008c
};
// Convenience shorthands.
private static final int FPAR = LinearLayout.LayoutParams.FILL_PARENT;
private static final int WCON = LinearLayout.LayoutParams.WRAP_CONTENT;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The main top-level view; the scroll view that contains the
// top-level help widget.
private ScrollView mainView = null;
}
| 17,374 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SplashActivity.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/SplashActivity.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
/**
* An activity which displays a splash screen and then returns to the
* calling activity.
*/
public class SplashActivity
extends Activity
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Extras key for the image resource ID. The extras data named
* by this key is an int which specifies the image to display.
*/
public static final String EXTRAS_IMAGE_ID = "image_id";
/**
* Extras key for the splash screen display time. The extras data named
* by this key is the time in ms for which the splash screen should be
* displayed.
*/
public static final String EXTRAS_TIME_ID = "splash_time";
// ******************************************************************** //
// Activity Lifecycle.
// ******************************************************************** //
/**
* Called when the activity is starting. This is where most
* initialization should go: calling setContentView(int) to inflate
* the activity's UI, etc.
*
* @param icicle Saved application state, if any.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// We don't want a title bar or status bar.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Get our parameters from the intent.
Intent intent = getIntent();
int imageId = intent.getIntExtra(EXTRAS_IMAGE_ID, 0);
long time = intent.getLongExtra(EXTRAS_TIME_ID, 3000);
// Create the splash view.
ImageView splashView = new ImageView(this);
splashView.setScaleType(ScaleType.CENTER_CROP);
splashView.setImageResource(imageId);
setContentView(splashView);
// On click, finish.
splashView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Set up a handler that closes the splash screen.
Handler splashHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
finish();
}
};
splashHandler.sendEmptyMessageDelayed(1, time);
}
// ******************************************************************** //
// Convenience Methods.
// ******************************************************************** //
/**
* Launch a splash screen displaying the given drawable.
*
* @param context Application context we're running in.
* @param image Resource ID of the image to display.
* @param time Time in ms for which the splash screen should
* be visible.
*/
public static void launch(Context context, int image, long time) {
Intent intent = new Intent(context, SplashActivity.class);
intent.putExtra(SplashActivity.EXTRAS_IMAGE_ID, image);
intent.putExtra(SplashActivity.EXTRAS_TIME_ID, time);
context.startActivity(intent);
}
}
| 4,453 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
MainActivity.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/MainActivity.java | /**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* * © 2014 Michael Mueller <[email protected]>
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import java.util.HashMap;
import org.hermit.android.R;
import org.hermit.android.notice.InfoBox;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
/**
* An enhanced Activity class, for use as the main activity of an application.
* The main thing this class provides is a nice callback-based mechanism for
* starting sub-activities. This makes it easier for different parts of an app
* to kick off sub-activities and get the results.
*
* <p>
* Note: it is best that sub-classes do not implement onActivityResult(int, int,
* Intent). If they do, then for safety use small request codes, and call
* super.onActivityResult(int, int, Intent) when you get an unknown code.
*
* @author Ian Cameron Smith
*/
public class MainActivity extends Activity {
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* This interface defines a listener for sub-activity results.
*/
public static abstract class ActivityListener {
/**
* Called when an activity you launched exits.
*
* <p>
* Applications can override this to be informed when an activity
* finishes, either by an error, the user pressing "back", or normally,
* or whatever. The default implementation calls either
* onActivityCanceled(), if resultCode == RESULT_CANCELED, or else
* onActivityResult().
*
* @param resultCode
* The integer result code returned by the child activity
* through its setResult().
* @param data
* Additional data returned by the activity.
*/
public void onActivityFinished(int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED)
onActivityCanceled(data);
else
onActivityResult(resultCode, data);
}
/**
* Called when an activity you launched exits with a result code of
* RESULT_CANCELED. This will happen if the user presses "back", or if
* the activity returned that code explicitly, didn't return any result,
* or crashed during its operation.
*
* <p>
* Applications can override this if they want to be separately notified
* of a RESULT_CANCELED. It doesn't make sense to override both
* onActivityFinished() and this method.
*
* @param data
* Additional data returned by the activity.
*/
public void onActivityCanceled(Intent data) {
}
/**
* Called when an activity you launched exits with a result code other
* than RESULT_CANCELED, giving you the resultCode it returned, and any
* additional data from it.
*
* <p>
* Applications can override this if they want to be separately notified
* of a normal exit. It doesn't make sense to override both
* onActivityFinished() and this method.
*
* @param resultCode
* The integer result code returned by the child activity
* through its setResult().
* @param data
* Additional data returned by the activity.
*/
public void onActivityResult(int resultCode, Intent data) {
}
// This listener's request code. This code is auto-assigned
// the first time the listener is used, and is used to find it
// from the response.
private int requestCode = 0;
}
// ******************************************************************** //
// Activity Lifecycle.
// ******************************************************************** //
/**
* Called when the activity is starting. This is where most initialisation
* should go: calling setContentView(int) to inflate the activity's UI, etc.
*
* You can call finish() from within this function, in which case
* onDestroy() will be immediately called without any of the rest of the
* activity lifecycle executing.
*
* Derived classes must call through to the super class's implementation of
* this method. If they do not, an exception will be thrown.
*
* @param icicle
* If the activity is being re-initialised after previously being
* shut down then this Bundle contains the data it most recently
* supplied in onSaveInstanceState(Bundle). Note: Otherwise it is
* null.
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
appUtils = AppUtils.getInstance(this);
errorReporter = Errors.getInstance(this);
}
// ******************************************************************** //
// EULA Dialog.
// ******************************************************************** //
/**
* Create a dialog for showing the EULA, or other warnings / disclaimers.
* When your app starts, call {@link #showFirstEula()} to display the dialog
* the first time your app runs. To display it on demand, call
* {@link #showEula()}.
*
* @param title
* Resource ID of the dialog title.
* @param text
* Resource ID of the EULA / warning text.
* @param close
* Resource ID of the close button.
*/
public void createEulaBox(int title, int text, int close) {
eulaDialog = new OneTimeDialog(this, "eula", title, text, close);
}
/**
* Show the EULA dialog if this is the first program run. You need to have
* created the dialog by calling {@link #createEulaBox(int, int, int)}.
*/
public void showFirstEula() {
if (eulaDialog != null)
eulaDialog.showFirst();
}
/**
* Show the EULA dialog unconditionally. You need to have created the dialog
* by calling {@link #createEulaBox(int, int, int)}.
*/
public void showEula() {
if (eulaDialog != null)
eulaDialog.show();
}
// ******************************************************************** //
// Help and About Boxes.
// ******************************************************************** //
/**
* Create a dialog for help / about boxes etc. If you want to display one of
* those, set up the info in it by calling {@link #setHomeInfo(int, int)},
* {@link #setAboutInfo(int)} and {@link #setLicenseInfo(int, int)}; then
* pop up a dialog by calling {@link #showAbout()}.
*
* @param close
* Resource ID of the close button.
* @deprecated The message box is now created automatically.
*/
@Deprecated
public void createMessageBox(int close) {
messageDialog = new InfoBox(this, close);
String version = appUtils.getVersionString();
messageDialog.setTitle(version);
}
/**
* Set up the about info for dialogs. See {@link #showAbout()}.
*
* @param about
* Resource ID of the about text.
*/
public void setAboutInfo(int about) {
aboutText = about;
}
/**
* Set up the homepage info for dialogs. See {@link #showAbout()}.
*
* @param link
* Resource ID of the URL the button links to.
*/
public void setHomeInfo(int link) {
homeButton = R.string.button_homepage;
homeLink = link;
}
/**
* Set up the homepage info for dialogs. See {@link #showAbout()}.
*
* @param button
* Resource ID of the button text.
* @param link
* Resource ID of the URL the button links to.
*/
@Deprecated
public void setHomeInfo(int button, int link) {
homeButton = button;
homeLink = link;
}
/**
* Set up the license info for dialogs. See {@link #showAbout()}.
*
* @param link
* Resource ID of the URL the button links to.
*/
public void setLicenseInfo(int link) {
licButton = R.string.button_license;
licLink = link;
}
/**
* Set up the license info for dialogs. See {@link #showAbout()}.
*
* @param button
* Resource ID of the button text.
* @param link
* Resource ID of the URL the button links to.
*/
@Deprecated
public void setLicenseInfo(int button, int link) {
licButton = button;
licLink = link;
}
/**
* Show an about dialog. You need to have configured it by calling
* {@link #setAboutInfo(int)}, {@link #setHomeInfo(int, int)} and
* {@link #setLicenseInfo(int, int)}.
*/
public void showAbout() {
// Create the dialog the first time.
if (messageDialog == null)
createMessageBox();
messageDialog.setLinkButton(1, homeButton, homeLink);
if (licButton != 0 && licLink != 0)
messageDialog.setLinkButton(2, licButton, licLink);
messageDialog.show(aboutText);
}
/**
* Create a dialog for help / about boxes etc. If you want to display one of
* those, set up the info in it by calling {@link #setHomeInfo(int, int)},
* {@link #setAboutInfo(int)} and {@link #setLicenseInfo(int, int)}; then
* pop up a dialog by calling {@link #showAbout()}.
*/
private void createMessageBox() {
messageDialog = new InfoBox(this);
String version = appUtils.getVersionString();
messageDialog.setTitle(version);
}
// ******************************************************************** //
// Exception Reporting.
// ******************************************************************** //
/**
* Report an unexpected exception to the user by popping up a dialog with
* some debug info. Don't report the same exception more than twice, and if
* we get floods of exceptions, just bomb out.
*
* <p>
* This method may be called from any thread. The reporting will be deferred
* to the UI thread.
*
* @param e
* The exception.
*/
public void reportException(final Exception e) {
errorReporter.reportException(e);
}
// ******************************************************************** //
// Sub-Activities.
// ******************************************************************** //
/**
* Launch an activity for which you would like a result when it finished.
* When this activity exits, the given ActivityListener will be invoked.
*
* <p>
* Note that this method should only be used with Intent protocols that are
* defined to return a result. In other protocols (such as ACTION_MAIN or
* ACTION_VIEW), you may not get the result when you expect.
*
* As a special case, if you call startActivityForResult() during the
* initial onCreate() / onResume() of your activity, then your window will
* not be displayed until a result is returned back from the started
* activity.
*
* This method throws ActivityNotFoundException if there was no Activity
* found to run the given Intent.
*
* @param intent
* The intent to start.
* @param listener
* Listener to invoke when the activity returns.
*/
public void startActivityForResult(Intent intent, ActivityListener listener) {
// If this listener doesn't yet have a request code, give it one,
// and add it to the map so we can find it again. On subsequent calls
// we re-use the same code.
if (listener.requestCode == 0) {
listener.requestCode = nextRequest++;
codeMap.put(listener.requestCode, listener);
}
// Start the sub-activity.
startActivityForResult(intent, listener.requestCode);
}
// ******************************************************************** //
// Activity Management.
// ******************************************************************** //
/**
* Called when an activity you launched exits, giving you the requestCode
* you started it with, the resultCode it returned, and any additional data
* from it. The resultCode will be RESULT_CANCELED if the activity
* explicitly returned that, didn't return any result, or crashed during its
* operation.
*
* @param requestCode
* The integer request code originally supplied to
* startActivityForResult(), allowing you to identify who this
* result came from.
* @param resultCode
* The integer result code returned by the child activity through
* its setResult().
* @param data
* Additional data to return to the caller.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ActivityListener listener = codeMap.get(requestCode);
if (listener == null)
Log.e("MainActivity", "Unknown request code: " + requestCode);
else
listener.onActivityFinished(resultCode, data);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application utilities instance, used to get app version.
private AppUtils appUtils = null;
// Exception reporter.
private Errors errorReporter;
// The next request code available to be used. Our request codes
// start at a large number, for no special reason.
private int nextRequest = 0x60000000;
// This map translates request codes to the listeners registered for
// those requests. It is used when a response is received to activate
// the correct listener.
private HashMap<Integer, ActivityListener> codeMap = new HashMap<Integer, ActivityListener>();
// The EULA dialog. Null if the user hasn't set one up.
private OneTimeDialog eulaDialog = null;
// Dialog used to display about etc.
private InfoBox messageDialog = null;
// IDs of the button strings and URLs for "Home" and "License".
private int homeButton = 0;
private int homeLink = 0;
private int licButton = 0;
private int licLink = 0;
// ID of the about text.
private int aboutText = 0;
}
| 14,078 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
SurfaceRunner.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/SurfaceRunner.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import org.hermit.utils.CharFormatter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Common base for applications with an animated view. This class can be
* used in games etc. It handles all the setup states of a SurfaceView,
* and provides a Thread which the app can use to manage the animation.
*
* <p>When using this class in an app, the app context <b>must</b> call
* these methods (usually from its corresponding Activity methods):
*
* <ul>
* <li>{@link #onStart()}
* <li>{@link #onResume()}
* <li>{@link #onPause()}
* <li>{@link #onStop()}
* </ul>
*
* <p>The surface is enabled once it is created and sized, and
* {@link #onStart()} and {@link #onResume()} have been called. You then
* start and stop it by calling {@link #surfaceStart()} and
* {@link #surfaceStop()}.
*/
public abstract class SurfaceRunner
extends SurfaceView
implements SurfaceHolder.Callback
{
// ******************************************************************** //
// Public Constants.
// ******************************************************************** //
/**
* Surface runner option: handle configuration changes dynamically.
* If set, configuration changes such as screen orientation changes
* will be passed up to the app; otherwise, it is assumed that we
* will re-start for these.
*/
public static final int SURFACE_DYNAMIC = 0x0001;
/**
* Surface runner option: use a Looper to drive animations.
* This allows asynchronous updates to be posted by the app.
*/
public static final int LOOPED_TICKER = 0x0002;
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a SurfaceRunner instance.
*
* @param app The application context we're running in.
*/
public SurfaceRunner(Context app) {
super(app);
init(app, 0);
}
/**
* Create a SurfaceRunner instance.
*
* @param app The application context we're running in.
* @param options Options for this SurfaceRunner. A bitwise OR of
* SURFACE_XXX constants.
*/
public SurfaceRunner(Context app, int options) {
super(app);
init(app, options);
}
/**
* Create a SurfaceRunner instance.
*
* @param app The application context we're running in.
* @param attrs Layout attributes for this SurfaceRunner.
*/
public SurfaceRunner(Context app, AttributeSet attrs) {
super(app, attrs);
init(app, 0);
}
/**
* Initialize this SurfaceRunner instance.
*
* @param app The application context we're running in.
* @param options Options for this SurfaceRunner. A bitwise OR of
* SURFACE_XXX constants.
*/
private void init(Context app, int options) {
appContext = app;
errorReporter = Errors.getInstance(app);
surfaceOptions = options;
animationDelay = 0;
// Register for events on the surface.
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
// Workaround for edge fading -- sometimes after repeated orientation
// changes one edge will fade; this fixes it.
setHorizontalFadingEdgeEnabled(false);
setVerticalFadingEdgeEnabled(false);
}
// ******************************************************************** //
// Configuration.
// ******************************************************************** //
/**
* Check whether the given option flag is set on this surface.
*
* @param option The option flag to test; one of SURFACE_XXX.
* @return true iff the option is set.
*/
public boolean optionSet(int option) {
return (surfaceOptions & option) != 0;
}
// ******************************************************************** //
// State Handling.
// ******************************************************************** //
/**
* Set the delay in ms in each iteration of the main loop.
*
* @param delay The time in ms to sleep each time round the main
* animation loop. If zero, we will not sleep,
* but will run continuously.
*
* <p>If you want to do all your animation under
* direct app control using {@link #postUpdate()},
* just set a large delay. You may want to consider
* using 1000 -- i.e. one second -- to make sure
* you get a refresh at a decent interval.
*/
public void setDelay(long delay) {
Log.i(TAG, "setDelay " + delay);
animationDelay = delay;
}
/**
* This is called immediately after the surface is first created.
* Implementations of this should start up whatever rendering code
* they desire.
*
* Note that only one thread can ever draw into a Surface, so you
* should not draw into the Surface here if your normal rendering
* will be in another thread.
*
* @param holder The SurfaceHolder whose surface is being created.
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
setEnable(ENABLE_SURFACE, "surfaceCreated");
}
/**
* This is called immediately after any structural changes (format or
* size) have been made to the surface. This method is always
* called at least once, after surfaceCreated(SurfaceHolder).
*
* @param holder The SurfaceHolder whose surface has changed.
* @param format The new PixelFormat of the surface.
* @param width The new width of the surface.
* @param height The new height of the surface.
*/
@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height)
{
// On Droid (at least) this can get called after a rotation,
// which shouldn't happen as we should get shut down first.
// Ignore that, unless we're handling config changes dynamically.
if (!optionSet(SURFACE_DYNAMIC) && isEnable(ENABLE_SIZE)) {
Log.e(TAG, "ignored surfaceChanged " + width + "x" + height);
return;
}
setSize(format, width, height);
setEnable(ENABLE_SIZE, "set size " + width + "x" + height);
}
/**
* This is called immediately before a surface is destroyed.
* After returning from this call, you should no longer try to
* access this surface. If you have a rendering thread that directly
* accesses the surface, you must ensure that thread is no longer
* touching the Surface before returning from this function.
*
* @param holder The SurfaceHolder whose surface is being destroyed.
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
clearEnable(ENABLE_SURFACE, "surfaceDestroyed");
}
/**
* The application is starting. Applications must call this from their
* Activity.onStart() method.
*/
public void onStart() {
Log.i(TAG, "onStart");
// Tell the subclass to start.
try {
appStart();
} catch (Exception e) {
errorReporter.reportException(e);
}
}
/**
* We're resuming the app. Applications must call this from their
* Activity.onResume() method.
*/
public void onResume() {
setEnable(ENABLE_RESUMED, "onResume");
}
/**
* Start the surface running. Applications must call this to set
* the surface going. They may use this to implement their own level
* of start/stop control, for example to implement a "pause" button.
*/
public void surfaceStart() {
setEnable(ENABLE_STARTED, "surfaceStart");
}
/**
* Stop the surface running. Applications may call this to stop
* the surface running. They may use this to implement their own level
* of start/stop control, for example to implement a "pause" button.
*/
public void surfaceStop() {
clearEnable(ENABLE_STARTED, "surfaceStop");
}
/**
* Pause the app. Applications must call this from their
* Activity.onPause() method.
*/
public void onPause() {
clearEnable(ENABLE_RESUMED, "onPause");
}
/**
* The application is closing down. Applications must call
* this from their Activity.onStop() method.
*/
public void onStop() {
Log.i(TAG, "onStop()");
// Make sure we're paused.
onPause();
// Tell the subclass.
try {
appStop();
} catch (Exception e) {
errorReporter.reportException(e);
}
}
/**
* Handle changes in focus. When we lose focus, pause the game
* so a popup (like the menu) doesn't cause havoc.
*
* @param hasWindowFocus True iff we have focus.
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (!hasWindowFocus)
clearEnable(ENABLE_FOCUSED, "onWindowFocusChanged");
else
setEnable(ENABLE_FOCUSED, "onWindowFocusChanged");
}
/**
* Query the given enable flag.
*
* @param flag The flag to check.
* @return The flag value.
*/
private boolean isEnable(int flag) {
boolean val = false;
synchronized (surfaceHolder) {
val = (enableFlags & flag) == flag;
}
return val;
}
/**
* Set the given enable flag, and see if we're good to go.
*
* @param flag The flag to set.
* @param why Short tag explaining why, for debugging.
*/
private void setEnable(int flag, String why) {
boolean enabled1 = false;
boolean enabled2 = false;
synchronized (surfaceHolder) {
enabled1 = (enableFlags & ENABLE_ALL) == ENABLE_ALL;
enableFlags |= flag;
enabled2 = (enableFlags & ENABLE_ALL) == ENABLE_ALL;
Log.i(TAG, "EN + " + why + " -> " + enableString());
}
// Are we all set?
if (!enabled1 && enabled2)
startRun();
}
/**
* Clear the given enable flag, and see if we need to shut down.
*
* @param flag The flag to clear.
* @param why Short tag explaining why, for debugging.
*/
private void clearEnable(int flag, String why) {
boolean enabled1 = false;
boolean enabled2 = false;
synchronized (surfaceHolder) {
enabled1 = (enableFlags & ENABLE_ALL) == ENABLE_ALL;
enableFlags &= ~flag;
enabled2 = (enableFlags & ENABLE_ALL) == ENABLE_ALL;
Log.i(TAG, "EN - " + why + " -> " + enableString());
}
// Do we need to stop?
if (enabled1 && !enabled2)
stopRun();
}
/**
* Get the current enable state as a string for debugging.
*
* @return The current enable state as a string.
*/
private String enableString() {
char[] buf = new char[5];
buf[0] = (enableFlags & ENABLE_SURFACE) != 0 ? 'S' : '-';
buf[1] = (enableFlags & ENABLE_SIZE) != 0 ? 'Z' : '-';
buf[2] = (enableFlags & ENABLE_RESUMED) != 0 ? 'R' : '-';
buf[3] = (enableFlags & ENABLE_STARTED) != 0 ? 'A' : '-';
buf[4] = (enableFlags & ENABLE_FOCUSED) != 0 ? 'F' : '-';
return String.valueOf(buf);
}
/**
* Start the animation running. All the conditions we need to
* run are present (surface, size, resumed).
*/
private void startRun() {
synchronized (surfaceHolder) {
// Tell the subclass we're running.
try {
animStart();
} catch (Exception e) {
errorReporter.reportException(e);
}
if (animTicker != null && animTicker.isAlive())
animTicker.kill();
Log.i(TAG, "set running: start ticker");
animTicker = !optionSet(LOOPED_TICKER) ?
new ThreadTicker() : new LoopTicker();
}
}
/**
* Stop the animation running. Our surface may have been destroyed, so
* stop all accesses to it. If the caller is not the ticker thread,
* this method will only return when the ticker thread has died.
*/
private void stopRun() {
// Kill the thread if it's running, and wait for it to die.
// This is important when the surface is destroyed, as we can't
// touch the surface after we return. But if I am the ticker
// thread, don't wait for myself to die.
Ticker ticker = null;
synchronized (surfaceHolder) {
ticker = animTicker;
}
if (ticker != null && ticker.isAlive()) {
if (onSurfaceThread())
ticker.kill();
else
ticker.killAndWait();
}
synchronized (surfaceHolder) {
animTicker = null;
}
// Tell the subclass we've stopped.
try {
animStop();
} catch (Exception e) {
errorReporter.reportException(e);
}
}
/**
* Set the size of the table.
*
* @param format The new PixelFormat of the surface.
* @param width The new width of the surface.
* @param height The new height of the surface.
*/
private void setSize(int format, int width, int height) {
synchronized (surfaceHolder) {
canvasWidth = width;
canvasHeight = height;
// Create the pixmap for the background image.
switch (format) {
case PixelFormat.A_8:
canvasConfig = Bitmap.Config.ALPHA_8;
break;
case PixelFormat.RGBA_4444:
canvasConfig = Bitmap.Config.ARGB_4444;
break;
case PixelFormat.RGBA_8888:
canvasConfig = Bitmap.Config.ARGB_8888;
break;
case PixelFormat.RGB_565:
canvasConfig = Bitmap.Config.RGB_565;
break;
default:
canvasConfig = Bitmap.Config.RGB_565;
break;
}
try {
appSize(canvasWidth, canvasHeight, canvasConfig);
} catch (Exception e) {
errorReporter.reportException(e);
}
}
// Do the stats setup.
statsInit();
}
// ******************************************************************** //
// Run Control.
// ******************************************************************** //
/**
* Asynchronously schedule an update; i.e. a frame of animation.
* This can only be called if the SurfaceRunner was created with
* the option LOOPED_TICKER.
*/
public void postUpdate() {
synchronized (surfaceHolder) {
if (!(animTicker instanceof LoopTicker))
throw new IllegalArgumentException("Can't post updates" +
" without LOOPED_TICKER set");
LoopTicker ticker = (LoopTicker) animTicker;
ticker.post();
}
}
private void tick() {
try {
// Do the application's physics.
long now = System.currentTimeMillis();
doUpdate(now);
if (showPerf)
statsTimeInt(1, (System.currentTimeMillis() - now) * 1000);
// And update the screen.
refreshScreen(now);
} catch (Exception e) {
errorReporter.reportException(e);
}
}
/**
* Draw the game board to the screen in its current state, as a one-off.
* This can be used to refresh the screen.
*/
private void refreshScreen(long now) {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
long drawStart = System.currentTimeMillis();
doDraw(canvas, now);
if (showPerf) {
long drawEnd = System.currentTimeMillis();
statsTimeInt(2, (drawEnd - drawStart) * 1000);
}
// Show performance data, if required.
if (showPerf) {
// Count frames per second.
statsCountInt(0, 1);
// If it's time to make a new displayed total, tot up
// the figures and reset the running counts.
if (now - perfLastTime > STATS_UPDATE) {
statsDraw();
perfLastTime = now;
}
// Draw the stats on screen.
canvas.drawBitmap(perfBitmap, perfPosX, perfPosY, null);
}
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (canvas != null)
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
// ******************************************************************** //
// Client Methods.
// ******************************************************************** //
/**
* The application is starting. Perform any initial set-up prior to
* starting the application. We may not have a screen size yet,
* so this is not a good place to allocate resources which depend on
* that.
*/
protected abstract void appStart();
/**
* Set the screen size. This is guaranteed to be called before
* animStart(), but perhaps not before appStart().
*
* @param width The new width of the surface.
* @param height The new height of the surface.
* @param config The pixel format of the surface.
*/
protected abstract void appSize(int width, int height, Bitmap.Config config);
/**
* We are starting the animation loop. The screen size is known.
*
* <p>doUpdate() and doDraw() may be called from this point on.
*/
protected abstract void animStart();
/**
* We are stopping the animation loop, for example to pause the app.
*
* <p>doUpdate() and doDraw() will not be called from this point on.
*/
protected abstract void animStop();
/**
* The application is closing down. Clean up any resources.
*/
protected abstract void appStop();
/**
* Update the state of the application for the current frame.
*
* <p>Applications must override this, and can use it to update
* for example the physics of a game. This may be a no-op in some cases.
*
* <p>doDraw() will always be called after this method is called;
* however, the converse is not true, as we sometimes need to draw
* just to update the screen. Hence this method is useful for
* updates which are dependent on time rather than frames.
*
* @param now Current time in ms.
*/
protected abstract void doUpdate(long now);
/**
* Draw the current frame of the application.
*
* <p>Applications must override this, and are expected to draw the
* entire screen into the provided canvas.
*
* <p>This method will always be called after a call to doUpdate(),
* and also when the screen needs to be re-drawn.
*
* @param canvas The Canvas to draw into.
* @param now Current time in ms. Will be the same as that
* passed to doUpdate(), if there was a preceeding
* call to doUpdate().
*/
protected abstract void doDraw(Canvas canvas, long now);
// ******************************************************************** //
// Client Utilities.
// ******************************************************************** //
/**
* Get the String value of a resource.
*
* @param resid The ID of the resource we want.
* @return The resource value.
*/
public String getRes(int resid) {
return appContext.getString(resid);
}
/**
* Get a Bitmap which is the same size and format as the surface.
* This can be used to get an off-screen rendering buffer, for
* example.
*
* @return A Bitmap which is the same size and pixel
* format as the screen.
*/
public Bitmap getBitmap() {
return Bitmap.createBitmap(canvasWidth, canvasHeight, canvasConfig);
}
/**
* Get a Bitmap of a given size, in the same format as the surface.
* This can be used to get an off-screen rendering buffer, for
* example.
*
* @param w Desired width in pixels.
* @param h Desired height in pixels.
* @return A Bitmap which is the same size and pixel
* format as the screen.
*/
public Bitmap getBitmap(int w, int h) {
return Bitmap.createBitmap(w, h, canvasConfig);
}
/**
* Determine whether the caller is on the surface's animation thread.
*
* @return The resource value.
*/
public boolean onSurfaceThread() {
return Thread.currentThread() == animTicker;
}
// ******************************************************************** //
// Debug Control.
// ******************************************************************** //
/**
* Turn display of performance info on or off.
*
* @param enable True to enable performance display.
*/
public void setDebugPerf(boolean enable) {
showPerf = enable;
}
/**
* Set the screen position at which we display performance info.
*
* @param x Screen X position.
* @param y Screen Y position.
*/
public void setDebugPos(int x, int y) {
perfPosX = x;
perfPosY = y;
}
// ******************************************************************** //
// Stats Handling.
// ******************************************************************** //
/**
* Reserve space in the stats display for some application performance
* stats. The given labels will become stats which will be displayed if
* {@link #setDebugPerf(boolean enable)} is passed true. Each stat is
* subsequently referred to by its index in this labels array.
*
* <p>This method must be called before appStart() in order for the
* app's stats to be displayed. After appStart() is called, the stats
* content is frozen until the next appStop() / appStart().
* Typically the app should invoke this method from its constructor.
* However this method is, of course, optional.
*
* @param labels Labels for the app's stats, one label
* per stat. Labels need to be 7 chars or less.
*/
protected void statsCreate(String[] labels) {
perfAppLabels = labels;
}
/**
* Set up the stats display for the next run. At this point the stats
* the app has prepared by calling statsCreate() are frozen.
*/
private void statsInit() {
// Make a Paint for drawing performance data.
perfPaint = new Paint();
perfPaint.setColor(0xffff0000);
perfPaint.setTypeface(Typeface.MONOSPACE);
// Set up buffers for the performance data OSD. Make space for the
// app's stats as well as our own.
int nstats = 3;
if (perfAppLabels != null)
nstats += perfAppLabels.length;
perfBuffers = new char[nstats][];
int i;
for (i = 0; i < nstats; ++i)
perfBuffers[i] = new char[14];
i = 0;
CharFormatter.formatString(perfBuffers[i++], 6, " fps", 8);
CharFormatter.formatString(perfBuffers[i++], 6, " µs phys", 8);
CharFormatter.formatString(perfBuffers[i++], 6, " µs draw", 8);
if (perfAppLabels != null)
for (String alab : perfAppLabels)
CharFormatter.formatString(perfBuffers[i++], 6, " " + alab, 8);
// Now make a bitmap for the stats.
perfBitmap = Bitmap.createBitmap(100, nstats * 12 + 4, canvasConfig);
perfCanvas = new Canvas(perfBitmap);
// Make the values and counts arrays.
perfStats = new int[nstats];
perfCounts = new int[nstats];
}
/**
* Increment a performance counter. This method is used for counts
* of specific quantities, which will be displayed as counts per second;
* for example frames per second.
*
* @param index Index of the stat to bump (its index in the
* "labels" argument to
* {@link #statsCreate(String[] labels)}).
* @param val Amount to add to the counter.
*/
public void statsCount(int index, int val) {
statsCountInt(index + 3, val);
}
/**
* Increment a performance counter. This method is used for counts
* of specific quantities, which will be displayed as counts per second;
* for example frames per second.
*
* @param index Index of the stat to bump (its absolute index,
* which includes internal stats).
* @param val Amount to add to the counter.
*/
private void statsCountInt(int index, int val) {
if (val < 0)
return;
if (showPerf && index >= 0 && index < perfStats.length)
perfStats[index] += val;
}
/**
* Record a performance timer. This method is used for timings
* of specific activities; the average of the recorded values will
* be displayed.
*
* @param index Index of the stat to record (its index in the
* "labels" argument to
* {@link #statsCreate(String[] labels)}).
* @param val The time value for this iteration.
*/
public void statsTime(int index, long val) {
statsTimeInt(index + 3, val);
}
/**
* Record a performance timer. This method is used for timings
* of specific activities; the average of the recorded values will
* be displayed.
*
* @param index Index of the stat to record (its absolute index,
* which includes internal stats).
* @param val The time value for this iteration.
*/
private void statsTimeInt(int index, long val) {
if (val < 0)
return;
if (showPerf && index >= 0 && index < perfStats.length) {
perfStats[index] += (int) val;
++perfCounts[index];
}
}
/**
* Draw the stats into perfBitmap.
*/
private void statsDraw() {
// Format all the values we have.
for (int i = 0; i < perfStats.length && i < perfBuffers.length; ++i) {
int v = perfStats[i];
int c = perfCounts[i];
if (c != 0)
v /= c;
else
v = v * 1000 / STATS_UPDATE;
CharFormatter.formatInt(perfBuffers[i], 0, v, 6, false);
}
// Draw the stats into the canvas.
perfCanvas.drawColor(0xff000000);
for (int i = 0; i < perfBuffers.length; ++i)
perfCanvas.drawText(perfBuffers[i], 0, perfBuffers[i].length,
0, i * 12 + 12, perfPaint);
// Reset all stored stats.
for (int i = 0; i < perfStats.length && i < perfBuffers.length; ++i) {
perfStats[i] = 0;
perfCounts[i] = 0;
}
}
// ******************************************************************** //
// Private Classes.
// ******************************************************************** //
/**
* Base interface for the ticker we use to control the animation.
*/
private interface Ticker {
// Stop this thread. There will be no new calls to tick() after this.
public void kill();
// Stop this thread and wait for it to die. When we return, it is
// guaranteed that tick() will never be called again.
//
// Caution: if this is called from within tick(), deadlock is
// guaranteed.
public void killAndWait();
// Run method for this thread -- simply call tick() a lot until
// enable is false.
public void run();
// Determine whether this ticker is still going.
public boolean isAlive();
}
/**
* Thread-based ticker class. This may be faster than LoopTicker.
*/
private class ThreadTicker
extends Thread
implements Ticker
{
// Constructor -- start at once.
private ThreadTicker() {
super("Surface Runner");
Log.v(TAG, "ThreadTicker: start");
enable = true;
start();
}
// Stop this thread. There will be no new calls to tick() after this.
@Override
public void kill() {
Log.v(TAG, "ThreadTicker: kill");
enable = false;
}
// Stop this thread and wait for it to die. When we return, it is
// guaranteed that tick() will never be called again.
//
// Caution: if this is called from within tick(), deadlock is
// guaranteed.
@Override
public void killAndWait() {
Log.v(TAG, "ThreadTicker: killAndWait");
if (Thread.currentThread() == this)
throw new IllegalStateException("ThreadTicker.killAndWait()" +
" called from ticker thread");
enable = false;
// Wait for the thread to finish. Ignore interrupts.
if (isAlive()) {
boolean retry = true;
while (retry) {
try {
join();
retry = false;
} catch (InterruptedException e) { }
}
Log.v(TAG, "ThreadTicker: killed");
} else {
Log.v(TAG, "Ticker: was dead");
}
}
// Run method for this thread -- simply call tick() a lot until
// enable is false.
@Override
public void run() {
while (enable) {
tick();
if (animationDelay != 0) try {
sleep(animationDelay);
} catch (InterruptedException e) { }
}
}
// Flag used to terminate this thread -- when false, we die.
private boolean enable = false;
}
/**
* Looper-based ticker class. This has the advantage that asynchronous
* updates can be scheduled by passing it a message.
*/
private class LoopTicker
extends Thread
implements Ticker
{
// Constructor -- start at once.
private LoopTicker() {
super("Surface Runner");
Log.v(TAG, "Ticker: start");
start();
}
// Post a tick. An update will be done near-immediately on the
// appropriate thread.
public void post() {
synchronized (this) {
if (msgHandler == null)
return;
// Remove any delayed ticks.
msgHandler.removeMessages(MSG_TICK);
// Do a tick right now.
msgHandler.sendEmptyMessage(MSG_TICK);
}
}
// Stop this thread. There will be no new calls to tick() after this.
@Override
public void kill() {
Log.v(TAG, "LoopTicker: kill");
synchronized (this) {
if (msgHandler == null)
return;
// Remove any delayed ticks.
msgHandler.removeMessages(MSG_TICK);
// Do an abort right now.
msgHandler.sendEmptyMessage(MSG_ABORT);
}
}
// Stop this thread and wait for it to die. When we return, it is
// guaranteed that tick() will never be called again.
//
// Caution: if this is called from within tick(), deadlock is
// guaranteed.
@Override
public void killAndWait() {
Log.v(TAG, "LoopTicker: killAndWait");
if (Thread.currentThread() == this)
throw new IllegalStateException("LoopTicker.killAndWait()" +
" called from ticker thread");
synchronized (this) {
if (msgHandler == null)
return;
// Remove any delayed ticks.
msgHandler.removeMessages(MSG_TICK);
// Do an abort right now.
msgHandler.sendEmptyMessage(MSG_ABORT);
}
// Wait for the thread to finish. Ignore interrupts.
if (isAlive()) {
boolean retry = true;
while (retry) {
try {
join();
retry = false;
} catch (InterruptedException e) { }
}
Log.v(TAG, "LoopTicker: killed");
} else {
Log.v(TAG, "LoopTicker: was dead");
}
}
@Override
public void run() {
Looper.prepare();
msgHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_TICK:
tick();
if (!msgHandler.hasMessages(MSG_TICK))
msgHandler.sendEmptyMessageDelayed(MSG_TICK,
animationDelay);
break;
case MSG_ABORT:
Looper.myLooper().quit();
break;
}
}
};
// Schedule the first tick.
msgHandler.sendEmptyMessageDelayed(MSG_TICK, animationDelay);
// Go into the processing loop.
Looper.loop();
}
// Message codes.
private static final int MSG_TICK = 6;
private static final int MSG_ABORT = 9;
// Our message handler.
private Handler msgHandler = null;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "SurfaceRunner";
// Enable flags. In order to run, we need onSurfaceCreated() and
// onResume(), which can come in either order. So we track which ones
// we have by these flags. When all are set, we're good to go. Note
// that this is distinct from the game state machine, and its pause
// and resume actions -- the whole game is enabled by the combination
// of these flags set in enableFlags.
private static final int ENABLE_SURFACE = 0x01;
private static final int ENABLE_SIZE = 0x02;
private static final int ENABLE_RESUMED = 0x04;
private static final int ENABLE_STARTED = 0x08;
private static final int ENABLE_FOCUSED = 0x10;
private static final int ENABLE_ALL =
ENABLE_SURFACE | ENABLE_SIZE | ENABLE_RESUMED |
ENABLE_STARTED | ENABLE_FOCUSED;
// Time in ms between stats updates. Figures will be averaged over
// this time.
private static final int STATS_UPDATE = 5000;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application handle.
private Context appContext;
// Error reporter.
private Errors errorReporter;
// The surface manager for the view.
private SurfaceHolder surfaceHolder = null;
// The time in ms to sleep each time round the main animation loop.
// If zero, we will not sleep, but will run continuously.
private long animationDelay = 0;
// Option flags for this instance. A bitwise OR of SURFACE_XXX constants.
private int surfaceOptions = 0;
// Enablement flags; see comment above.
private int enableFlags = 0;
// Width, height and pixel format of the surface.
private int canvasWidth = 0;
private int canvasHeight = 0;
private Bitmap.Config canvasConfig = null;
// The ticker thread which runs the animation. null if not active.
private Ticker animTicker = null;
// Display performance data on-screen.
private boolean showPerf = false;
// Labels for app-supplied performance stats.
private String[] perfAppLabels = null;
// Stored perf stats values for all stats. Counters for each stat.
private int[] perfStats = null;
private int[] perfCounts = null;
// Character buffers for performance / stats annotations.
private char[][] perfBuffers;
// Bitmap for drawing the stats into. Canvas for drawing into it.
private Bitmap perfBitmap = null;
private Canvas perfCanvas = null;
// Paint for drawing performance data.
private Paint perfPaint = null;
// Time of last performance display update.
private long perfLastTime = 0;
// Position to display performance info at.
private int perfPosX = 0;
private int perfPosY = 0;
}
| 38,921 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Errors.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/core/Errors.java |
/**
* org.hermit.android.core: useful Android foundation classes.
*
* These classes are designed to help build various types of application.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.core;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;
/**
* Error handling and reporting utilities.
*
* @author Ian Cameron Smith
*/
public class Errors
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an instance. Since we're a singleton, this is private.
*
* @param context The application context.
*/
private Errors(Context context) {
appContext = context;
}
// ******************************************************************** //
// Exception Reporting.
// ******************************************************************** //
/**
* Get the single instance of this class for the given Activity,
* creating it if necessary.
*
* @param context The Activity for which we want an error reporter.
* @return The single instance of this class.
*/
public static Errors getInstance(Context context) {
Errors instance = activityInstances.get(context);
if (instance == null) {
instance = new Errors(context);
activityInstances.put(context, instance);
}
return instance;
}
// ******************************************************************** //
// Exception Reporting.
// ******************************************************************** //
/**
* Report an unexpected exception to the user by popping up a dialog
* with some debug info. Don't report the same exception more than twice,
* and if we get floods of exceptions, just bomb out.
*
* <p>This method may be called from any thread. The reporting will be
* deferred to the UI thread.
*
* @param context The Activity for which we want an error reporter.
* @param e The exception.
*/
public static void reportException(Context context, final Exception e) {
getInstance(context).reportException(e);
}
/**
* Report an unexpected exception to the user by popping up a dialog
* with some debug info. Don't report the same exception more than twice,
* and if we get floods of exceptions, just bomb out.
*
* <p>This method may be called from any thread. The reporting will be
* deferred to the UI thread.
*
* @param e The exception.
*/
public void reportException(final Exception e) {
final String exString = getErrorString(e);
Log.e("Hermit", exString, e);
if (appContext instanceof Activity) {
((Activity) appContext).runOnUiThread(new Runnable() {
@Override
public void run() {
reportActivityException(e, exString);
}
});
} else {
reportToastException(e, exString);
}
}
// ******************************************************************** //
// Dialog Notifications.
// ******************************************************************** //
/**
* Report an unexpected exception to the user by popping up a dialog
* with some debug info. Don't report the same exception more than twice,
* and if we get floods of exceptions, just bomb out.
*
* <p>This method must be called from the UI thread.
*
* @param e The exception.
* @param exString A string describing the exception.
*/
private void reportActivityException(Exception e, String exString) {
// If we're already shutting down, ignore it.
if (shuttingDown)
return;
String exTitle = "Unexpected Exception";
// Bump the counter for this exception.
int count = countError(exString);
// Over 5 exceptions total, that's too many.
if (exceptionTotal > 5) {
exTitle = "Too Many Errors";
exString += "\n\nToo many errors: closing down";
shuttingDown = true;
}
// Now, if we've had fewer than three, or if we've had too many,
// report it.
if (shuttingDown || count < 3)
showDialog(exTitle, exString);
}
private void showDialog(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(appContext);
builder.setMessage(text)
.setCancelable(false)
.setTitle(title)
.setPositiveButton("OK", dialogListener);
AlertDialog alert = builder.create();
alert.show();
}
private DialogInterface.OnClickListener dialogListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (shuttingDown)
((Activity) appContext).finish();
}
};
// ******************************************************************** //
// Toast Notifications.
// ******************************************************************** //
/**
* Report an unexpected exception to the user by popping up a dialog
* with some debug info. Don't report the same exception more than twice,
* and if we get floods of exceptions, just bomb out.
*
* <p>This method must be called from the UI thread.
*
* @param e The exception.
* @param exString A string describing the exception.
*/
private void reportToastException(Exception e, String exString) {
// If we're already shutting down, ignore it.
if (shuttingDown)
return;
// Bump the counter for this exception.
countError(exString);
// Over 10 exceptions total, that's too many. Don't report any
// more. (We can't actually shut down.)
if (exceptionTotal > 10) {
exString += "\n\nToo many errors: stopping reports";
shuttingDown = true;
}
// Now report it.
showToast(exString);
}
private void showToast(String text) {
Toast toast = Toast.makeText(appContext, text, Toast.LENGTH_LONG);
toast.show();
}
// ******************************************************************** //
// Exception Utilities.
// ******************************************************************** //
private String getErrorString(Exception e) {
StringBuilder text = new StringBuilder();
text.append("Exception: ");
text.append(e.getClass().getName());
String msg = e.getMessage();
if (msg != null)
text.append(": \"" + msg + "\"");
StackTraceElement[] trace = e.getStackTrace();
if (trace != null && trace.length > 0) {
StackTraceElement where = trace[0];
String file = where.getFileName();
int line = where.getLineNumber();
if (file != null && line > 0)
text.append("; " + file + " line " + line);
}
return text.toString();
}
private int countError(String text) {
// Count the specific type of exception.
Integer count = exceptionCounts.get(text);
if (count == null)
count = 1;
else
count = count + 1;
exceptionCounts.put(text, count);
// Count the total number of exceptions for this app. Deduct one
// exception for each 20 seconds that have passed.
long now = System.currentTimeMillis();
exceptionTotal -= (now - lastException) / (20 * 1000);
lastException = now;
if (exceptionTotal < 0)
exceptionTotal = 0;
++exceptionTotal;
return count;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// The Errors instance for each context.
private static HashMap<Context, Errors> activityInstances =
new HashMap<Context, Errors>();
// Counts of how often we've seen each exception type.
private static HashMap<String, Integer> exceptionCounts =
new HashMap<String, Integer>();
// Time of the last exception, and the time-decaying count of exceptions.
private static long lastException = 0;
private static long exceptionTotal = 0;
// True if we've had too many exceptions and need to shut down.
private static boolean shuttingDown = false;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Application handle.
private Context appContext = null;
}
| 9,965 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Player.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/sound/Player.java |
/**
* org.hermit.android.sound: sound effects for Android.
*
* These classes provide functions to help apps manage their sound effects.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.hermit.android.sound;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.util.Log;
/**
* Main sound effects player class. This is a pretty thin wrapper around
* {@link android.media.SoundPool}, but adds some mild usefulness such as
* per-effect volume.
*/
public class Player
{
// ******************************************************************** //
// Package-Shared Types.
// ******************************************************************** //
// Class wrapping up a MediaPlayer with our information about its state.
class PoolPlayer {
/**
* Create a PoolPlayer. This allocates the MediaPlayer.
*/
private PoolPlayer() {
mediaPlayer = new MediaPlayer();
loadedEffect = null;
}
/**
* Play the given sound effect. The sound won't be played if the volume
* would be zero or less.
*
* @param effect The sound effect to play.
* @param vol Volume for this sound, 0 - 1.
* @param loop If true, loop the sound forever.
* @return true iff the sound was loaded OK.
*/
private boolean load(Effect effect, float vol, boolean loop) {
// Set this player up for the given sound.
int resId = effect.getResourceId();
AssetFileDescriptor afd =
appContext.getResources().openRawResourceFd(resId);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(),
afd.getDeclaredLength());
mediaPlayer.prepare();
} catch (Exception e) {
Log.e(TAG, "Failed to set up media player: " + e.getMessage(), e);
return false;
} finally {
try {
afd.close();
} catch (IOException e) { }
}
loadedEffect = effect;
// Set the play volume.
mediaPlayer.setVolume(vol, vol);
// Loop if required.
mediaPlayer.setLooping(loop);
return true;
}
/**
* Start this player.
*/
private void start() {
if (mediaPlayer == null || loadedEffect == null)
throw new IllegalStateException("tried to play with no effect");
mediaPlayer.start();
}
/**
* Stop this player.
*/
private void stop() {
if (mediaPlayer == null || loadedEffect == null)
throw new IllegalStateException("tried to stop with no effect");
mediaPlayer.stop();
loadedEffect = null;
}
/**
* Determine whether this player is playing anything.
*
* @return True iff something is playing in this player.
*/
final boolean isPlaying() {
return mediaPlayer.isPlaying();
}
/**
* Determine whether this player is playing the given effect.
*
* @param e Effect to check.
* @return True iff e is playing in this player.
*/
final boolean isPlaying(Effect e) {
return loadedEffect == e && mediaPlayer.isPlaying();
}
/**
* Releases resources associated with this player and its MediaPlayer
* object.
*/
private void release() {
if (mediaPlayer == null) {
mediaPlayer.release();
mediaPlayer = null;
loadedEffect = null;
}
}
// The actual media player.
private MediaPlayer mediaPlayer;
// The effect it is playing.
private Effect loadedEffect;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a sound effect player that can handle 3 streams at once.
*
* @param context Application context we're running in.
*/
public Player(Context context) {
this(context, 3);
}
/**
* Create a sound effect player.
*
* @param context Application context we're running in.
* @param streams Maximum number of sound streams to play
* simultaneously.
*/
public Player(Context context, int streams) {
appContext = context;
numStreams = streams;
soundEffects = new ArrayList<Effect>();
// The player pool is null until we resume.
playerPool = null;
}
// ******************************************************************** //
// Sound Setup.
// ******************************************************************** //
/**
* Add a sound effect to this player.
*
* @param resId Resource ID of the sound sample for this effect.
* @return An Effect object representing the new effect.
* Use this object to actually play the sound.
*/
public Effect addEffect(int resId) {
return addEffect(resId, 1f);
}
/**
* Add a sound effect to this player.
*
* @param resId Resource ID of the sound sample for this effect.
* @param vol Base volume for this effect.
* @return An Effect object representing the new effect.
* Use this object to actually play the sound.
*/
public Effect addEffect(int resId, float vol) {
Effect effect = new Effect(this, resId, vol);
synchronized (this) {
soundEffects.add(effect);
}
return effect;
}
// ******************************************************************** //
// Suspend / Resume.
// ******************************************************************** //
/**
* Resume this player. This allocates the media resources for all our
* registered sound effects. This method must be called before the
* player can be used, and must be called again after calling
* {@link #suspend()}
*
* <p>It's a good idea for apps to do this in Activity.onResume().
*/
public void resume() {
synchronized (this) {
// Create the player pool.
if (playerPool == null) {
playerPool = new LinkedList<PoolPlayer>();
for (int i = 0; i < numStreams; ++i)
playerPool.add(new PoolPlayer());
}
}
}
/**
* Suspend this player. This closes down the media resources the
* player is using. It's a good idea for apps to do this in
* Activity.onPause().
*
* <p>Following suspend, {@link #resume()} must be called before this
* player can be used again.
*/
public void suspend() {
synchronized (this) {
if (playerPool != null) {
PoolPlayer pp;
while ((pp = playerPool.poll()) != null)
pp.release();
playerPool = null;
}
}
}
/**
* Shut this player down completely. This frees all resources
* associated with this Player.
*
* <p>Following shutdown, this instance can not be used again.
*/
public void shutdown() {
synchronized (this) {
suspend();
soundEffects = null;
appContext = null;
}
}
// ******************************************************************** //
// Sound Playing.
// ******************************************************************** //
/**
* Get the overall gain for sounds.
*
* @return Current gain. 1 = normal; 0 means don't play
* sounds.
*/
public float getGain() {
return soundGain;
}
/**
* Set the overall gain for sounds.
*
* @param gain Desired gain. 1 = normal; 0 means don't play
* sounds.
*/
public void setGain(float gain) {
soundGain = gain;
}
/**
* Play the given sound effect.
*
* @param effect Sound effect to play.
*/
public void play(Effect effect) {
play(effect, 1f, false);
}
/**
* Play the given sound effect. The sound won't be played if the volume
* would be zero or less.
*
* @param effect Sound effect to play.
* @param rvol Relative volume for this sound, 0 - 1.
* @param loop If true, loop the sound forever.
* @throws IllegalStateException Attempting to play before
* {@link #resume()} or after {@link #resume()}.
*/
public void play(Effect effect, float rvol, boolean loop) {
synchronized (this) {
if (playerPool == null)
throw new IllegalStateException("can't play while suspended");
// Calculate the play volume.
float vol = soundGain * rvol;
if (vol <= 0f) {
Log.e(TAG, "Computed volume=" + vol + "; ignoring");
return;
}
if (vol > 1f)
vol = 1f;
// Get the next idle player and push it to the end. Failing that,
// use the least recently used player, which is the first one.
PoolPlayer player = null;
for (PoolPlayer p : playerPool) {
if (!p.isPlaying()) {
player = p;
break;
}
}
if (player == null)
player = playerPool.poll();
playerPool.addLast(player);
// Set this player up for the given sound.
player.load(effect, vol, loop);
// Set it playing.
effect.setPlayer(player);
player.start();
}
}
/**
* Stop the given effect, if it's playing.
*
* @param effect Sound effect to stop.
* @throws IllegalStateException Attempting to stop before
* {@link #resume()} or after {@link #resume()}.
*/
public void stop(Effect effect) {
synchronized (this) {
if (playerPool == null)
throw new IllegalStateException("can't stop while suspended");
PoolPlayer player = effect.getPlayer();
if (player != null) {
player.stop();
effect.setPlayer(null);
}
}
}
/**
* Stop all streams.
*/
public void stopAll() {
synchronized (this) {
for (Effect e : soundEffects)
stop(e);
}
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
private static final String TAG = "sound";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Our parent application context.
private Context appContext;
// Maximum number of sound streams to play simultaneously.
private final int numStreams;
// The pool of players we use to play sounds. The most recently
// started player will be at the end; so the least recently used,
// and the one which should be recycled next, is on top.
// playerPool is null while we are suspended.
private LinkedList<PoolPlayer> playerPool;
// All sound effects.
private ArrayList<Effect> soundEffects;
// Current overall sound gain. If zero, sounds are suppressed.
private float soundGain = 1f;
}
| 12,630 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.