code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * use this in conjunction with other 0LISM classes to make map of neutral densities or temperatures etc. * */ public class NeutralMapMaker { public NeutralMapMaker() { HelioVector bulk = new HelioVector(HelioVector.SPHERICAL,26000.0,(74+180)*Math.PI/180.0,5.5*Math.PI/180); // inflow velocity, density, temperature GaussianVLISM gv = new GaussianVLISM(bulk,1,6300.0); // neutral distribution, mu, ionization rate NeutralDistribution ndH = new NeutralDistribution(gv, 0.0, 3.0*Math.pow(10,-7)); MultipleIntegration mi = new MultipleIntegration(); // set up the coordinates int res = 100; double[] x = new double[res]; double[] y = new double[res]; double[] z = new double[res*res]; double xMin = double yMin = for (int i=0; i<res; i++) int index = 0; for (int i=0; i<res; i++) { for (int j=0; j<res; j++) { z[index]= index++; JColorGraph jcg; if (theMain.monochromeCheckBox.isSelected()) jcg = new JColorGraph(x,y,z,false); else jcg = new JColorGraph(x,y,z); String unitString = "Diff. EFlux (1/cm^2/s/sr)"; if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)"; if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)"; if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)"; jcg.setLabels("SOHO CTOF He+","1996",unitString); jcg.run(); jcg.showIt();\ public static final void main(String[] args) { NeutralMapMaker nmm = new NeutralMapMaker(); } }
Java
/** * The usual "hot model" here.. only with one species for now * */ public class GaussianOxVLISM extends InterstellarMedium { public HelioVector vBulk1; public HelioVector vBulk2; public double temp1, temp2, density, fraction; public static double KB = 1.3807*Math.pow(10,-23); // J/K public static double MP = 1.672621*Math.pow(10,-27); // kg private double Mover2KbT1, Mover2KbT2, norm1, norm2, tt11, tt21, tt31, tt12, tt22, tt32, tt1, tt2; public static double NaN = Double.NaN; /** * Construct a gaussian VLISM * * Here we put a primary and secondary component */ public GaussianOxVLISM(HelioVector _vBulk1, HelioVector _vBulk2, double _density, double _temp1, double _temp2, double _fraction) { vBulk1 = _vBulk1; temp1 = _temp1; vBulk2 = _vBulk2; temp2 = _temp2; density = _density; fraction = _fraction; //System.out.println("created gaussian vlism with ro: " + density + " temp: " + temp + " bulk: " + vBulk.getR()); // normalization for maxwellian distribution norm1 = (1.0-fraction)*density*Math.pow(16.0*MP/2.0/Math.PI/KB/temp1,3.0/2.0); norm2 = fraction*density*Math.pow(16.0*MP/2.0/Math.PI/KB/temp2,3.0/2.0); // argument of exponential requires this factor Mover2KbT1 = 16.0*MP/2.0/KB/temp1; Mover2KbT2 = 16.0*MP/2.0/KB/temp2; } /** * * Pass in a heliovector if you feel like it.. slower? * probably not.. */ public double heliumDist(HelioVector v) { return dist(v.getX(), v.getY(), v.getZ()); } public double heliumDist(double v1, double v2, double v3) { return dist(v1,v2,v3); } /** * default - pass in 3 doubles */ public double dist(double v1, double v2, double v3) { if (v1==NaN | v2==NaN | v3==NaN) return 0.0; tt11 = v1-vBulk1.getX(); tt21 = v2-vBulk1.getY(); tt31 = v3-vBulk1.getZ(); tt12 = v1-vBulk2.getX(); tt22 = v2-vBulk2.getY(); tt32 = v3-vBulk2.getZ(); tt1 = tt11*tt11+tt21*tt21+tt31*tt31; tt2 = tt12*tt12+tt22*tt22+tt32*tt32; return norm1*Math.exp(-Mover2KbT1*tt1) + norm2*Math.exp(-Mover2KbT2*tt2); } public double dist(HelioVector hv) { return dist(hv.getX(), hv.getY(), hv.getZ()); } public double protonDist(double v1, double v2, double v3) { return 0; } public double hydrogenDist(double v1, double v2, double v3) { return 0; } public double deuteriumDist(double v1, double v2, double v3) { return 0; } public double electronDist(double v1, double v2, double v3) { return 0; } public double alphaDist(double v1, double v2, double v3) { return 0; } // etcetera...+ /** * Finally well tested, Aug. 2004 */ public static final void main(String[] args) { /*final GaussianOxVLISM gvli = new GaussianOxVLISM(new HelioVector(HelioVector.CARTESIAN, -20000.0,0.0,0.0), 100.0, 6000.0); System.out.println("Created GVLISM" ); //System.out.println("Maxwellian VLISM created, norm = " + norm); MultipleIntegration mi = new MultipleIntegration(); //mi.setEpsilon(0.001); FunctionIII dist = new FunctionIII () { public double function3(double x, double y, double z) { return gvli.heliumDist(x, y, z); } }; System.out.println("Test dist: " + dist.function3(20000,0,0)); double[] limits = new double[6]; limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY; limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY; limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY; double[] limits2 = new double[6]; limits2[0]=-100000.0; limits2[1]=100000.0; limits2[2]=-100000.0; limits2[3]=100000.0; limits2[4]=-100000.0; limits2[5]=100000.0; double z = mi.integrate(dist,limits,128 ); double z2 = mi.integrate(dist,limits2,128); System.out.println("Integral should equal density= " + z + " " + z2); FunctionIII distZw = new FunctionIII () { public double function3(double r, double p, double t) { HelioVector hv = new HelioVector(HelioVector.SPHERICAL,r,p,t); return gvli.heliumDist(hv)*r*r*Math.sin(t); } }; double[] limitsZw = {0.0,100000.0,0.0,2*Math.PI,0,Math.PI}; double ans = mi.mcIntegrate(distZw, limitsZw, 200000); System.out.println("Integral should equal density= " + ans + " old: " + z + " " + z2);*/ } }
Java
/** * This is an abstract class for modelling the interstellar medium * * use this assuming that the distributions are homogenous * but not necessarily isotropic * * extend this and change the distributions needed for the model */ public abstract class InterstellarMedium { public static double KB = 1.38*Math.pow(10,-23); public static double MP = 1.67*Math.pow(10,-27); public static double PI = Math.PI; /** * Make this maxwellian for now * */ public double dist(double v1, double v2, double v3) { return 0; } public double heliumDist(double v1, double v2, double v3) { return 0; } public double protonDist(double v1, double v2, double v3) { return 0; } public double hydrogenDist(double v1, double v2, double v3) { return 0; } public double deuteriumDist(double v1, double v2, double v3) { return 0; } public double electronDist(double v1, double v2, double v3) { return 0; } public double alphaDist(double v1, double v2, double v3) { return 0; } // etcetera...+ }
Java
import java.lang.Math; import java.util.*; /* Attempt to model pickup distribution including Vincident and B in 3D Warsaw - July 2000 - Lukas Saul Parameters from PickMain (Moebius et al) : "Solar wind: Velocity [km/s], Azimuth[deg],Elevation[deg], Density [cm^(-3)]y" 540.000 177.000 0. 5.00000 "IMF: Magnitude [nT], Azimuth [deg], Elevation [deg]" 10.00000 135.000 0. "Neutr.gas: Density [cm^(-3)],Velocity [km/s],Loss rate [1/s],Ioniz. rate [1/s]" 7.00000E-03 22.5000 6.90000E-08 6.50000E-08 "Pickup ions: Mass [amu], Charge [e], Mean Free Path [AU]" 4.00000 1.00000 1.00000E-01 "Case studies: Interpl. cond., Neutral gas , Velocity Evolution Model." 1.00000 3.00000 1.00000 "Distr.func.: Conv.crit.(dF/F), Diff. Param. Chi0, Adiab. Exp. GAMMA" 1.00000E-02 0.500000 2.00000 "SC attitude (north ecl.pole: elev.=90 deg) and position: " " Elevation [deg], Azimuth [deg], Sun distance [AU]" 90.0000 0. 1.00000 "Vel. distr. F(u,V)- calc. grid: N (<72)-angle, M(<28)-velocity" 18.0000 32.0000 "Accumulation grid in instr. acceptance: E-steps, Ang.steps" 10.00000 10.00000 */ // Distribution in a given "parcel" - region of constant vsw, and B field. public class PickupDistribution { public NeutralDistribution NHe; public SurvivalProbability LHe; public double br,btheta,bphi,vsw,vb,phi0,theta0,T,N0,mu,betaPlus,betaMinus; public PickupDistribution( // all the parameters: // sw parameters: assume radial double br, double btheta, double bphi, double vsw // vlism parameters: double bulkVelocity, double phi0 double theta0 double temperature, double density, // ionization parameters: double radiationToGravityRatio, double lossRate1AU, double pickupRate1AU) { this.br = br; this.btheta = btheta; this.bphi = bphi; this.vsw = vsw; vb = bulkVelocity; this.phi0 = phi0; this.theta0 = theta0; T = temperature; N0 = density; mu = radiationToGravityRation; betaMinus = lossRate1AU; betaPlus = pickupRate1AU; NHe = new NeutralDistribution(vb, phi0, theta0, T, N0, mu); LHe = new SurvivalProbability(betaMinus); } // done constructor public compute(r,theta,phi, vr, vtheta, vphi) { }
Java
import java.util.Vector; /** * DIsplay the results of a NeutralDensity calculation * - lukas saul Nov. 2004 * */ public class DensityDisplay { private file f; private JColorGraph jcg; private double[] x,y,z; public static double AU = 1.49598* Math.pow(10,11); //meters public DensityDisplay() { this("testoutput3.dat"); } public DensityDisplay(String filename) { f = new file(filename); f.initRead(); Vector xv = new Vector(); String line = ""; while ( (line=f.readLine()).length()>2 ) { xv.add(new Double(Double.parseDouble(line))); } x = new double[xv.size()]; y = new double[xv.size()]; z = new double[x.length * y.length]; // cast vector to array for (int i=0; i<x.length; i++) { x[i] = ((Double)xv.elementAt(i)).doubleValue(); //if (x[i]>AU/10) x[i] = x[i]/AU; y[i] = x[i]; System.out.println("i: " + i + " x[i]: " + x[i]); } for (int i=0; i<z.length; i++) { line=f.readLine(); z[i]=Double.parseDouble(line); } jcg = new JColorGraph(x,y,z); jcg.run(); jcg.showIt(); } /** * run this bad boy * */ public static final void main (String[] args) { if (args.length==1) { DensityDisplay dd = new DensityDisplay(args[0]); } else { DensityDisplay dd = new DensityDisplay();} } }
Java
import java.util.Random; public class BenfordDataMaker { public file f; public Random r; public BenfordDataMaker() { r = new Random(); f = new file("testdatarandom.txt"); f.initWrite(false); for (int i =0; i<10000; i++) { f.write(r.nextDouble()+"\t"); f.write(r.nextGaussian()+"\t"); f.write(nextLogNormal()+"\n"); } f.closeWrite(); } public double nextLogNormal() { double q = r.nextGaussian(); return Math.exp(q); } public static final void main(String[] args) { BenfordDataMaker bdm = new BenfordDataMaker(); } }
Java
/** * Utility class for passing around 2D functions * * Use this to get a 1D function by fixing one of the variables.. * the index to fix is passed in ( 0 or 1 ) */ //import gaiatools.numeric.function.Function; public abstract class FunctionII { /** * Override this for the function needed!! * */ public double function2(double x, double y) { return 0; } /** * don't override this one... * */ //MyDouble value_ = new MyDouble(0.0); double value_ = 0.0; /** * here's the Function implementation to return, modified in the public method.. * return this for index = 0 */ FunctionI ff0 = new FunctionI() { public double function(double x) { return function2(value_,x); } }; /** * here's the Function implementation to return, modified in the public method.. * return this for index = 1 */ FunctionI ff1 = new FunctionI() { public double function(double x) { return function2(x,value_); } }; /** * * This returns a one dimensional function, given one of the values fixed * */ public final FunctionI getFunction(final int index, final double value) { //value_=value; if (index == 0) return new FunctionI() { public double function(double x) { return function2(value,x); } }; else if (index == 1) return new FunctionI() { public double function(double x) { return function2(x,value); } }; else { System.out.println("index out of range in FunctionII.getFunction"); return null; } } public static final void main(String[] args) { FunctionI f1 = new FunctionI() { public double function(double x) { return (Math.exp(x*x)); } }; FunctionII f2 = new FunctionII() { public double function2(double x, double y) { return (Math.exp(x*x+y*y)); } }; FunctionI f3 = f2.getFunction(0,0.0); FunctionI f4 = f2.getFunction(1,0.0); System.out.println("f1: " + f1.function(0.5)); System.out.println("f3: " + f3.function(0.5)); System.out.println("f4: " + f4.function(0.5)); } }
Java
// import flanagan.integration.*; //import drasys.or.nonlinear.*; /* * Utility class for passing around functions * * implements the drasys "FunctionI" interface to enable Simpsons method * outsource. */ public abstract class Function implements IntegralFunction { public double function(double var) { return 0; } }
Java
import java.util.StringTokenizer; import java.util.Vector; /** * Adapted for heliosphere display- * * Lets generalize this to read from an unknown 3d (color +2d) field * where we don't know how many points there are. * */ public class IBEX_image { public static double AU = 1.49598* Math.pow(10,11); //meters public IBEX_image(String filename) { file f = new file(filename); //int num2 = 101; Vector xVec = new Vector(); Vector yVec = new Vector(); Vector zVec = new Vector(); String garbage = "garbage"; f.initRead(); String line = ""; // garbage - header int index = 0; while ((line=f.readLine())!=null) { int x=0; int y=0; int z=0; double num=0; StringTokenizer st = new StringTokenizer(line); try { x = (int)(1000.0*(double)Float.parseFloat(st.nextToken())); y = (int)(1000.0*(double)Float.parseFloat(st.nextToken())); garbage = st.nextToken(); z = (int)(1000.0*(double)Float.parseFloat(st.nextToken())); Integer x_d = new Integer(x); Integer y_d = new Integer(y); Integer z_d = new Integer(z); if (!xVec.contains(x_d)) xVec.add(x_d); if (!yVec.contains(y_d)) yVec.add(y_d); zVec.add(z_d); } catch (Exception e) {e.printStackTrace();} index ++; } // lets take a look at what we got.. not sure I like "contains".. for (int i=0; i<yVec.size(); i++) o("y_"+i+" : " + (Integer)yVec.elementAt(i)); for (int i=0; i<xVec.size(); i++) o("x_"+i+" : " + (Integer)xVec.elementAt(i)); System.out.println("x leng: " + xVec.size()); System.out.println("y leng: " + yVec.size()); System.out.println("z leng: " + zVec.size()); double[] xArray = new double[xVec.size()]; double[] yArray = new double[yVec.size()]; double[] zArray = new double[zVec.size()]; for (int i = 0; i<xVec.size(); i++) { xArray[i]=(double)(Integer)xVec.elementAt(i); xArray[i]/=1000.0; } for (int i = 0; i<yVec.size(); i++) { yArray[i]=(double)(Integer)yVec.elementAt(i); yArray[i]/=1000.0; } for (int i = 0; i<zVec.size(); i++) { zArray[i]=(double)(Integer)zVec.elementAt(i); zArray[i]/=1000.0; //zArray[i] = 10.0+Math.log(zArray[i]); } // get min and max of zarray double minz = 1000.0; double maxz = 0.0; for (int j=0; j<zArray.length; j++) { if (zArray[j]>maxz) maxz=zArray[j]; if (zArray[j]<minz) minz=zArray[j]; } System.out.println("minz: "+minz+" maxz: "+maxz); double[][] zArray2 = new double[xVec.size()][yVec.size()]; for (int i=0; i<xArray.length; i++) { for (int j=0; j<yArray.length; j++) { zArray2[i][j]= minz; } } // read file again and assign z value in double array to fix any problems in grid f.initRead(); line = ""; // garbage - header index = 0; while ((line=f.readLine())!=null) { int x=0; int y=0; double z=0.0; double num=0; StringTokenizer st = new StringTokenizer(line); try { x = (int)(1000.0*(double)Float.parseFloat(st.nextToken())); y = (int)(1000.0*(double)Float.parseFloat(st.nextToken())); garbage = st.nextToken(); z = Double.parseDouble(st.nextToken()); //z = 10.0+Math.log(Double.parseDouble(st.nextToken())); Integer x_d = new Integer(x); Integer y_d = new Integer(y); int x_ind = xVec.indexOf(x_d); int y_ind = yVec.indexOf(y_d); if (z<1.0) zArray2[x_ind][y_ind]=0.0; else zArray2[x_ind][y_ind]=z; } catch (Exception e) {e.printStackTrace();} index ++; } zArray = new double[xArray.length*yArray.length]; int iii = 0; for (int i=0; i<xArray.length; i++) { for (int j=0; j<yArray.length; j++) { zArray[iii]=zArray2[i][j]; iii++; } } for (int i = 0; i<yVec.size(); i++) { yArray[i]=yArray[i]*180.0/Math.PI; } JColorGraph jcg = new JColorGraph(xArray,yArray,zArray,true); String unitString = "Counts"; //if (histType == "Flux") unitString = "Diff. Flux (1/cm^2/s/sr/keV)"; //if (histType == "Distribution Function") unitString = "Dist. Function (s^3/km^6)"; //if (histType == "Log Distribution Function") unitString = "log Dist. Function (s^3/km^6)"; jcg.setLabels("IBEX-LO Simulation","UniBern 2008",unitString); jcg.run(); jcg.showIt(); } public static final void main(String[] args) { IBEX_image m = new IBEX_image(args[0]); } public static final void o(String arg) { System.out.println(arg); } }
Java
import java.util.Random; /** * do some time stepping and track trajectories * */ public class HelioTrajectories { public int numToRun = 10000; public int timeStep = 10; // seconds public static double KB = 1.38065 * Math.pow(10,-23); public static double Ms = 1.98892 * Math.pow(10,30); // kg //public static double Ms = 0.0; // kg public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg public static double AU = 1.49598* Math.pow(10,11); //meters public static double NaN = Double.NaN; public static double MAX = Double.MAX_VALUE; // photon momentum = hv/c public static double LA = 2.47 * Math.pow(10,15); // 1/s public static double PC = 6.626 * Math.pow(10,-34); // J*sec public static double CC = 2.998 * Math.pow(10,8); public static double MOM = PC*LA/CC; public HelioVector cPos; // current position public HelioVector cVel; // current velocity public double auFlux = 3.5*Math.pow(10,11); // photons per cm^2 public double crossSection = 1.0*Math.pow(10,-14); public double auFluxOnAtom = auFlux/crossSection; public HelioVector radVec = new HelioVector(); public HelioTrajectories () { r=new Random(); o("one photon momentum: " + MOM); // start them all at the same location.. public HelioVector initPos = new HelioVector(HelioVector.CARTESIAN,-100*AU,0,0); public HelioVector initSpeed = new HelioVector(HelioVector.CARTESIAN,28000.0,0,0); cPos = initPos; cVel = initVel; for (int i=0; i<numToRun; i++) { int numSteps = 100000; for (int step = 0; step<numSteps; step++) { // move the particle according to current velocity cPos.sum(cVel.product(timeStep)); // add to the velocity according to gravity and photon pressure radVec = cPos.normalize().invert(); // points to sun cVel.sum(radVec.product(timeStep*Ms/G/cPos.getR()/cPos.getR())); // ad // give them a speed according to 6300 degrees kelvin and 28 m/s ba // bulk speed is in +x direction // actually lets go with cold model for now.. keep it simple } while ( } public static final void main(String[] args) { HelioTrajectories ht = new HelioTrajectories(); } public void o(String s) { System.out.println(s); } }
Java
import cern.jet.math.Bessel; import java.lang.Math; import java.util.Date; import drasys.or.nonlinear.*; public class VIonBulk{ public static double Ms = 2 * Math.pow(10,30); public static double G = 6.67 * Math.pow(10,-11); BofTheta boftheta; double b,r,v0; public VIonBulk(double r, double v0, double theta) { this.r = r; this.v0 = v0; boftheta = new BofTheta(r, v0); b = boftheta.calculate(theta); } public double Vr() { return -Math.sqrt(2*Ms*G/r - v0*v0*b*b/r/r + v0*v0); } public double Vperp() { return v0*b/r; } } class BofTheta { public static double Ms = 2 * Math.pow(10,30); //kg public static double G = 6.67 * Math.pow(10,-11); // m^3 / (kg s^2) public static double AU = 1.5* Math.pow(10,11); // m private double r, v0; private Trapezoidal s; private EquationSolution es; public BofTheta(double r, double v0) { this.r = r; this.v0 = v0; System.out.println("r= " + r); s = new Trapezoidal(); s.setEpsilon(.1); es = new EquationSolution(); es.setAccuracy(100); es.setMaxIterations(100); } class DThetaDr implements FunctionI { private double b = 0; public DThetaDr(double b) { this.b = b; } public double function(double r_) { return v0*b/(r_*r_) / Math.sqrt(2*Ms*G/r_ - v0*v0*b*b/(r_*r_) + v0*v0); } } class ThetaOfB implements FunctionI { public double function(double b) { System.out.println("ThetaOfB called: b="+b); DThetaDr dthDr = new DThetaDr(b); try { double test= s.integrate(dthDr, 1000*AU, r); System.out.println("integral returns: " + test); return test; }catch (Exception e) { e.printStackTrace(); return 0; } } } public double testThetaOfB(double b_) { ThetaOfB tobTest = new ThetaOfB(); return tobTest.function(b_); } public double calculate(double theta) { ThetaOfB tob = new ThetaOfB(); try { double bLimit = Math.sqrt(2*Ms*G*r/(v0*v0) + r*r); System.out.println("blimit = "+bLimit); double q= es.solve(tob, -bLimit+1000, bLimit-1000, theta); System.out.println("b (AU)= " + q/AU); return q; }catch (Exception e) { e.printStackTrace(); return 0; } } }
Java
/** * * * */ public class MaxwellianDistribution extends Distribution { public double temperature, density, thermalSpeed; /** * */ public MaxwellianDistribution () { temperature = 0; density = 0; thermalSpeed = 0; } public MaxwellianDistribution (double n, double t)) { m/2pikt ^ 3/2 }
Java
public class AI { private Vector aiInputs; // only put AIInputInterfaces here private Vector aiOutputs; // only put AIOutputInterfaces here private AIManager aim; private Compiler compiler; private Runners[] runners; public AI() {
Java
import java.math.*; import java.number.BigInteger; public class JulyPonder { public JulyPonder () { } public static final void main(String[] args) { JulyPonder jp = new JulyPonder(); } }
Java
import java.awt.*; import java.beans.*; import java.awt.print.*; import javax.swing.*; import java.io.*; /** * Allows printing of documents displayed in JDialogs */ class PrintableDialog extends JDialog implements Printable,Serializable { /** * The method @print@ must be implemented for @Printable@ interface. * Parameters are supplied by system. */ public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException { Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.black); //set default foreground color to black //for faster printing, turn off double buffering //RepaintManager.currentManager(this).setDoubleBufferingEnabled(false); Dimension d = this.getSize(); //get size of document double panelWidth = d.width; //width in pixels double panelHeight = d.height; //height in pixels double pageHeight = pf.getImageableHeight(); //height of printer page double pageWidth = pf.getImageableWidth(); //width of printer page double scale = pageWidth/panelWidth; int totalNumPages = (int)Math.ceil(scale * panelHeight / pageHeight); //make sure not print empty pages if(pageIndex >= totalNumPages) { return Printable.NO_SUCH_PAGE; } //shift Graphic to line up with beginning of print-imageable region g2.translate(pf.getImageableX(), pf.getImageableY()); //shift Graphic to line up with beginning of next page to print g2.translate(0f, -pageIndex*pageHeight); //scale the page so the width fits... g2.scale(scale, scale); this.paint(g2); //repaint the page for printing return Printable.PAGE_EXISTS; } }
Java
/** * * Use this to calculate the v dist. of int. helium using * the assumption of isotropic adiabatic cooling * */ public class AdiabaticModel { public double AU = 1.49598* Math.pow(10,11); //meters public double NaN = Double.NaN; public double MAX = Double.MAX_VALUE; public double N0 = Math.pow(10,-6); public double GAMMA = 3.0/2.0; // energy dependence in eflux ?? - inverse gamma in derivation.. //public double beta = 1.0*Math.pow(10,-7); // that is for He public double beta = 7.4*Math.pow(10,-7); static double PI = Math.PI; public double VSW = 350000.0; public static double v_infinity = 27500.0; //m/s public double G = 6.673 * Math.pow(10,-13); // m^3/s^2/kg public static double Ms = 1.98892 * Math.pow(10,30); // kg public static double VINF = 26000.0; public AdiabaticModel() { } public double f(double norm, double gam, double w) { GAMMA = gam; return f(w)*norm; } public double f(double norm, double gam, double w, double _beta) { beta = _beta; return f(norm,gam,w); } public double f(double w) { //if (w<=1-Math.sqrt(VINF*VINF+2*Ms*G/AU)/VSW) return Math.pow(w,1.0-1.0/GAMMA)*N(AU*Math.pow(w,1.0/GAMMA))/GAMMA; //return 0.0; } public double f_old(double w) { if (w<=1) return Math.pow(w,1.0-1.0/GAMMA)*N(AU*Math.pow(w,1.0/GAMMA)); return 0.0; } public double f_test(double w) { return Math.pow(w,1.0-1.0/GAMMA) * N(AU*Math.pow(w,1.0/GAMMA)) / square(1.0 + 1/VSW*Math.sqrt(VINF*VINF+2*Ms*G/AU/Math.pow(w,1.0/GAMMA))); } public double f(double gam, double w) { GAMMA = gam; return f(w); } public static double square(double s) {return s*s;} /** * *Vasyliunas & Siscoe for comparison * */ public double f_vs1(double w) { return Math.exp(-Math.pow(w,-2.0)); } public double f_vs2(double w) { double lam=15.2; return Math.pow(w,-0.75)*Math.exp(-lam*Math.pow(w,-1.5)); } /** * The model of interstellar neutral density.. * * based on cold model, due upwind.. * see Moebius SW&CR homework set #4! */ private double N(double r) { return N0*Math.exp(-beta*AU*AU*Math.sqrt(v_infinity*v_infinity+/*2.0**/G*Ms/2.0/r)/G/Ms); //return N0*Math.exp(-2*beta*AU*AU/r/v_infinity); } public static double e(double a, double b) { return a*Math.pow(10,b); } public static final void main(String[] args) { AdiabaticModel sm = new AdiabaticModel(); sm.G=Math.pow(10.0,-11.0); file f = new file("adiabatic_out_close2.dat"); f.initWrite(false); for (double w=0.0; w<=3.0; w+=0.02) { f.write(w+"\t"); f.write(sm.f(w)+"\t"+sm.f_vs1(w)+"\t"+sm.f_vs2(w)+"\n"); //f.write(""+sm.f(1.0,1.5,w)); //f.write(sm.f(1.0,1.5,w,e(5.0,-9.0))+"\t"+sm.f(1.0,1.5,w,e(1.0,-8.0))+"\t"+sm.f(1.0,1.25,w,e(5.0,-8.0))+"\t"+ // sm.f(1.0,1.5,w,e(1.0,-7.0))+"\t"+sm.f(1.0,1.5,w,e(5.0,-7.0))+"\t"+sm.f(1.0,1.25,w,e(1.0,-6.0)) // ); //f.write("\n"); } f.closeWrite(); /*double[] test = new double[20]; double[] test1 = new double[20]; double[] test2 = new double[20]; double[] test3 = new double[20]; double[] test4 = new double[20]; double[] test5 = new double[20]; double[] test6 = new double[20]; double[] gamma = {0.3d, 0.8d, 1.3d, 1.8d}; file f = new file("adiabatic_out_test2.dat"); f.initWrite(false); int index = 0; for (double w=0.0; w<=1.0; w+=0.02) { index=0; f.write(w+"\t"); while (index<4) { f.write(sm.f(gamma[index],w)+"\t"); index++; } f.write("\n"); } f.closeWrite(); */ } }
Java
//import ij.*; //import ij.gui.*; import java.util.*; import flanagan.math.*; /** * Lukas Saul, UNH Space Science Dept. * Curvefitting utilities here. * * Adapted to use simplex method from flanagan java math libraries - March 2006 * * * > * -- added step function and pulled out of package IJ -- lukas saul, 11/04 * * -- adding EXHAUSTIVE SEARCH ability.. for nonlinear fits * * * -- adding HEMISPHERIC - analytic fit to hemispheric model w/ radial field * see Hemispheric.java for info * * -- adding quadratic that passes through origin for PUI / Np correlation */ public class CurveFitter { public static final int STRAIGHT_LINE=0,POLY2=1,POLY3=2,POLY4=3, EXPONENTIAL=4,POWER=5,LOG=6,RODBARD=7,GAMMA_VARIATE=8, LOG2=9, STEP=10, HEMISPHERIC=11, HTEST=12, QUAD_ORIGIN=13, GAUSSIAN=14, SEMI=15; public static final String[] fitList = {"Straight Line","2nd Degree Polynomial", "3rd Degree Polynomial", "4th Degree Polynomial","Exponential","Power", "log","Rodbard", "Gamma Variate", "y = a+b*ln(x-c)", "Step Function", "Hemispheric", "H-test", "Quadratic Through Origin","Gaussian","Semi"}; public static final String[] fList = {"y = a+bx","y = a+bx+cx^2", "y = a+bx+cx^2+dx^3", "y = a+bx+cx^2+dx^3+ex^4","y = a*exp(bx)","y = ax^b", "y = a*ln(bx)", "y = d+(a-d)/(1+(x/c)^b)", "y = a*(x-b)^c*exp(-(x-b)/d)", "y = a+b*ln(x-c)", "y = a*step(x-b)", "y=hem.f(a,x)", "y = norm*step()..","y=ax+bx^2", "y=a*EXP(-(x-b)^2/c)","y=semi.f(a,b,x)"}; private static final double root2 = 1.414214; // square root of 2 private int fit; // Number of curve type to fit private double[] xData, yData; // x,y data to fit public double[] bestParams; // take this after doing exhaustive for the answer public Hemispheric hh; public SemiModel sm; /** * build it with floats and cast */ public CurveFitter (float[] xData, float[] ydata) { this.xData = new double[xData.length]; this.yData = new double[xData.length]; for (int i=0; i<xData.length; i++) { this.xData[i]=(float)xData[i]; this.yData[i]=(float)yData[i]; } numPoints = xData.length; } /** Construct a new CurveFitter. */ public CurveFitter (double[] xData, double[] yData) { this.xData = xData; this.yData = yData; numPoints = xData.length; } /** * Perform curve fitting with the simplex method */ public void doFit(int fitType) { doFit(fitType, false); } /** * Here we cannot check our error and move toward the next local minima in error.. * * we must compare every possible fit. * * For now, only 2d fits here.. */ public void doExhaustiveFit(int fitType, double[] param_limits, int[] steps) { if (fitType < STRAIGHT_LINE || fitType > GAUSSIAN) throw new IllegalArgumentException("Invalid fit type"); fit = fitType; if (fit == HEMISPHERIC) hh=new Hemispheric(); if (fit == SEMI) semi = new SemiModel(); numParams = getNumParams(); if (numParams*2!=param_limits.length) throw new IllegalArgumentException("Invalid fit type"); if (numParams!=2) throw new IllegalArgumentException("Invalid fit type"); double[] params = new double[numParams]; double bestFit = Math.pow(10,100.0); bestParams = new double[numParams]; double[] startParams = new double[numParams]; double[] deltas = new double[numParams]; for (int i=0; i<params.length; i++) { // set miminimum of space to search params[i]=param_limits[2*i]; // find deltas of space to search deltas[i]=(param_limits[2*i+1]-param_limits[2*i])/steps[i]; // set the best to the first for now bestParams[i]=params[i]; startParams[i]=params[i]; } System.out.println("deltas: " + deltas[0] + " " + deltas[1]); System.out.println("steps: " + steps[0] + " " + steps[1]); System.out.println("startParams: " + startParams[0] + " " + startParams[1]); //start testing them for (int i=0; i<steps[0]; i++) { for (int j=0; j<steps[1]; j++) { params[0]=startParams[0]+i*deltas[0]; params[1]=startParams[1]+j*deltas[1]; double test = getError(params); // System.out.println("prms: " + params[0] + " " + params[1]+ " er: " + test); if (test<bestFit) { //System.out.println("found one: " + test + " i:" + params[0] + " j:" + params[1]); bestFit = test; bestParams[0] = params[0]; bestParams[1] = params[1]; } } } } public void doFit(int fitType, boolean showSettings) { if (fitType < STRAIGHT_LINE || fitType > GAUSSIAN) throw new IllegalArgumentException("Invalid fit type"); fit = fitType; if (fit == HEMISPHERIC) hh=new Hemispheric(); initialize(); //if (showSettings) settingsDialog(); restart(0); numIter = 0; boolean done = false; double[] center = new double[numParams]; // mean of simplex vertices while (!done) { numIter++; for (int i = 0; i < numParams; i++) center[i] = 0.0; // get mean "center" of vertices, excluding worst for (int i = 0; i < numVertices; i++) if (i != worst) for (int j = 0; j < numParams; j++) center[j] += simp[i][j]; // Reflect worst vertex through centre for (int i = 0; i < numParams; i++) { center[i] /= numParams; next[i] = center[i] + alpha*(simp[worst][i] - center[i]); } sumResiduals(next); // if it's better than the best... if (next[numParams] <= simp[best][numParams]) { newVertex(); // try expanding it for (int i = 0; i < numParams; i++) next[i] = center[i] + gamma * (simp[worst][i] - center[i]); sumResiduals(next); // if this is even better, keep it if (next[numParams] <= simp[worst][numParams]) newVertex(); } // else if better than the 2nd worst keep it... else if (next[numParams] <= simp[nextWorst][numParams]) { newVertex(); } // else try to make positive contraction of the worst else { for (int i = 0; i < numParams; i++) next[i] = center[i] + beta*(simp[worst][i] - center[i]); sumResiduals(next); // if this is better than the second worst, keep it. if (next[numParams] <= simp[nextWorst][numParams]) { newVertex(); } // if all else fails, contract simplex in on best else { for (int i = 0; i < numVertices; i++) { if (i != best) { for (int j = 0; j < numVertices; j++) simp[i][j] = beta*(simp[i][j]+simp[best][j]); sumResiduals(simp[i]); } } } } order(); double rtol = 2 * Math.abs(simp[best][numParams] - simp[worst][numParams]) / (Math.abs(simp[best][numParams]) + Math.abs(simp[worst][numParams]) + 0.0000000001); if (numIter >= maxIter) done = true; else if (rtol < maxError) { System.out.print(getResultString()); restarts--; if (restarts < 0) { done = true; } else { restart(best); } } } } /** * *Initialise the simplex * * Here we put starting point for search in parameter space */ void initialize() { // Calculate some things that might be useful for predicting parametres numParams = getNumParams(); numVertices = numParams + 1; // need 1 more vertice than parametres, simp = new double[numVertices][numVertices]; next = new double[numVertices]; double firstx = xData[0]; double firsty = yData[0]; double lastx = xData[numPoints-1]; double lasty = yData[numPoints-1]; double xmean = (firstx+lastx)/2.0; double ymean = (firsty+lasty)/2.0; double slope; if ((lastx - firstx) != 0.0) slope = (lasty - firsty)/(lastx - firstx); else slope = 1.0; double yintercept = firsty - slope * firstx; maxIter = IterFactor * numParams * numParams; // Where does this estimate come from? restarts = 1; maxError = 1e-9; switch (fit) { case STRAIGHT_LINE: simp[0][0] = yintercept; simp[0][1] = slope; break; case POLY2: simp[0][0] = yintercept; simp[0][1] = slope; simp[0][2] = 0.0; break; case POLY3: simp[0][0] = yintercept; simp[0][1] = slope; simp[0][2] = 0.0; simp[0][3] = 0.0; break; case POLY4: simp[0][0] = yintercept; simp[0][1] = slope; simp[0][2] = 0.0; simp[0][3] = 0.0; simp[0][4] = 0.0; break; case EXPONENTIAL: simp[0][0] = 0.1; simp[0][1] = 0.01; break; case POWER: simp[0][0] = 0.0; simp[0][1] = 1.0; break; case LOG: simp[0][0] = 0.5; simp[0][1] = 0.05; break; case RODBARD: simp[0][0] = firsty; simp[0][1] = 1.0; simp[0][2] = xmean; simp[0][3] = lasty; break; case GAMMA_VARIATE: // First guesses based on following observations: // t0 [b] = time of first rise in gamma curve - so use the user specified first limit // tm = t0 + a*B [c*d] where tm is the time of the peak of the curve // therefore an estimate for a and B is sqrt(tm-t0) // K [a] can now be calculated from these estimates simp[0][0] = firstx; double ab = xData[getMax(yData)] - firstx; simp[0][2] = Math.sqrt(ab); simp[0][3] = Math.sqrt(ab); simp[0][1] = yData[getMax(yData)] / (Math.pow(ab, simp[0][2]) * Math.exp(-ab/simp[0][3])); break; case LOG2: simp[0][0] = 0.5; simp[0][1] = 0.05; simp[0][2] = 0.0; break; case STEP: simp[0][0] = yData[getMax(yData)]; simp[0][1] = 2.0; break; case HEMISPHERIC: simp[0][0] = 1.0; simp[0][1] = yData[getMax(yData)]; break; case QUAD_ORIGIN: simp[0][0] = yData[getMax(yData)]/2; simp[0][1] = 1.0; break; case GAUSSIAN: simp[0][0] = yData[getMax(yData)]; simp[0][1] = xData[getMax(yData)]; simp[0][2] = Math.abs((lastx-firstx)/2); System.out.println(""+simp[0][0]+" "+simp[0][1]+" "+simp[0][2]); break; case SEMI: simp[0][0] = 1.0; simp[0][2] = y.Data[getMax(yData)]; break; } } /** Restart the simplex at the nth vertex */ void restart(int n) { // Copy nth vertice of simplex to first vertice for (int i = 0; i < numParams; i++) { simp[0][i] = simp[n][i]; } sumResiduals(simp[0]); // Get sum of residuals^2 for first vertex double[] step = new double[numParams]; for (int i = 0; i < numParams; i++) { step[i] = simp[0][i] / 2.0; // Step half the parametre value if (step[i] == 0.0) // We can't have them all the same or we're going nowhere step[i] = 0.01; } // Some kind of factor for generating new vertices double[] p = new double[numParams]; double[] q = new double[numParams]; for (int i = 0; i < numParams; i++) { p[i] = step[i] * (Math.sqrt(numVertices) + numParams - 1.0)/(numParams * root2); q[i] = step[i] * (Math.sqrt(numVertices) - 1.0)/(numParams * root2); } // Create the other simplex vertices by modifing previous one. for (int i = 1; i < numVertices; i++) { for (int j = 0; j < numParams; j++) { simp[i][j] = simp[i-1][j] + q[j]; } simp[i][i-1] = simp[i][i-1] + p[i-1]; sumResiduals(simp[i]); } // Initialise current lowest/highest parametre estimates to simplex 1 best = 0; worst = 0; nextWorst = 0; order(); } /** Get number of parameters for current fit function */ public int getNumParams() { switch (fit) { case STRAIGHT_LINE: return 2; case POLY2: return 3; case POLY3: return 4; case POLY4: return 5; case EXPONENTIAL: return 2; case POWER: return 2; case LOG: return 2; case RODBARD: return 4; case GAMMA_VARIATE: return 4; case LOG2: return 3; case STEP: return 2; case HEMISPHERIC: return 2; case SEMI return 2; case QUAD_ORIGIN: return 2; case GAUSSIAN: return 3; } return 0; } /** *Returns "fit" function value for parametres "p" at "x" * * Define function to fit to here!! */ public double f(int fit, double[] p, double x) { switch (fit) { case STRAIGHT_LINE: return p[0] + p[1]*x; case POLY2: return p[0] + p[1]*x + p[2]* x*x; case POLY3: return p[0] + p[1]*x + p[2]*x*x + p[3]*x*x*x; case POLY4: return p[0] + p[1]*x + p[2]*x*x + p[3]*x*x*x + p[4]*x*x*x*x; case EXPONENTIAL: return p[0]*Math.exp(p[1]*x); case POWER: if (x == 0.0) return 0.0; else return p[0]*Math.exp(p[1]*Math.log(x)); //y=ax^b case LOG: if (x == 0.0) x = 0.5; return p[0]*Math.log(p[1]*x); case RODBARD: double ex; if (x == 0.0) ex = 0.0; else ex = Math.exp(Math.log(x/p[2])*p[1]); double y = p[0]-p[3]; y = y/(1.0+ex); return y+p[3]; case GAMMA_VARIATE: if (p[0] >= x) return 0.0; if (p[1] <= 0) return -100000.0; if (p[2] <= 0) return -100000.0; if (p[3] <= 0) return -100000.0; double pw = Math.pow((x - p[0]), p[2]); double e = Math.exp((-(x - p[0]))/p[3]); return p[1]*pw*e; case LOG2: double tmp = x-p[2]; if (tmp<0.001) tmp = 0.001; return p[0]+p[1]*Math.log(tmp); case STEP: if (x>p[1]) return 0.0; else return p[0]; case HEMISPHERIC: return hh.eflux(p[0],p[1],x); case SEMI: return sm.f(p[0],p[1],x); case QUAD_ORIGIN: return p[0]*x + p[1]*x*x; case GAUSSIAN: return p[0]/p[2]/Math.sqrt(Math.PI*2)*Math.exp(-(x-p[1])*(x-p[1])/p[2]/p[2]/2); default: return 0.0; } } /** Get the set of parameter values from the best corner of the simplex */ public double[] getParams() { order(); return simp[best]; } /** Returns residuals array ie. differences between data and curve. */ public double[] getResiduals() { double[] params = getParams(); double[] residuals = new double[numPoints]; for (int i = 0; i < numPoints; i++) residuals[i] = yData[i] - f(fit, params, xData[i]); return residuals; } /** Returns sum of squares of residuals */ public double getError(double[] params_) { double tbr = 0.0; for (int i = 0; i < numPoints; i++) { tbr += sqr(yData[i] - f(fit, params_, xData[i])); } //System.out.println("error: " + tbr); return tbr; } /* Last "parametre" at each vertex of simplex is sum of residuals * for the curve described by that vertex */ public double getSumResidualsSqr() { double sumResidualsSqr = (getParams())[getNumParams()]; return sumResidualsSqr; } /** SD = sqrt(sum of residuals squared / number of params+1) */ public double getSD() { double sd = Math.sqrt(getSumResidualsSqr() / numVertices); return sd; } /** Get a measure of "goodness of fit" where 1.0 is best. * */ public double getFitGoodness() { double sumY = 0.0; for (int i = 0; i < numPoints; i++) sumY += yData[i]; double mean = sumY / numVertices; double sumMeanDiffSqr = 0.0; int degreesOfFreedom = numPoints - getNumParams(); double fitGoodness = 0.0; for (int i = 0; i < numPoints; i++) { sumMeanDiffSqr += sqr(yData[i] - mean); } if (sumMeanDiffSqr > 0.0 && degreesOfFreedom != 0) fitGoodness = 1.0 - (getSumResidualsSqr() / degreesOfFreedom) * ((numParams) / sumMeanDiffSqr); return fitGoodness; } /** Get a string description of the curve fitting results * for easy output. */ public String getResultString() { StringBuffer results = new StringBuffer("\nNumber of iterations: " + getIterations() + "\nMaximum number of iterations: " + getMaxIterations() + "\nSum of residuals squared: " + getSumResidualsSqr() + "\nStandard deviation: " + getSD() + "\nGoodness of fit: " + getFitGoodness() + "\nParameters:"); char pChar = 'a'; double[] pVal = getParams(); for (int i = 0; i < numParams; i++) { results.append("\n" + pChar + " = " + pVal[i]); pChar++; } return results.toString(); } public static double sqr(double d) { return d * d; } /** Adds sum of square of residuals to end of array of parameters */ void sumResiduals (double[] x) { x[numParams] = 0.0; for (int i = 0; i < numPoints; i++) { x[numParams] = x[numParams] + sqr(f(fit,x,xData[i])-yData[i]); // if (IJ.debugMode) ij.IJ.log(i+" "+x[n-1]+" "+f(fit,x,xData[i])+" "+yData[i]); } } /** Keep the "next" vertex */ void newVertex() { for (int i = 0; i < numVertices; i++) simp[worst][i] = next[i]; } /** Find the worst, nextWorst and best current set of parameter estimates */ void order() { for (int i = 0; i < numVertices; i++) { if (simp[i][numParams] < simp[best][numParams]) best = i; if (simp[i][numParams] > simp[worst][numParams]) worst = i; } nextWorst = best; for (int i = 0; i < numVertices; i++) { if (i != worst) { if (simp[i][numParams] > simp[nextWorst][numParams]) nextWorst = i; } } // IJ.write("B: " + simp[best][numParams] + " 2ndW: " + simp[nextWorst][numParams] + " W: " + simp[worst][numParams]); } /** Get number of iterations performed */ public int getIterations() { return numIter; } /** Get maximum number of iterations allowed */ public int getMaxIterations() { return maxIter; } /** Set maximum number of iterations allowed */ public void setMaxIterations(int x) { maxIter = x; } /** Get number of simplex restarts to do */ public int getRestarts() { return restarts; } /** Set number of simplex restarts to do */ public void setRestarts(int x) { restarts = x; } /** * Gets index of highest value in an array. * * @param Double array. * @return Index of highest value. */ public static int getMax(double[] array) { double max = array[0]; int index = 0; for(int i = 1; i < array.length; i++) { if(max < array[i]) { max = array[i]; index = i; } } return index; } /** * Use this to fit a curve or * for testing... * * Reads a file for data and fits to a curve at command line * */ public static final void main(String[] args) { int numLines = 17; int linesToSkip = 0; int type = CurveFitter.QUAD_ORIGIN; file f = new file(args[0]); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); CurveFitter cf = new CurveFitter(x,y); /*cf.setRestarts(100); Date d1 = new Date(); cf.doFit(type); Date d2 = new Date(); System.out.println(cf.getResultString()+"\n\n"); System.out.println("param[0]: " + cf.getParams()[0]); System.out.println("param[1]: " + cf.getParams()[1]); System.out.println("took: " + (d2.getTime()-d1.getTime())); */ //int max = getMax(y); //System.out.println("y_max: " + y[max]); //double[] lims = {0.0 , 10.0, y[max]/2.0, 4*y[max]}; //System.out.println("lims: " + lims[0] + " " + lims[1] + " " + lims[2] + " " + lims[3]); //int[] steps = {256,128}; //Date d3 = new Date(); //cf.doExhaustiveFit(CurveFitter.QUAD_ORIGIN,lims,steps); cf.doFit(type); //Date d4 = new Date(); //double[] ans = cf.bestParams; //System.out.println("a[0]: " + ans[0]); //System.out.println("a[1]: " + ans[1]); System.out.println(cf.getResultString()); //System.out.println("took: " + (d4.getTime()-d3.getTime())); } }
Java
import java.lang.Math; import java.util.Vector; import java.util.Date; public class Sieve { private static long MAX = (long)Math.pow(10,10); private static long MIN = (long)Math.pow(10,9); public long[] eNums; public int[] primes10000; private int numDigits = 20; private long numDivides = 0; public Sieve() { file ef = new file("e_digits.txt"); ef.initRead(); StringBuffer e = new StringBuffer(""); eNums = new long[1000]; int index = 0; String line=""; while ((line=ef.readLine())!=null) { e.append(line); } System.out.println("read e file"); for (int i=0; i<eNums.length; i++) { String sub = e.substring(i,i+numDigits); if (index < eNums.length-1) eNums[index]=Long.parseLong(sub); System.out.println(eNums[index]+""); index++; } long num = MAX-MIN; System.out.println("num= " + num +" initializing vector.. "); Vector primes = new Vector(); int debug = 0; for (int i=2; i<10000; i++) { primes.addElement(new Long(i)); } System.out.println("finished init vector.. "); Date d1 = new Date(); sieve(primes); Date d2 = new Date(); System.out.println("sieve of 10000 took: " + (d2.getTime()-d1.getTime())); // sytem time test here.. int doNothing; d1 = new Date(); for (int i=0; i<1000000; i++) { doNothing = i/17; } d2 = new Date(); System.out.println("10^6 divides took: " + (d2.getTime()-d1.getTime())); System.out.println("Found : " + primes.size() + "primes"); primes10000 = new int[primes.size()]; for (int i=0; i<primes.size(); i++) { primes10000[i] = ((Long)primes.elementAt(i)).intValue(); } primes.clear(); System.out.println("now we build our start vector"); /*for (long l=MIN; l<MAX; l++) { debug ++; if (addIt(l,primes10000)) { primes.add(new Long(l)); } if (debug==100000) { System.out.println("left: " + (num-l)); System.out.println("primes.size: " + primes.size()); debug = 0; } }*/ // now we need to sieve.. // for (long l=101; l< d1 = new Date(); long firstPrime = 0; int sequence = 0; int i = 0; while (i<eNums.length && firstPrime == 0) { if (checkPrime(eNums[i])) { if (firstPrime==0) { firstPrime=eNums[i]; sequence = i; } } i++; } d2 = new Date(); System.out.println(numDigits + " digits took: " + (d2.getTime()-d1.getTime())); System.out.println(sequence + " " + firstPrime); System.out.println("numDivides: " + numDivides); } private static boolean addIt(long l, long[] ll) { for (int i=0; i<ll.length; i++) { if (l%ll[i] == 0) return false; } return true; } /** * The basic sieve - * it starts from 2 * and goes to length of Vector.. * * not segmented! */ public static void sieve(Vector primes) { long tl=0; long ll=0; long min = ((Long)primes.elementAt(0)).longValue(); if (min != 2) { System.out.println("incorrect use of sieve(v)"); return; } for (int l=2; l<primes.size(); l++) { tl = ((Long)primes.elementAt(l)).longValue(); int i=0; while (i<primes.size()) { ll=((Long)primes.elementAt(i)).longValue(); if (tl>=ll) i++; else if (ll%tl==0) { // not a prime //System.out.println("not prime: " + ll); primes.remove(i); } else i++; } } } /** * works pretty well * */ public boolean checkPrime(long l) { // first check from our list of first few.. for (int i=0; i<primes10000.length; i++) { numDivides++; if (l%primes10000[i]==0) { //System.out.println(l + " = " + primes10000[i] +" * " + l/primes10000[i]); return false; } } long s = (long)Math.sqrt((double)l); for (long i=3; i<=s; i+=2) { numDivides++; if (l%i==0) { System.out.println(l + " = " + i + " * " + l/i); return false; } } System.out.println(l + " is prime!"); return true; } public static void main(String[] args) { Sieve a = new Sieve(); // how many binaries < 10^10 } }
Java
public class SphericalHarmonics { public static double Ylm(int l, int m, double theta, double phi) { return ( (-1)^m*Math.sqrt(((2*l+1)/(4*Math.PI)*fact(l-m)/fact(l+m))* Legendre.compute(m,l,Math.cos(theta)) ; } } }
Java
//Lukas Saul - Warsaw 2000 // // modified - jan. 2006 import java.util.StringTokenizer; public class Legendre { public int N=200; // change to max polynomial size double[][] P, P_t; //= new double[N+1][N+1]; // coefficients of Pn(x) double[][] DP;// = new double[N][N]; // derivitives of Pn(x) double[][] R;// = new double[N][N]; // roots of Pn(x) the x[i] double[][] W; //= new double[N][N]; // weights of Pn(x) the w[i] public Legendre() { this(200); } public Legendre(int k) { N = k; P = new double[N+1][N+1]; // coefficients of Pn(x) P_t = new double [N+1][N+1]; DP = new double[N][N]; // derivitives of Pn(x) R = new double[N][N]; // roots of Pn(x) the x[i] W = new double[N][N]; // weights of Pn(x) the w[i] //createCoefficientFile(); loadFromFile(); } public double p(int n, double arg) { double tbr = 0.0; double argPow = 1.0; for(int i=0; i<N-1; i++) { tbr+=P[n][i]*argPow; argPow*=arg; } return tbr; } public void loadFromFile() { file f = new file("legendre200.dat"); f.initRead(); String s = ""; StringTokenizer st; String garbage = f.readLine(); int counter = 0; try { while ((s=f.readLine())!=null) { st=new StringTokenizer(s); int i = Integer.parseInt(st.nextToken()); int j = Integer.parseInt(st.nextToken()); if (i<N && j<N) P[i][j] = Double.parseDouble(st.nextToken()); } } catch(Exception e) { e.printStackTrace(); } } public void createCoefficientFile() { System.out.println("Legendre.java running"); file ldatf = new file("legendre200.dat"); ldatf.initWrite(false); // generate family of Legendre polynomials Pn(x) // as P[degree][coefficients] // build coefficients of Pn(x) for(int n=0; n<N+1; n++) for(int i=0; i<N; i++) P[n][i]=0.0; P[0][0]=1.0; P[1][1]=1.0; // start for recursion for(int n=2; n<N+1; n++) { for(int i=0; i<=n; i++) { if(i<n-1) P[n][i]=-((n-1)/(double)n)*P[n-2][i]; if(i>0) P[n][i]=P[n][i]+((2*n-1)/(double)n)*P[n-1][i-1]; System.out.println("P["+n+"]["+i+"]="+P[n][i]); } } /*System.out.println("checking calcuations: "); for (int i=0; i<N+1; i++) { for (int j=0; j<=i; j++) { P_t[i][j] = binomial(i,j)*binomial(i,i-j)/Math.pow(2.0,i); if (P[i][j] != P_t[i][j]) { System.out.println("problem: P_ij: " +i + " " + j + " "+ P[i][j] + " P_tij: " + P_t[i][j]); } ldatf.write(i + "\t" + j +"\t" + P[i][j]+"\n"); } }*/ System.out.println("saving to data file.."); ldatf.write("Coefficients of Legendre Polynomials \n" ); for (int i=0; i<N+1; i++) { for (int j=0; j<=i; j++) { ldatf.write(i + "\t" + j +"\t" + P[i][j]+"\n"); } } ldatf.closeWrite(); } public static double binomial(int i, int j) { return fact(i) / (fact(j)*fact(i-j)); } public static double fact(int i) { if (i==0) return 1.0; if (i==1) return 1.0; else return i*fact(i-1); } // recursively computes legendre polynomial of order n, argument x public static double compute(int n,double x) { if (n == 0) return 1; else if (n == 1) return x; return ( (2*n-1)*x*compute(n-1,x) - (n-1)*compute(n-2,x) ) / n; } public static final void main(String[] args) { //System.out.println(fact(2) + " " + fact(4) + " " + fact(6)); //System.out.println(binomial(2,1) + " " + binomial(3,1) + " " + binomial(3,2)); Legendre l = new Legendre(200); System.out.println(l.p(1,0) + " " + l.p(2,0) + l.p(3, 0.5)); } } // Guess we don't need this stuff... /*public static long factorial(int m) { if (m==1) return 1; else return m*factorial(m-1); } }*/// L /*C*** LEGENDRE POLYNOM P(X) OF ORDER N C*** EXPLICIT EXPRESSION POLLEG=0. NEND=N/2 DO M=0,NEND N2M2=N*2-M*2 NM2=N-M*2 NM=N-M TERM=X**NM2*(-1.)**M TERM=TERM/NFAK(M)*NFAK(N2M2) TERM=TERM/NFAK(NM)/NFAK(NM2) POLLEG=POLLEG+TERM END DO POLLEG=POLLEG/2**N RETURN END C */ // I love fortran!
Java
import java.lang.Math; import java.util.Date; import gaiatools.numeric.integration.Simpson; //import drasys.or.nonlinear.*; // our friend mr. simpson resides here /** * This class should take care of doing multi-dimensional numeric integrations. * This will be slow!! * * Actually not half bad... * * * Lukas Saul * UNH Physics * May, 2001 * * Updated Aug. 2003 - only works with 2D integrals for now... * * Updated Aug. 2004 - 3D integrals OK! Did that really take 1 year?? * * About 2.1 seconds to integrate e^(-x^2-y^2-z^2) !! */ public class MultipleIntegration { private double result; private Simpson s; // tool to do integrations /** * for testing - increments at every 1D integration performed */ public long counter, counter2; /** * Constructor just sets up the 1D integration routine for running * after which all integrations may be called. */ public MultipleIntegration() { counter = 0; counter2 = 0; result = 0.0; s=new Simpson(); s.setErrMax(0.2); // s.setMaxIterations(15); } /** * sets counter to zero */ public void reset() { counter = 0; } public void reset2() { counter2 = 0; } /** * Set accuracy of integration */ public void setEpsilon(double d) { s.setMaxErr(d); } /** * Here's the goods, for 3D integrations. * * Limits are in order as folows: zlow, zhigh, ylow, yhigh, xlow, xhigh * */ public double integrate(final FunctionIII f, final double[] limits) { reset(); System.out.println("Called 3D integrator"); System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+ "\n"+limits[2]+" "+limits[3]+"\n"+limits[4]+" "+limits[5]); double[] nextLims = new double[4]; for (int i=0; i<4; i++) { nextLims[i] = limits[i+2]; } final double[] nextLimits = nextLims; Function funcII = new Function () { public double function(double x) { return integrate(f.getFunctionII(2,x), nextLimits); } }; s.setInterval(limits[0],limits[1]); result=s.integrate(funcII); //result = integrate(funcII, limits[0], limits[1]); return result; // each call to funcII by the integrator does a double integration } /** * Here's the goods, for 2D integrations */ public double integrate(final FunctionII f, final double[] limits) { //System.out.println("called 2D integrator"); //System.out.println("Integrating from: \n"+limits[0]+" "+limits[1]+ // "\n"+limits[2]+" "+limits[3]); //reset2(); //if (limits.length!=4) return null; //System.out.println("called 2D integrator"); Function f1 = new Function() { public double function(double x) { return integrate(f.getFunction(1,x),limits[2],limits[3]); } }; s.setInterval(limits[0],limits[1]); result=s.integrate(f1); //result = integrate(f1, limits[0], limits[1]); //System.out.println("in2d - result: " + result + " " + counter); return result; // each call to f1 by the intgrator does an integration } /** * Here's the simple goods, for 1D integrations * courtesy of our friends at drasys.or.nonlinear */ public double integrate(final Function f, double lowLimit, double highLimit) { //System.out.println("Called 1D integrator"); try { counter2++; counter++; if (counter%10000==1) System.out.println("Counter: " + counter); s.setInterval(lowLimit,highLimit); return s.integrate(f); //return s.integrate(f,lowLimit,highLimit); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Just for testing only here!!! * * seems to work - may 3, 2001 * * lots more testing for limits of 3d , polar vs. cartesian - Oct. 2004 */ public static final void main(String[] args) { MultipleIntegration mi = new MultipleIntegration(); // some functions to integrate!! Function testf3 = new Function() { public double function(double x) { return Math.exp(-x*x); } }; FunctionIII testf = new FunctionIII () { public double function3(double x, double y, double z) { return (Math.exp(-(x*x+y*y+z*z))); } }; FunctionIII testlims = new FunctionIII () { public double function3(double x, double y, double z) { return (x*y*y*z*z*z); } }; FunctionIII testfs = new FunctionIII () { public double function3(double r, double p, double t) { return (r*r*Math.sin(t)*Math.exp(-(r*r))); } }; FunctionII testf2a = new FunctionII () { public double function2(double x, double y) { return (Math.exp(-(x*x+y*y))); } }; FunctionII testf2b = new FunctionII () { public double function2(double r, double t) { return r*Math.exp(-(r*r)); } }; FunctionII testf2 = testf.getFunctionII(0,0.0); // these should be the same!! compare z=0 in above.. test here... System.out.println("test2val: " + testf2.function2(0.1,0.2)); System.out.println("test2aval: " + testf2a.function2(0.1,0.2)); Date d5 = new Date(); double test3 = mi.integrate(testf3,-100.0,100.0); Date d6 = new Date(); System.out.println("Answer: " + test3); System.out.println("answer^2: " + test3*test3); System.out.println("took: " + (d6.getTime()-d5.getTime())); System.out.println("1D integrations: " + mi.counter); double[] lims2 = new double[4]; lims2[0]=-100.0; lims2[1]=100.0; lims2[2]=-100.0; lims2[3]=100.0; Date d3 = new Date(); double test2 = mi.integrate(testf2,lims2); Date d4 = new Date(); System.out.println("Answer frm 2d testf2: " + test2); System.out.println("took: " + (d4.getTime()-d3.getTime())); System.out.println("1D integrations: " + mi.counter); d3 = new Date(); test2 = mi.integrate(testf2a,lims2); d4 = new Date(); System.out.println("Answer frm 2d testf2a: " + test2); System.out.println("took: " + (d4.getTime()-d3.getTime())); System.out.println("1D integrations: " + mi.counter); System.out.println("trying polar 2d now"); lims2 = new double[4]; lims2[0]=0; lims2[1]=2*Math.PI; lims2[2]=0; lims2[3]=10; d3 = new Date(); double ttest = mi.integrate(testf2b,lims2); d4 = new Date(); System.out.println("2d polar Answer: " + ttest); System.out.println("took: " + (d4.getTime()-d3.getTime())); System.out.println("1D integrations: " + mi.counter); System.out.println("trying 3d now... "); // basic limit test here, double[] lims = new double[6]; lims[0]=0.0; lims[1]=3.00; lims[2]=0.0; lims[3]=1.0; lims[4]=0.0; lims[5]=2.0; Date d1 = new Date(); double test = mi.integrate(testlims,lims); Date d2 = new Date(); System.out.println("Answer: " + test); System.out.println("took: " + (d2.getTime()-d1.getTime())); System.out.println("1D integrations: " + mi.counter); System.out.println("answer: " + 8*81/2/3/4); lims = new double[6]; lims[0]=-10.0; lims[1]=10.00; lims[2]=-10.0; lims[3]=10.0; lims[4]=-10.0; lims[5]=10.0; d1 = new Date(); test = mi.integrate(testf,lims); d2 = new Date(); System.out.println("Answer: " + test); System.out.println("took: " + (d2.getTime()-d1.getTime())); System.out.println("1D integrations: " + mi.counter); System.out.println("test^2/3: " + Math.pow(test,2.0/3.0)); System.out.println("trying 3d now... "); // 3d Function integration working in spherical coords?? lims = new double[6]; lims[0]=0; lims[1]=Math.PI; lims[2]=0; lims[3]=2*Math.PI; lims[4]=0; lims[5]=10.0; d1 = new Date(); test = mi.integrate(testfs,lims); d2 = new Date(); System.out.println("Answer: " + test); System.out.println("took: " + (d2.getTime()-d1.getTime())); System.out.println("1D integrations: " + mi.counter); System.out.println("test^2/3: " + Math.pow(test,2.0/3.0)); } }
Java
import java.util.Date; public class BofThetaTest { public static void main(String[] args) { //System.out.println(10^2+" "+10^1+" "+1000+" "+Math.pow(10,2)); double AU = 1.5* Math.pow(10,11); Date d1 = new Date(); VIonBulk vib = new VIonBulk(AU, 28000,135*Math.PI/180); System.out.println(vib.Vr()+" " + vib.Vperp()); Date d2 = new Date(); System.out.println("Took: "+(d2.getTime()-d1.getTime())+ " milliseconds"); } }
Java
//import gov.noaa.noaaserver.sgt.awt.*; //import gov.noaa.noaaserver.sgt.*; //import gov.noaa.noaaserver.sgt.datamodel.*; import gov.noaa.pmel.sgt.swing.*; import gov.noaa.pmel.sgt.dm.*; import gov.noaa.pmel.util.*; import gov.noaa.pmel.sgt.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.print.*; import java.awt.event.*; import java.awt.image.*; import net.jmge.gif.*; import java.io.*; import javax.imageio.*; import java.util.Vector; /** * * OK, time to make a panel plot composer, unfortunately we're not using IDL here... * the goal is for making a catalog of prime parameters of the CTOF dataset * The components will be instances of gov.noaa.pmel.sgt.CartesianGraph * * of course this can be extended to include other SGT objects * PASS IN GRAPHS that works better than layers, panes, or (heaven forbit) * - jplotlayouts. * @author lukas saul Jan. 2003 */ public class NOAAPanelPlotFrame extends PrintableDialog { private Container contentPane; //private JButton printButton, closeButton; //private JPanel buttonPanel; private CartesianGraph[] theGraphs; private double[] theHeights; private double keyHeight; private Vector v_heights, v_graphs; private JPane jpane; private ColorKey colorKey; //private JPHA theMain; /** * Just construct an instance here, * we build it later after adding the plots with build() * * do other gui stuff here */ public NOAAPanelPlotFrame() { setTitle("SOHO CTOF Panel Plot - NOAA/JAVA/SGT meets UNH/ESA/NASA"); v_heights = new Vector(); v_graphs = new Vector(); keyHeight = 0.0; jpane = new JPane("Top Pane", new Dimension(1000,1000)); jpane.setBatch(true); jpane.setBackground(Color.white); jpane.setForeground(Color.black); jpane.setLayout(new StackedLayout()); // ok, pane is ready for some layers contentPane = getContentPane(); contentPane.setBackground(Color.white); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ setVisible(false); }}); //keyPane = new JPane(); /*buttonPanel = new JPanel(); printButton = new JButton("Print"); printButton.addActionListener(this); buttonPanel.add(printButton); closeButton = new JButton("Close"); closeButton.addActionListener(this); buttonPanel.add(closeButton);*/ contentPane.add(jpane, "Center"); //contentPane.add(keyPane, "South"); } public void addKey(ColorKey ck, float relativeHeight) { colorKey = ck; keyHeight = (double)relativeHeight; //contentPane.add(keyPane, "South"); } /* * Send in a jpl to add a layer - layer is resized later. */ public void addPanel(JPlotLayout jpl, float relativeHeight) { addPanel((CartesianGraph)jpl.getFirstLayer().getGraph(), relativeHeight); } /** * Just add the layer in - we resize it later */ public void addPanel(Layer l, float relativeHeight) { addPanel((CartesianGraph)l.getGraph(), relativeHeight); } /* * Add a cartesianGraph at appropriate relative height */ public void addPanel(CartesianGraph cg, float relativeHeight) { try { SpaceAxis pa = (SpaceAxis)cg.getYAxis("Left Axis"); pa.setLabelInterval(3); Font yAxisFont = new Font("Helvetica", Font.BOLD, 20); pa.setLabelFont(yAxisFont); pa.setThickTicWidthP(relativeHeight/8.0); cg.removeAllYAxes(); cg.addYAxis(pa); } catch (Exception e) {e.printStackTrace();} v_graphs.add(cg); v_heights.add(new Float(relativeHeight)); } // go from vectors to arrays for ease of use private void createArrays() { theGraphs = new CartesianGraph[v_graphs.size()]; theHeights = new double[v_heights.size()]; for (int i=0; i<v_graphs.size(); i++) { theGraphs[i] = (CartesianGraph)v_graphs.elementAt(i); theHeights[i] = ((Float)v_heights.elementAt(i)).doubleValue(); } } /** * Here's where the panel plot is built and drawn - * call it after adding all the JPlotLayouts (thats where the real work is, creating them) * We are going to need to resize the layers - redo the transformations even... */ public void build() { createArrays(); // OK, what kind of height we got here float tot =0; for (int i=0; i<theHeights.length; i++) tot+=theHeights[i]; tot += keyHeight*5; // that's because we have two spaces at twice a clorkey size each, plus the key System.out.println("created arrays in build.. tot height: " + tot); // size entire pane here double ysize = (double)tot - keyHeight; double xsize = 8.0/11.0*ysize; // 8x11 paper? // add the key layer first Layer keyLayer = new Layer("",new Dimension2D(xsize,ysize)); colorKey.setBoundsP(new Rectangle2D.Double(0.0,keyHeight*2,xsize-xsize/15,keyHeight)); keyLayer.addChild(colorKey); keyLayer.setBackground(Color.white); jpane.add(keyLayer); double currentBottom = keyHeight + 2*keyHeight; double currentTop = keyHeight + 2*keyHeight + theHeights[0]; // build the rest from the ground up for (int i=0; i<theGraphs.length; i++) { // for VSW we need to adjust the axis labels if (i==5 | i==6 | i==7) { try { SpaceAxis pa = (SpaceAxis)theGraphs[i].getYAxis("Left Axis"); pa.setLabelInterval(6); } catch (Exception e) {e.printStackTrace();} } Layer layer = new Layer("", new Dimension2D(xsize, ysize)); AxisTransform xtransform = theGraphs[i].getXTransform(); AxisTransform ytransform = theGraphs[i].getYTransform(); xtransform.setRangeP(xsize/10,xsize-xsize/10); ytransform.setRangeP(currentBottom+theHeights[i]/10, currentTop-theHeights[i]/10); // does that set the transform of the graph? With true pointers it should.. // but Vectors could have f-ed them up layer.setGraph(theGraphs[i]); layer.setBackground(Color.white); jpane.add(layer); // increment for next one if we expect another in new location if (i<theGraphs.length-1 && i!=1 && i!=2) { currentBottom = currentTop; currentTop = currentTop+theHeights[i+1]; } } setDefaultSizes(); //pack(); show(); jpane.setBackground(Color.white); jpane.draw(); } /*public void actionPerformed(ActionEvent evt) { Object source = evt.getActionCommand(); if (source == "Close") { setVisible(false); } else if (source == "Print") { System.out.println("Trying to print..."); //setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); if (job.printDialog()) { try { job.print(); } catch (Exception ex) { ex.printStackTrace(); } } //setCursor(Cursor.getDefaultCursor()); } }*/ private void setDefaultSizes() { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int width = (int)screen.getWidth()*1/2; int height = (int)screen.getHeight(); Point centerPoint = new Point((screen.width-width)/2,(screen.height-height)/2); //setLocation(centerPoint); setSize(width,height); } /* * Save the image of this panel plot to a png file */ private BufferedImage ii; public void save(String fileName) { ii = getImage(); try { ImageIO.write(ii,"png",new File(fileName+".png")); } catch (Exception e) { System.out.println("image io probs in PanelPlot.save() : "); e.printStackTrace(); } setVisible(false); try {dispose(); this.finalize();} catch (Throwable e) {e.printStackTrace();} } /* * Get a BufferedImage of the panel plot */ public BufferedImage getImage() { try { //rpl_.draw(); Robot r = new Robot(); Point p = jpane.getLocationOnScreen(); Dimension d = new Dimension(jpane.getSize()); //d.setSize( d.getWidth()+d.getWidth()/2, // d.getHeight()+d.getHeight()/2 ); Rectangle rect = new Rectangle(p,d); //BufferedImage bi = r.createScreenCapture(rect); //ImageIcon i = new ImageIcon(r.createScreenCapture(rect)); return r.createScreenCapture(rect); //setVisible(false); //return i.getImage(); } catch (Exception e) { e.printStackTrace(); return null; } } }
Java
import java.util.StringTokenizer; import java.util.Vector; import java.util.StringTokenizer; import java.util.Date; import java.util.*; /** * * Simulating response at IBEX_LO with this class * * Create interstellar medium and perform integration * */ public class IBEXWind { public int mcN = 100000; // number of iterations per 3D integral public String outFileName = "lo_fit_09.txt"; public static final double EV = 1.60218 * Math.pow(10, -19); public static double MP = 1.672621*Math.pow(10.0,-27.0); public static double AU = 1.49598* Math.pow(10,11); //meters public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0; public static double Ms = 1.98892 * Math.pow(10,30); // kg //public static double Ms = 0.0; // kg public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg // define angles and energies of the instrument here // H mode (standard) energy bins in eV public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6}; public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5}; public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO; // Interstellar mode energies // { spring min, spring max, fall min, fall max } public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 }; public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 }; public double[] heSpeeds; public double[] oSpeeds; // O mode efficiencies // public double heSpringEff = 1.0*Math.pow(10,-7); // this was the original.. now going to adjust to match data including sputtering etc. public double heSpringEff = 1.0*Math.pow(10,-7)/7.8; // nominal efficiency to "roughly" match data.. public double heFallEff = 1.6*Math.pow(10,-6); public double oSpringEff = 0.004; public double oFallEff = 0.001; // angular acceptance - assume rectangular windows.. this is for integration limits only // these are half widths, e.g. +- for acceptance public double spinWidth = 4.0*Math.PI/180.0; public double hrWidth = 3.5*Math.PI/180.0; public double lrWidth = 7.0*Math.PI/180.0; public double eightDays = 8.0*24.0*60.0*60.0; public double oneHour = 3600.0; public double upWind = 74.0 * 3.14 / 180.0; public double downWind = 254.0 * 3.14 / 180.0; public double startPerp = 180*3.14/180; // SPRING public double endPerp = 240*3.14/180; // SPRING //public double startPerp = 260.0*3.14/180.0; // FALL //public double endPerp = 340.0*3.14/180.0; // FALL public double he_ion_rate = 6.00*Math.pow(10,-8); public GaussianVLISM gv1; // temporarily make them very small //public double spinWidth = 0.5*Math.PI/180.0; //public double hrWidth = 0.5*Math.PI/180.0; //public double lrWidth = 0.5*Math.PI/180.0; public double activeArea = 100.0/100.0/100.0; // 100 cm^2 in square meters now!! public file outF; public MultipleIntegration mi; public NeutralDistribution ndHe; public double look_offset=Math.PI; public double currentLongitude, currentSpeed, currentDens, currentTemp; public HelioVector bulkHE; public double low_speed, high_speed; public int yearToAnalyze = 2010; public EarthIBEX ei = new EarthIBEX(yearToAnalyze); public TimeZone tz = TimeZone.getTimeZone("UTC"); public file logFile = new file("IBEXWind_logfile2.txt"); /** * General constructor to do IBEX simulation */ public IBEXWind() { logFile.initWrite(true); // calculate speed ranges with v = sqrt(2E/m) heSpeeds = new double[heEnergies.length]; oSpeeds = new double[oEnergies.length]; o("calculating speed range"); for (int i=0; i<4; i++) { heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV); oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV); System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]); } minSpeedsHe = new double[8]; maxSpeedsHe = new double[8]; minSpeedsO = new double[8]; maxSpeedsO = new double[8]; for (int i=0; i<8; i++) { minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV); maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV); minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV); maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV); //System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]); } System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]); // lets calculate the speed of the exact cold gas at 1AU // potential energy double pot = 4.0*MP*Ms*G/AU; o("pot: "+ pot); double energy1= 4.0*MP/2.0*28000*28000; o("energy1: " + energy1); double kEn = energy1+pot; double calcHeSpeed = Math.sqrt(2.0*kEn/4.0/MP); calcHeSpeed += EARTHSPEED; o("calcHeSpeed: "+ calcHeSpeed); // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // // test distribution, coming in here: bulkHE = new HelioVector(HelioVector.SPHERICAL, 28000.0, (74.68)*Math.PI/180.0, 85.0*Math.PI/180.0); // here's a test distribution putting in helium from x axis (vel in -x) //bulkHE = new HelioVector(HelioVector.CARTESIAN, 28000.0, 0.0, 0.0); //HelioVector.invert(bulkHE); // invert it, we want the real velocity vector out there at infinity :D // LISM PARAMS GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0, 6000.0); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he //ndHe = new NeutralDistribution(gv1, 0.0, 0.0); // mu is 0.0 for he ndHe.debug=false; currentLongitude = 74.0; currentSpeed = 28000.0; currentDens = 0.015; currentTemp = 6000.0; // DONE CREATING MEDIUM o("earthspeed: " + EARTHSPEED); mi = new MultipleIntegration(); o("done creating IBEXLO_09 object"); // DONE SETUP //- //- // now lets run the test, see how this is doing //for (double vx = 0; /* // moving curve fitting routine here for exhaustive and to make scan plots file ouf = new file("scanResults1.txt"); file f = new file("cleaned_ibex_data.txt"); int numLines = 413; f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); // first scan: V vs Long. // for (int i=0; i< */ // LOAD THE REAL DATA /* file df = new file("second_pass.txt"); int numLines2 = 918; df.initRead(); double[] xD = new double[numLines2]; double[] yD = new double[numLines2]; String line = ""; for (int i=0; i<numLines2; i++) { line = df.readLine(); StringTokenizer st = new StringTokenizer(line); xD[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! yD[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]); //line = f.readLine(); //line = f.readLine(); } df.closeRead(); // END LOADING REAL DATA */ // MAKE SPIN PHASE SIMULATION // test here to match the ibex data and determine normalization /* file spFile = new file("doy_sim_test_31.txt"); spFile.initWrite(false); //for (int ss = 20000; ss<100000; ss+=5000) { // low_speed = ss; // high_speed = ss+5000; //spFile.write("\n\n ss= "+ss); for (double tt = 68.0; tt<113.0; tt+=2) { //tt is the theta angle double ans = getRate(30.00, tt*Math.PI/180.0); spFile. write(tt+"\t"+Math.abs(ans)+"\n"); o("trying tt = " + tt + " : "+ Math.abs(ans)); } // spFile.closeWrite(); */ // OR MAKE TIME SERIES SIMULATION /* file outFF = new file("sp_sim_01.txt"); outFF.initWrite(false); for (double doy=10.0 ; doy<70.0 ; doy+=1) { outFF.write(doy+"\t"); double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outFF.write(9*rr +"\t"); // TESTED WITH 2010 data... factor 9 is about right for starting outFF.write("\n"); } outFF.closeWrite(); */ // MAKE SIMULATION FROM REAL DATA.. STEP WITH TIME AND PARAMS FOR MAKING 2D PARAM PLOT // Feb 2011 last used // loop through parameters here // standard params: int res = 30; double lamdaWidth = 20; double vWidth = 8000; double lamdaMin = 65.0; //double tMin = 1000.0; double vMin=22000.0; double lamdaDelta = lamdaWidth/res; double vDelta = vWidth/res; double lamda = lamdaMin; //temp=tMin; double v = vMin; // this time use a curvefitter in real time to fit the model to the data and report min error CurveFitter cf = new CurveFitter(); cf.setFitData("2010_fit_time.txt"); file outF = new file("vVSlamda_6000_2010_2Db.txt"); outF.initWrite(false); for (int i=0; i<res; i++) { v=vMin; for (int j=0; j<res; j++) { setParams(lamda,v,0.015,6000.0); System.out.println(" now calc for params landa: "+lamda+" and v: "+v+".txt"); double [] doyD = new double[51]; double [] rateD = new double[51]; int doyIndex = 0; for (double doy=12.0 ; doy<=62.0 ; doy+=1.0) { doyD[doyIndex]=doy; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); rateD[doyIndex] = rr; doyIndex++; } // ok we have a set of model data, now let's bring the curvefitter out and go buck wild cf.setData(doyD,rateD); cf.doFit(CurveFitter.ONE_PARAM_FIT); System.out.println("did fit.. results: " + cf.minimum_pub + " at param " + cf.bestParams[0]); outF.write(lamda+"\t"+v+ "\t"+cf.minimum_pub+ "\t"+cf.bestParams[0]+ "\n"); v+=vDelta; } //temp+=tDelta; lamda+=lamdaDelta; } outF.closeWrite(); // MAKE SIMULATION FROM REAL DATA.. STEP WITH SPIN PHASE AND PARAMS FOR MAKING 2D PARAM PLOT // feb 2011 // loop through parameters here // standard params: /* int res = 30; double tempWidth = 7000; double vWidth = 10000; double tempMin = 1000.0; //double tMin = 1000.0; double vMin=20000.0; double tempDelta = tempWidth/res; double vDelta = vWidth/res; double temp = tempMin; //temp=tMin; double v = vMin; // this time use a curvefitter in real time to fit the model to the data and report min error CurveFitter cf = new CurveFitter(); cf.setFitData("2010_fit_sp.txt"); file outF = new file("tVSv_75_85p7_1m.txt"); outF.initWrite(false); for (int i=0; i<res; i++) { v=vMin; for (int j=0; j<res; j++) { bulkHE = new HelioVector(HelioVector.SPHERICAL, v, 75.0*Math.PI/180.0, 85.7*Math.PI/180.0); gv1 = new GaussianVLISM(bulkHE,100.0*100.0*100.0,temp); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; System.out.println(" now calc for params t: "+temp+" and v: "+v+".txt"); double [] thetaD = new double[25]; double [] rateD = new double[25]; int doyIndex = 0; for (double theta=65.0 ; theta<=108.0 ; theta+=1.75) { thetaD[doyIndex]=theta; double rr = getRate(39.15, theta*Math.PI/180.0); System.out.println("trying: " + theta + " got "+rr); rateD[doyIndex] = rr; doyIndex++; } System.out.println("doy index should be 25: "+ doyIndex); // ok we have a set of model data, now let's bring the curvefitter out and go buck wild cf.setData(thetaD,rateD); cf.doFit(CurveFitter.ONE_PARAM_FIT); System.out.println("did fit.. results: " + cf.minimum_pub + " at param " + cf.bestParams[0]); outF.write(temp+"\t"+v+ "\t"+cf.minimum_pub+ "\t"+cf.bestParams[0]+ "\n"); v+=vDelta; } //temp+=tDelta; temp+=tempDelta; } outF.closeWrite(); */ // MAKE SIMULATION FROM REAL DATA.. STEP WITH SPIN PHASE AND PARAMS FOR MAKING 2D PARAM PLOT // THIS TIME WE USE BOTH SPIN PHASE AND TIME SERIES TO GET CRAZY ON YO ASS // feb 2011 // loop through parameters here // standard params: /* int res = 30; double lamdaWidth = 20.0; double vWidth = 12000; double lamdaMin = 65.0; //double tMin = 1000.0; double vMin=20000.0; double lamdaDelta = lamdaWidth/res; double vDelta = vWidth/res; double lamda = lamdaMin; //temp=tMin; double v = vMin; // this time use a curvefitter in real time to fit the model to the data and report min error CurveFitter cf = new CurveFitter(); cf.setFitData("2010_fit_sp.txt"); CurveFitter cf2 = new CurveFitter(); cf2.setFitData("2010_fit_time.txt"); file outF = new file("lVSv_6000_86p5_200k.txt"); outF.initWrite(false); for (int i=0; i<res; i++) { v=vMin; for (int j=0; j<res; j++) { bulkHE = new HelioVector(HelioVector.SPHERICAL, v, lamda*Math.PI/180.0, 86.5*Math.PI/180.0); gv1 = new GaussianVLISM(bulkHE,100.0*100.0*100.0,6000.0); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; System.out.println(" now calc for params lam: "+lamda+" and v: "+v+".txt"); // first create the spin phase profile double [] thetaD = new double[25]; double [] rateD = new double[25]; int spIndex = 0; for (double theta=65.0 ; theta<=108.0 ; theta+=1.75) { thetaD[spIndex]=theta; double rr = getRate(39.15, theta*Math.PI/180.0); System.out.println("trying: " + theta + " got "+rr); rateD[spIndex] = rr; spIndex++; } cf.setData(thetaD,rateD); cf.doFit(CurveFitter.ONE_PARAM_FIT); System.out.println("did fit.. results: " + cf.minimum_pub + " at param " + cf.bestParams[0]); //outF.write(temp+"\t"+v+ "\t"+cf.minimum_pub+ "\t"+cf.bestParams[0]+ "\n"); // now create the time profile double [] doyC = new double[51]; double [] rateC = new double[51]; int doyIndex = 0; for (double doy=12.0 ; doy<=62.0 ; doy+=1.0) { doyC[doyIndex]=doy; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); rateC[doyIndex] = rr; doyIndex++; } System.out.println("doy index should be 25: "+ doyIndex); // ok we have a set of model data, now let's bring the curvefitter out and go buck wild cf2.setData(doyC,rateC); cf2.doFit(CurveFitter.ONE_PARAM_FIT); System.out.println("did fit.. results: " + cf2.minimum_pub + " at param " + cf2.bestParams[0]); outF.write(lamda+"\t"+v+ "\t"+(cf.minimum_pub+cf2.minimum_pub)+"\n"); v+=vDelta; } //temp+=tDelta; lamda+=lamdaDelta; } outF.closeWrite(); */ /* for (int temptemp = 1000; temptemp<20000; temptemp+=2000) { file outf = new file("fitB_"+temptemp+"_7468_26000.txt"); outf.initWrite(false); setParams(74.68,26000,0.015,(double)temptemp); for (double doy=10.0 ; doy<65.0 ; doy+=0.1) { outf.write(doy+"\t"); //for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) { //look_offset=off; look_offset=3.0*Math.PI/2.0; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outf.write(rr +"\t"); //} //double rr = getRate(doy); //System.out.println("trying: " + doy + " got "+rr); outf.write("\n"); } outf.closeWrite(); } */ } // END CONSTRUCTOR public void setParams(double longitude, double speed, double dens, double temp) { currentLongitude = longitude; currentSpeed = speed; currentDens = dens; currentTemp = temp; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // bulkHE = new HelioVector(HelioVector.SPHERICAL, speed, longitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } public void setParams(double dens) { currentDens = dens; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,currentTemp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } public void setParams(double dens, double temp) { currentDens = dens; currentTemp = temp; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } /* public void setParamsN(double dens, double ion) { currentDens = dens; //currentTemp = temp; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } */ /* public double getRate(double dens, double doy) { if ((currentDens!=dens)) { System.out.println("new params: " + dens); setParams(dens); } return getRate(doy); } public double getRate(double dens, double temp, double doy) { if ((currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + dens + " " + temp); setParams(dens,temp); } return getRate(doy); } public double getRate(double longitude, double speed, double dens, double temp, double doy) { if ((currentLongitude!=longitude)|(currentSpeed!=speed)|(currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + longitude + " " + speed + " " + dens + " " + temp); setParams(longitude,speed,dens,temp); } return getRate(doy); } /* use this to set the look direction in latitude */ double midThe = Math.PI/2.0; /** * We want to enable testing the rate for either spin phase or DOY * thus we are going to add 10000 to the spin phase data, then we know * which test we are doing */ public double getRateMulti(double n1, double n2, double t, double v, double phi, double theta, double doy_or_sp) { // n,t,v, phi, theta logFile.initWrite(true); double tbr = 0.0; // params are density_series, density_sp, temp, v, lamda, theta bulkHE = new HelioVector(HelioVector.SPHERICAL, v, phi*Math.PI/180.0, theta*Math.PI/180.0); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,100.0*100.0*100.0,t); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1,0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; if (doy_or_sp >= 10000) { // we are looking for spin phase at doy 41 doSP = true; tbr = n2*getRate(39.15, (doy_or_sp-10000.0)*Math.PI/180.0); } else { doSP = false; midThe = Math.PI/2.0; tbr = n1*getRate(doy_or_sp); // a real DOY } logFile.write(n1+"\t"+n2+"\t"+t+"\t"+v+"\t"+phi+"\t"+theta+"\t"+doy_or_sp+"\t"+tbr+"\n"); logFile.closeWrite(); return tbr; } public boolean doSP = false; /** * Use this one to set the look direction in spin phase and then get the rate * */ public double getRate(double doy, double theta) { midThe = theta; doSP = true; return getRate(doy); } /** * We want to call this from an optimization routine.. * */ public double getRate(double doy) { int day = (int)doy; double fract = doy-day; //System.out.println(fract); int hour = (int)(fract*24.0); Calendar c = Calendar.getInstance(); c.setTimeZone(tz); c.set(Calendar.YEAR, yearToAnalyze); c.set(Calendar.DAY_OF_YEAR, day); c.set(Calendar.HOUR_OF_DAY, hour); //c.set(Calendar.MINUTE, 0); //c.set(Calendar.SECOND, 0); Date ourDate = c.getTime(); //System.out.println("trying getRate w/ " + doy + " the test Date: " + ourDate.toString()); if (!doSP) midThe = Math.PI/2.0; // we look centered if we aren't doing a scan // spacecraft position .. assume at earth at doy final HelioVector pointVect = ei.getIbexPointing(ourDate); // test position for outside of heliosphere //final HelioVector pointVect = new HelioVector(HelioVector.CARTESIAN, 0.0,1.0,0.0); //if (doSP) final HelioVector lookVect = new HelioVector(HelioVector.SPHERICAL,1.0, pointVect.getPhi()+Math.PI/2.0, midThe); //else final HelioVector lookVect = new HelioVector(HelioVector.SPHERICAL,1.0, pointVect.getPhi()+Math.PI/2.0, pointVect.getTheta()); // TESTED SERIES OK !/11 //final HelioVector lookVect = new HelioVector(HelioVector.SPHERICAL,1.0, pointVect.getPhi()-Math.PI/2.0, midThe); // here's the now position (REAL) final HelioVector posVec = ei.getEarthPosition(ourDate); final HelioVector scVelVec = ei.getEarthVelocity(ourDate); // temp! set it to zero for debug // final HelioVector scVelVec = new HelioVector(HelioVector.CARTESIAN, 0.0, 0.0, 0.0); //System.out.println("trying getRate w/ " + doy + " the test Date: " + ourDate.toString() + " posvec: " + posVec.toAuString() + // " scvelvec: " + scVelVec.toKmString() + " midthe " + midThe); // use a test position that puts the Earth out in the VLISM .. lets go with 200AU //final HelioVector posVec = new HelioVector(HelioVector.CARTESIAN, 200*AU, 0.0, 0.0); // due upwind //final HelioVector scVelVec = new HelioVector(HelioVector.CARTESIAN, 0.0, 0.0, 0.0); // not moving double midPhi = lookVect.getPhi(); //final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0); //final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0); // placeholder for zero //final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, 0.0, pos+Math.PI/2.0, Math.PI/2.0); // HERES WHAT WE NEED TO INTEGRATE final FunctionIII he_func = new FunctionIII() { // helium neutral distribution public double function3(double v, double p, double t) { HelioVector testVect = new HelioVector(HelioVector.SPHERICAL,v,p,t); HelioVector.difference(testVect,scVelVec); // TESTED SERIES OK 1/11 double tbr = activeArea*ndHe.dist(posVec, testVect)*v*v*Math.sin(t)*v; // extra v for flux tbr *= angleResponse(testVect,lookVect); //tbr *= angleResponse(lookPhi,p); // that is the integrand of our v-space integration return tbr; } }; // set limits for integration - spring only here //double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; // old limits for including all spin.. //double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, 3.0*Math.PI/8.0, 5.0*Math.PI/8.0 }; // new limits for including just a single point in spin phase double[] he_lr_lims = { 0.0, maxSpeedsHe[5], midPhi-lrWidth, midPhi+lrWidth, 0.0, Math.PI }; //TESTED SERIES OK 1/11 if (doSP) { he_lr_lims[4]=midThe-2*lrWidth; he_lr_lims[5]=midThe+2*lrWidth; //lookVect = new HelioVector(HelioVector.SPHERICAL,lookVect.getR(), lookVect.getPhi(), midThe); } // this needs to change for the case of spin phase simulation.. w //double[] he_lr_lims = { minSpeedsHe[2], maxSpeedsHe[5], midPhi-lrWidth, midPhi+lrWidth, 0, Math.PI }; //he_lr_lims[0]=low_speed; he_lr_lims[1]=high_speed; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; //PERFORM INTEGRATION double he_ans_lr = 12.0*oneHour *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN); he_ans_lr*=heSpringEff; doSP = false; // return he_ans_lr; } public double sigma=6.1; /** * From calibrated response * */ public double angleResponse(double centerA, double checkA) { double cA = centerA*180.0/Math.PI; double chA = checkA*180.0/Math.PI; // This is the Gaussian Response double tbr = Math.exp(-(cA-chA)*(cA-chA)/sigma/sigma); return tbr; } public double angleResponse(HelioVector center, HelioVector look) { double angle = center.getAngle(look); angle = Math.abs(angle * 180.0/Math.PI); // This is the Triangle Response double tbr = 0.0; if (angle<7.0) { double m = -1.0/7.0; tbr = m*angle+1.0; } // This is the Gaussian Response //double tbr = Math.exp(-angle*angle/sigma/sigma); return tbr; } public static final void main(String[] args) { IBEXWind il = new IBEXWind(); } public static void o(String s) { System.out.println(s); } /* * This is to load a given model from a file and give a proper normalization to match the ibex data * for using a one parameter (normalization) fit. */ public class FitData { public StringTokenizer st; public double[] days; public double[] rates; public Vector daysV; public Vector ratesV; public FitData(String filename) { daysV = new Vector(); ratesV = new Vector(); file f = new file(filename); f.initRead(); String line = ""; while ((line=f.readLine())!=null) { st = new StringTokenizer(line); daysV.add(st.nextToken()); ratesV.add(st.nextToken()); } // time to fix the arrays days = new double[daysV.size()]; rates = new double[daysV.size()]; for (int i=0; i<days.length; i++) { days[i]=Double.parseDouble((String)daysV.elementAt(i)); rates[i]=Double.parseDouble((String)ratesV.elementAt(i)); } } // we are going to interpolate here public double getRate(double day) { for (int i=0; i<days.length; i++) { if (day<days[i]) { // this is where we want to be return (rates[i]+rates[i+1])/2; } } return 0; } } } /* We need to keep track of Earth's Vernal Equinox and use J2000 Ecliptic Coordinates!!! March 2009 20 11:44 2010 20 17:32 2011 20 23:21 2012 20 05:14 2013 20 11:02 2014 20 16:57 2015 20 22:45 2016 20 04:30 2017 20 10:28 This gives the location of the current epoch zero ecliptic longitude.. However /* /* Earth peri and aphelion perihelion aphelion 2007 January 3 20:00 July 7 00:00 2008 January 3 00:00 July 4 08:00 2009 January 4 15:00 July 4 02:00 2010 January 3 00:00 July 6 12:00 2011 January 3 19:00 July 4 15:00 2012 January 5 01:00 July 5 04:00 2013 January 2 05:00 July 5 15:00 2014 January 4 12:00 July 4 00:00 2015 January 4 07:00 July 6 20:00 2016 January 2 23:00 July 4 16:00 2017 January 4 14:00 July 3 20:00 2018 January 3 06:00 July 6 17:00 2019 January 3 05:00 July 4 22:00 2020 January 5 08:00 July 4 12:00 */
Java
/** * Simulating response at hypothetical imaging platform * * Create interstellar medium and perform integration * */ public class Skymap { public int mcN = 8000; // number of iterations per 3D integral public double smartMin = 1.0; // lowest flux to continue integration of sector public String outFileName = "skymap_out4.txt"; public String filePrefix = "sky_add_2fine_"; String dir = "SPRING"; //String dir = "FALL"; public static final double EV = 1.60218 * Math.pow(10, -19); public static double MP = 1.672621*Math.pow(10.0,-27.0); public static double AU = 1.49598* Math.pow(10,11); //meters public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0; public double he_ion_rate = 1.0*Math.pow(10,-7); public double o_ion_rate = 8.0*Math.pow(10,-7); // define angles and energies of the instrument here // H mode (standard) energy bins in eV // angular acceptance - assume rectangular windows.. // chaged from IBEX to higher resolution "perfect" imager // these are half widths, e.g. +- for acceptance public double angleWidth = 0.5*Math.PI/180.0; public file outF; public MultipleIntegration mi; /** * * * */ public Skymap() { o("earthspeed: " + EARTHSPEED); mi = new MultipleIntegration(); mi.smartMin=smartMin; // set up output file outF = new file(outFileName); // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); // implement test 1 - a vector coming in along x axis //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, Math.PI, Math.PI/2.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,25000.0, Math.PI, Math.PI/2.0); //HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, Math.PI, Math.PI/2.0); // standard hot helium GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0,6300.0); GaussianOxVLISM gv2 = new GaussianOxVLISM(bulkO1, bulkO2, 0.00005*100*100*100, 1000.0, 90000.0, 0.0); // last is fraction in 2ndry final NeutralDistribution ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); final NeutralDistribution ndO = new NeutralDistribution(gv2, 0.0, o_ion_rate); ndHe.debug=false; ndO.debug=false; // DONE CREATING MEDIUM final double activeArea = 0.0001; // one square cm, assuming a nice detector here, detects everything that hits int index = 1; for (double pos = 0.0*Math.PI/180.0; pos<360.0*Math.PI/180.0; pos+= 4.0*Math.PI/180.0) { // position of spacecraft final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0); final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0); // helium neutral distribution FunctionIII he_func = new FunctionIII() { public double function3(double v, double p, double t) { double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).sum(scVelVec))*v*v*Math.sin(t)*v; // extra v for flux // that is the integrand of our v-space integration return tbr; } }; /* FunctionIII o_func = new FunctionIII() { // oxygen neutral distribution public double function3(double v, double p, double t) { double tbr = activeArea*ndO.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t))*v*v*Math.sin(t)*v; // extra v for flux // that is the integrand of our v-space integration return tbr; } }; */ outF=new file(filePrefix+""+(1000+index)+".txt"); outF.initWrite(false); // now make the image for (double theta=Math.PI/3.0; theta<2.0*Math.PI/3.0; theta+=1.0*Math.PI/180.0) { for (double phi=0.0; phi<2.0*Math.PI; phi+=1.0*Math.PI/180) { // set limits for integration.. double[] lims = {0.0, 100000.0, phi-angleWidth, phi+angleWidth, theta-angleWidth, theta+angleWidth}; // time * spin_duty * energy_duty * area_factor //double o_ans = mi.mcIntegrateSS(o_func, lims, mcN); double he_ans = mi.mcIntegrateSS(he_func, lims, mcN); //System.out.println(phi+"\t"+theta+"\t"+mi.lastNP+"\t"+he_ans); //outF.write(pos +"\t"+theta+"\t"+phi+"\t"+he_ans+"\t"+o_ans+"\n"); outF.write(pos*180.0/Math.PI +"\t"+theta*180.0/Math.PI +"\t"+phi*180.0/Math.PI+"\t"+he_ans+"\n"); } System.out.println("Theta= " + theta); } outF.closeWrite(); index++; } } public static final void main(String[] args) { Skymap il = new Skymap(); } public static void o(String s) { System.out.println(s); } }
Java
import java.lang.Math; /** Utility class for transforming coordinates, etc. * * (this is a general vector class, formulated for use in heliosphere) * (GSE not really implemented yet) * * Lukas Saul - Warsaw - July 2000 * Last updated May, 2001 * renamed to HelioVector, Oct 2002 * */ public class HelioVector { /* * These static ints are for discerning coordinate systems */ public static final int CARTESIAN = 1; // heliocentric public static final int SPHERICAL = 2; // heliocentric public static final int PLANAR = 3; // ?? public static final int GSE = 4; //?? public static final int NAHV = 5; // not a heliovector public static double AU = 1.49598* Math.pow(10,11); //meters private double x,y,z; private double r,theta,phi; /** * these booleans are so we know when we need to calculate the conversion * just to make sure we don't do extra work here */ private boolean haveX, haveY, haveZ, haveR, havePhi, haveTheta; /** * Default constructor - creates zero vector */ public HelioVector() { haveX=true; haveY=true; haveZ=true; haveR=true; haveTheta=true; havePhi=true; x=0; y=0; z=0; r=0; theta=0; phi=0; } /** * constructor sets up SPHERICAL and CARTESIAN coordinates * CARTESIAN heliocentric coordinates. x axis = jan 1 00:00:00. */ public HelioVector(int type, double a, double b, double c) { if (type == CARTESIAN) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = a; y = b; z = c; } if (type == SPHERICAL) { haveX=false; haveY=false; haveZ=false; haveR=true; haveTheta=true; havePhi=true; r = a; phi = b; theta = c; //syntax= give azimuth first! } } /** * Use this to save overhead by eliminating "new" statements, * otherwise same as constructors */ public void setCoords(int type, double a, double b, double c) { if (type == CARTESIAN) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = a; y = b; z = c; } if (type == SPHERICAL) { haveX=false; haveY=false; haveZ=false; haveR=true; haveTheta=true; havePhi=true; r = a; phi = b; theta = c; //syntax= give azimuth first! } } /** * Use this to save overhead by eliminating "new" statements */ public void setCoords(HelioVector hp) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = hp.getX(); y = hp.getY(); z = hp.getZ(); } /** * Access methods - use these to get coordinates of this point */ public double getX() { if (haveX) return x; else { x = getR()*Math.cos(getPhi())*Math.sin(getTheta()); haveX = true; return x; } } /** * Access methods - use these to get coordinates of this point */ public double getY(){ if (haveY) return y; else { y = getR()*Math.sin(getPhi())*Math.sin(getTheta()); haveY = true; return y; } } /** * Access methods - use these to get coordinates of this point */ public double getZ() { if (haveZ) return z; else { z = getR()*Math.cos(getTheta()); haveZ = true; return z; } } /** * Access methods - use these to get coordinates of this point */ public double getR() { if (haveR) return r; else { r = Math.sqrt(getX()*x + getY()*y + getZ()*z); haveR = true; return r; } } /** * Access methods - use these to get coordinates of this point */ public double getPhi() { if (havePhi) return phi; else { // this stuff is because Math.atrig(arg) returns -pi/2<theta<pi/2 : // we want 0<phi<2pi if (getX()>0) phi = Math.atan(getY()/x); else if (x<0) phi = Math.atan(y/x) + Math.PI; else if (x==0 & y>0) phi = Math.PI/2; else if (x==0 & y<0) phi = 3*Math.PI/2; else if (x==0 & y==0) phi = 0; havePhi = true; if (phi<0) phi+=Math.PI*2; else if (phi>Math.PI*2) phi-=Math.PI*2; return phi; } } /** * Access methods - use these to get coordinates of this point */ public double getTheta() { if (haveTheta) return theta; else if(getR()==0) { theta=0; haveTheta=true; return 0; } else { // we want theta>=0 & theta<= PI theta = Math.acos(getZ()/getR()); //else if (z<0) theta = Math.PI + Math.acos(z/r); //else if (z==0) theta = Math.PI/2; haveTheta = true; //if (theta<0) theta+=|(theta>Math.PI)) System.out.println("theta? " + theta); return theta; } } // SOME VECTOR OPERATIONS // each operation comes in two forms, one creating a new object // and one changing an argument /** * Add two vectors easily */ public HelioVector sum(HelioVector hp) { return new HelioVector( CARTESIAN,getX()+hp.getX(),getY()+hp.getY(),getZ()+hp.getZ() ); } public static void sum(HelioVector x, HelioVector y) { x.setCoords(CARTESIAN, x.getX()+y.getX(), x.getY()+y.getY(), x.getZ()+y.getZ()); } /** * Subtract two vectors easily */ public HelioVector difference(HelioVector hp) { return new HelioVector( CARTESIAN,getX()-hp.getX(),getY()-hp.getY(),getZ()-hp.getZ() ); } public static void difference(HelioVector x, HelioVector y) { x.setCoords( CARTESIAN, x.getX()-y.getY(), x.getY()-y.getY(), x.getZ()-y.getZ() ); } /** * Multiply a vector by a scalar */ public HelioVector product(double d) { return new HelioVector( SPHERICAL, d*getR(), getPhi(), getTheta() ); } public static void product(HelioVector x, double d) { x.setCoords( SPHERICAL, d*x.getR(), x.getPhi(), x.getTheta() ); } public HelioVector product(int d) { return new HelioVector( SPHERICAL, d*getR(), getPhi(), getTheta() ); } /** * returns vector of same size pointing in opposite direction - * ADDITIVE inverse NOT MULTIPLICATIVE * */ public HelioVector invert() { return new HelioVector(CARTESIAN, -getX(), -getY(), -getZ()); } public static void invert(HelioVector x) { x.setCoords( CARTESIAN, -x.getX(), -x.getY(), -x.getZ() ); } /** * returns unit vector in same direction * */ public HelioVector normalize() { return new HelioVector(SPHERICAL, 1, getPhi(), getTheta()); } public static void normalize(HelioVector x) { x.setCoords( SPHERICAL, 1, x.getPhi(), x.getTheta() ); } /** * returns standard dot product */ public double dotProduct(HelioVector hp) { return getX()*hp.getX() + getY()*hp.getY() + getZ()*hp.getZ(); } /** * returns standard cross product */ public HelioVector crossProduct(HelioVector hp) { return new HelioVector( CARTESIAN, (getY()*hp.getZ() - getZ()*hp.getY()), (getZ()*hp.getX() - getX()*hp.getZ()), (getX()*hp.getY() - getY()*hp.getX()) ); } public static void crossProduct(HelioVector x, HelioVector y) { x.setCoords( CARTESIAN, (x.getY()*y.getZ() - x.getZ()*y.getY()), (x.getZ()*y.getX() - x.getX()*y.getZ()), (x.getX()*y.getY() - x.getY()*y.getX()) ); } /** * this returns the angle between our vector and inflow as expressed * with elevation and azimuth * * (assuming inflow is at phi, theta) * (Range = from 0 to PI) */ public double angleToInflow(double phi0,double theta0) { HelioVector lism = new HelioVector(HelioVector.SPHERICAL, 1, phi0, theta0); return getAngle(lism); } /** * This calculates the angle between two vectors. * Should range from 0 to PI */ public double getAngle(HelioVector hp) { double cosAngle = this.dotProduct(hp)/(getR()*hp.getR()); return Math.acos(cosAngle); } /** * HOPEFULLY DEPRECATED BY NOW * these routines for converting to a cylindrical coordinate system * note: axis must be non-zero vector! */ public double cylCoordRad(HelioVector axis) { o("Deprecated: cylCoordRad in HelioVector"); double tbr = this.dotProduct(axis) / axis.getR(); // ref plane doesnt matter here return tbr; } public double cylCoordTan(HelioVector axis) { o("Deprecated: cylCoordTan in HelioVector"); return this.crossProduct(axis).getR() / axis.getR(); // lenght of cross product = Vtangent? } public double cylCoordPhi(HelioVector axis, HelioVector refPlaneVector) { o("Deprecated: cylCoordPhi in HelioVector"); // a bit trickier here... using convention from Judge and Wu (sin Psi) HelioVector newThis = moveZAxis(axis); HelioVector newRefPlaneVector = moveZAxis(axis); return (newThis.getPhi() - newRefPlaneVector.getPhi() - Math.PI/2); } /** * this routine returns a new helioPoint expressed in terms of new z axis * lets try to take the cross product with current z axis and rotate around that. */ public HelioVector moveZAxis(HelioVector newAxis) { HelioVector cp = new HelioVector(CARTESIAN, getY(), -getX(), 0); cp = cp.normalize(); return rotateAroundArbitraryAxis(cp, newAxis.getTheta()).invert(); } /** * This routine uses a matrix transformation to * return a vector (HelioVector) which has been rotated about * the axis (axis) by some degree (t). */ public HelioVector rotateAroundArbitraryAxis(HelioVector axis, double t) { x=getX(); y=getY(); z=getZ(); // make sure we have coords we need double s = Math.sin(t); double c=Math.cos(t);// useful quantities double oc = 1-c ; // this is unneccessary but I think I have an extra 16bits around somewhere double u = axis.getX(); double v = axis.getY(); double w = axis.getZ(); // this is a matrix transformation return new HelioVector(CARTESIAN, x*(c + u*u*oc) + y*(-w*s + u*v*oc) + z*(v*s + u*w*oc), //x x*(w*s + u*v*oc) + y*(c + v*v*oc) + z*(-u*s + v*w*oc), //y x*(-v*s + u*w*oc) + y*(u*s + v*w*oc) + z*(c + w*w*oc) //z ); } public String o() { return new String("X=" + getX()/AU + " Y=" + getY()/AU + " Z=" + getZ()/AU); } public String toAuString() { String tbr = new String("\n"); tbr += "X = " + getX()/AU + "\n"; tbr += "Y = " + getY()/AU + "\n"; tbr += "Z = " + getZ()/AU + "\n"; tbr += "r = " + getR()/AU + "\n"; tbr += "phi = " + getPhi() + "\n"; tbr += "theta = " + getTheta() + "\n"; return tbr; } public String toKmString() { String tbr = new String("\n"); tbr += "X = " + getX()/1000 + "\n"; tbr += "Y = " + getY()/1000 + "\n"; tbr += "Z = " + getZ()/1000 + "\n"; tbr += "r = " + getR()/1000 + "\n"; tbr += "phi = " + getPhi() + "\n"; tbr += "theta = " + getTheta() + "\n"; return tbr; } public String toString() { String tbr = new String("\n"); tbr += "X = " + getX() + "\n"; tbr += "Y = " + getY() + "\n"; tbr += "Z = " + getZ() + "\n"; tbr += "r = " + getR() + "\n"; tbr += "phi = " + getPhi() + "\n"; tbr += "theta = " + getTheta() + "\n"; return tbr; } /** * for testing!! */ public static final void main(String[] args) { // let's test rotation routine // // THese are all checked and good to go May 2004 /*HelioVector hp1 = new HelioVector(CARTESIAN, 1,0,0); HelioVector hp2 = new HelioVector(CARTESIAN, 0,1,0); HelioVector hp3 = new HelioVector(CARTESIAN, 0,0,1); HelioVector hp4 = new HelioVector(CARTESIAN, -1,0,0); HelioVector hp5 = new HelioVector(CARTESIAN, 0,-1,0); HelioVector hp6 = new HelioVector(CARTESIAN, 0,0,-1); HelioVector hp7 = new HelioVector(CARTESIAN, 1,1,0); HelioVector hp8 = new HelioVector(CARTESIAN, 0,1,-1); HelioVector hp9 = new HelioVector(CARTESIAN, 3,1,0); HelioVector hp10 = new HelioVector(CARTESIAN, 0,4,3); */ HelioVector hp11 = new HelioVector(CARTESIAN, 1.0*AU, 0.01*AU,0.01*AU); HelioVector hp12 = new HelioVector(SPHERICAL, 1.0*AU, 0.0, Math.PI/2.0); /*o("hp1: " + hp1); o("hp2: " + hp2); o("hp3: " + hp3); o("hp4: " + hp4); o("hp5: " + hp5); o("hp6: " + hp6); o("hp4: " + hp7); o("hp5: " + hp8); o("hp6: " + hp9); o("hp6: " + hp10); */ o("hp6: " + hp11); o("hp12: "+ hp12); //HelioVector hp3 = hp1.rotateAroundArbitraryAxis(hp2, Math.PI/2); //System.out.println(hp3.getX()+" "+hp3.getY()+" "+hp3.getZ()); // ok, let's test this cylindrical coordinate bullshit //HelioVector hp4 = new HelioVector(CARTESIAN, 0,0,1); //HelioVector hp5 = new HelioVector(CARTESIAN, -1,0,0); //System.out.println(hp5.cylCoordRad(hp4)+""); //System.out.println(hp5.cylCoordTan(hp4)+""); //System.out.println(hp5.cylCoordPhi(hp4,new HelioVector(CARTESIAN,1,0,0))); } public static void o(String s) { System.out.println(s); } }
Java
import java.util.StringTokenizer; public class IbexPostFitter { public CurveFitter cf; public IbexPostFitter() { file asciiOutFile = new file("second_pass_ascii.txt"); file f = new file("dirD.txt"); int numLines = 900; // load the real data file df = new file("second_pass.txt"); int numLines2 = 918; df.initRead(); double[] xD = new double[numLines2]; double[] yD = new double[numLines2]; String line = ""; for (int i=0; i<numLines2; i++) { line = df.readLine(); StringTokenizer st = new StringTokenizer(line); xD[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! yD[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]); //line = f.readLine(); //line = f.readLine(); } df.closeRead(); // then first lets get file list of model data String fileList[] = new String[900]; f.initRead(); line = ""; String garbage = ""; int ii=0; while ((line=f.readLine())!=null) { StringTokenizer st1 = new StringTokenizer(line); // throw out 4 and take the 5th garbage = st1.nextToken(); garbage = st1.nextToken(); garbage = st1.nextToken(); garbage = st1.nextToken(); fileList[ii]=st1.nextToken(); //System.out.println(i+" " + fileList[i]); ii++; } // now get the params from the model filename double[] x = new double[30]; double[] y = new double[30]; double[] z = new double[900]; int xNum = 0; int yNum = 0; for (int j=0; j<fileList.length; j++) { StringTokenizer st2 = new StringTokenizer(fileList[j],"_vl"); garbage = st2.nextToken(); o(garbage); String sss = st2.nextToken(); o("good?: " + sss); double test1 = Double.parseDouble(sss); //System.out.println(test1); if (!contains(x,test1)) { x[xNum]=test1; xNum++; } String aNumber = st2.nextToken(); o("good2?: " + aNumber); int len = aNumber.length(); aNumber = aNumber.substring(0,len-4); double test2 = Double.parseDouble(aNumber); if (!contains(y,test2)) { y[yNum]=test2; yNum++; } //System.out.println(xNum+" "+yNum); // ok we have params now lets load the file and get the fit factor cf = new CurveFitter(xD,yD,fileList[j]); cf.doFit(CurveFitter.IBEXFIT); z[j] = (cf.minimum_pub); System.out.println("did fit: "+ j + " : " + z[j]); } // write output to ascii file for later graphing asciiOutFile.initWrite(false); for (int i=0; i<x.length; i++) asciiOutFile.write(x[i]+"\n"); for (int i=0; i<y.length; i++) asciiOutFile.write(y[i]+"\n"); for (int i=0; i<z.length; i++) asciiOutFile.write(z[i]+"\n"); asciiOutFile.closeWrite(); JColorGraph jcg = new JColorGraph(x,y,z); String unitString = "log (sum square model error)"; jcg.setLabels("IBEX-LO","2010",unitString); jcg.run(); jcg.showIt(); } public static boolean contains(double[] set, double test) { for (int i=0; i<set.length; i++) { if (set[i]==test) return true; } return false; } public static void o(String s) { System.out.println(s); } public static final void main(String[] args) { IbexPostFitter theMain = new IbexPostFitter(); } }
Java
import java.lang.Math; /** Utility class for transforming coordinates, etc. * * * * (this is a general vector class, formulated for use in heliosphere) * (GSE not really implemented yet) * * Lukas Saul - Warsaw - July 2000 * Last updated May, 2001 */ public class HelioPoint { /* * These static ints are for discerning coordinate systems */ public static final int CARTESIAN = 1; public static final int SPHERICAL = 2; public static final int PLANAR = 3; public static final int GSE = 4; private double x,y,z; private double r,theta,phi; // phi=azimuth, theta=polar //private double xGSE, yGSE, zGSE; //private double psi, chi, ptheta; //private HelioPoint hp1, hp2, hp3; /* * these booleans are so we know when we need to calculate the conversion */ private boolean haveX, haveY, haveZ, haveR, havePhi, haveTheta; /**Default constructor - creates zero vector */ public HelioPoint() { haveX=true; haveY=true; haveZ=true; haveR=true; haveTheta=true; havePhi=true; x=0; y=0; z=0; r=0; theta=0; phi=0; } /** * constructor sets up SPHERICAL and CARTESIAN coordinates * CARTESIAN heliocentric coordinates. x axis = jan 1 00:00:00. */ public HelioPoint(int type, double a, double b, double c) { if (type == CARTESIAN) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = a; y = b; z = c; } if (type == SPHERICAL) { haveX=false; haveY=false; haveZ=false; haveR=true; haveTheta=true; havePhi=true; r = a; phi = b; theta = c; //syntax= give azimuth first! } } /** * Constructor to use when given an r and theta for a given plane (psi, chi) * psi is the angle of the intersection in the xy plane to x axis * chi is the closest angle of the plane to the z axis */ /*public HelioPoint(int type, double a, double b, double c, double d) { if (type == PLANAR) { haveX=true; haveY=true; haveZ=true; haveR=true; haveTheta=false; havePhi=false; psi=a; chi=b, r=c; ptheta=d; hp1 = new HelioPoint( SPHERICAL, */ /** * Use this to save overhead by eliminating "new" statements, same as constructors */ public void setCoords(int type, double a, double b, double c) { if (type == CARTESIAN) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = a; y = b; z = c; } if (type == SPHERICAL) { haveX=false; haveY=false; haveZ=false; haveR=true; haveTheta=true; havePhi=true; r = a; phi = b; theta = c; //syntax= give azimuth first! } } /** * Use this to save overhead by eliminating "new" statements */ public void setCoords(HelioPoint hp) { haveX=true; haveY=true; haveZ=true; haveR=false; haveTheta=false; havePhi=false; x = hp.getX(); y = hp.getY(); z = hp.getZ(); } /** Access methods - use these to get coordinates of this point */ public double getX() { if (haveX) return x; else { x = getR()*Math.cos(getPhi())*Math.sin(getTheta()); haveX = true; return x; } } public double getY(){ if (haveY) return y; else { y = getR()*Math.sin(getPhi())*Math.sin(getTheta()); haveY = true; return y; } } public double getZ() { if (haveZ) return z; else { z = getR()*Math.cos(getTheta()); haveZ = true; return z; } } public double getR() { if (haveR) return r; else { r = Math.sqrt(getX()*x + getY()*y + getZ()*z); haveR = true; return r; } } public double getPhi() { if (havePhi) return phi; else { // this stuff is because Math.atrig(arg) returns -pi/2<theta<pi/2 : // we want 0<phi<2pi if (getX()>0) phi = Math.atan(getY()/x); else if (x<0) phi = Math.atan(y/x) + Math.PI; else if (x==0 & y>0) phi = Math.PI/2; else if (x==0 & y<0) phi = 3*Math.PI/2; else if (x==0 & y==0) phi = 0; havePhi = true; if (phi<0) phi+=Math.PI*2; else if (phi>Math.PI*2) phi-=Math.PI*2; return phi; } } public double getTheta() { if (haveTheta) return theta; else if(getR()==0) { theta=0; haveTheta=true; return 0; } else { // we want theta>=0 & theta<= PI theta = Math.acos(z/getR()); //else if (z<0) theta = Math.PI + Math.acos(z/r); //else if (z==0) theta = Math.PI/2; haveTheta = true; //if (theta<0) theta+=|(theta>Math.PI)) System.out.println("theta? " + theta); return theta; } } // some vector operations here: /** * Add two vectors easily */ public HelioPoint sum(HelioPoint hp) { return new HelioPoint( CARTESIAN,getX()+hp.getX(),getY()+hp.getY(),getZ()+hp.getZ() ); } public static void sum(HelioPoint x, HelioPoint y) { x.setCoords(CARTESIAN, x.getX()+y.getX(), x.getY()+y.getY(), x.getZ()+y.getZ()); } /** * Subtract two vectors easily */ public HelioPoint difference(HelioPoint hp) { return new HelioPoint( CARTESIAN,getX()-hp.getX(),getY()-hp.getY(),getZ()-hp.getZ() ); } public static void difference(HelioPoint x, HelioPoint y) { x.setCoords( CARTESIAN, x.getX()-y.getY(), x.getY()-y.getY(), x.getZ()-y.getZ() ); } /** * Multiply a vector by a scalar */ public HelioPoint product(double d) { return new HelioPoint( SPHERICAL, d*getR(), getPhi(), getTheta() ); } public static void product(HelioPoint x, double d) { x.setCoords( SPHERICAL, d*x.getR(), x.getPhi(), x.getTheta() ); } /** * returns vector of same size pointing in opposite direction * */ public HelioPoint invert() { return new HelioPoint(CARTESIAN, -getX(), -getY(), -getZ()); } public static void invert(HelioPoint x) { x.setCoords( CARTESIAN, -x.getX(), -x.getY(), -x.getZ() ); } /** * returns unit vector in same direction * */ public HelioPoint normalize() { return new HelioPoint(SPHERICAL, 1, getPhi(), getTheta()); } public static void normalize(HelioPoint x) { x.setCoords( SPHERICAL, 1, x.getPhi(), x.getTheta() ); } /** * returns standard dot product */ public double dotProduct(HelioPoint hp) { return getX()*hp.getX() + getY()*hp.getY() + getZ()*hp.getZ(); } /** * returns standard cross product */ public HelioPoint crossProduct(HelioPoint hp) { return new HelioPoint( CARTESIAN, (getY()*hp.getZ() - getZ()*hp.getY()), (getZ()*hp.getX() - getX()*hp.getZ()), (getX()*hp.getY() - getY()*hp.getX()) ); } public static void crossProduct(HelioPoint x, HelioPoint y) { x.setCoords( CARTESIAN, (x.getY()*y.getZ() - x.getZ()*y.getY()), (x.getZ()*y.getX() - x.getX()*y.getZ()), (x.getX()*y.getY() - x.getY()*y.getX()) ); } /** * this returns the angle between our vector and inflow as expressed * with elevation and azimuth * (Range = from 0 to PI) */ public double angleToInflow(double phi0,double theta0) { HelioPoint lism = new HelioPoint(HelioPoint.SPHERICAL, 1, phi0, theta0); return getAngle(lism); } /** * This calculates the angle between two vectors. * Should range from 0 to PI * */ public double getAngle(HelioPoint hp) { double cosAngle = this.dotProduct(hp)/(getR()*hp.getR()); return Math.acos(cosAngle); } /** * HOPEFULLY DEPRECATED BY NOW * these routines for converting to a cylindrical coordinate system * note: axis must be non-zero vector! */ public double cylCoordRad(HelioPoint axis) { double tbr = this.dotProduct(axis) / axis.getR(); // ref plane doesnt matter here return tbr; } public double cylCoordTan(HelioPoint axis) { return this.crossProduct(axis).getR() / axis.getR(); // lenght of cross product = Vtangent? } public double cylCoordPhi(HelioPoint axis, HelioPoint refPlaneVector) { // a bit trickier here... using convention from Judge and Wu (sin Psi) HelioPoint newThis = moveZAxis(axis); HelioPoint newRefPlaneVector = moveZAxis(axis); return (newThis.getPhi() - newRefPlaneVector.getPhi() - Math.PI/2); } /** * this routine returns a new helioPoint expressed in terms of new z axis * lets try to take the cross product with current z axis and rotate around that. */ public HelioPoint moveZAxis(HelioPoint newAxis) { HelioPoint cp = new HelioPoint(CARTESIAN, getY(), -getX(), 0); cp = cp.normalize(); return rotateAroundArbitraryAxis(cp, newAxis.getTheta()).invert(); } /** * This routine uses a matrix transformation to * return a vector (HelioPoint) which has been rotated about * the axis (axis) by some degree (t). */ public HelioPoint rotateAroundArbitraryAxis(HelioPoint axis, double t) { x=getX(); y=getY(); z=getZ(); // make sure we have coords we need double s = Math.sin(t); double c=Math.cos(t);// useful quantities double oc = 1-c ; // this is unneccessary but I think I have an extra 16bits around somewhere double u = axis.getX(); double v = axis.getY(); double w = axis.getZ(); // this is a matrix transformation return new HelioPoint(CARTESIAN, x*(c + u*u*oc) + y*(-w*s + u*v*oc) + z*(v*s + u*w*oc), //x x*(w*s + u*v*oc) + y*(c + v*v*oc) + z*(-u*s + v*w*oc), //y x*(-v*s + u*w*oc) + y*(u*s + v*w*oc) + z*(c + w*w*oc) //z ); } public String toString() { String tbr = new String("\n"); tbr += "X = " + getX() + "\n"; tbr += "Y = " + getY() + "\n"; tbr += "Z = " + getZ() + "\n"; tbr += "r = " + getR() + "\n"; tbr += "phi = " + getPhi() + "\n"; tbr += "theta = " + getTheta() + "\n"; return tbr; } /** * for testing */ public static final void main(String[] args) { // let's test rotation routine HelioPoint hp1 = new HelioPoint(CARTESIAN, 0,0,1); HelioPoint hp2 = new HelioPoint(CARTESIAN, 1,0,0); HelioPoint hp3 = hp1.rotateAroundArbitraryAxis(hp2, Math.PI/2); System.out.println(hp3.getX()+" "+hp3.getY()+" "+hp3.getZ()); // ok, let's test this cylindrical coordinate bullshit HelioPoint hp4 = new HelioPoint(CARTESIAN, 0,0,1); HelioPoint hp5 = new HelioPoint(CARTESIAN, -1,0,0); System.out.println(hp5.cylCoordRad(hp4)+""); System.out.println(hp5.cylCoordTan(hp4)+""); System.out.println(hp5.cylCoordPhi(hp4,new HelioPoint(CARTESIAN,1,0,0))); } } /* // this is probably not the way to go here.... HelioPoint r1, r2, r3; o(getX() + " " + getY() + " " + getZ()); // first change (spin) to new coordinate frame so newAxis is above x axis r1 = new HelioPoint(SPHERICAL, getR(), getPhi()-newAxis.getPhi(), getTheta()); o(r1.getX() + " " + r1.getY() + " " + r1.getZ()); // then rename axes so we can do another spin r2 = new HelioPoint(CARTESIAN, r1.getZ(), r1.getX(), -r1.getY()); o(r2.getX() + " " + r2.getY() + " " + r2.getZ()); // now do the spin so the new axis is along x r3 = new HelioPoint(SPHERICAL, getR(), r2.getPhi()-newAxis.getTheta(), r2.getTheta()); o(r3.getX() + " " + r3.getY() + " " + r3.getZ()); // finally rename axes so new axis (currently on x) is along z return new HelioPoint(CARTESIAN, -r3.getZ(), r3.getY(), r3.getX());*/
Java
public class TestFunction { public TestFunction() { MyF test = new MyF(); MyF test1 = new MyF(); MyF test2 = new MyF(); MyF test3 = new MyF(); Function a = test.getFunction(0,1.0); Function b = test1.getFunction(0,0.0); Function c = test2.getFunction(1,5.0); Function d = test3.getFunction(1,10.0); System.out.println(a.function(0.0)+" "+b.function(0.0)+" "+c.function(0.0)+" "+ d.function(0.0)); } public static final void main(String[] args) { TestFunction tf = new TestFunction(); } } class MyF extends FunctionII { public double function2(double x, double y) { return Math.exp(x*x+y*y); } }
Java
import java.util.Date; public class ThetaOfBTest { public static void main(String[] args) { //System.out.println(10^2+" "+10^1+" "+1000+" "+Math.pow(10,2)); double AU = 1.5* Math.pow(10,11); Date d1 = new Date(); BofTheta vib = new BofTheta(AU, 28000); System.out.println(vib.testThetaOfB(AU)); System.out.println(vib.testThetaOfB(3*AU)); System.out.println(vib.testThetaOfB(1.8*AU)); System.out.println(vib.testThetaOfB(2*AU)); Date d2 = new Date(); System.out.println("Took: "+(d2.getTime()-d1.getTime())+ " milliseconds"); } }
Java
/* * Class MaximisationExample * * An example of the use of the class Maximisation * and the interface MaximisationFunction * * Finds the maximum of the function * z = a + x^2 + 3y^4 * where a is constant * (an easily solved function has been chosen * for clarity and easy checking) * * WRITTEN BY: Michael Thomas Flanagan * * DATE: 29 December 2005 * * PERMISSION TO COPY: * Permission to use, copy and modify this software and its documentation * for NON-COMMERCIAL purposes and without fee is hereby granted provided * that an acknowledgement to the author, Michael Thomas Flanagan, and the * disclaimer below, appears in all copies. * * The author makes no representations or warranties about the suitability * or fitness of the software for any or for a particular purpose. * The author shall not be liable for any damages suffered as a result of * using, modifying or distributing this software or its derivatives. * **********************************************************/ import flanagan.math.*; // Class to evaluate the function z = a + -(x-1)^2 - 3(y+1)^4 // where a is fixed and the values of x and y // (x[0] and x[1] in this method) are the // current values in the maximisation method. class MaximFunct implements MaximisationFunction{ private double a = 0.0D; // evaluation function public double function(double[] x){ double z = a - (x[0]-1.0D)*(x[0]-1.0D) - 3.0D*Math.pow((x[1]+1.0D), 4); return z; } // Method to set a public void setA(double a){ this.a = a; } } // Class to demonstrate maximisation method, Maximisation nelderMead public class MaximisationExample{ public static void main(String[] args){ //Create instance of Maximisation Maximisation max = new Maximisation(); // Create instace of class holding function to be maximised MaximFunct funct = new MaximFunct(); // Set value of the constant a to 5 funct.setA(5.0D); // initial estimates double[] start = {1.0D, 3.0D}; // initial step sizes double[] step = {0.2D, 0.6D}; // convergence tolerance double ftol = 1e-15; // Nelder and Mead maximisation procedure max.nelderMead(funct, start, step, ftol); // get the maximum value double maximum = max.getMaximum(); // get values of y and z at maximum double[] param = max.getParamValues(); // Print results to a text file max.print("MaximExampleOutput.txt"); // Output the results to screen System.out.println("Maximum = " + max.getMaximum()); System.out.println("Value of x at the maximum = " + param[0]); System.out.println("Value of y at the maximum = " + param[1]); } }
Java
/** * Utility class for passing around 3D functions * * Use this to generate a 2D function by fixing one of the variables */ public abstract class FunctionIII { /** * Override this with an interesting 3D function * */ public double function3(double x, double y, double z) { return 0; } /** * here's the Function implementation to return, modified in the public method.. * return this for index = 0 */ FunctionII ff0 = new FunctionII() { public double function2(double x, double y) { return function3(value_,x,y); } }; /** * here's the Function implementation to return, modified in the public method.. * return this for index = 1 */ FunctionII ff1 = new FunctionII() { public double function2(double x, double y) { return function3(x,value_,y); } }; /** * here's the Function implementation to return, modified in the public method.. * return this for index = 2 */ FunctionII ff2 = new FunctionII() { public double function2(double x, double y) { return function3(x,y,value_); } }; /* * This returns a two dimensional function, given one of the values * */ public final FunctionII getFunctionII(final int index, final double value) { //value_ = value; if (index == 0) return new FunctionII() { public double function2(double x, double y) { return function3(value,x,y); } }; else if (index == 1) return new FunctionII() { public double function2(double x, double y) { return function3(x,value,y); } }; else if (index == 2) return new FunctionII() { public double function2(double x, double y) { return function3(x,y,value); } }; else { System.out.println("index out of range in FunctionIII.getFunctionII"); return null; } } public static final void main(String[] args) { FunctionII f1 = new FunctionII() { public double function2(double x, double y) { return (Math.exp(x*x+y*y)); } }; FunctionIII f2 = new FunctionIII() { public double function3(double x, double y, double z) { return (Math.exp(x*x+y*y+z*z)); } }; FunctionII f3 = f2.getFunctionII(0,0.0); FunctionII f4 = f2.getFunctionII(1,0.0); FunctionII f5 = f2.getFunctionII(2,0.0); System.out.println("f1: " + f1.function2(0.5,0.0)); System.out.println("f3: " + f3.function2(0.5,0.0)); System.out.println("f4: " + f4.function2(0.5,0.0)); System.out.println("f5: " + f5.function2(0.0,0.5)); } }
Java
/** * Use a NeutralDistribution to compute a NeutralDensity in the heliosphere * * this is done by integrating over all velocity space for a desired grid * * x, y, built around origin from + to - 'scale'. */ public class NeutralDensity { private static int gridsize = 40; // gridsize^2 spatial calcualtion points public static double AU = 1.49598* Math.pow(10,11); //meters private static double scale = 100; // edge size in AU public String filename = "testoutput3.dat"; //private static double vMax = 10000000.0 // 10 k km/s // x and y are now the same but we hang onto them for clarity private double[] x = new double[gridsize]; private double[] y = new double[gridsize]; private double[] z = new double[gridsize*gridsize]; private NeutralDistribution nd; private MultipleIntegration mi; /** * Default, add lism params by hand here */ public NeutralDensity () { this(new NeutralDistribution( new KappaVLISM( new HelioVector(HelioVector.CARTESIAN,26000.0,0.0,0.0), 100.0,8000.0,1.6), 0.0, 0.0));//7*Math.pow(10.0,-8.0))); } /** * Build this object from a distribution. * 0th order moment creation here */ public NeutralDensity(NeutralDistribution nd_) { nd = nd_; mi = new MultipleIntegration(); //mi.setEpsilon(0.0001); nd.debug=false; //calculateGrid(); } private void calculateGrid() { double delta = scale*AU/(double)gridsize; System.out.println("delta: " + delta); System.out.println("gridsize " + gridsize); int index = 0; for (int i=1; i<=gridsize; i++) { x[index]=0.0-(scale*AU/2)+delta*i; y[index]=0.0-(scale*AU/2)+delta*i; System.out.println("x["+index+"] : " + x[index]); index++; } index = 0; for (int i=0; i<x.length; i++) { for (int j=0; j<y.length; j++) { HelioVector pos = new HelioVector(HelioVector.CARTESIAN, x[i], y[j], 0.0); z[index]=vint(pos); index++; System.out.println("calculated z[" + (index-1) + "] : " + z[index-1]); } } file f = new file(filename); f.initWrite(false); for (int i=0; i<x.length; i++) { f.write(x[i]+"\n"); } f.write("\n"); for (int i=0; i<z.length; i++) { f.write(z[i]+"\n"); } f.closeWrite(); //JColorGraph jcg = new JColorGraph(x,y,z); //jcg.run(); } /** * Do the integration! Pass in a the position as a heliovector */ private double vint(HelioVector hp) { final HelioVector hpf = hp; FunctionIII dist = new FunctionIII () { // r,p,t here actually a velocity passed in... public double function3(double r, double p, double t) { return r*r*Math.sin(t)*nd.dist(hpf,new HelioVector(HelioVector.SPHERICAL, r, p, t)); } }; double[] limits = new double[6]; limits[0]=0.0; limits[1]=100000; limits[2]=0.001; limits[3]=2*Math.PI; limits[4]=0.001; limits[5]=Math.PI; //limits[4]=Math.sqrt(2*nd.gmodMs/hp.getR()); limits[5]=300000; return mi.mcIntegrateSS(dist,limits, 100000); } /** * Use for testing first, then for starting routine to generate grid */ public static void main(String[] args) { // first we do some tests // first test - density at 1000AU,1000AU,1000AU /*HelioVector tv = new HelioVector(HelioVector.CARTESIAN, 100*AU, 100*AU, 100*AU); NeutralDistribution ndist = new NeutralDistribution( new GaussianVLISM(new HelioVector(HelioVector.CARTESIAN,50.0,0.0,0.0), 50000,8000.0) ,0.0,0.0); NeutralDensity nd = new NeutralDensity(ndist); System.out.println("test: " + nd.vint(tv)); System.out.println("nd.counter: " + ndist.counter); */ NeutralDensity nd = new NeutralDensity(); nd.calculateGrid(); } }
Java
/* * $Id: JGridDemo.java,v 1.8 2001/02/05 23:28:46 dwd Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ //package gov.noaa.pmel.sgt.demo; import gov.noaa.pmel.sgt.swing.JPlotLayout; import gov.noaa.pmel.sgt.swing.JClassTree; import gov.noaa.pmel.sgt.swing.prop.GridAttributeDialog; import gov.noaa.pmel.sgt.JPane; import gov.noaa.pmel.sgt.GridAttribute; import gov.noaa.pmel.sgt.ContourLevels; import gov.noaa.pmel.sgt.CartesianRenderer; import gov.noaa.pmel.sgt.CartesianGraph; import gov.noaa.pmel.sgt.GridCartesianRenderer; import gov.noaa.pmel.sgt.IndexedColorMap; import gov.noaa.pmel.sgt.ColorMap; import gov.noaa.pmel.sgt.LinearTransform; import gov.noaa.pmel.sgt.dm.SGTData; import gov.noaa.pmel.util.GeoDate; import gov.noaa.pmel.util.TimeRange; import gov.noaa.pmel.util.Range2D; import gov.noaa.pmel.util.Dimension2D; import gov.noaa.pmel.util.Rectangle2D; import gov.noaa.pmel.util.Point2D; import gov.noaa.pmel.util.IllegalTimeValue; import java.awt.*; import javax.swing.*; /** * Example demonstrating how to use <code>JPlotLayout</code> * to create a raster-contour plot. * * @author Donald Denbo * @version $Revision: 1.8 $, $Date: 2001/02/05 23:28:46 $ * @since 2.0 */ public class JGridDemo extends JApplet { static JPlotLayout rpl_; private GridAttribute gridAttr_; JButton edit_; JButton space_ = null; JButton tree_; public void init() { /* * Create the demo in the JApplet environment. */ getContentPane().setLayout(new BorderLayout(0,0)); setBackground(java.awt.Color.white); setSize(600,550); JPanel main = new JPanel(); rpl_ = makeGraph(); JPanel button = makeButtonPanel(false); rpl_.setBatch(true); main.add(rpl_, BorderLayout.CENTER); JPane gridKeyPane = rpl_.getKeyPane(); gridKeyPane.setSize(new Dimension(600,100)); main.add(gridKeyPane, BorderLayout.SOUTH); getContentPane().add(main, "Center"); getContentPane().add(button, "South"); rpl_.setBatch(false); } JPanel makeButtonPanel(boolean mark) { JPanel button = new JPanel(); button.setLayout(new FlowLayout()); tree_ = new JButton("Tree View"); MyAction myAction = new MyAction(); tree_.addActionListener(myAction); button.add(tree_); edit_ = new JButton("Edit GridAttribute"); edit_.addActionListener(myAction); button.add(edit_); /* * Optionally leave the "mark" button out of the button panel */ if(mark) { space_ = new JButton("Add Mark"); space_.addActionListener(myAction); button.add(space_); } return button; } public static void main(String[] args) { /* * Create the demo as an application */ JGridDemo gd = new JGridDemo(); /* * Create a new JFrame to contain the demo. */ JFrame frame = new JFrame("Grid Demo"); JPanel main = new JPanel(); main.setLayout(new BorderLayout()); frame.setSize(600,500); frame.getContentPane().setLayout(new BorderLayout()); /* * Listen for windowClosing events and dispose of JFrame */ frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent event) { JFrame fr = (JFrame)event.getSource(); fr.setVisible(false); fr.dispose(); System.exit(0); } public void windowOpened(java.awt.event.WindowEvent event) { rpl_.getKeyPane().draw(); } }); /* * Create button panel with "mark" button */ JPanel button = gd.makeButtonPanel(true); /* * Create JPlotLayout and turn batching on. With batching on the * plot will not be updated as components are modified or added to * the plot tree. */ rpl_ = gd.makeGraph(); rpl_.setBatch(true); /* * Layout the plot, key, and buttons. */ main.add(rpl_, BorderLayout.CENTER); JPane gridKeyPane = rpl_.getKeyPane(); gridKeyPane.setSize(new Dimension(600,100)); rpl_.setKeyLayerSizeP(new Dimension2D(6.0, 1.0)); rpl_.setKeyBoundsP(new Rectangle2D.Double(0.0, 1.0, 6.0, 1.0)); main.add(gridKeyPane, BorderLayout.SOUTH); frame.getContentPane().add(main, BorderLayout.CENTER); frame.getContentPane().add(button, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); /* * Turn batching off. JPlotLayout will redraw if it has been * modified since batching was turned on. */ rpl_.setBatch(false); } void edit_actionPerformed(java.awt.event.ActionEvent e) { /* * Create a GridAttributeDialog and set the renderer. */ GridAttributeDialog gad = new GridAttributeDialog(); gad.setJPane(rpl_); CartesianRenderer rend = ((CartesianGraph)rpl_.getFirstLayer().getGraph()).getRenderer(); gad.setGridCartesianRenderer((GridCartesianRenderer)rend); // gad.setGridAttribute(gridAttr_); gad.setVisible(true); } void tree_actionPerformed(java.awt.event.ActionEvent e) { /* * Create a JClassTree for the JPlotLayout objects */ JClassTree ct = new JClassTree(); ct.setModal(false); ct.setJPane(rpl_); ct.show(); } JPlotLayout makeGraph() { /* * This example uses a pre-created "Layout" for raster time * series to simplify the construction of a plot. The * JPlotLayout can plot a single grid with * a ColorKey, time series with a LineKey, point collection with a * PointCollectionKey, and general X-Y plots with a * LineKey. JPlotLayout supports zooming, object selection, and * object editing. */ SGTData newData; TestData td; JPlotLayout rpl; ContourLevels clevels; /* * Create a test grid with sinasoidal-ramp data. */ Range2D xr = new Range2D(190.0f, 250.0f, 1.0f); Range2D yr = new Range2D(0.0f, 45.0f, 1.0f); td = new TestData(TestData.XY_GRID, xr, yr, TestData.SINE_RAMP, 12.0f, 30.f, 5.0f); newData = td.getSGTData(); /* * Create the layout without a Logo image and with the * ColorKey on a separate Pane object. */ rpl = new JPlotLayout(true, false, false, "test layout", null, true); rpl.setEditClasses(false); /* * Create a GridAttribute for CONTOUR style. */ Range2D datar = new Range2D(-20.0f, 45.0f, 5.0f); clevels = ContourLevels.getDefault(datar); gridAttr_ = new GridAttribute(clevels); /* * Create a ColorMap and change the style to RASTER_CONTOUR. */ ColorMap cmap = createColorMap(datar); gridAttr_.setColorMap(cmap); gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR); /* * Add the grid to the layout and give a label for * the ColorKey. */ rpl.addData(newData, gridAttr_, "First Data"); /* * Change the layout's three title lines. */ rpl.setTitles("Raster Plot Demo", "using a JPlotLayout", ""); /* * Resize the graph and place in the "Center" of the frame. */ rpl.setSize(new Dimension(600, 400)); /* * Resize the key Pane, both the device size and the physical * size. Set the size of the key in physical units and place * the key pane at the "South" of the frame. */ rpl.setKeyLayerSizeP(new Dimension2D(6.0, 1.02)); rpl.setKeyBoundsP(new Rectangle2D.Double(0.01, 1.01, 5.98, 1.0)); return rpl; } ColorMap createColorMap(Range2D datar) { int[] red = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 23, 39, 55, 71, 87,103, 119,135,151,167,183,199,215,231, 247,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,246,228,211,193,175,158,140}; int[] green = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 27, 43, 59, 75, 91,107, 123,139,155,171,187,203,219,235, 251,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0}; int[] blue = { 0,143,159,175,191,207,223,239, 255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; IndexedColorMap cmap = new IndexedColorMap(red, green, blue); cmap.setTransform(new LinearTransform(0.0, (double)red.length, datar.start, datar.end)); return cmap; } class MyAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object obj = event.getSource(); if(obj == edit_) edit_actionPerformed(event); if(obj == space_) { System.out.println(" <<Mark>>"); } if(obj == tree_) tree_actionPerformed(event); } } }
Java
import cern.jet.math.Bessel; import java.lang.Math; import java.util.Date; import drasys.or.nonlinear.*; public class SimpleNeutralDistribution { // constants not correct yet public static double Ms = 2 * Math.pow(10,30); public static double G = 6.67 * Math.pow(10,-11); public static double AU = 1.5* Math.pow(10,11); public static double K = 1.380622 * Math.pow(10,-23); //1.380622E-23 kg/m/s/s/K public static double Mhe = 4*1.6726231 * Math.pow(10,-27); // 4 * 1.6726231 x 10-24 gm public double Q, F1, F2, Temp, Vb, N, Vtemp, V0, mu, r, theta, betaPlus, betaMinus; public double phi0, theta0; // direction of bulk flow - used when converting to GSE //public Trapezoidal s; public Integration s; public SurvivalProbability sp; public SimpleNeutralDistribution(double bulkVelocity, double phi0, double theta0, double temperature, double density, double radiationToGravityRatio, double lossRate1AU) { // the constructor just sets up the parameters Temp = temperature; Vb = bulkVelocity; this.phi0 = phi0; this.theta0 = theta0; N = density; mu = radiationToGravityRatio; betaMinus=lossRate1AU; Vtemp = Math.sqrt(2*K*Temp/Mhe); //average velocity due to heat sp = new SurvivalProbability(betaMinus); } // this function returns N(r,theta) /*public double N(double r, double theta) { this.r = r; this.theta = theta; // set the location Q = Math.sqrt((1-mu)*G*Ms/r); Nvr nvr = new Nvr(); try { return s.integrate(nvr, -10000, 10000); } catch(Exception e) { e.printStackTrace(); return 0; } }*/ // this function returns N(r,theta, vt) public double N(double r, double theta, double vt) { this.r=r; this.theta=theta; Q = Math.sqrt((1-mu)*G*Ms/r); Nvr nvr = new Nvr(vt); //s = new Trapezoidal(); s.setMaxIterations(15); s.setEpsilon(1000000); s=new Integration(); s.setFunction(nvr); s.setMaxError(.01); try { return s.integrate( -100000, 100000); }catch(Exception e) { e.printStackTrace(); return 0; } } class Nvt implements FunctionI, Function { // Here's the neutral distribution as a function of vr, vt: private double vr; public Nvt(double vr_) { vr = vr_; } public double function(double vt) { V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q); F1 = 2*Vb*vr/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) - ((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp); F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q)); return sp.compute(r,theta,vt,vr) * N*Math.pow((Math.sqrt(Math.PI)*Vtemp),-3) * Math.exp(F1)*Bessel.i0(F2); } } class Nvr implements FunctionI, Function { // this is the function we integrate over vr public double vt; public Nvr(double vt_) { System.out.println("nvr constructor"); vt = vt_; // System.out.println("set vt"); } public double function(double vr) { // System.out.println("Trying nvr.function vr= " + vr); V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q); F1 = 2*Vb*vr/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) - ((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp); F2 = 2*V0*Vb/(Vtemp*Vtemp) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q)); return sp.compute(r,theta,vt,vr)*N*Math.pow((Math.sqrt(Math.PI)*Vtemp),-3) * Math.exp(F1)*Bessel.i0(F2); // here we integrate over L(r,v)*N(r,v) with L = survival probability. // this could be all put into this routine but I leave it out for other // factors to be added in later } } }
Java
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import javax.swing.text.DefaultEditorKit; import java.net.*; import java.io.*; import java.util.*; import java.text.DateFormat; import java.text.SimpleDateFormat; // Now keeps the last dates in memory to avoid parsing again. // Also remembers most recent format and uses it, rather than trying with each one. public class MyDate2 { private int lastPattern=0; private String lastDateString=""; private Date lastDate=null; private Date toBeReturned=null; private boolean didIt = false; private int iCounter = 0; private SimpleDateFormat sdf; private String pattern[] = { "EEE, dd MMM yyyy HH:mm:ss z", // this one works for most services "EEE, dd MMM yyyy HH:mm:ss zzzz", // does this help? "dd MMM yyyy HH:mm:ss z", // this one works for hotmail "EEE MMM dd HH:mm:ss zzz yyyy", "d MMM yy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:ss", // Needed to aid at hotmail "dd MMM yyyy HH:mm:ss", // Another hotmail fix: 7 Feb 2000 01:30:18 "EEE, dd MMM yy hh:mma z", //usa.net? "EEE, dd MMM yy HH:mm:ss z", // Hotmail strikes: Sat, 12 Aug 00 12:03:18 Pacific Daylight Time "dd MMM yy hh:mm:ss a", // Hotmail strikes: 11 Aug 00 7:29:09 AM "EEE, dd MMM yy HH:mma z", // Usa.net: Thu, 21 Sep 00 13:18PM PDT "EEEE, MMMM d, yyyy h:mm:ss 'o''clock' a z", // the rest here are guesses "MMMM d, yyyy hh:mm:ss a z", "dd-MMM-yy h:mm:ss a", "MM/dd/yy h:mm a", "EEE, dd MMM yyyy HH:mm z", /// Tue, 19 Dec 2000 15:57 +0000 "EEE, dd MMM yyyy :mm z", /// Thu, 2 Nov 2000 :21 EST "dd-MM-yy hh:mm:ss a", "MM/dd/yy HH:mm:ss", "EEE, MMM dd, yyyy hh:mm:ss a", // the new netscape: Saturday, January 13, 2001 1:47:58 AM "EEE, dd MMM yyyy HH:mm", // Australia, telstra.com: Sunday, 7 January 2001 23:16 "HH:mm:ss MM/dd/yy" }; //NOTE KEY HERE: under 4 letters - look for abbreviation. 4 0r more for written out. // H - 24 hr scale h - 12 hr scale a - am/pm E - day of week - see API /* Symbol Meaning Presentation Example ------ ------- ------------ ------- G era designator (Text) AD y year (Number) 1996 M month in year (Text & Number) July & 07 d day in month (Number) 10 h hour in am/pm (1~12) (Number) 12 H hour in day (0~23) (Number) 0 m minute in hour (Number) 30 s second in minute (Number) 55 S millisecond (Number) 978 E day in week (Text) Tuesday D day in year (Number) 189 F day of week in month (Number) 2 (2nd Wed in July) w week in year (Number) 27 W week in month (Number) 2 a am/pm marker (Text) PM k hour in day (1~24) (Number) 24 K hour in am/pm (0~11) (Number) 0 z time zone (Text) Pacific Standard Time ' escape for text (Delimiter) '' single quote (Literal) ' The count of pattern letters determine the format. (Text): 4 or more pattern letters--use full form, < 4--use short or abbreviated form if one exists. (Number): the minimum number of digits. Shorter numbers are zero-padded to this amount. Year is handled specially; that is, if the count of 'y' is 2, the Year will be truncated to 2 digits. (Text & Number): 3 or over, use text, otherwise use number. */ //here's the main routine: public Date parse(String date) { // In order to be a little efficient, we are going to try // and check our last known good date against this one // Some services standardize on dates, so we'll be able // to be more efficient and then faster if (date.equals(lastDateString)) return lastDate; // if so, we audi. sdf = new SimpleDateFormat(pattern[lastPattern]); sdf.setLenient(false); // lenient my ass! try { toBeReturned = sdf.parse(date); didIt = true; lastDateString = date; lastDate = toBeReturned; } catch (Exception e) {didIt = false; } if (didIt) return toBeReturned; // if so, we audi again // counter needs to be reset so that we start from the beginning of our patterns iCounter = 0; // worst case scenario, loop through all patterns while (!didIt) { // System.out.println("Checking pattern: " + pattern[iCounter]); sdf.applyPattern(pattern[iCounter]); sdf.setLenient(false); // lenient my ass! // System.out.println("Checking pattern: " + pattern[iCounter]); try { toBeReturned = sdf.parse(date); didIt = true; lastDateString = date; lastDate = toBeReturned; } catch (Exception e) {didIt = false; } if (didIt) return toBeReturned; // we audi // System.out.println("date: " + date); if (iCounter==pattern.length-1) { // so we couldn't parse it! System.out.println("FIX THIS!! UNABLE TO PARSE: " + date); toBeReturned = new Date(); return toBeReturned; } else iCounter++; } // We should never get here System.out.println("problems in the date parser of a serious nature!!"); return toBeReturned; //required for compilation } }
Java
import java.io.*; /** * Read and parse a single "*.MCA" file * These MCA files are outputs of our positional MCP detector * sometimes known as "quanta" or "carlson" detector * */ public class 3DFileReader { public DataInputStream dis; int maxbin = 128; int betamax = 3; int alphamax = 109; int alphabegin = -7; float pictratio = alphamax/betamax; float[][] image = new float[maxbin][maxbin]; public 3DFileReader (String t) { String testFile = t; try { dis = new DataInputStream(new FileInputStream(testFile)); short alpha = dis.readShort(); float beta = dis.readFloat(); float theta = dis.readFloat(); float bm = dis.readFloat(); float energy = dis.readFloat(); float acctime = dis.readFloat(); float totalCounts = dis.readFloat(); // end reading header for (int i=0; i<maxbin; i++) { for (int j=0; j<maxbin; j++) { image[i][j]=dis.readFloat(); } } System.out.println("read file: " + testFile); System.out.println("alpha: " + alpha); System.out.println("beta: " + beta); System.out.println("theta: " + theta); System.out.println("bm: " + bm); System.out.println("acctime: " + acctime); System.out.println("total counts: " + totalCounts); System.out.println("0,0 : " + image[0][0]); } catch (Exception e) { e.printStackTrace(); System.out.println("Couldn't find file: " + testFile); } } public static final void main(String[] args) { if (args.length<1) {3DFileReader mr = new 3DFileReader("1209_1.mca");} else {3DFileReader mr = new 3DFileReader(args[0]);} } }
Java
import java.lang.Math; import java.util.Date; //Put your own function here and intgrate it // Lukas Saul - Warsaw 2000 // lets use someone elses, shall we? // nah, they all suck. I'll write my own public class Integration { private int startDivision = 5; private long maxDivision = 100000; private int maxTime = 60; private boolean checkTime = false; private double maxError = .1; private double averageValue; private Function f; //private int splitSize; private double f1, f2, f3, f4, f5, f6, f7; private Date d1, d2, d3; private double ll,ul,last; public void setStartDivision(int s) { startDivision = s; } public int getStartDivision() {return startDivision; } public void setMaxDivision(long m) {maxDivision = m; } public long getMaxDivision() {return maxDivision;} public void setMaxTime(int mt) {maxTime = mt;} public int getMaxTime() {return maxTime; } public void setCheckTime(boolean ct) {checkTime = ct; } public boolean getCheckTime() {return checkTime; } public void setMaxError(double me) { if (me<1 & me>0) maxError = me; } public double getMaxError() {return maxError;} public void setFunction(Function fi) {f=fi;} //public void setSplitSize (int ss) {splitSize = ss;} //public int getSplitSize () {return splitSize; } private double IntegrateSimple(double lowerLimit, double upperLimit) { if (lowerLimit==ll & upperLimit == ul) return last; else { ll = lowerLimit; ul=upperLimit; f1 = f.function(lowerLimit); f2 = f.function(upperLimit); last = (upperLimit - lowerLimit) * (f1 + .5*(f2-f1)); // trapezoidal area return last; } } public double integrate (double lowerLimit, double upperLimit) { if (checkTime) d1 = new Date(); f3 = 0; f4 = (upperLimit - lowerLimit)/startDivision; // f4 = divisionSize for (int i = 0; i< startDivision; i++) { f3 += recurse(lowerLimit+(i*f4), lowerLimit+((i+1)*f4), startDivision); } return f3; } private double recurse (double lower, double upper, long depth) { if (checkTime) { d2 = new Date(); if ((d2.getTime() - d1.getTime())/1000 > maxTime) { return IntegrateSimple(lower, upper); } } if (depth >= maxDivision) return IntegrateSimple(lower, upper); f5 = IntegrateSimple(lower, lower + (upper-lower)/2); f5 += IntegrateSimple(lower+ (upper-lower)/2, upper); f6 = IntegrateSimple(lower, upper); // if the difference between these two intgrals is within error, return the better if (Math.abs(1-f6/f5) < maxError) return f5; // if not divide up the two and recurse else return recurse(lower, lower + (upper-lower)/2, depth*2) + recurse(lower+ (upper-lower)/2, upper, depth*2); } }
Java
import java.util.*; /** * Lukas Saul, UNH Space Science Dept. * Curvefitting utilities here. * * Adapted to use simplex method from flanagan java math libraries - March 2006 * * * > * -- added step function and pulled out of package IJ -- lukas saul, 11/04 * * -- adding EXHAUSTIVE SEARCH ability.. for nonlinear fits * * * -- adding HEMISPHERIC - analytic fit to hemispheric model w/ radial field * see Hemispheric.java for info * * -- adding quadratic that passes through origin for PUI / Np correlation * * -- adding SEMI - analytic fit assuming constant adiabatic acceleration * that uses legendre polynomials for pitch angle diffusion. see SemiModel.java * March, 2006 * */ public class CurveFitter implements MinimisationFunction { public static final int STRAIGHT_LINE=0,POLY2=1,POLY3=2,POLY4=3, EXPONENTIAL=4,POWER=5,LOG=6,RODBARD=7,GAMMA_VARIATE=8, LOG2=9, STEP=10, HEMISPHERIC=11, HTEST=12, QUAD_ORIGIN=13, GAUSSIAN=14, SEMI=15, SEMI_1=16, IBEX=17, /** this one is custom, change at will */ IBEXFIT=18, IBEX1=19, SPINPHASE = 20,COMBO = 21, DOUBLE_NORM = 22, ONE_PARAM_FIT = 23; public static final String[] fitList = {"Straight Line","2nd Degree Polynomial", "3rd Degree Polynomial", "4th Degree Polynomial","Exponential","Power", "log","Rodbard", "Gamma Variate", "y = a+b*ln(x-c)", "Step Function", "Hemispheric", "H-test", "Quadratic Through Origin","Gaussian","Semi","Semi-one-param", "IBEX_sim","IBEX_fitfit","1 param IBEX fit"," T,V,lat fit ", "T, v,lamda,beta fit", "two norm", "one norm"}; public static final String[] fList = {"y = a+bx","y = a+bx+cx^2", "y = a+bx+cx^2+dx^3", "y = a+bx+cx^2+dx^3+ex^4","y = a*exp(bx)","y = ax^b", "y = a*ln(bx)", "y = d+(a-d)/(1+(x/c)^b)", "y = a*(x-b)^c*exp(-(x-b)/d)", "y = a+b*ln(x-c)", "y = a*step(x-b)", "y=hem.f(a,x)", "y = norm*step()..","y=ax+bx^2", "y=a*EXP(-(x-b)^2/c)","y=semi.f(a,b,x)","y=ibex.f(temp,norm,pos,doy(a,b,c,x))", "y = a*fit(x)", "y=ibex.f(norm)", "y=ibex.f(t,v,lat,sp)", "y=ibex.f(t,v,lamda,beta", "y=a*stuff orb*stuff", "y=a*stuff"}; private static final double root2 = Math.sqrt(2.0);//1.414214; // square root of 2 private int fit; // Number of curve type to fit private double[] xData, yData; // x,y data to fit public double[] bestParams; // take this after doing exhaustive for the answer public double minimum_pub; //public Hemispheric hh; public SemiModel sm; public AdiabaticModel am; public IBEXLO_09fit ib; public FitData ff; public IBEXWind iw, ibw; public double[] start, step; public double ftol; public double gamma = 1.5; public Minimisation min; public String fitFile; public FitData fitData; public CurveFitter() { min = new Minimisation(); // beware to set data before using this one! } /** * build it with floats and cast */ public CurveFitter (float[] xDat, float[] yDat) { xData = new double[xDat.length]; yData = new double[yDat.length]; for (int i=0; i<xData.length; i++) { xData[i]=(double)xDat[i]; yData[i]=(double)yDat[i]; } min = new Minimisation(); //numPoints = xData.length; } public CurveFitter (double[] xData, double[] yData, String fname) { fitFile = fname; this.xData = xData; this.yData = yData; min = new Minimisation(); } public CurveFitter (double[] xData, double[] yData, FitData fname) { fitData = fname; this.xData = xData; this.yData = yData; min = new Minimisation(); } /** Construct a new CurveFitter. */ public CurveFitter (double[] xData, double[] yData) { this.xData = xData; this.yData = yData; min = new Minimisation(); //numPoints = xData.length; } /** * Construct a new CurveFitter. * * this time with some params for the ibex fitter */ public CurveFitter (double[] xData, double[] yData, double lam, double vv) { this.xData = xData; this.yData = yData; min = new Minimisation(); ib = new IBEXLO_09fit(); // public void setParams(double longitude, double speed, double dens, double temp) { ib.setParams(lam, vv, ib.currentDens, ib.currentTemp); //numPoints = xData.length; } /** * Set the actual data that we are fitting * */ public void setData(double[] xx, double[] yy) { xData = xx; yData = yy; } /** * Set a curve to use for the one parameter fit method * */ public void setFitData(String fname) { fitData = new FitData(fname); } /** * Perform curve fitting with the simplex method */ public void doFit(int fitType) { fit = fitType; //if (fit == HEMISPHERIC) hh=new Hemispheric(); if (fit == SEMI | fit==SEMI_1) am = new AdiabaticModel(); if (fit == IBEX) ib = new IBEXLO_09fit(); //if (fit == IBEX1) ib = new IBEXLO_09fit(); //if (fit == IBEXFIT) ff = new FitData(fitFile); if (fit == IBEXFIT) ff = fitData; if (fit == SPINPHASE) iw = new IBEXWind(); if (fit == COMBO) ibw = new IBEXWind(); // SIMPLEX INITIALIZTION initialize(); ftol = 1e-4; // Nelder and Mead minimisation procedure min.nelderMead(this, start, step, ftol, 10000); //min.nelderMead(this, start, step, 1000); // get the minimum value minimum_pub = min.getMinimum(); // get values of y and z at minimum double[] param = min.getParamValues(); bestParams = param; /* // Output the results to screen for (int i=0; i<param.length; i++) { System.out.println("param_" + i + " : " + param[i]); } System.out.println("Minimum = " + min.getMinimum()); System.out.println("Error: " + getError(param)); //if (fit == SEMI) System.out.println("sm tests: "+ sm.counter + " "+ sm.counter/25); String tbr = ""; tbr+=("Minimum = " + min.getMinimum() + "\n"); tbr+=("Error: " + getError(param) + "\n"); for (int i=0; i<param.length; i++) { System.out.println("param_" + i + " : " + param[i]); tbr+=("param_" + i + " : " + param[i] + "\n"); } //if (fit == SEMI) System.out.println("sm tests: "+ sm.counter + " "+ sm.counter/25); tbr+="xdata \t ydata \t fitdata \n"; //outF.closeWrite(); for (int i=0; i<xData.length; i++) { tbr+=(xData[i]+"\t"+yData[i]+"\t"+f(fit,param,xData[i])+"\n"); } file f = new file("curvefit_results.txt"); f.saveShit(tbr); */ } /** * Here we cannot check our error and move toward the next local minima in error.. * * we must compare every possible fit. * * For now, only 2d fits here.. */ public void doExhaustiveFit(int fitType, double[] param_limits, int[] steps) { fit = fitType; // if (fit == HEMISPHERIC) hh=new Hemispheric(); if (fit == SEMI) sm = new SemiModel(); if (fit == SEMI_1) sm = new SemiModel(); int numParams = getNumParams(); if (numParams!=2) throw new IllegalArgumentException("Invalid fit type"); double[] params = new double[numParams]; double bestFit = Math.pow(10,100.0); bestParams = new double[numParams]; double[] startParams = new double[numParams]; double[] deltas = new double[numParams]; for (int i=0; i<params.length; i++) { // set miminimum of space to search params[i]=param_limits[2*i]; // find deltas of space to search deltas[i]=(param_limits[2*i+1]-param_limits[2*i])/steps[i]; // set the best to the first for now bestParams[i]=params[i]; startParams[i]=params[i]; } System.out.println("deltas: " + deltas[0] + " " + deltas[1]); System.out.println("steps: " + steps[0] + " " + steps[1]); System.out.println("startParams: " + startParams[0] + " " + startParams[1]); //start testing them for (int i=0; i<steps[0]; i++) { for (int j=0; j<steps[1]; j++) { params[0]=startParams[0]+i*deltas[0]; params[1]=startParams[1]+j*deltas[1]; double test = getError(params); // System.out.println("prms: " + params[0] + " " + params[1]+ " er: " + test); if (test<bestFit) { //System.out.println("found one: " + test + " i:" + params[0] + " j:" + params[1]); bestFit = test; bestParams[0] = params[0]; bestParams[1] = params[1]; } } } } /** * *Initialise the simplex * * Here we put starting point for search in parameter space */ void initialize() { start = new double[getNumParams()]; step = new double[getNumParams()]; java.util.Arrays.fill(step,1.0); double firstx = xData[0]; double firsty = yData[0]; double lastx = xData[xData.length-1]; double lasty = yData[xData.length-1]; double xmean = (firstx+lastx)/2.0; double ymean = (firsty+lasty)/2.0; double slope; if ((lastx - firstx) != 0.0) slope = (lasty - firsty)/(lastx - firstx); else slope = 1.0; double yintercept = firsty - slope * firstx; switch (fit) { case STRAIGHT_LINE: start[0] = yintercept; start[1] = slope; break; case POLY2: start[0] = yintercept; start[1] = slope; start[2] = 0.0; break; case POLY3: start[0] = yintercept; start[1] = slope; start[2] = 0.0; start[3] = 0.0; break; case POLY4: start[0] = yintercept; start[1] = slope; start[2] = 0.0; start[3] = 0.0; start[4] = 0.0; break; case EXPONENTIAL: start[0] = 0.1; start[1] = 0.01; break; case POWER: start[0] = 0.0; start[1] = 1.0; break; case LOG: start[0] = 0.5; start[1] = 0.05; break; case RODBARD: start[0] = firsty; start[1] = 1.0; start[2] = xmean; start[3] = lasty; break; case GAMMA_VARIATE: // First guesses based on following observations: // t0 [b] = time of first rise in gamma curve - so use the user specified first limit // tm = t0 + a*B [c*d] where tm is the time of the peak of the curve // therefore an estimate for a and B is sqrt(tm-t0) // K [a] can now be calculated from these estimates start[0] = firstx; double ab = xData[getMax(yData)] - firstx; start[2] = Math.sqrt(ab); start[3] = Math.sqrt(ab); start[1] = yData[getMax(yData)] / (Math.pow(ab, start[2]) * Math.exp(-ab/start[3])); break; case LOG2: start[0] = 0.5; start[1] = 0.05; start[2] = 0.0; break; case STEP: start[0] = yData[getMax(yData)]; start[1] = 2.0; break; case HEMISPHERIC: start[0] = 1.0; start[1] = yData[getMax(yData)]; break; case QUAD_ORIGIN: start[0] = yData[getMax(yData)]/2; start[1] = 1.0; break; case GAUSSIAN: start[0] = yData[getMax(yData)]; start[1] = xData[getMax(yData)]; start[2] = Math.abs((lastx-firstx)/2); System.out.println(""+start[0]+" "+start[1]+" "+start[2]); break; case SEMI: start[0] = 1; start[1] = 1.5; //start[2] = 1.5; step[0] = 100; step[1] = 0.1; //step[2] = 1; // min.addConstraint(0,-1,0); min.addConstraint(1,-1,0); // min.addConstraint(1,1,0.001); //min.addConstraint(2,-1,0); //start[2] = 1.5; //step[2] = 1.0; break; case SEMI_1: start[0] = 1; step[0] = 100; break; case IBEX: // new params are density and temp start[0] = 0.015; start[1] = 6300; step[0] = 0.008; step[1] = 6000; // params are longitude (deg), speed(m/s), density(cm3), temp(k) // old start params for 4 parameter fit.. now we use two parameter fit /*start[0] = 75.0; start[1] = 26000.0; start[2] = 0.015; start[3] = 6300; step[0] = 5; step[1] = 5000; step[2] = 0.003; step[3] = 1000;*/ break; case IBEXFIT: start[0] = 6000.0; step[0] = 20.0; break; case IBEX1: start[0] = 0.0001; step[0] = 0.001; break; case SPINPHASE: // params are density, temp, v, theta start[0] = 0.015; start[1] = 5000.0; start[2] = 25000.0; start[3] = 96.5; step[0] = 0.008; step[1] = 3000.0; step[2] = 5000.0; step[3] = 4.0; break; case COMBO: // params are density_series, density_sp, temp, v, lamda, theta start[0] = 0.10; start[1] = 0.37; start[2] = 5800.0; start[3] = 30000.0; //start[4] = 73.4; start[4] = 85.0; step[0] = 0.03; step[1] = 0.05; step[2] = 500.0; step[3] = 1000.0; //step[4] = 2.0; step[4] = 1.0; // temp constraint min.addConstraint(2,-1,3000); min.addConstraint(2,+1,12000); // v constraint min.addConstraint(3,-1,20000); min.addConstraint(3,+1,30000); // norm constraints min.addConstraint(0,-1,0); min.addConstraint(1,-1,0); // longitude constraint //min.addConstraint(4,-1,60); //min.addConstraint(4,+1,85); break; case ONE_PARAM_FIT: start[0] = 1.0; break; } } /** Get number of parameters for current fit function */ public int getNumParams() { switch (fit) { case STRAIGHT_LINE: return 2; case POLY2: return 3; case POLY3: return 4; case POLY4: return 5; case EXPONENTIAL: return 2; case POWER: return 2; case LOG: return 2; case RODBARD: return 4; case GAMMA_VARIATE: return 4; case LOG2: return 3; case STEP: return 2; case HEMISPHERIC: return 2; case SEMI: return 2; case QUAD_ORIGIN: return 2; case GAUSSIAN: return 3; case SEMI_1: return 1; case IBEX: return 2; case IBEXFIT: return 1; case IBEX1: return 1; case SPINPHASE: return 4; case COMBO: return 5; case ONE_PARAM_FIT: return 1; } return 0; } /** *Returns "fit" function value for parametres "p" at "x" * * Define function to fit to here!! */ public double f(int fit, double[] p, double x) { switch (fit) { case STRAIGHT_LINE: return p[0] + p[1]*x; case POLY2: return p[0] + p[1]*x + p[2]* x*x; case POLY3: return p[0] + p[1]*x + p[2]*x*x + p[3]*x*x*x; case POLY4: return p[0] + p[1]*x + p[2]*x*x + p[3]*x*x*x + p[4]*x*x*x*x; case EXPONENTIAL: return p[0]*Math.exp(p[1]*x); case POWER: if (x == 0.0) return 0.0; else return p[0]*Math.exp(p[1]*Math.log(x)); //y=ax^b case LOG: if (x == 0.0) x = 0.5; return p[0]*Math.log(p[1]*x); case RODBARD: double ex; if (x == 0.0) ex = 0.0; else ex = Math.exp(Math.log(x/p[2])*p[1]); double y = p[0]-p[3]; y = y/(1.0+ex); return y+p[3]; case GAMMA_VARIATE: if (p[0] >= x) return 0.0; if (p[1] <= 0) return -100000.0; if (p[2] <= 0) return -100000.0; if (p[3] <= 0) return -100000.0; double pw = Math.pow((x - p[0]), p[2]); double e = Math.exp((-(x - p[0]))/p[3]); return p[1]*pw*e; case LOG2: double tmp = x-p[2]; if (tmp<0.001) tmp = 0.001; return p[0]+p[1]*Math.log(tmp); case STEP: if (x>p[1]) return 0.0; else return p[0]; case HEMISPHERIC: //return hh.eflux(p[0],p[1],x); return 0.0; case SEMI: return am.f(p[0],p[1],x); case SEMI_1: return am.f(p[0],gamma,x); //return sm.f(p[0],p[1],p[2],x); case QUAD_ORIGIN: return p[0]*x + p[1]*x*x; case GAUSSIAN: return p[0]/p[2]/Math.sqrt(Math.PI*2)*Math.exp(-(x-p[1])*(x-p[1])/p[2]/p[2]/2); case IBEX: //return ib.getRate(p[0],p[1],x); return 0.0; case IBEX1: return 0.0; //return ib.getRate(p[0],x); case IBEXFIT: return p[0]*ff.getRate(x); case SPINPHASE: //density, temperature, v, theta, x (sp) return ib.getRate(p[0], p[1], p[2], p[3],x); case COMBO: //return ibw.getRateMulti(p[0],p[1],p[2],p[3],p[4],p[5],x); return ibw.getRateMulti(p[0],p[1],p[2],p[3],74.68,p[4],x); case ONE_PARAM_FIT: return p[0]*fitData.getRate(x); default: return 0.0; } } file f_log = new file("curve_fit_log_9.txt"); /** Returns sum of squares of residuals */ public double getError(double[] params_) { f_log.initWrite(true); double tbr = 0.0; for (int i = 0; i < xData.length; i++) { tbr += sqr(yData[i] - f(fit, params_, xData[i])); } for (int i=0; i<params_.length; i++) { f_log.write(params_[i]+"\t" ); } f_log.write(tbr + "\n"); f_log.closeWrite(); //System.out.println("error: " + tbr); return tbr; } /** Here's the one to minimize!! */ public double function(double[] params) { return getError(params); } public static double sqr(double d) { return d * d; } /** * Gets index of highest value in an array. * * @param Double array. * @return Index of highest value. */ public static int getMax(double[] array) { double max = array[0]; int index = 0; for(int i = 1; i < array.length; i++) { if(max < array[i]) { max = array[i]; index = i; } } return index; } /** * Use this to fit a curve or * for testing... * * Reads a file for data and fits to a curve at command line * */ public static final void main(String[] args) { int numLines = 62; int linesToSkip = 0; if (args.length==1) { //double[] x = {0,1,2,3,4,5,6,7,8,9}; //double[] y = {1,3,5,7,9,11,13,15,17,19}; //CurveFitter cf = new CurveFitter(x,y); //cf.doFit(CurveFitter.STRAIGHT_LINE); file f = new file(args[0]); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); CurveFitter cf = new CurveFitter(x,y); System.out.println("starting doFit routine"); cf.doFit(CurveFitter.COMBO); } //if (args.length==2) { else if (args.length==2) { file f = new file(args[0]); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); for (double gamma =0.8; gamma<2.2; gamma+=0.1) { CurveFitter cf = new CurveFitter(x,y); cf.gamma = gamma; System.out.println("gamma: " + gamma); cf.doFit(CurveFitter.SEMI_1); //ystem.out.println( } } // testing here!! else if (args.length==0) { double[] x = new double[100]; double[] y = new double[100]; for (int i=0; i<100; i++) { x[i]=i*0.1; //return p[0]/p[2]/Math.sqrt(Math.PI*2)*Math.exp(-(x-p[1])*(x-p[1])/p[2]/p[2]/2); y[i]=Math.exp(-(x[i]-4.0)*(x[i]-4.0)/2.0/2.0/2.0); } CurveFitter cf = new CurveFitter(x,y); cf.doFit(CurveFitter.GAUSSIAN); } //double[] lims = {1E6,1E10, 0.00000001, 0.0001}; //int[] steps = {4,4}; //cf.doExhaustiveFit(CurveFitter.SEMI,lims,steps); //System.out.println("param[0]: " + cf.bestParams[0]); //System.out.println("param[1]: " + cf.bestParams[1]); //cf.setRestarts(100); //Date d1 = new Date(); //cf.doFit(type); //Date d2 = new Date(); // cf.print(); // System.out.println(cf.getResultString()+"\n\n"); //System.out.println("param[0]: " + cf.getParams()[0]); //System.out.println("param[1]: " + cf.getParams()[1]); //System.out.println("took: " + (d2.getTime()-d1.getTime())); //int max = getMax(y); //System.out.println("y_max: " + y[max]); //double[] lims = {0.0 , 10.0, y[max]/2.0, 4*y[max]}; //System.out.println("lims: " + lims[0] + " " + lims[1] + " " + lims[2] + " " + lims[3]); //int[] steps = {256,128}; //Date d3 = new Date(); //cf.doExhaustiveFit(CurveFitter.QUAD_ORIGIN,lims,steps); //cf.doFit(type); //Date d4 = new Date(); //double[] ans = cf.bestParams; //System.out.println("a[0]: " + ans[0]); //System.out.println("a[1]: " + ans[1]); //System.out.println(cf.getResultString()); //System.out.println("took: " + (d4.getTime()-d3.getTime())); } /* public double getSPError(double[] spModel) { file f = new file("2010_fit_sp.txt"); int numLines = f.readShitNumLines(); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); y[i]=Double.parseDouble(st.nextToken()); } f.closeRead(); } public double getTimeError(double[] timeModel) { file f = new file("2010_fit_time.txt"); int numLines = f.readShitNumLines(); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); } public double getNormalizedError(double[] timeModel, double[] spModel) { // first load the fit set to compare the model to file f = new file("2010_fit_set.txt"); f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<linesToSkip; i++) { line = f.readLine(); } for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); // ok we have the data to fit our result to, and the data itself is passed in here.. */ /* * This is to load a given model from a file and give a proper normalization to match the ibex data * for using a one parameter (normalization) fit. */ public class FitData { public StringTokenizer st; public double[] days; public double[] rates; public Vector daysV; public Vector ratesV; // we call this days and rates, but could be any x and y public FitData(String filename) { daysV = new Vector(); ratesV = new Vector(); file f = new file(filename); f.initRead(); String line = ""; while ((line=f.readLine())!=null) { st = new StringTokenizer(line); daysV.add(st.nextToken()); ratesV.add(st.nextToken()); } // time to fix the arrays days = new double[daysV.size()]; rates = new double[daysV.size()]; for (int i=0; i<days.length; i++) { days[i]=Double.parseDouble((String)daysV.elementAt(i)); rates[i]=Double.parseDouble((String)ratesV.elementAt(i)); } } // we are going to interpolate here public double getRate(double day) { for (int i=0; i<days.length-1; i++) { if (day<days[i]) { // this is where we want to be return (rates[i]+rates[i+1])/2; } } return 0; } } }
Java
/** * Use this to compute the original velocity vector at infinity, * given a velocity and position at a current time. * * // note velocity vector is reversed, represents origin to point at t=-infinity * * Use static heliovector methods to avoid the dreaded "new Object()"... * * * !!! tested extensively May 2004 !!! * not extensively enough. Starting again - sept 2004 */ private HelioVector getHPInfinity(HelioVector hpr, HelioVector hpv) { //System.out.println("test!"); counter++; r = hpr.getR(); if (r==0.0) r=Double.MIN_VALUE; // - define orbital plane as hpn // orbital plane is all vectors r with: r dot hpn = 0 // i.e. hpn = n^hat (normal vector to orbital plane) hpn.setCoords(hpr); HelioVector.crossProduct(hpn, hpv); // defines orbital plane HelioVector.normalize(hpn); // We are going to set up coordinates in the orbital plane.. // unit vectors in this system are hpox and hpoy // choose hpox so the particle is on the +x axis // such that hpox*hpn=0 (dot product) theta of the given position is zero //hpox.setCoords(HelioVector.CARTESIAN, hpn.getY(), -hpn.getX(), 0); hpox.setCoords(HelioVector.CARTESIAN, hpr.getX()/r, hpr.getY()/r, hpr.getZ()/r); // this is the y axis in orbital plane hpoy.setCoords(hpn); HelioVector.crossProduct(hpoy, hpox); // hopy (Y) = hpn(Z) cross hpox (X) // ok, we have defined the orbital plane ! // now lets put the given coordinates into this plane // they are: r, ptheta, rdot, thetadot // // we want rDot. This is the component of traj. away from sun // rdot = hpv.dotProduct(hpr)/r; goingIn = true; if (rdot>=0) goingIn = false; // what is thetaDot? // // use v_ = rdot rhat + r thetadot thetahat... // // but we need the thetaHat .. // thetaHat is just (0,1) in our plane // because we are sitting on the X axis // thats how we chose hpox // thetaHat.setCoords(hpoy); thetadot = hpv.dotProduct(thetaHat)/r; // NOW WE CAN DO THE KEPLERIAN MATH // let's calculate the orbit now, in terms of eccentricity e // ,semi-major axis a, and rdoti (total energy = 1/2(rdoti^2)) // // the orbit equation is a conic section // r(theta) = a(1-e^2) / [ 1 + e cos (theta - theta0) ] // // thanks Bernoulli.. // // note: a(1-e^2) = L^2/GM // // rMin = a(1-e) // // for hyperbolics, e>1 // L=r*r*thetadot; // ok - we know our angular momentum (per unit mass) E=hpv.dotProduct(hpv)/2.0 - gmodMs/r; if (E <= 0) { d("discarding elipticals..."); return null; } // speed at infinity better be more negative than current speed! if (rdoti > hpv.getR()) o("rdoti < hpv.getR() !! "); if (thetadot==0.0) { rMin = 0.0; //o("Trajectory entirely radial! "); } else { rMin= (Math.sqrt(gmodMs*gmodMs/E/E+2.0*L*L/E)-gmodMs/E)/2.0; //rMin = Math.sqrt(2.0/thetadot/thetadot*(E+gmodMs/r)); } // d("rmin:" + rMin); // the speed at infinity is all in the radial direction, rdoti (negative) rdoti=-Math.sqrt(2.0*E); // rMin had better be smaller than R.. if (rMin > r) { // d("rMin > r !! "); rMin = r; } // e and a now are available.. e = L*L/rMin/gmodMs - 1.0; oneOverE = 1/e; if (e<=1) { d("didn't we throw out ellipticals already?? e= " + e); return null; } //a = rMin/(1.0-e); // do some debugging.. // /* d("rdoti: " + rdoti);d("r: " + r + " L: " + L); d("ke: " + hpv.dotProduct(hpv)/2.0); d("pe: " + gmodMs/r); d("ke - pe: " + (hpv.dotProduct(hpv)/2.0 - gmodMs/r)); d("rke: " + rdot*rdot/2.0); d("energy in L comp. " + L*L/r/r/2.0); d("ke - (rke+thetake): " + (hpv.dotProduct(hpv)/2.0 - rdot*rdot/2.0 - L*L/r/r/2.0)); d("E dif: " + ( (rdot*rdot/2.0 + L*L/r/r/2.0 - gmodMs/r) - E )); d("E dif: " + ( (rdot*rdot/2.0 + thetadot*thetadot*r*r/2.0 - gmodMs/r) - E )); d("thetadot: " + thetadot); d("e: " + e); d("rMin: " + rMin+ "a: " + a + " e: " + e); */ // WE HAVE EVERYTHING in the orbit equation now except theta0 // the angle at which the orbit reaches rMin // now we use our current position to solve for theta - theta0 //arg = a*(1.0-e*e)/e/r - 1.0/e; arg = rMin*(1.0+e)/e/r - oneOverE; // could also be arg = L*L/r/e/gmodMs - oneOverE; //d("arg: " + arg); theta0 = Math.acos(arg); // correct for going in when sitting really on x axis // we have the angle but we need to make sure we get the sign right // what with implementing the mulitvalued acos and all.. // acos returns a value from 0 to pi if (!goingIn) theta0 = -theta0; //d("theta0: "+ theta0); // the angle "swept out by the particle" to its current location is // // this is also useful for the ionization calculation // //if (thetadot>0) pthetai = theta0 + Math.acos(-oneOverE); //else pthetai = theta0 - Math.acos(-oneOverE); //if (!goingIn) { // angleSwept = Math.abs(pthetai - theta0) + Math.abs(Math.PI-theta0); //} //else { // angleSwept = Math.abs(pthetai - Math.PI); //} //if (angleSwept>=Math.PI) o("angleSwept too big : " + angleSwept); angleSwept = Math.acos(-oneOverE); pthetai = -angleSwept + theta0; //if (!goingIn) pthetai = angleSwept - theta0; // d("angle swept: "+ angleSwept); // d("pthetai: " + pthetai); // now we know everything!! The vector to the original v (t=-infinity) // // Vinf_ = - rdoti * rHat ( thetaInf ) // vinfxo = rdoti*Math.cos(pthetai); vinfyo = rdoti*Math.sin(pthetai); // put together our answer from the coords in the orbital plane // and the orbital plane unit vectors answer.setCoords(hpox); HelioVector.product(answer,vinfxo); HelioVector.product(hpoy,vinfyo); // destroy hpoy here HelioVector.sum(answer,hpoy); //HelioVector.invert(answer); return answer; }
Java
import java.util.StringTokenizer; import java.util.Vector; import java.util.StringTokenizer; import java.util.Date; import java.util.*; /** * * Simulating response at IBEX_LO with this class * * Create interstellar medium and perform integration * */ public class IBEXWind2 { public int mcN = 10000; // number of iterations per 3D integral public String outFileName = "lo_fit_09.txt"; public static final double EV = 1.60218 * Math.pow(10, -19); public static double MP = 1.672621*Math.pow(10.0,-27.0); public static double AU = 1.49598* Math.pow(10,11); //meters public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0; public static double Ms = 1.98892 * Math.pow(10,30); // kg //public static double Ms = 0.0; // kg public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg // define angles and energies of the instrument here // H mode (standard) energy bins in eV public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6}; public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5}; public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO; // Interstellar mode energies // { spring min, spring max, fall min, fall max } public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 }; public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 }; public double[] heSpeeds; public double[] oSpeeds; // O mode efficiencies // public double heSpringEff = 1.0*Math.pow(10,-7); // this was the original.. now going to adjust to match data including sputtering etc. public double heSpringEff = 1.0*Math.pow(10,-7)/7.8; // nominal efficiency to "roughly" match data.. public double heFallEff = 1.6*Math.pow(10,-6); public double oSpringEff = 0.004; public double oFallEff = 0.001; // angular acceptance - assume rectangular windows.. this is for integration limits only // these are half widths, e.g. +- for acceptance public double spinWidth = 4.0*Math.PI/180.0; public double hrWidth = 3.5*Math.PI/180.0; public double lrWidth = 7.0*Math.PI/180.0; public double eightDays = 8.0*24.0*60.0*60.0; public double oneHour = 3600.0; public double upWind = 74.0 * 3.14 / 180.0; public double downWind = 254.0 * 3.14 / 180.0; public double startPerp = 180*3.14/180; // SPRING public double endPerp = 240*3.14/180; // SPRING //public double startPerp = 260.0*3.14/180.0; // FALL //public double endPerp = 340.0*3.14/180.0; // FALL public double he_ion_rate = 6.00*Math.pow(10,-8); public GaussianVLISM gv1; // temporarily make them very small //public double spinWidth = 0.5*Math.PI/180.0; //public double hrWidth = 0.5*Math.PI/180.0; //public double lrWidth = 0.5*Math.PI/180.0; public double activeArea = 100.0/100.0/100.0; // 100 cm^2 in square meters now!! public file outF; public MultipleIntegration mi; public NeutralDistribution ndHe; public double look_offset=Math.PI; public double currentLongitude, currentSpeed, currentDens, currentTemp; public HelioVector bulkHE; public double low_speed, high_speed; public int yearToAnalyze = 2009; public EarthIBEX ei = new EarthIBEX(yearToAnalyze); public TimeZone tz = TimeZone.getTimeZone("UTC"); /** * 830 - zurri carlie wednesday - * patrick, melissa, tupac Tuesday * lara.. sophie.. vero.. */ public IBEXWind2() { // calculate speed ranges with v = sqrt(2E/m) heSpeeds = new double[heEnergies.length]; oSpeeds = new double[oEnergies.length]; o("calculating speed range"); for (int i=0; i<4; i++) { heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV); oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV); System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]); } minSpeedsHe = new double[8]; maxSpeedsHe = new double[8]; minSpeedsO = new double[8]; maxSpeedsO = new double[8]; for (int i=0; i<8; i++) { minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV); maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV); minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV); maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV); //System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]); } System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]); // lets calculate the speed of the exact cold gas at 1AU // potential energy double pot = 4.0*MP*Ms*G/AU; o("pot: "+ pot); double energy1= 4.0*MP/2.0*28000*28000; o("energy1: " + energy1); double kEn = energy1+pot; double calcHeSpeed = Math.sqrt(2.0*kEn/4.0/MP); calcHeSpeed += EARTHSPEED; o("calcHeSpeed: "+ calcHeSpeed); // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //bulkHE = new HelioVector(HelioVector.SPHERICAL, 28000.0, (180.0 + 74.68)*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); //GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0,10000.0); // test distribution, coming in here: //ndHe = new NeutralDistribution(gv1, 0.0, 0.0); // mu is 0.0 for he currentLongitude = 74.0; currentSpeed = 28000.0; currentDens = 0.015; currentTemp = 100.0; // DONE CREATING MEDIUM o("earthspeed: " + EARTHSPEED); mi = new MultipleIntegration(); o("done creating IBEXLO_09 object"); // DONE SETUP //- //- // now lets run the test, see how this is doing //for (double vx = 0; /* // moving curve fitting routine here for exhaustive and to make scan plots file ouf = new file("scanResults1.txt"); file f = new file("cleaned_ibex_data.txt"); int numLines = 413; f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); // first scan: V vs Long. // for (int i=0; i< */ // LOAD THE REAL DATA - AZIMUTH or TIME SERIES /* file df = new file("second_pass.txt"); int numLines2 = 918; df.initRead(); double[] xD = new double[numLines2]; double[] yD = new double[numLines2]; String line = ""; for (int i=0; i<numLines2; i++) { line = df.readLine(); StringTokenizer st = new StringTokenizer(line); xD[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! yD[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]); //line = f.readLine(); //line = f.readLine(); } df.closeRead(); // END LOADING REAL DATA */ // LOAD THE REAL DATA - Spin Phase Info - Orbit 61 for now!!! /* file df = new file("second_pass.txt"); int numLines2 = 918; df.initRead(); double[] xD = new double[numLines2]; double[] yD = new double[numLines2]; String line = ""; for (int i=0; i<numLines2; i++) { line = df.readLine(); StringTokenizer st = new StringTokenizer(line); xD[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! yD[i]=Double.parseDouble(st.nextToken()); System.out.println("row: " + i + " x: " + xD[i] + " y: " + yD[i]); //line = f.readLine(); //line = f.readLine(); } df.closeRead(); // END LOADING REAL DATA */ // MAKE SPIN PHASE SIMULATION /* for (double ttt = 3000; ttt< file spFile = new file("doy_sim.txt"); spFile.initWrite(false); //for (int ss = 20000; ss<100000; ss+=5000) { // low_speed = ss; // high_speed = ss+5000; //spFile.write("\n\n ss= "+ss); bulkHE = new HelioVector(HelioVector.SPHERICAL, 26000.0, (74.0)*Math.PI/180.0, 96.5*Math.PI/180.0); HelioVector.invert(bulkHE); // invert it, we want the real velocity vector out there at infinity :D GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0, 3900.0); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he for (double tt = 50.0; tt<120; tt+=1) { //tt is the theta angle double ans = getRate(41.0, tt*Math.PI/180.0); spFile. write(tt+"\t"+Math.abs(ans)+"\n"); o("trying tt = " + tt + " : "+ Math.abs(ans)); } //} spFile.closeWrite(); */ // MAKE SPIN PHASE PARAM PLOT double v = 23000.0; double vwidth = 8000.0; double t = 3000.0; double twidth = 7000.0; int res = 30; // resolution, 30 by 30 is enough apparently double tdelta = twidth/res; double vdelta = vwidth/res; double vmin = v; double tmin = t; // this one is for checking that we are comparing the right data file sampleFile = new file("sample_data.txt"); sampleFile.initWrite(false); file spFile = new file("sp_param_65_74_6_5.txt"); spFile.initWrite(false); // initialze file with header of x and y axis numbers for (int i=0; i<res; i++) { spFile.write(v+"\n"); v+=vdelta; } v=vmin; for (int i=0; i<res; i++) { spFile.write(t+"\n"); t+=tdelta; } t=tmin; for (int i=0; i<res; i++) { // v loop t=tmin; for (int j=0; j<res; j++) { // t loop o("trying temp: "+ t + " vel: " + v); // set up the interstellar medium flow model bulkHE = new HelioVector(HelioVector.SPHERICAL, v, (74.0)*Math.PI/180.0, 96.5*Math.PI/180.0); HelioVector.invert(bulkHE); // invert it, we want the real velocity vector out there at infinity :D GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0, t); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // store the results here.. fit them later and determine how well they fit the data double [] ans = new double[28]; double ansMax = 0.0; double theta = 59; for (int k = 0; k<28; k++) { //tt is the theta angle // start of orbit 65 is doy 41 !! that's where the good data is.. . ans[k] = getRate(41.0, theta*Math.PI/180.0); if (ans[k]>ansMax) ansMax=ans[k]; //spFile. write(tt+"\t"+Math.abs(ans)+"\n"); //o("trying theta = " + theta + " : "+ Math.abs(ans[k]) + " i: " + i + " j: " + j); theta+= 2.0; } // ok we have the answers, now lets compare to the loaded data double nfactor = (double)spDataMax/ansMax; double error = 0.0; sampleFile.write(t+ "\t" + v + "\n"); for (int k = 0; k<28; k++) { ans[k]*=nfactor; error += Math.abs(ans[k]-spData[k]); sampleFile.write(ans[k] + "\t" + spData[k] + "\n"); } // we got the error.. output to file //spFile.write(t + "\t" + v + "\t" + nfactor); spFile.write(error + "\n"); o("nfactor data/model : "+ nfactor + " error: " + error); t += tdelta; } v += vdelta; } sampleFile.closeWrite(); spFile.closeWrite(); /* // MAKE SIMULATION FROM REAL DATA.. STEP WITH TIME AND PARAMS FOR MAKING 2D PARAM PLOT // loop through parameters here // standard params: double lamda = 74.7; //double temp = 6000.0; double v = 26000.0; int res = 30; double lamdaWidth = 20; //double tWidth = 10000; double vWidth = 10000; double lamdaMin = 65.0; //double tMin = 1000.0; double vMin=21000.0; double lamdaDelta = lamdaWidth/res; //double tDelta = tWidth/res; double vDelta = vWidth/res; lamda = lamdaMin; //temp=tMin; v = vMin; //file outF = new file("testVL_pass2_Out.txt"); //outF.initWrite(false); for (int i=0; i<res; i++) { v=vMin; for (int j=0; j<res; j++) { file outf = new file("fitP2_vl"+lamda+"_"+v+".txt"); outf.initWrite(false); setParams(lamda,v,0.015,6000.0); System.out.println(" now calc for: fitTTT_"+lamda+"_"+v+".txt"); double [] doyD = new double[110]; double [] rateD = new double[110]; in doyIndex = 0; for (double doy=10.0 ; doy<65.0 ; doy+=0.5) { outf.write(doy+"\t"); doyD[doyIndex]=doy; doyIndex++; //for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) { //look_offset=off; look_offset=3.0*Math.PI/2.0; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outf.write(rr +"\t"); //} //double rr = getRate(doy); //System.out.println("trying: " + doy + " got "+rr); outf.write("\n"); } outf.closeWrite(); v+=vDelta; } //temp+=tDelta; lamda+=lamdaDelta; } //outF.closeWrite(); */ /* for (int temptemp = 1000; temptemp<20000; temptemp+=2000) { file outf = new file("fitB_"+temptemp+"_7468_26000.txt"); outf.initWrite(false); setParams(74.68,26000,0.015,(double)temptemp); for (double doy=10.0 ; doy<65.0 ; doy+=0.1) { outf.write(doy+"\t"); //for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) { //look_offset=off; look_offset=3.0*Math.PI/2.0; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outf.write(rr +"\t"); //} //double rr = getRate(doy); //System.out.println("trying: " + doy + " got "+rr); outf.write("\n"); } outf.closeWrite(); } */ } // END CONSTRUCTOR /*public double getRate(double dens, double temp, double doy) { if ((currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + dens + " " + temp); setParams(dens,temp); } return getRate(doy); } public double getRate(double longitude, double speed, double dens, double temp, double doy) { if ((currentLongitude!=longitude)|(currentSpeed!=speed)|(currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + longitude + " " + speed + " " + dens + " " + temp); setParams(longitude,speed,dens,temp); } return getRate(doy); } */ /* use this to set the look direction in latitude */ double midThe = Math.PI/2.0; /** * Use this one to set the look direction in spin phase and then get the rate * */ public double getRate(double doy, double theta) { midThe = theta; return getRate(doy); } /** * We want to call this from an optimization routine.. * */ public double getRate(double doy) { int day = (int)doy; double fract = doy-day; //System.out.println(fract); int hour = (int)(fract*24.0); Calendar c = Calendar.getInstance(); c.setTimeZone(tz); c.set(Calendar.YEAR, yearToAnalyze); c.set(Calendar.DAY_OF_YEAR, day); c.set(Calendar.HOUR_OF_DAY, hour); //c.set(Calendar.MINUTE, 0); //c.set(Calendar.SECOND, 0); Date ourDate = c.getTime(); //System.out.println("trying getRate w/ " + doy + " the test Date: " + ourDate.toString()); // spacecraft position .. assume at earth at doy final HelioVector pointVect = ei.getIbexPointing(ourDate); // test position for outside of heliosphere //final HelioVector pointVect = new HelioVector(HelioVector.CARTESIAN, 0.0,1.0,0.0); final HelioVector lookVect = new HelioVector(HelioVector.SPHERICAL,1.0, pointVect.getPhi()-Math.PI/2.0, pointVect.getTheta()); //final HelioVector lookVect = new HelioVector(HelioVector.SPHERICAL,1.0, pointVect.getPhi()-Math.PI/2.0, midThe); // here's the now position (REAL) final HelioVector posVec = ei.getEarthPosition(ourDate); final HelioVector scVelVec = ei.getEarthVelocity(ourDate); //System.out.println("trying getRate w/ " + doy + " the test Date: " + ourDate.toString() + " posvec: " + posVec.toAuString() + // " scvelvec: " + scVelVec.toKmString() + " midthe " + midThe); // use a test position that puts the Earth out in the VLISM .. lets go with 200AU //final HelioVector posVec = new HelioVector(HelioVector.CARTESIAN, 200*AU, 0.0, 0.0); // due upwind //final HelioVector scVelVec = new HelioVector(HelioVector.CARTESIAN, 0.0, 0.0, 0.0); // not moving double midPhi = lookVect.getPhi(); //final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0); //final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0); // placeholder for zero //final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, 0.0, pos+Math.PI/2.0, Math.PI/2.0); // HERES WHAT WE NEED TO INTEGRATE FunctionIII he_func = new FunctionIII() { // helium neutral distribution public double function3(double v, double p, double t) { HelioVector testVect = new HelioVector(HelioVector.SPHERICAL,v,p,t); HelioVector.sum(testVect,scVelVec); double tbr = activeArea*ndHe.dist(posVec, testVect)*v*v*Math.sin(t)*v; // extra v for flux tbr *= angleResponse(testVect,lookVect); //tbr *= angleResponse(lookPhi,p); // that is the integrand of our v-space integration return tbr; } }; // set limits for integration - spring only here //double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; // old limits for including all spin.. //double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, 3.0*Math.PI/8.0, 5.0*Math.PI/8.0 }; // new limits for including just a single point in spin phase double[] he_lr_lims = { 0.0, maxSpeedsHe[4], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth, midThe+lrWidth }; //double[] he_lr_lims = { minSpeedsHe[2], maxSpeedsHe[5], midPhi-lrWidth, midPhi+lrWidth, 0, Math.PI }; //he_lr_lims[0]=low_speed; he_lr_lims[1]=high_speed; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; //PERFORM INTEGRATION double he_ans_lr = 12.0*oneHour *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN); he_ans_lr*=heSpringEff; return he_ans_lr; } public double sigma=6.1; /** * From calibrated response * */ public double angleResponse(double centerA, double checkA) { double cA = centerA*180.0/Math.PI; double chA = checkA*180.0/Math.PI; // This is the Gaussian Response double tbr = Math.exp(-(cA-chA)*(cA-chA)/sigma/sigma); return tbr; } public double angleResponse(HelioVector center, HelioVector look) { double angle = center.getAngle(look); angle = Math.abs(angle * 180.0/Math.PI); // This is the Triangle Response double tbr = 0.0; if (angle<7.0) { double m = -1.0/7.0; tbr = m*angle+1.0; } // This is the Gaussian Response //double tbr = Math.exp(-angle*angle/sigma/sigma); return tbr; } // starts at 59, goes up by 2 !! int [] spData = {4,12,8,24,51,75,133,196,388,464,799,848,1221,1255,1048,1125,704,706,420,307,143,120,51,22,17,9,7,7,4,9,3,6}; int spDataMax = 1255; // spin phase data from 1 day start of orbit 65 /* 59.0000136 4 60.9999972 12 63.0000024 8 65.000004 24 67.00002 51 69 75 71.0000016 133 72.999996 196 75.000012 388 77.0000172 464 79.000008 799 81.000006 848 83.000004 1221 85.00002 1255 87 1048 89.0000052 1125 91.0000104 704 93.000012 706 94.999992 420 97.000008 307 99.0000096 143 101.0000148 120 102.9999984 51 105 22 107.000016 17 109.000014 9 110.9999976 7 113.0000028 7 115.000008 4 117.000024 9 119.000004 3 121.000002 6 */ public static final void main(String[] args) { IBEXWind2 il = new IBEXWind2(); } public static void o(String s) { System.out.println(s); } /* * This is to load a given model from a file and give a proper normalization to match the ibex data * for using a one parameter (normalization) fit. */ public class FitData { public StringTokenizer st; public double[] days; public double[] rates; public Vector daysV; public Vector ratesV; public FitData(String filename) { daysV = new Vector(); ratesV = new Vector(); file f = new file(filename); f.initRead(); String line = ""; while ((line=f.readLine())!=null) { st = new StringTokenizer(line); daysV.add(st.nextToken()); ratesV.add(st.nextToken()); } // time to fix the arrays days = new double[daysV.size()]; rates = new double[daysV.size()]; for (int i=0; i<days.length; i++) { days[i]=Double.parseDouble((String)daysV.elementAt(i)); rates[i]=Double.parseDouble((String)ratesV.elementAt(i)); } } // we are going to interpolate here public double getRate(double day) { for (int i=0; i<days.length; i++) { if (day<days[i]) { // this is where we want to be return (rates[i]+rates[i+1])/2; } } return 0; } } } /* We need to keep track of Earth's Vernal Equinox and use J2000 Ecliptic Coordinates!!! March 2009 20 11:44 2010 20 17:32 2011 20 23:21 2012 20 05:14 2013 20 11:02 2014 20 16:57 2015 20 22:45 2016 20 04:30 2017 20 10:28 This gives the location of the current epoch zero ecliptic longitude.. However /* /* Earth peri and aphelion perihelion aphelion 2007 January 3 20:00 July 7 00:00 2008 January 3 00:00 July 4 08:00 2009 January 4 15:00 July 4 02:00 2010 January 3 00:00 July 6 12:00 2011 January 3 19:00 July 4 15:00 2012 January 5 01:00 July 5 04:00 2013 January 2 05:00 July 5 15:00 2014 January 4 12:00 July 4 00:00 2015 January 4 07:00 July 6 20:00 2016 January 2 23:00 July 4 16:00 2017 January 4 14:00 July 3 20:00 2018 January 3 06:00 July 6 17:00 2019 January 3 05:00 July 4 22:00 2020 January 5 08:00 July 4 12:00 */
Java
import flanagan.analysis.Stat; /** * A basic power law in ENERGY * */ public class KappaVLISM extends InterstellarMedium { public HelioVector vBulk; public double power, density, kappa, norm, ee, temp, omega; public static double NaN = Double.NaN; public static double MP = 1.672621*Math.pow(10,-27); public static double EV = 6.24150965*Math.pow(10,18); public static double KB = 1.3807*Math.pow(10,-23); /** * Construct a power law VLISM */ public KappaVLISM(HelioVector _vBulk, double _density, double _temp, double _kappa) { vBulk = _vBulk; kappa = _kappa; density = _density; temp = _temp; // calculate normalization omega = Math.sqrt(2*temp*KB*(kappa-1.5)/kappa/4/MP); System.out.println("kappa " + kappa + " omega: " + omega); norm = density*gamma(kappa+1.0)/omega/omega/omega/Math.pow(kappa*Math.PI,1.5)/gamma(kappa-0.5); System.out.println("norm: " + norm); } public double gamma(double q) { return Stat.gammaFunction(q); } /** * * Pass in a heliovector if you feel like it.. slower? * probably not.. */ public double heliumDist(HelioVector v) { return dist(v.getX(), v.getY(), v.getZ()); } public double heliumDist(double v1, double v2, double v3) { return dist(v1,v2,v3); } /** * default - pass in 3 doubles */ public double dist(double v1, double v2, double v3) { if (v1==NaN | v2==NaN | v3==NaN) return 0.0; // calculate energy double vv1 = v1-vBulk.getX(); double vv2 = v2-vBulk.getY(); double vv3 = v3-vBulk.getZ(); double vv = Math.sqrt(vv1*vv1+vv2*vv2+vv3*vv3); // ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV; // System.out.println("ee: " + ee); //if (vv>lim1 && vv<lim2) return norm*Math.pow(vv,power); //else return 0.0; return norm*Math.pow(1+vv*vv/kappa/omega/omega,-kappa-1.0); } /** * default - pass in 1 energy */ //public double dist(double energy) { // if (v1==NaN | v2==NaN | v3==NaN) return 0.0; // calculate energy //double vv1 = v1-vBulk.getX(); //double vv2 = v2-vBulk.getY(); //double vv3 = v3-vBulk.getZ(); //ee = 4*MP/2*(vv1*vv1+vv2*vv2+vv3*vv3)*EV; // System.out.println("ee: " + ee); // ee=energy; // if (ee>lim1 && ee<lim2) return norm*Math.pow(ee,power); // else return 0.0; //} public double protonDist(double v1, double v2, double v3) { return 0; } public double hydrogenDist(double v1, double v2, double v3) { return 0; } public double deuteriumDist(double v1, double v2, double v3) { return 0; } public double electronDist(double v1, double v2, double v3) { return 0; } public double alphaDist(double v1, double v2, double v3) { return 0; } // etcetera...+ /** * */ public static final void main(String[] args) { final KappaVLISM gvli = new KappaVLISM(new HelioVector(HelioVector.CARTESIAN, -20000.0,0.0,0.0), 1.0, 800.0, 1.6); System.out.println("Created KVLISM" ); //System.out.println("Maxwellian VLISM created, norm = " + norm); MultipleIntegration mi = new MultipleIntegration(); //mi.setEpsilon(0.001); FunctionIII dist = new FunctionIII () { public double function3(double x, double y, double z) { return gvli.heliumDist(x, y, z); } }; System.out.println("Test dist: " + dist.function3(20000,0,0)); double[] limits = new double[6]; limits[0]=mi.MINUS_INFINITY; limits[1]=mi.PLUS_INFINITY; limits[2]=mi.MINUS_INFINITY; limits[3]=mi.PLUS_INFINITY; limits[4]=mi.MINUS_INFINITY; limits[5]=mi.PLUS_INFINITY; double[] limits2 = new double[6]; limits2[0]=-100000.0; limits2[1]=100000.0; limits2[2]=-100000.0; limits2[3]=100000.0; limits2[4]=-100000.0; limits2[5]=100000.0; //double z = mi.mcIntegrate(dist,limits,128 ); double z2 = mi.mcIntegrate(dist,limits2,1000000); System.out.println("Integral should equal density= " + z2); } }
Java
import java.io.File; import java.lang.Math; import java.util.*; public class NeutralDistribution { public static double Ms = 2 * 10^30; public static double G = 6.67 * .00000000001; public static double K = 1; // correct this soon! public static double Mhe = 1 * 10^-80; public double Q, F1, F2, Temp, Vb, N, Vtemp, V0; // V0 = Moebius/Rucinski's Vinfinity // lowercase parameters are inputs to distribution function public NeutralDistribution(double bulkVelocity, double temperature, double density) { Temp = temperature; Vb = bulkVelocity; N = density; Vtemp = Math.sqrt(2*K*Temp/Mhe); //average velocity due to heat } //NOTE: for now parameters of distribution must be given in coordinates // relative to inflow direction public double distributionFunction(double r, double theta, double vr, double vt, double vPhi) { // Damby & Camm 1957 Q = Math.sqrt(G*Ms/r); V0 = Math.sqrt(vr*vr + vt*vt - 2*Q*Q); F1 = 2*Vb*vr/(Vtemp*Vtemp) * Math.cos(theta)*(V0 - vr)*(V0 - vr) / (V0*(V0-vr)+Q*Q) - ((Vb*Vb)+(V0*V0)+2*V0*Vb*Math.cos(theta))/(Vtemp*Vtemp); F2 = 2*V0*Vb/(vt*vt) * Math.sin(theta)*(V0-vr)*vt/ (V0*(V0-vr) + (Q*Q)); return N*Math.pow((Math.sqrt(Math.PI)*Vtemp),-3) * Math.exp(F1 + F2*Math.sin(vPhi)); } }
Java
/** * Simulating response at IBEX_LO with this class * * Create interstellar medium and perform integration * * This one assumes spacecraft can look all around the world and makes 2D maps for each spacecraft location. */ public class IBEXLO_super { public int mcN = 20000; // number of iterations per 3D integral public String outFileName = "ibex_lo_out17.txt"; String dir = "SPRING"; //String dir = "FALL"; public static final double EV = 1.60218 * Math.pow(10, -19); public static double MP = 1.672621*Math.pow(10.0,-27.0); public static double AU = 1.49598* Math.pow(10,11); //meters public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0; // define angles and energies of the instrument here // H mode (standard) energy bins in eV public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6}; public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5}; public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO; // Interstellar mode energies // { spring min, spring max, fall min, fall max } public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 }; public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 }; public double[] heSpeeds; public double[] oSpeeds; // O mode efficiencies public double heSpringEff = 1.0*Math.pow(10,-7); public double heFallEff = 1.6*Math.pow(10,-6); public double oSpringEff = 0.004; public double oFallEff = 0.001; // angular acceptance - assume rectangular windows.. // these are half widths, e.g. +- for acceptance public double spinWidth = 4.0*Math.PI/180.0; public double hrWidth = 3.5*Math.PI/180.0; public double lrWidth = 7.0*Math.PI/180.0; public double eightDays = 8.0*24.0*60.0*60.0; public double oneHour = 3600.0; public double upWind = 74.0 * 3.14 / 180.0; public double downWind = 254.0 * 3.14 / 180.0; public double startPerp = 180*3.14/180; // SPRING public double endPerp = 240*3.14/180; // SPRING public double he_ion_rate = 1.0*Math.pow(10,-7); public double o_ion_rate = 8.0*Math.pow(10,-7); public double activeArea = 100.0/100.0/100.0; // in square meters now!! public file outF; public MultipleIntegration mi; /** * * * */ public IBEXLO_super() { if (dir.equals("SPRING")) { startPerp = 175*3.14/180; endPerp = 235*3.14/180; } else if (dir.equals("FALL")) { startPerp = 290.0*3.14/180.0; // FALL endPerp = 360.0*3.14/180.0; // FALL } o("earthspeed: " + EARTHSPEED); mi = new MultipleIntegration(); // set up output file outF = new file(outFileName); outF.initWrite(false); // calculate speed ranges with v = sqrt(2E/m) heSpeeds = new double[heEnergies.length]; oSpeeds = new double[oEnergies.length]; o("calculating speed range"); for (int i=0; i<4; i++) { heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV); oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV); System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]); } minSpeedsHe = new double[8]; maxSpeedsHe = new double[8]; minSpeedsO = new double[8]; maxSpeedsO = new double[8]; // still setting up speeds to integrate over.. for (int i=0; i<8; i++) { minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV); maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV); minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV); maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV); System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]); } System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]); // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); // implement test 1 - a vector coming in along x axis //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL,26000.0, Math.PI, Math.PI/2.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,25000.0, Math.PI, Math.PI/2.0); //HelioVector bulkO2 = new HelioVector(HelioVector.SPHERICAL,21000.0, Math.PI, Math.PI/2.0); // standard hot helium GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100*100*100,6300.0); GaussianOxVLISM gv2 = new GaussianOxVLISM(bulkO1, bulkO2, 0.00005*100*100*100, 1000.0, 90000.0, 0.0); // last is fraction in 2ndry final NeutralDistribution ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); final NeutralDistribution ndO = new NeutralDistribution(gv2, 0.0, o_ion_rate); ndHe.debug=false; ndO.debug=false; // DONE CREATING MEDIUM // PASSAGE SIMULATION - IN ECLIPTIC - SPRING or FALL - use String dir = "FALL" or "SPRING" to set all pointing params properly double initPos = startPerp; double finalPos = endPerp; double step = 8.0*360.0/365.0*3.14/180.0; // these are orbit adjusts - every eight days //double step2 = step/8.0/2.0; // here we take smaller integration timest than an orbit.. current: 12 hours // sweep this now around 360 // determine entrance velocity vector and integration range double midPhi = initPos-Math.PI/2.0; double midThe = Math.PI/2.0; // move spacecraft for (double pos = initPos; pos<finalPos; pos+= step) { // inner loop moves pos2 - pos is what gives us pointing, not position! for (double pos2 = pos; pos2<pos+step; pos2+= step2) { // here's the now position final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos2, Math.PI/2.0); final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos2+Math.PI/2.0, Math.PI/2.0); FunctionIII he_func = new FunctionIII() { // helium neutral distribution public double function3(double v, double p, double t) { double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).difference(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux // that is the integrand of our v-space integration return tbr; } }; FunctionIII o_func = new FunctionIII() { // oxygen neutral distribution public double function3(double v, double p, double t) { double tbr = activeArea*ndO.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).difference(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux // that is the integrand of our v-space integration return tbr; } }; // set look direction and limits - if (dir.equals("FALL")) midPhi = pos-Math.PI/2+(4.0*3.1416/180.0); // change look direction at downwind point else if (dir.equals("SPRING")) midPhi = pos+Math.PI/2+(4.0*3.1416/180.0); // change look direction at downwind point // now step through the spin - out of ecliptic double theta_step = 6.0*Math.PI/180.0; for (double pos3 = Math.PI/2.0 - 3.0*theta_step; pos3<= (Math.PI/2.0 + 4.0*theta_step); pos3 += theta_step) { midThe = pos3; // set limits for integration, fall is first here.. //if (dir.equals("FALL")) { double[] he_hr_lims = { heSpeeds[2], heSpeeds[3], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; double[] o_hr_lims = { oSpeeds[2], oSpeeds[3], midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth }; double[] o_lr_lims = { minSpeedsO[1], maxSpeedsO[1], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; //} if (dir.equals("SPRING")) { he_hr_lims[0]=heSpeeds[0]; he_hr_lims[1]=heSpeeds[1]; //, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth }; he_lr_lims[0]=minSpeedsHe[3]; he_lr_lims[1]=maxSpeedsHe[3]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; o_hr_lims[0]=oSpeeds[0]; o_hr_lims[1]=oSpeeds[1]; //, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth }; o_lr_lims[0]=minSpeedsO[5]; o_lr_lims[1]=maxSpeedsO[5]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; } // time * spin_duty * energy_duty * area_factor double o_ans_hr = 12.0*oneHour *0.017 *7.0/8.0 *0.25 * mi.mcIntegrate(o_func, o_hr_lims, mcN); double o_ans_lr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(o_func, o_lr_lims, mcN); //double he_ans_hr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_hr_lims, mcN); double he_ans_lr = 12.0*oneHour *0.017 *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN); if (dir.equals("SPRING")) { o_ans_hr*=oSpringEff; o_ans_lr*=oSpringEff; //he_ans_hr*=heSpringEff; he_ans_lr*=heSpringEff; } else if (dir.equals("FALL")) { o_ans_hr*=oFallEff; o_ans_lr*=oFallEff; //he_ans_hr*=heFallEff; he_ans_lr*=heFallEff; } // double doy = (pos2*180.0/3.14)*365.0/360.0; outF.write(pos2*180.0/3.14 + "\t" + pos3 + "\t" + o_ans_hr + "\t" + o_ans_lr +"\t" + he_ans_lr + "\n"); o("pos: " + pos2 +"\t"+ "the: " + pos3*180.0/3.14 + "\t" + o_ans_hr + "\t" + o_ans_lr + "\t" + he_ans_lr); } } } outF.closeWrite(); //double[] limits = {heSpeeds[0], heSpeeds[1], midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth}; // THIS TEST is moving the look angle with the Earth at the supposed proper position. //double step = Math.abs((finalPos-initPos)/11.0); /* initPos = 0.0; finalPos = 2.0*Math.PI; step = Math.abs((finalPos-initPos)/60.0); for (double pos = initPos; pos<finalPos; pos+= step) { // here's the now position final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 100*AU, 0.0*Math.PI, Math.PI/2.0); midPhi = pos; midThe = Math.PI/2.0; double[] limits = { 30000.0, 300000.0, midPhi-hrWidth, midPhi+hrWidth, midThe-hrWidth-spinWidth, midThe+hrWidth+spinWidth }; o("doing pos: " + pos); FunctionIII f3 = new FunctionIII() { public double function3(double v, double p, double t) { double tbr = ndH.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t))*v*v*Math.sin(t); // extra v for flux // that is the integrand of our v-space integration return tbr; } }; outF.write(pos + "\t" + mi.mcIntegrate(f3, limits, 10000) + "\n"); } outF.closeWrite(); */ // 8 days, break to 12 hr } public static final void main(String[] args) { IBEXLO_super il = new IBEXLO_super(); } public static void o(String s) { System.out.println(s); } }
Java
public class InvertibleFunction extends FunctionI { double inverse(double y) { return 0.0; } }
Java
// THIS CLASS HAS SOME FILE UTILITY STUFF // // Updated Version 02/28/00 // Copyright 9 Elder // nice synchronizations stuff here- //new : initRead, initWrite, closeRead, closeWrite, readLine, write // improved: readShitLn //// be sure to use openFile() and closeFile() when using getLine and putLine // now catches those null pointers! // // Does not support: good error handling // politically correct java syntax import java.util.*; import java.io.*; class file { private int numLines; private FileReader fr; private BufferedReader br; private FileWriter fw; private BufferedWriter bw; private boolean lineNumberCoherence; private boolean frozen = false; public String fileName = ""; File test; // used for functionality of Java's "File" class public file(String filename) { // here's the constructor lineNumberCoherence = false; fileName = filename; numLines = 0; } public file() { lineNumberCoherence = false; fileName = ""; numLines = 0; } private void o(String message) { System.out.println(message); } public synchronized void initRead() { // this is for manual file access o("initRead"); frozen = true; try { fr = new FileReader(fileName); br = new BufferedReader(fr); }catch (Exception e) { System.out.println("Error- " + e.toString()); } } public synchronized void initWrite(boolean append) { frozen = true; lineNumberCoherence=false; try { fw = new FileWriter(fileName, append); bw = new BufferedWriter(fw); }catch (Exception e) { System.out.println("Error- " + e.toString()); } } public synchronized String readLine() { try { return br.readLine(); }catch (Exception e) { System.out.println("Error- " + e.toString()); return null; } } public synchronized void write(String shita) { try { bw.write(shita); }catch (Exception e) { System.out.println("Error- " + e.toString()); } } public synchronized void closeRead() { frozen = false; try { br.close(); }catch (Exception e) { System.out.println("Error- " + e.toString()); } } public synchronized void closeWrite() { frozen = false; try { bw.close(); }catch (Exception e) { System.out.println("Error- " + e.toString()); } } // this should put shita (text) in a file public synchronized void saveShit (String shita, boolean append) { while (frozen) {}; lineNumberCoherence = false; try { fw = new FileWriter(fileName,append); bw = new BufferedWriter(fw); bw.write(shita); bw.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException c) { System.out.println("Null pointer, dude!"+c.toString()); } } public synchronized void saveShit(String shita) { // if you leave out the boolean, it's auto-overwrite saveShit(shita, false); } // this returns shita from a text file public synchronized String readShit() { checkFrozen(); String textToBeReturned = null; try { String line = ""; numLines = 0; fr = new FileReader(fileName); br = new BufferedReader(fr); boolean eof = false; while (!eof) { line = br.readLine(); if (line == null) eof = true; else { if (textToBeReturned == null) { textToBeReturned = line; } else { textToBeReturned += System.getProperty("line.separator")+line; } numLines++; } } br.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (Exception e) { e.printStackTrace(); } return textToBeReturned; } // this is a little bit better- no tempFile means more memory taken up, // but we won't have any huge files here hopefully. public synchronized void deleteShitLn(int lineNumber) { checkFrozen(); // we still have coherence... int currentLine=0; file oldFile = new file(fileName); String textToBeReturned = null; //file tempFile = new file("12345test.test"); try { String line = ""; fr = new FileReader(fileName); br = new BufferedReader(fr); boolean eof = false; while (!eof) { currentLine++; line = br.readLine(); if (line == null) eof = true; else if (currentLine != lineNumber) { if (textToBeReturned == null) textToBeReturned = line; else textToBeReturned += System.getProperty("line.separator")+line; } } br.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException n) { System.out.println("Null Pointer in DeleteShitLn"); } catch (Exception e) { e.printStackTrace(); } oldFile.saveShit(textToBeReturned); numLines--; } /*public synchronized void deleteShitLn(int lineNumber) { // we still have coherence... int currentLine=0; file oldFile = new file(fileName); String textToBeReturned = null; //file tempFile = new file("12345test.test"); try { String line = ""; char char1; char char2; FileReader letters = new FileReader(fileName); BufferedReader buff = new BufferedReader(letters); boolean eof = false; while (!eof) { currentLine++; char1 = (char)buff.read(); char2 = (char)buff.read(); if (char1 == null) eof = true; else if (currentLine != lineNumber) { if (textToBeReturned == null) textToBeReturned = line; else textToBeReturned += System.getProperty("line.separator")+line; } } buff.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException n) { System.out.println("Null Pointer in DeleteShitLn"); } oldFile.saveShit(textToBeReturned); numLines--; }*/ public synchronized void changeShitLn(int lineNumber, String newStuff) { checkFrozen(); int currentLine=0; file oldFile = new file(fileName); String textToBeReturned = null; //file tempFile = new file("12345test.test"); try { String line = ""; fr = new FileReader(fileName); br = new BufferedReader(fr); boolean eof = false; while (!eof) { currentLine++; line = br.readLine(); if (line == null) eof = true; else { if (currentLine != lineNumber) { //just add the line here if (textToBeReturned == null) textToBeReturned = line; else textToBeReturned += System.getProperty("line.separator")+line; } else { if (textToBeReturned == null) // here we add the new line textToBeReturned = newStuff; else textToBeReturned += System.getProperty("line.separator")+newStuff; } } } br.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException n) { System.out.println("Null Pointer in ChangeShitLn"); } catch (Exception e) { e.printStackTrace(); } oldFile.saveShit(textToBeReturned); // here we save it! } public synchronized String readShitLn(int lineNumber) { // this returns the string from a line checkFrozen(); String textToBeReturned = null; try { fr = new FileReader(fileName); br = new BufferedReader(fr); //LineNumberReader buff = new LineNumberReader(letters); String line = null; for (int i = 0; i<lineNumber; i++) { line = br.readLine(); } //buff.setLineNumber(lineNumber+1); //textToBeReturned=buff.readLine(); textToBeReturned = line; o("readShitLn got: " + textToBeReturned); br.close(); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Invalid security clearance- prepare to die"); } catch (NullPointerException n) { System.out.println("Null pointer in readShitLn dude"); }catch (Exception e) { e.printStackTrace(); } return textToBeReturned; } // JON - these next routines go through the file 2N+1 times or some shit, compared to once above. // hopefully deprecated soon /* DO NOT DELETE*/ public synchronized void jonDeleteShitLn(int lineNumber) { checkFrozen(); file oldFile = new file(fileName); file tempFile = new file("12345test.test"); int numLines = oldFile.readShitNumLines(); tempFile.saveShit(""); if (lineNumber <= numLines) { // this method does nothing if linenumber > numlines for (int k = 1; k<lineNumber; k++) { tempFile.saveShit(oldFile.readShitLn(k)+System.getProperty("line.separator"),true); } if (numLines > lineNumber) { for (int j = lineNumber+1; j<numLines; j++) { tempFile.saveShit(oldFile.readShitLn(j)+ System.getProperty("line.separator"),true); } tempFile.saveShit(oldFile.readShitLn(numLines),true); // no extra "\n" } oldFile.saveShit(tempFile.readShit() + "\n"); boolean ahSo = tempFile.delete(); } numLines--; } /* DO NOT DELETE */ public synchronized void jonChangeShitLn(int lineNumber, String newStuff) { checkFrozen(); file oldFile = new file(fileName); file tempFile = new file("12345test.test"); int numLines = oldFile.readShitNumLines(); tempFile.saveShit(""); if (lineNumber <= numLines) { // this method does nothing if linenumber > numlines for (int k = 1; k<lineNumber; k++) { tempFile.saveShit(oldFile.readShitLn(k)+System.getProperty("line.separator"),true); } if (lineNumber == numLines) { tempFile.saveShit(newStuff + "\n",true); } else { tempFile.saveShit(newStuff + System.getProperty("line.separator"), true); for (int j = lineNumber+1; j<numLines; j++) { tempFile.saveShit(oldFile.readShitLn(j)+ System.getProperty("line.separator"),true); } tempFile.saveShit(oldFile.readShitLn(numLines),true); } oldFile.saveShit(tempFile.readShit() + "\n"); tempFile.delete(); } } // use this for adding lines to a file in the fastest possible way public synchronized void addLines(int firstLineGoesHere, String[] lines) { // we still have line coherence, we know how many we are adding checkFrozen(); System.out.println("starting file.addLInes- first line:" + lines[0]); int numNewLines = lines.length; boolean tempIsEmpty = true; int currentLine=1; //this is the syntax. First line = line 1 NOT line 0 String line = ""; //boolean done = false; try { // these are my boys fr = new FileReader(fileName); br = new BufferedReader(fr); String toBeReturned = ""; boolean eof = false; while (!eof) { line=br.readLine(); // first check if we need to add the goods and do it if(currentLine==firstLineGoesHere) { System.out.println("should be doing addLInes NOW"); for(int i=0; i<numNewLines; i++) { if(tempIsEmpty) { toBeReturned = lines[i]; tempIsEmpty = false; } else toBeReturned += System.getProperty("line.separator")+lines[i]; } currentLine = currentLine + numNewLines; } // now check for eof if (line == null) eof = true; else { if(tempIsEmpty) { toBeReturned = line; tempIsEmpty = false; } else toBeReturned += System.getProperty("line.separator")+line; currentLine++; } } saveShit(toBeReturned); numLines = numLines + numNewLines; } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException n) { System.out.println("Null Pointer in DeleteShitLn"); } catch (Exception e) { System.out.println("Error - " + e.toString()); } } public synchronized void addText(int firstLineGoesHere, String text) { checkFrozen(); lineNumberCoherence = false; boolean tempIsEmpty = true; int currentLine=1; //this is the syntax. First line = line 1 NOT line 0 String toBeReturned = ""; String line = ""; boolean eof = false; try { // these are my boys fr = new FileReader(fileName); br = new BufferedReader(fr); while (!eof) { line=br.readLine(); // first check if we need to add the goods and do it if(currentLine==firstLineGoesHere) { if(tempIsEmpty) { toBeReturned = text; tempIsEmpty = false; } else toBeReturned += System.getProperty("line.separator")+text; } // now check for eof if (line == null) eof = true; else { if(tempIsEmpty) { toBeReturned = line; tempIsEmpty = false; } else toBeReturned += System.getProperty("line.separator")+line; currentLine++; } } saveShit(toBeReturned); } catch (IOException e) { System.out.println("Error - " + e.toString()); } catch (SecurityException b) { System.out.println("Go check security shit"); } catch (NullPointerException n) { System.out.println("Null Pointer in DeleteShitLn"); } catch (Exception e) { System.out.println("Error - " + e.toString()); } } public synchronized int readShitNumLines() { if (lineNumberCoherence) return numLines; String test = readShit(); //file could be changed or readShit not called yet. return numLines; } public synchronized boolean exists() { // useful exists method test = new File(fileName); return test.exists(); } public synchronized boolean delete() { // useful delete method test = new File(fileName); return test.delete(); } public synchronized long length() { // returns size of file in bytes test = new File(fileName); return test.length(); } public synchronized void setContents(file gehFile) { // this is quick! lineNumberCoherence = false; // of a serious nature! File gf = new File(gehFile.fileName); test = new File(fileName); boolean niceAss = delete(); try{ gf.renameTo(test); } catch (Exception e) { System.out.println("Error in file class setCOntents: "+e.toString()); } } private void checkFrozen() { if (frozen) { System.out.println("Important! Somewhere there is no closeRead or closeWrite!!! "+fileName); try {Thread.sleep(1000);} catch(Exception e) {e.printStackTrace();} } } } // --- END FILE CLASS ---
Java
public class MakeDrDtArray { public static void main(String[] args) { VIonBulk vib; file myFile; double AU = 1.5* Math.pow(10,11); myFile = new file("testArray2.txt"); myFile.initWrite(false); for (double theta = -3.14; theta<= 3.14; theta=theta+3.14/30) { vib = new VIonBulk(AU, 28000, theta); myFile.write(theta+" "+vib.Vr()+" " + vib.Vperp()+System.getProperty("line.separator")); } myFile.closeWrite(); } }
Java
import java.util.StringTokenizer; /** * Simulating response at IBEX_LO with this class * * Create interstellar medium and perform integration * */ public class IBEXLO_09fit { public int mcN = 100000; // number of iterations per 3D integral public String outFileName = "lo_fit_09.txt"; public static final double EV = 1.60218 * Math.pow(10, -19); public static double MP = 1.672621*Math.pow(10.0,-27.0); public static double AU = 1.49598* Math.pow(10,11); //meters public static double EARTHSPEED = AU*2.0*3.14/365.0/24.0/3600.0; // define angles and energies of the instrument here // H mode (standard) energy bins in eV public double[] minEnergies = {8.8, 17.6, 35.8, 74.2, 153.5, 330.6, 663.3, 1298.6}; public double[] maxEnergies = {23.2, 46.4, 94.3, 195.8, 404.6, 871.5, 1748.7, 3423.5}; public double[] minSpeedsHe, maxSpeedsHe, minSpeedsO, maxSpeedsO; // Interstellar mode energies // { spring min, spring max, fall min, fall max } public double[] heEnergies = { 73.7, 194.3, 4.4, 11.6 }; public double[] oEnergies = {293.7, 774.3, 18.15, 47.9 }; public double[] heSpeeds; public double[] oSpeeds; // O mode efficiencies // public double heSpringEff = 1.0*Math.pow(10,-7); // this was the original.. now going to adjust to match data including sputtering etc. public double heSpringEff = 1.0*Math.pow(10,-7)/7.8; // nominal efficiency to "roughly" match data.. public double heFallEff = 1.6*Math.pow(10,-6); public double oSpringEff = 0.004; public double oFallEff = 0.001; // angular acceptance - assume rectangular windows.. // these are half widths, e.g. +- for acceptance public double spinWidth = 4.0*Math.PI/180.0; public double hrWidth = 3.5*Math.PI/180.0; public double lrWidth = 10.0*Math.PI/180.0; public double eightDays = 8.0*24.0*60.0*60.0; public double oneHour = 3600.0; public double upWind = 74.0 * 3.14 / 180.0; public double downWind = 254.0 * 3.14 / 180.0; public double startPerp = 180*3.14/180; // SPRING public double endPerp = 240*3.14/180; // SPRING //public double startPerp = 260.0*3.14/180.0; // FALL //public double endPerp = 340.0*3.14/180.0; // FALL public double he_ion_rate = 6.00*Math.pow(10,-8); public GaussianVLISM gv1; // temporarily make them very small //public double spinWidth = 0.5*Math.PI/180.0; //public double hrWidth = 0.5*Math.PI/180.0; //public double lrWidth = 0.5*Math.PI/180.0; public double activeArea = 100.0/100.0/100.0; // 100 cm^2 in square meters now!! public file outF; public MultipleIntegration mi; public NeutralDistribution ndHe; public double look_offset=Math.PI; public double currentLongitude, currentSpeed, currentDens, currentTemp; public HelioVector bulkHE; /** * * * */ public IBEXLO_09fit() { // calculate speed ranges with v = sqrt(2E/m) heSpeeds = new double[heEnergies.length]; oSpeeds = new double[oEnergies.length]; o("calculating speed range"); for (int i=0; i<4; i++) { heSpeeds[i]=Math.sqrt(2.0*heEnergies[i]/4.0/MP*EV); oSpeeds[i]=Math.sqrt(2.0*oEnergies[i]/16.0/MP*EV); System.out.println(heEnergies[i] +" = " + heSpeeds[i] + " , " + oEnergies[i] + " = " + oSpeeds[i]); } minSpeedsHe = new double[8]; maxSpeedsHe = new double[8]; minSpeedsO = new double[8]; maxSpeedsO = new double[8]; for (int i=0; i<8; i++) { minSpeedsHe[i]=Math.sqrt(2.0*minEnergies[i]/4.0/MP*EV); maxSpeedsHe[i]=Math.sqrt(2.0*maxEnergies[i]/4.0/MP*EV); minSpeedsO[i]=Math.sqrt(2.0*minEnergies[i]/16.0/MP*EV); maxSpeedsO[i]=Math.sqrt(2.0*maxEnergies[i]/16.0/MP*EV); System.out.println(minSpeedsHe[i] +" = " + maxSpeedsHe[i] + " , " + minSpeedsO[i] + " = " + maxSpeedsO[i]); } System.out.println(minSpeedsHe[0] + "\t" + maxSpeedsHe[0] +"\t" + heSpeeds[2] + "\t" + heSpeeds[3]); // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // bulkHE = new HelioVector(HelioVector.SPHERICAL, 26000.0, (74.68)*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,0.015*100.0*100.0*100.0,6000.0); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; currentLongitude = 74.68; currentSpeed = 26000.0; currentDens = 0.015; currentTemp = 6000.0; // DONE CREATING MEDIUM o("earthspeed: " + EARTHSPEED); mi = new MultipleIntegration(); o("done creating IBEXLO_09 object"); // DONE SETUP //- //- // now lets run the test, see how this is doing /* // moving curve fitting routine here for exhaustive and to make scan plots file ouf = new file("scanResults1.txt"); file f = new file("cleaned_ibex_data.txt"); int numLines = 413; f.initRead(); double[] x = new double[numLines]; double[] y = new double[numLines]; String line = ""; for (int i=0; i<numLines; i++) { line = f.readLine(); StringTokenizer st = new StringTokenizer(line); x[i]=Double.parseDouble(st.nextToken()); //x[i]-=1.0; // IMPORTANT _ SHIFT BY 1.0 TO MOVE TO HELIOCENTRIC FRAME!! y[i]=Double.parseDouble(st.nextToken()); //System.out.println("row: " + i + " x: " + x[i] + " y: " + y[i]); } f.closeRead(); // first scan: V vs Long. // for (int i=0; i< */ // loop through parameters here // standard params: double lamda = 74.7; //double temp = 6000.0; double v = 26000.0; int res = 30; double lamdaWidth = 20; //double tWidth = 10000; double vWidth = 10000; double lamdaMin = 65.0; //double tMin = 1000.0; double vMin=21000.0; double lamdaDelta = lamdaWidth/res; //double tDelta = tWidth/res; double vDelta = vWidth/res; lamda = lamdaMin; //temp=tMin; v = vMin; //file outF = new file("testVL_pass2_Out.txt"); //outF.initWrite(false); for (int i=0; i<res; i++) { v=vMin; for (int j=0; j<res; j++) { file outf = new file("fitP2_vl"+lamda+"_"+v+".txt"); outf.initWrite(false); setParams(lamda,v,0.015,6000.0); System.out.println(" now calc for: fitTTT_"+lamda+"_"+v+".txt"); for (double doy=10.0 ; doy<65.0 ; doy+=0.5) { outf.write(doy+"\t"); //for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) { //look_offset=off; look_offset=3.0*Math.PI/2.0; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outf.write(rr +"\t"); //} //double rr = getRate(doy); //System.out.println("trying: " + doy + " got "+rr); outf.write("\n"); } outf.closeWrite(); v+=vDelta; } //temp+=tDelta; lamda+=lamdaDelta; } //outF.closeWrite(); /* for (int temptemp = 1000; temptemp<20000; temptemp+=2000) { file outf = new file("fitB_"+temptemp+"_7468_26000.txt"); outf.initWrite(false); setParams(74.68,26000,0.015,(double)temptemp); for (double doy=10.0 ; doy<65.0 ; doy+=0.1) { outf.write(doy+"\t"); //for (double off = 0.0 ; off<=3.0*Math.PI/2.0; off+=Math.PI/2.0) { //look_offset=off; look_offset=3.0*Math.PI/2.0; double rr = getRate(doy); System.out.println("trying: " + doy + " got "+rr); outf.write(rr +"\t"); //} //double rr = getRate(doy); //System.out.println("trying: " + doy + " got "+rr); outf.write("\n"); } outf.closeWrite(); } */ } // END CONSTRUCTOR public void setParams(double longitude, double speed, double dens, double temp) { currentLongitude = longitude; currentSpeed = speed; currentDens = dens; currentTemp = temp; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // bulkHE = new HelioVector(HelioVector.SPHERICAL, speed, longitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } public void setParams(double dens) { currentDens = dens; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,currentTemp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } public void setParams(double dens, double temp) { currentDens = dens; currentTemp = temp; // BUILD INTERSTERLLAR MEDIUM - helium and oxygen here, primary and secondary oxygen.. // //HelioVector bulkHE = new HelioVector(HelioVector.SPHERICAL, currentSpeed, currentLongitude*Math.PI/180.0, 95.5*Math.PI/180.0); //HelioVector bulkO1 = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); GaussianVLISM gv1 = new GaussianVLISM(bulkHE,dens*100.0*100.0*100.0,temp); //KappaVLISM gv3 = new KappaVLISM(bulkO1, 0.00005*100*100*100, 6300, 1.6); ndHe = new NeutralDistribution(gv1, 0.0, he_ion_rate); // mu is 0.0 for he ndHe.debug=false; // DONE CREATING MEDIUM } public double getRate(double dens, double doy) { if ((currentDens!=dens)) { System.out.println("new params: " + dens); setParams(dens); } return getRate(doy); } public double getRate(double dens, double temp, double doy) { if ((currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + dens + " " + temp); setParams(dens,temp); } return getRate(doy); } public double getRate(double longitude, double speed, double dens, double temp, double doy) { if ((currentLongitude!=longitude)|(currentSpeed!=speed)|(currentDens!=dens)|(currentTemp!=temp)) { System.out.println("new params: " + longitude + " " + speed + " " + dens + " " + temp); setParams(longitude,speed,dens,temp); } return getRate(doy); } /** * We want to call this from an optimization routine.. * */ public double getRate(double doy) { // spacecraft position .. assume at earth at doy //double pos = ((doy-80.0)/365.0); double pos = (doy-265.0)*(360.0/365.0)*Math.PI/180.0;// - Math.PI; // set look direction double midPhi = 0.0; double midThe = Math.PI/2.0; double appogee = 0; // SET LOOK DIRECTION // THIS SET IS FOR FIRST PASS /*if (doy>10 && doy<15.5) { //orbit 13 appogee = 13.1; } else if (doy>15.5 && doy<24.1) { //orbit 14 appogee = 20.5; } else if (doy>24.1 && doy<32.0) { //orbit 15 appogee = 28.1; } else if (doy>32.0 && doy<39.7) { //orbit 16 appogee = 35.8; } else if (doy>39.7 && doy<47.5) { //orbit 17 appogee = 43.2; } else if (doy>47.5 && doy<55.2) { //orbit 18 appogee = 51.3; } else if (doy>55.2 && doy<62.6) { //orbit 19 appogee = 58.8; } else if (doy>62.6 && doy<70.2) { //orbit 20 appogee = 66.4; }*/ // SECOND PASS if (doy>10.5 && doy<18.0) { //orbit 13 appogee = 14.0; } else if (doy>18.0 && doy<25.6) { //orbit 14 appogee = 21.6; } else if (doy>25.6 && doy<33.3) { //orbit 15 appogee = 29.25; } else if (doy>33.3 && doy<40.85) { //orbit 16 appogee = 36.8; } else if (doy>40.85 && doy<48.85) { //orbit 17 appogee = 44.6; } else if (doy>48.85 && doy<56.4) { //orbit 18 appogee = 52.4; } else if (doy>56.4 && doy<64.0) { //orbit 19 appogee = 60.0; } else if (doy>64.0 && doy<71.6) { //orbit 20 appogee = 67.6; } //orbit 21 - apogee= 73.9 //orbit 22 - apogee = 81.8 else { appogee=doy; } //doy = doy-183.0; //appogee = appogee-183.0; double he_ans_lr; midPhi = (appogee-3.0-265.0)*360.0/365.0*Math.PI/180.0 + look_offset; final double lookPhi = midPhi; // centered at look diretion.. convert doy+10 (dec 21-jan1) to angle //midPhi = (appogee+3.0-80.0)*360.0/365.0*Math.PI/180.0 + Math.PI/2; //midPhi = midPhi; // here's the now position final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 1*AU, pos, Math.PI/2.0); final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, EARTHSPEED, pos+Math.PI/2.0, Math.PI/2.0); // placeholder for zero //final HelioVector scVelVec = new HelioVector(HelioVector.SPHERICAL, 0.0, pos+Math.PI/2.0, Math.PI/2.0); FunctionIII he_func = new FunctionIII() { // helium neutral distribution public double function3(double v, double p, double t) { double tbr = activeArea*ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t).sum(scVelVec) )*v*v*Math.sin(t)*v; // extra v for flux tbr *= angleResponse(lookPhi,p); // that is the integrand of our v-space integration return tbr; } }; // set limits for integration - spring only here //double[] he_lr_lims = { minSpeedsHe[0], maxSpeedsHe[0], midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; double[] he_lr_lims = { minSpeedsHe[1], maxSpeedsHe[7], midPhi-lrWidth, midPhi+lrWidth, 3.0*Math.PI/8.0, 5.0*Math.PI/8.0 }; he_lr_lims[0]=minSpeedsHe[3]; he_lr_lims[1]=maxSpeedsHe[5]; //, midPhi-lrWidth, midPhi+lrWidth, midThe-lrWidth-spinWidth, midThe+lrWidth+spinWidth }; //PERFORM INTEGRATION he_ans_lr = 12.0*oneHour *1.0/8.0 *1.0 * mi.mcIntegrate(he_func, he_lr_lims, mcN); he_ans_lr*=heSpringEff; return he_ans_lr; } public double sigma=6.1; public double angleResponse(double centerA, double checkA) { double cA = centerA*180.0/Math.PI; double chA = checkA*180.0/Math.PI; double tbr = Math.exp(-(cA-chA)*(cA-chA)/sigma/sigma); return tbr; } public static final void main(String[] args) { IBEXLO_09fit il = new IBEXLO_09fit(); } public static void o(String s) { System.out.println(s); } }
Java
import java.util.*; import cern.jet.math.Bessel; // use cern library for i0 and j0 /** * Use this to model PUI distribution & observed eflux a la * * Isenberg, JGR, 102, A3, 4719-4724, 1997 * * * Assume spacecraft samples only antisunwardest hemisphere, * field near radial... * */ public class Hemispheric { public static double AU = 1.49598* Math.pow(10,11); //meters public static double NaN = Double.NaN; public static double MAX = Double.MAX_VALUE; public static double U = 440*1000; public static double N0 = Math.pow(10,-6); public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg public static double Ms = 1.98892 * Math.pow(10,30); // kg //public static double gamma = -3.0/2.0; // energy dependence in eflux ?? // The diffusion coefficient for cross hemispheric transport double D = 0.0; double gamma; public static double beta = 3*Math.pow(10,-8); public static double PI = Math.PI; MultipleIntegration mi; /** * THe velocity of a cold interstellar particle at earth. Calculate in constructor. */ public double v_earth; public static double v_infinity = 27500.0; //m/s //Integration ig; public Hemispheric() { this(0.0); } public Hemispheric(double gg) { gamma = gg; // we need to do a numeric integral mi = new MultipleIntegration(); //ig = new Integration(); // calculate v_earth from energy conservation v_earth = Math.sqrt(2*G*Ms/AU + v_infinity*v_infinity); System.out.println("v_earth: " + v_earth); } public double eflux(final double _D, final double norm, final double w2) { double nrm = 3*beta*AU*AU/8/PI/AU/U/U/U/U*N(AU); double tbr = eflux(_D,norm/nrm,1.0,w2); //System.out.println("eflux: " + _D + "\t" + norm + "\t" + w2 + " " + tbr); return tbr; } /** *calculate EFlux at r in w = v/ v_sw */ public double eflux(final double _D, final double norm, final double gg, final double w2) { gamma = gg; return f(AU,_D,norm,w2)*Math.pow((w2),gamma); } public double f(final double r, final double _D, final double w) { return f(r,_D,1.0,w); } /** * The main portion of this class.. * here we calculate the f+ distribution analytically (except for one numeric * integration). */ public double f(final double r, final double _D, final double norm, final double w) { if (w>=1.0) return 0.0; // establish some variables D = _D; final double a = 3*(1-w)/4; final double b = r*Math.pow(w,3/2); // first we need to do an integral. Establish the integrand. FunctionI integrand = new FunctionI () { public double function(double z) { double phi; if (1-D*D > 0) { phi = Math.sqrt(z*(2*a-z)*(1-D*D)); return N(b*Math.exp(z-a)) * Bessel.j0(phi); } else { phi = Math.sqrt(z*(2*a-z)*(D*D-1)); return N(b*Math.exp(z-a)) * Bessel.i0(phi); } } }; //double phi = Math.sqrt(a/2*(2*a-a/2)*(1-D*D)); // System.out.println("int: " + N(r*b*Math.exp(a-a/2)) ); // System.out.println("int: " + Math.sqrt((2*a-a/2)/a/2) ); // System.out.println("int: " + phi); // System.out.println("int: " + j0(phi)); // System.out.println("integrand(a/2): " + integrand.function(a/2)); double integral = mi.integrate(integrand, 0.0, 2*a); // ig.setFunction(integrand); // ig.setMaxError(10); // double integral = ig.integrate(0.01,2*a-0.01); double factor = 3*beta*AU*AU/8/PI/U/U/U/U * (D+1)/b * Math.exp(-a*D); return factor*integral*norm; } /** * Taken from cern.jet.math, a fast Bessl Algorithm here. */ /*static public double j0(double x) { double ax; if( (ax=Math.abs(x)) < 8.0 ) { double y=x*x; double ans1=57568490574.0+y*(-13362590354.0+y*(651619640.7 +y*(-11214424.18+y*(77392.33017+y*(-184.9052456))))); double ans2=57568490411.0+y*(1029532985.0+y*(9494680.718 +y*(59272.64853+y*(267.8532712+y*1.0)))); return ans1/ans2; } else { double z=8.0/ax; double y=z*z; double xx=ax-0.785398164; double ans1=1.0+y*(-0.1098628627e-2+y*(0.2734510407e-4 +y*(-0.2073370639e-5+y*0.2093887211e-6))); double ans2 = -0.1562499995e-1+y*(0.1430488765e-3 +y*(-0.6911147651e-5+y*(0.7621095161e-6 -y*0.934935152e-7))); return Math.sqrt(0.636619772/ax)* (Math.cos(xx)*ans1-z*Math.sin(xx)*ans2); } }*/ /** * The model of interstellar neutral density.. * * based on no inflow, e.g. no angulage dependence just * ionization depletion. */ /*private static double N(double r) { double A = 4.0*AU; // one parameter model return N0*Math.exp(-A/r); }*/ /** * The model of interstellar neutral density.. * * based on cold model, due upwind.. * see Moebius SW&CR homework set #4! */ private double N(double r) { return N0*Math.exp(-beta*AU*AU*Math.sqrt(v_infinity*v_infinity+2*G*Ms/r)/G/Ms); //return N0*Math.exp(-2*beta*AU*AU/r/v_infinity); } /** * For Testing */ public static final void main(String[] args) { file q; System.out.println(""+2*beta*AU*AU/v_infinity/AU); System.out.println(""+beta*AU*AU*Math.sqrt(v_infinity*v_infinity+2*G*Ms/AU)/G/Ms); // test bessel function: /* q = new file("besselTest.dat"); q.initWrite(false); for (double i=-5; i<5; i+=.1) { try { q.write(i+"\t"+Bessel.i0(i)+"\n"); } catch (Exception e) {e.printStackTrace();} } q.closeWrite(); */ // a series of outputs of the model varying parameters.. double[] dd = {6.73,4.92,3.92,2.61,1.40,0.61}; double[] nn = {15776,14724,14185,14144,14643,19739}; file f = new file("hemis_0306_out.dat"); f.initWrite(false); int index = 0; Hemispheric h = new Hemispheric(); for (double w=0.0; w<=1.0; w+=0.02) { index=0; f.write(w+"\t"); while (index<6) { f.write(h.eflux(dd[index],nn[index],w)+"\t"); index++; } f.write("\n"); } f.closeWrite(); // single output //double norm = 3*beta*AU*AU/8/PI/AU/U/U/U/U*N(AU); /*double a=0.586; double b=19830.0; Hemispheric h = new Hemispheric(); q = new file("hemisTest.dat"); q.initWrite(false); for (double w=0.01; w<1.01; w+=.01) { try { q.write((w+1.0)+"\t"+h.eflux(a,b,w)+"\n"); //q.write((w+1.0)+"\t"+h.f(AU,1.0,1.0,w)+"\n"); } catch (Exception e) {e.printStackTrace();} } q.closeWrite();*/ } }
Java
import java.util.Date; import java.lang.Math; public class HelioTester { public static void main(String[] args) { // THis tests the moveZAxis routine Date d1 = new Date(); //HelioVector h1 = new HelioVector(HelioVector.Spherical, 1,Math.PI/2, Math.PI/4); //HelioVector h2 = new HelioVector(HelioVector.Spherical, 1,Math.PI/2, Math.PI/4); HelioVector h1 = new HelioVector(HelioVector.Cartesian, 1,0,1); HelioVector h2 = new HelioVector(HelioVector.Cartesian, 1,0,0); //HelioVector h3 = h2.moveZAxis(h1); System.out.println("cylCOordPhi = " + h1.cylCoordPhi(h1,h2)); //System.out.println("new point: "+h3.getX()+" "+h3.getY()+" "+h3.getZ()); HelioVector h4 = new HelioVector(HelioVector.Cartesian, 0,1,0); HelioVector h5 = new HelioVector(HelioVector.Cartesian, 0,1,0); HelioVector h6 = h5.moveZAxis(h1); System.out.println("new point: "+h6.getX()+" "+h6.getY()+" "+h6.getZ()); HelioVector h7 = new HelioVector(HelioVector.Cartesian, 2,0,0); HelioVector h8 = new HelioVector(HelioVector.Cartesian, 0,1,0); HelioVector h9 = h7.rotateAroundArbitraryAxis(h8,3.14/2); System.out.println("new point: "+h9.getX()+" "+h9.getY()+" "+h9.getZ()); Date d2 = new Date(); System.out.println(d2.getTime() - d1.getTime()+""); } }
Java
import java.util.*; //import cern.jet.math.Bessel; //import com.imsl.math.Complex; /** * This calculates the velocity distribution of neutral atoms in the heliosphere. * (according to the hot model or interstellar neutral dist. of choice) * * Also computes losses to ionization - based on 1/r^2 rate * * Uses an input distribution class to determine LISM f. * * Lukas Saul - Warsaw 2000 * * Winter 2001 or so - got rid of Wu & Judge code * (still based on their calculation of course) * * Last Modified - October 2002 - moved lism distribution to separate class * reviving - April 2004 * Last used: * Sept 15. 2008 */ public class NeutralDistribution { public static double KB = 1.38065 * Math.pow(10,-23); public static double Ms = 1.98892 * Math.pow(10,30); // kg //public static double Ms = 0.0; // kg public static double G = 6.673 * Math.pow(10,-11); // m^3/s^2/kg public static double AU = 1.49598* Math.pow(10,11); //meters public static double NaN = Double.NaN; public static double MAX = Double.MAX_VALUE; private double mu, beta, Gmod; public static int monte_num = 1000; // this gives our original neutral distribution in LISM private InterstellarMedium im; // these variables are for getHPInfinity private double rdot, rdoti, thetadot, L, ptheta, pthetai, thc, vdif; private double e, a, phi, shift; private HelioVector hpr, hpv, hpn, hpox, hpoy, hpvi, hpdif, hpThetaHat, answer; public boolean goingIn; // other objects and primitives private InterstellarMedium vlism; private double E, rMin, theta0; private HelioVector tempHV, thetaHat, temp2; private double testX, testY, arg, vinfxo, vinfyo, angleSwept, r; private double survivalFactor; public double gmodMs; public int counter; // how many getHPInfinitys have been called? public boolean debug=true; private double oneOverE; /** * Parameters: * InterstellarMedium (starting point) * radiationToGravityRatio (mu) * SurvivalProbability (ionization rate calculatore) * */ public NeutralDistribution(InterstellarMedium im, double radiationToGravityRatio, double beta0) { mu = radiationToGravityRatio; beta = beta0; //sp = new SurvivalProbability(beta, mu); vlism = im; Gmod = G*(1.0-mu); oneOverE = 0.0; // initialize them now. We don't want to build java objects during calculations. hpr = new HelioVector(); hpv = new HelioVector(); hpn = new HelioVector(); hpox = new HelioVector(); hpoy = new HelioVector(); hpvi = new HelioVector(); hpdif = new HelioVector(); hpThetaHat = new HelioVector(); answer = new HelioVector(); tempHV = new HelioVector(); thetaHat = new HelioVector(); temp2 = new HelioVector(); goingIn=false; ptheta = Math.PI; gmodMs = Gmod*Ms; //if (gmodMs==0.0) gmodMs = Double.MIN_VALUE; counter = 0; } /** * Calculate the full distribution. This time perform all transformations * explicitly, instead of reading them from a paper (WU and JUDGE). * Coordinates are expected in Heliospheric coordinates (phi=0,theta=0 = direct upwind) * * Uses HelioVector.java to assist in geometry calculations * * we are being careful now not to create "new" variables (instances) to save time * especially our vectors (HelioVectors) */ public double dist(double r, double theta, double phi, double vx, double vy, double vz) { //o("Calling dist: "+r+" "+theta+" "+phi+" "+vx+" "+vy+" "+vz); // first make some reference vectors to help simplify geometryschool hou hpr.setCoords(HelioVector.SPHERICAL, r, theta, phi); // take the reverse of the velocity to help keep it straight hpv.setCoords(HelioVector.CARTESIAN, vx, vy, vz); return dist (hpr,hpv); } public double dist(HelioVector hpr_, HelioVector hpv_) { //System.out.println("test"); hpr.setCoords(hpr_); hpv.setCoords(hpv_); double r = hpr.getR(); hpvi = getHPInfinity(hpr, hpv); // here's the hard part - this call also sets thetaDif // the angle swept out by the particle from -inf to now if (hpvi==null) return 0.0; if ( !(hpvi.getX()<MAX && hpvi.getX()>-MAX) ) return 0.0; if ( !(hpvi.getY()<MAX && hpvi.getY()>-MAX) ) return 0.0; if ( !(hpvi.getZ()<MAX && hpvi.getZ()>-MAX) ) return 0.0; //System.out.println("made it here"); // we need to multiply by the survival probability here... //System.out.println("thetadot: " + thetadot); //System.out.println("r: " + r); survivalFactor = Math.exp(-beta*AU*AU*angleSwept/L); //o("survival Factor: " + survivalFactor + " angleSwept: " + angleSwept + " L: " + L); // then do the gaussian with survival probability //double answer = vlism.heliumDist(hpvi.getX(),hpvi.getY(),hpvi.getZ())*survivalFactor; //o(""+answer); //System.out.println(hpvi.getX() + " " + hpvi.getY() + " " + hpvi.getZ()); try { return vlism.dist(hpvi.getX(),hpvi.getY(),hpvi.getZ())*survivalFactor; } catch(Exception e) { return 0.0; } } /** * Use this to compute the original velocity vector at infinity, * given a velocity and position at a current time. * * // note velocity vector is reversed, represents origin to point at t=-infinity * * Use static heliovector methods to avoid the dreaded "new Object()"... * * * !!! tested extensively May 2004 !!! * not extensively enough. Starting again - sept 2004 */ private HelioVector getHPInfinity(HelioVector hpr, HelioVector hpv) { //System.out.println("test!"); counter++; r = hpr.getR(); if (r==0.0) r=Double.MIN_VALUE; // - define orbital plane as hpn // orbital plane is all vectors r with: r dot hpn = 0 // i.e. hpn = n^hat (normal vector to orbital plane) hpn.setCoords(hpr); HelioVector.crossProduct(hpn, hpv); // defines orbital plane HelioVector.normalize(hpn); // We are going to set up coordinates in the orbital plane.. // unit vectors in this system are hpox and hpoy // choose hpox so the particle is on the +x axis // such that hpox*hpn=0 (dot product) theta of the given position is zero //hpox.setCoords(HelioVector.CARTESIAN, hpn.getY(), -hpn.getX(), 0); hpox.setCoords(HelioVector.CARTESIAN, hpr.getX()/r, hpr.getY()/r, hpr.getZ()/r); // this is the y axis in orbital plane hpoy.setCoords(hpn); HelioVector.crossProduct(hpoy, hpox); // hopy (Y) = hpn(Z) cross hpox (X) // ok, we have defined the orbital plane ! // now lets put the given coordinates into this plane // they are: r, ptheta, rdot, thetadot // // we want rDot. This is the component of traj. away from sun // rdot = hpv.dotProduct(hpr)/r; goingIn = true; if (rdot>=0) goingIn = false; // what is thetaDot? // // use v_ = rdot rhat + r thetadot thetahat... // // but we need the thetaHat .. // thetaHat is just (0,1) in our plane // because we are sitting on the X axis // thats how we chose hpox // thetaHat.setCoords(hpoy); thetadot = hpv.dotProduct(thetaHat)/r; // NOW WE CAN DO THE KEPLERIAN MATH // let's calculate the orbit now, in terms of eccentricity e // ,semi-major axis a, and rdoti (total energy = 1/2(rdoti^2)) // // the orbit equation is a conic section // r(theta) = a(1-e^2) / [ 1 + e cos (theta - theta0) ] // // thanks Bernoulli.. // // note: a(1-e^2) = L^2/GM // // rMin = a(1-e) // // for hyperbolics, e>1 // L=r*r*thetadot; // ok - we know our angular momentum (per unit mass) E=hpv.dotProduct(hpv)/2.0 - gmodMs/r; if (E <= 0) { d("discarding elipticals..."); return null; } // speed at infinity better be more negative than current speed! if (rdoti > hpv.getR()) o("rdoti < hpv.getR() !! "); if (thetadot==0.0) { rMin = 0.0; //o("Trajectory entirely radial! "); } else { rMin= (Math.sqrt(gmodMs*gmodMs/E/E+2.0*L*L/E)-gmodMs/E)/2.0; //rMin = Math.sqrt(2.0/thetadot/thetadot*(E+gmodMs/r)); } // d("rmin:" + rMin); // the speed at infinity is all in the radial direction, rdoti (negative) rdoti=-Math.sqrt(2.0*E); // rMin had better be smaller than R.. if (rMin > r) { // d("rMin > r !! "); rMin = r; } // e and a now are available.. e = L*L/rMin/gmodMs - 1.0; oneOverE = 1/e; if (e<=1) { d("didn't we throw out ellipticals already?? e= " + e); return null; } //a = rMin/(1.0-e); // do some debugging.. // /* d("rdoti: " + rdoti);d("r: " + r + " L: " + L); d("ke: " + hpv.dotProduct(hpv)/2.0); d("pe: " + gmodMs/r); d("ke - pe: " + (hpv.dotProduct(hpv)/2.0 - gmodMs/r)); d("rke: " + rdot*rdot/2.0); d("energy in L comp. " + L*L/r/r/2.0); d("ke - (rke+thetake): " + (hpv.dotProduct(hpv)/2.0 - rdot*rdot/2.0 - L*L/r/r/2.0)); d("E dif: " + ( (rdot*rdot/2.0 + L*L/r/r/2.0 - gmodMs/r) - E )); d("E dif: " + ( (rdot*rdot/2.0 + thetadot*thetadot*r*r/2.0 - gmodMs/r) - E )); d("thetadot: " + thetadot); d("e: " + e); d("rMin: " + rMin+ "a: " + a + " e: " + e); */ // WE HAVE EVERYTHING in the orbit equation now except theta0 // the angle at which the orbit reaches rMin // now we use our current position to solve for theta - theta0 //arg = a*(1.0-e*e)/e/r - 1.0/e; arg = rMin*(1.0+e)/e/r - oneOverE; // could also be arg = L*L/r/e/gmodMs - oneOverE; //d("arg: " + arg); theta0 = Math.acos(arg); // correct for going in when sitting really on x axis // we have the angle but we need to make sure we get the sign right // what with implementing the mulitvalued acos and all.. // acos returns a value from 0 to pi if (!goingIn) theta0 = -theta0; //d("theta0: "+ theta0); // the angle "swept out by the particle" to its current location is // // this is also useful for the ionization calculation // //if (thetadot>0) pthetai = theta0 + Math.acos(-oneOverE); //else pthetai = theta0 - Math.acos(-oneOverE); //if (!goingIn) { // angleSwept = Math.abs(pthetai - theta0) + Math.abs(Math.PI-theta0); //} //else { // angleSwept = Math.abs(pthetai - Math.PI); //} //if (angleSwept>=Math.PI) o("angleSwept too big : " + angleSwept); angleSwept = Math.acos(-oneOverE); pthetai = -angleSwept + theta0; //if (!goingIn) pthetai = angleSwept - theta0; // d("angle swept: "+ angleSwept); // d("pthetai: " + pthetai); // now we know everything!! The vector to the original v (t=-infinity) // // Vinf_ = - rdoti * rHat ( thetaInf ) // vinfxo = rdoti*Math.cos(pthetai); vinfyo = rdoti*Math.sin(pthetai); // put together our answer from the coords in the orbital plane // and the orbital plane unit vectors answer.setCoords(hpox); HelioVector.product(answer,vinfxo); HelioVector.product(hpoy,vinfyo); // destroy hpoy here HelioVector.sum(answer,hpoy); //HelioVector.invert(answer); return answer; } /** * Use this to input a test for getHPInfinity.. * * That routine is driving me nuts. * * Tested! Working! 01:21 Dec4 2007 */ public void testI(double x, double y, double z, double vx, double vy, double vz) { //HelioVector tttt = new HelioVector(); HelioVector r1 = new HelioVector(HelioVector.CARTESIAN, x,y,z); HelioVector v1 = new HelioVector(HelioVector.CARTESIAN, vx,vy,vz); HelioVector tttt = getHPInfinity(r1,v1); o("r: " + r1.o()); o("v: " + v1.o()); o("goingIN: "+ goingIn + " theta0: " +theta0 + " pthetai: "+pthetai); o("angle swept: " + Math.acos(-1.0/e) + " rdoti: " + rdoti); if (tttt!=null) o("v_inf : " +tttt.o()); double einit= 0.5*v1.dotProduct(v1) - Ms*Gmod/Math.sqrt(r1.dotProduct(r1)); double efinal= 0.5*tttt.dotProduct(tttt); o("energy difference = " + Math.abs(efinal-einit)); o("\n\n\n"); } /** * Here is the formula to graph * r(theta) = a(1-e^2) / [ 1 + e cos (theta - theta0) * */ public void graphOrbit(HelioVector v_inf) { // not implemented } /** * Use this to do a more complete test of getHPInfinity */ /*public void testIII() { // first let's try a sweep in position phi coord, leaving v constant. // do a hundred for fun file fu = new file("testIII.dat"); fu.initWrite(false); for (int i=0; i<100; i++) { HelioVector r1 = new HelioVector(HelioVector.SPHERICAL, AU,i*2*Math.PI/100,0.0); HelioVector v1 = new HelioVector(HelioVector.CARTESIAN, 30000.0,0.0,0.0); HelioVector tttt = getHPInfinity(r1,v1); fu.write(i*2*Math.PI/100 + "\t" + */ /** * for testing only */ public static final void main(String[] args) { // o("MAX_VALUE: " + Double.MAX_VALUE); double test234=3.2/0.0; Date dt3 = new Date(); MultipleIntegration mi = new MultipleIntegration(); HelioVector bulk = new HelioVector(HelioVector.CARTESIAN,26000.0, 0.0, 0.0); final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 300*AU, 0.0, 0.0); // o("2 / min : " + 2.0/Double.MIN_VALUE); // bulk speed //HelioVector bulk = new HelioVector(HelioVector.SPHERICAL,26000.0,74.5*Math.PI/180.0,-5.0*Math.PI/180); // let's make three of these, H He O // set up the interstellar distribution // NeutralDistribution ndH = new NeutralDistribution(new GaussianVLISM(bulk,0.19,6300.0), 1.0, 7.4*Math.pow(10,-7)); //final NeutralDistribution ndHe = new NeutralDistribution(new GaussianVLISM(bulk,0.015,6300.0), 0.0, 1.1*Math.pow(10,-7)); final NeutralDistribution ndHe = new NeutralDistribution(new KappaVLISM(bulk,0.015,6300.0, 1.6), 0.0, 1.1*Math.pow(10,-7)); ndHe.debug=false; //NeutralDistribution ndO = new NeutralDistribution(new GaussianVLISM(bulk,0.00005,6300.0), 0.0, 7.5*Math.pow(10,-7)); //ndH.debug=false; //ndHe.debug=false; //ndO.debug=false; //TEST SPHERICAL LIMITS double[] limits = { 0.0, 300000.0, 0.0, 2.0*Math.PI, 0.0, Math.PI }; //o("doing pos: " + pos); //final HelioVector posVec = new HelioVector(HelioVector.SPHERICAL, 200*AU, 0.0, 0.0); FunctionIII f3 = new FunctionIII() { public double function3(double v, double p, double t) { double tbr = ndHe.dist(posVec, new HelioVector(HelioVector.SPHERICAL,v,p,t))*v*v*Math.sin(t); // that is the integrand of our v-space integration return tbr; } }; o( mi.mcIntegrate(f3, limits, 10000) + "\n"); /* // generated 2D color countour plot of heliospheric density of neutrals // file f = new file ("kappa_6300_5au_r100_l_6.txt"); f.initWrite(false); int res = 100; for (double xx=-5.0*AU; xx<=5.0*AU; xx+= 10.0*AU/res) { for (double yy=-5.0*AU; yy<=5.0*AU; yy+= 10.0*AU/res) { final double x = xx; final double y = yy; // test multiple integration FunctionIII f3 = new FunctionIII() { public double function3(double a, double b, double c) { HelioVector bulk = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); NeutralDistribution ndH = new NeutralDistribution(new GaussianVLISM(bulk,0.015,6300.0), 0.0, 1.0*Math.pow(10,-7)); ndH.debug=false; double tbr = ndH.dist(new HelioVector(HelioVector.CARTESIAN, x,y,0.0), new HelioVector(HelioVector.CARTESIAN,a,b,c)); //System.out.println(tbr); return tbr; } }; //System.out.println("test: " + f3.function3(500000,500000,500000)); //HelioVector testPos; //HelioVector testSpeed; //double minf = MultipleIntegration.MINUS_INFINITY; //double pinf = MultipleIntegration.PLUS_INFINITY; //MultipleIntegration mi = new MultipleIntegration(); //double[] limits = {minf,pinf,minf,pinf,minf,pinf}; //for (double lim=50000.0; lim<110000.0; lim+=10000.0) { // double[] limits2 = {-lim,lim,-lim,lim,-lim,lim}; // System.out.println("lim: " + lim + " ans: " +mi.integrate(f3,limits2,32)); //} // let's go with 70000 for now at 32 steps double lim = 80000.0; double[] limits2 = {-lim,lim,-lim,lim,-lim,lim}; //System.out.println("lim: " + lim + " ans: " +mi.integrate(f3,limits2,32)); double zz =mi.mcIntegrate(f3,limits2,monte_num); System.out.println("done x: "+xx+" y: "+yy+" dens: "+zz); f.write(xx+"\t"+yy+"\t"+zz+"\n"); } } f.closeWrite(); */ // Determine distribution of speeds at a point /*file newF = new file("speed_distribution_2.txt"); newF.initWrite(false); HelioVector bulk = new HelioVector(HelioVector.SPHERICAL,26000.0, (74+180)*Math.PI/180.0, 95.5*Math.PI/180); final NeutralDistribution ndH = new NeutralDistribution(new GaussianVLISM(bulk,0.015,6300.0), 0.0, 1.0*Math.pow(10,-7)); ndH.debug=false; // // set position final double x_pos = 100.0*AU; final double y_pos = 100.0*AU; final double z_pos = 100.0*AU; MultipleIntegration mi = new MultipleIntegration();double lim = 80000.0; double[] limits2 = {-lim,lim,-lim,lim}; for (double v=0; v<80000; v+=(80000.0/20.0)) { // step through speeds // at each speed go through final double ttv = v; FunctionII f2 = new FunctionII() { public double function2(double b, double c) { double tbr = ndH.dist(new HelioVector(HelioVector.CARTESIAN, x_pos, y_pos, z_pos), new HelioVector(HelioVector.CARTESIAN,Math.sqrt(ttv*ttv-b*b-c*c),b,c)); //System.out.println(tbr); return tbr; } }; newF.write(v+"\t"+mi.mcIntegrate(f2,limits2,10000)+"\n"); } newF.closeWrite();*/ // COMPARE FLUX AT POINTS AROUND SUN /*file f = new file("testrestults.txt"); f.initWrite(false); for (double phi=0; phi<2.0*Math.PI; phi+=8*Math.PI/360.0) { //o("trying phi: " + phi); testPos = new HelioVector(HelioVector.CARTESIAN, AU*Math.cos(200*Math.PI/180), AU*Math.sin(200*Math.PI/180),0.0); testSpeed = new HelioVector(HelioVector.CARTESIAN, 50000*Math.cos(200*3.14/180+Math.PI/2.0)*Math.cos(phi), 50000*Math.sin(200*3.14/180+Math.PI/2)*Math.cos(phi), 50000*Math.sin(phi)); f.write(phi*180/3.14159+"\t"+ndH.dist(testPos,testSpeed)+"\t"+ndHe.dist(testPos,testSpeed)+"\n"); } f.closeWrite(); */ /* file f = new file("testrestults.txt"); f.initWrite(false); for (double phi=0; phi<2.0*Math.PI; phi+=Math.PI/200.0) { //o("trying phi: " + phi); testPos = new HelioVector(HelioVector.CARTESIAN, AU,0.0,0.0); testSpeed = new HelioVector(HelioVector.CARTESIAN, 49000*Math.cos(phi+Math.PI/2.0), 49000*Math.sin(phi+Math.PI/2), 0.0); HelioVector hpinf = ndHe.getHPInfinity(testPos,testSpeed); if (hpinf!=null) f.write(phi*180/3.14159+"\t"+hpinf.getR()+"\t"+bulk.dotProduct(hpinf)+"\n"); } f.closeWrite(); */ // TEST OF GET HP INFINITY BELOW // Date dt4 = new Date(); //o("constructor took: "+(dt4.getTime()-dt3.getTime())); //System.out.println(nd.dist(0.0,0.0,0.0,0.0,0.0,0.0)); // Date dt1 = new Date(); // nd.testI(-AU,AU,0.0, -40000,-40000,0.0); // nd.testI(-AU,AU,0.0, -50000,-50000,0.0); // nd.testI(-AU,AU,0.0, -100000,-100000,0.0); // let's test going straight in from six cardinal directions.. // nd.testI(0.0,AU,0.0, 0.0,-20000.0,200000.0); // nd.testI(0.0,AU,0.0, 0.0,20000.0,200000.0); // nd.testI(0.0,-AU,0.0, 0.0,-20000.0,200000.0); // nd.testI(0.0,-AU,0.0, 0.0,20000.0,200000.0); // nd.testI(-AU,0.0,0.0, 0,0.-200000.0,0.0); // nd.testI(-AU,0.0,0.0, 0.0,0.0,200000.0); // nd.testI(-AU,0.0,0.0, 0.0,0.0,-200000.0); //nd.testI(0.0,-AU,0.0, 0.0,50000.0,0.0); //nd.testI(0.0,AU,0.0, 0.0,-50000.0,0.0); //nd.testI(0.0,0.0,-AU, 0.0,0.0,50000.0); //nd.testI(0.0,0.0,AU, 0.0,0.0,-50000.0); //nd.testI(0.0,-AU,0.0, 0.0,0.0,50000); //nd.testI(0.0,-AU,0.0, 0.0,0.0,100000); //nd.testI(0.0,-AU,0.0, 0.0,0.0,500000); //nd.testI(-AU,0.0,0.0, 0.0,0.0,50000); //nd.testI(-AU,0.0,0.0, 0.0,0.0,100000); //nd.testI(-AU,0.0,0.0, 0.0,0.0,500000); // Date dt2 = new Date(); // System.out.println("6 took: "+(dt2.getTime()-dt1.getTime())); // we are going to generate some line plots.. /* int ts = 10; double[] y = new double[ts]; double[] x = new double[ts]; // a point at 1AU for starters HelioVector pos = new HelioVector(HelioVector.CARTESIAN,AU,0,0); for (int i=0; i<y.length; i++) { HelioVector vel = new HelioVector(HelioVector.CARTESIAN,i*1000,0,0); x[i]=i*100; y[i]=nd.dist(pos,vel); System.out.println(x[i]+"\t"+y[i]); }*/ } private static void o(String s) { System.out.println(s); } private void d(String s) { if (debug) System.out.println(s); } }
Java
public class TestDistribution { public static void main(String[] args) { double AU = 15 * 10^13; // m SimpleNeutralDistribution snd = new SimpleNeutralDistribution( 25000, 0, 0, 10000, 7*Math.pow(10,-3), 0, 6.8*Math.pow(10,-8)); file f=new file("vrDist.txt"); f.initWrite(false); for (int v0=20000; v0<40000; v0=v0+1000) { double q = snd.N(AU, 135*Math.PI/180, v0); f.write(v0+" "+q+" " +System.getProperty("line.separator")); } f.closeWrite(); } }
Java
/* * Class Minimisation * * Contains methods for finding the values of the * function parameters that minimise that function * using the Nelder and Mead Simplex method. * * The function needed by the minimisation method * is supplied by though the interface, MinimisationFunction * * WRITTEN BY: Dr Michael Thomas Flanagan * * DATE: April 2003 * MODIFIED: 29 December 2005, 18 February 2006 * * DOCUMENTATION: * See Michael Thomas Flanagan's Java library on-line web page: * Minimisation.html * * Copyright (c) April 2003 * * PERMISSION TO COPY: * Permission to use, copy and modify this software and its documentation for * NON-COMMERCIAL purposes is granted, without fee, provided that an acknowledgement * to the author, Michael Thomas Flanagan at www.ee.ucl.ac.uk/~mflanaga, appears in all copies. * * Dr Michael Thomas Flanagan makes no representations about the suitability * or fitness of the software for any or for a particular purpose. * Michael Thomas Flanagan shall not be liable for any damages suffered * as a result of using, modifying or distributing this software or its derivatives. * ***************************************************************************************/ import java.util.*; import flanagan.io.FileOutput; // Minimisation class public class Minimisation{ private int nParam=0; // number of unknown parameters to be estimated private double[]paramValue = null; // function parameter values (returned at function minimum) private String[] paraName = null; // names of parameters, eg, c[0], c[1], c[2] . . . private double functValue = 0.0D; // current value of the function to be minimised private double lastFunctValNoCnstrnt=0.0D;// Last function value with no constraint penalty private double minimum = 0.0D; // value of the function to be minimised at the minimum private int prec = 4; // number of places to which double variables are truncated on output to text files private int field = 13; // field width on output to text files private boolean convStatus = false; // Status of minimisation on exiting minimisation method // = true - convergence criterion was met // = false - convergence criterion not met - current estimates returned private boolean supressNoConvergenceMessage = false; // if true - supress the print out of a message saying that convergence was not achieved. private int scaleOpt=0; // if = 0; no scaling of initial estimates // if = 1; initial simplex estimates scaled to unity // if = 2; initial estimates scaled by user provided values in scale[] // (default = 0) private double[] scale = null; // values to scale initial estimate (see scaleOpt above) private boolean penalty = false; // true if single parameter penalty function is included private boolean sumPenalty = false; // true if multiple parameter penalty function is included private int nConstraints = 0; // number of single parameter constraints private int nSumConstraints = 0; // number of multiple parameter constraints private Vector<Object> penalties = new Vector<Object>();// 3 method index, // number of single parameter constraints, // then repeated for each constraint: // penalty parameter index, // below or above constraint flag, // constraint boundary value private Vector<Object> sumPenalties = new Vector<Object>();// constraint method index, // number of multiple parameter constraints, // then repeated for each constraint: // number of parameters in summation // penalty parameter indices, // summation signs // below or above constraint flag, // constraint boundary value private int[] penaltyCheck = null; // = -1 values below the single constraint boundary not allowed // = +1 values above the single constraint boundary not allowed private int[] sumPenaltyCheck = null; // = -1 values below the multiple constraint boundary not allowed // = +1 values above the multiple constraint boundary not allowed private double penaltyWeight = 1.0e30; // weight for the penalty functions private int[] penaltyParam = null; // indices of paramaters subject to single parameter constraint private int[][] sumPenaltyParam = null; // indices of paramaters subject to multiple parameter constraint private int[][] sumPlusOrMinus = null; // sign before each parameter in multiple parameter summation private int[] sumPenaltyNumber = null; // number of paramaters in each multiple parameter constraint private double[] constraints = null; // single parameter constraint values private double[] sumConstraints = null; // multiple parameter constraint values private int constraintMethod = 0; // constraint method number // =0: cliff to the power two (only method at present) private int nMax = 3000; // Nelder and Mead simplex maximum number of iterations private int nIter = 0; // Nelder and Mead simplex number of iterations performed private int konvge = 3; // Nelder and Mead simplex number of restarts allowed private int kRestart = 0; // Nelder and Mead simplex number of restarts taken private double fTol = 1e-13; // Nelder and Mead simplex convergence tolerance private double rCoeff = 1.0D; // Nelder and Mead simplex reflection coefficient private double eCoeff = 2.0D; // Nelder and Mead simplex extension coefficient private double cCoeff = 0.5D; // Nelder and Mead simplex contraction coefficient private double[] startH = null; // Nelder and Mead simplex initial estimates private double[] step = null; // Nelder and Mead simplex step values private double dStep = 0.5D; // Nelder and Mead simplex default step value private int minTest = 0; // Nelder and Mead minimum test // = 0; tests simplex sd < fTol // allows options for further tests to be added later private double simplexSd = 0.0D; // simplex standard deviation //Constructors // Constructor with data with x as 2D array and weights provided public Minimisation(){ } // Supress the print out of a message saying that convergence was not achieved. public void supressNoConvergenceMessage(){ this.supressNoConvergenceMessage = true; } // Nelder and Mead Simplex minimisation public void nelderMead(MinimisationFunction g, double[] start, double[] step, double fTol, int nMax){ boolean testContract=false; // test whether a simplex contraction has been performed int np = start.length; // number of unknown parameters; this.nParam = np; this.convStatus = true; int nnp = np+1; // Number of simplex apices this.lastFunctValNoCnstrnt=0.0D; if(this.scaleOpt<2)this.scale = new double[np]; if(scaleOpt==2 && scale.length!=start.length)throw new IllegalArgumentException("scale array and initial estimate array are of different lengths"); if(step.length!=start.length)throw new IllegalArgumentException("step array length " + step.length + " and initial estimate array length " + start.length + " are of different"); // check for zero step sizes for(int i=0; i<np; i++)if(step[i]==0.0D)throw new IllegalArgumentException("step " + i+ " size is zero"); // set up arrays this.paramValue = new double[np]; this.startH = new double[np]; this.step = new double[np]; double[]pmin = new double[np]; //Nelder and Mead Pmin double[][] pp = new double[nnp][nnp]; //Nelder and Mead P double[] yy = new double[nnp]; //Nelder and Mead y double[] pbar = new double[nnp]; //Nelder and Mead P with bar superscript double[] pstar = new double[nnp]; //Nelder and Mead P* double[] p2star = new double[nnp]; //Nelder and Mead P** // Set any single parameter constraint parameters if(this.penalty){ Integer itemp = (Integer)this.penalties.elementAt(1); this.nConstraints = itemp.intValue(); this.penaltyParam = new int[this.nConstraints]; this.penaltyCheck = new int[this.nConstraints]; this.constraints = new double[this.nConstraints]; Double dtemp = null; int j=2; for(int i=0;i<this.nConstraints;i++){ itemp = (Integer)this.penalties.elementAt(j); this.penaltyParam[i] = itemp.intValue(); j++; itemp = (Integer)this.penalties.elementAt(j); this.penaltyCheck[i] = itemp.intValue(); j++; dtemp = (Double)this.penalties.elementAt(j); this.constraints[i] = dtemp.doubleValue(); j++; } } // Set any multiple parameter constraint parameters if(this.sumPenalty){ Integer itemp = (Integer)this.sumPenalties.elementAt(1); this.nSumConstraints = itemp.intValue(); this.sumPenaltyParam = new int[this.nSumConstraints][]; this.sumPlusOrMinus = new int[this.nSumConstraints][]; this.sumPenaltyCheck = new int[this.nSumConstraints]; this.sumPenaltyNumber = new int[this.nSumConstraints]; this.sumConstraints = new double[this.nSumConstraints]; int[] itempArray = null; Double dtemp = null; int j=2; for(int i=0;i<this.nSumConstraints;i++){ itemp = (Integer)this.sumPenalties.elementAt(j); this.sumPenaltyNumber[i] = itemp.intValue(); j++; itempArray = (int[])this.sumPenalties.elementAt(j); this.sumPenaltyParam[i] = itempArray; j++; itempArray = (int[])this.sumPenalties.elementAt(j); this.sumPlusOrMinus[i] = itempArray; j++; itemp = (Integer)this.sumPenalties.elementAt(j); this.sumPenaltyCheck[i] = itemp.intValue(); j++; dtemp = (Double)this.sumPenalties.elementAt(j); this.sumConstraints[i] = dtemp.doubleValue(); j++; } } // Store unscaled start values for(int i=0; i<np; i++)this.startH[i]=start[i]; // scale initial estimates and step sizes if(this.scaleOpt>0){ boolean testzero=false; for(int i=0; i<np; i++)if(start[i]==0.0D)testzero=true; if(testzero){ System.out.println("Neler and Mead Simplex: a start value of zero precludes scaling"); System.out.println("Regression performed without scaling"); this.scaleOpt=0; } } switch(this.scaleOpt){ case 0: for(int i=0; i<np; i++)scale[i]=1.0D; break; case 1: for(int i=0; i<np; i++){ scale[i]=1.0/start[i]; step[i]=step[i]/start[i]; start[i]=1.0D; } break; case 2: for(int i=0; i<np; i++){ step[i]*=scale[i]; start[i]*= scale[i]; } break; } // set class member values this.fTol=fTol; this.nMax=nMax; this.nIter=0; for(int i=0; i<np; i++){ this.step[i]=step[i]; this.scale[i]=scale[i]; } // initial simplex double sho=0.0D; for (int i=0; i<np; ++i){ sho=start[i]; pstar[i]=sho; p2star[i]=sho; pmin[i]=sho; } int jcount=this.konvge; // count of number of restarts still available for (int i=0; i<np; ++i){ pp[i][nnp-1]=start[i]; } yy[nnp-1]=this.functionValue(g, start); for (int j=0; j<np; ++j){ start[j]=start[j]+step[j]; for (int i=0; i<np; ++i)pp[i][j]=start[i]; yy[j]=this.functionValue(g, start); start[j]=start[j]-step[j]; } // loop over allowed iterations double ynewlo=0.0D; // current value lowest y double ystar = 0.0D; // Nelder and Mead y* double y2star = 0.0D; // Nelder and Mead y** double ylo = 0.0D; // Nelder and Mead y(low) double fMin; // function value at minimum // variables used in calculating the variance of the simplex at a putative minimum double curMin = 00D, sumnm = 0.0D, summnm = 0.0D, zn = 0.0D; int ilo=0; // index of low apex int ihi=0; // index of high apex int ln=0; // counter for a check on low and high apices boolean test = true; // test becomes false on reaching minimum while(test){ // Determine h ylo=yy[0]; ynewlo=ylo; ilo=0; ihi=0; for (int i=1; i<nnp; ++i){ if (yy[i]<ylo){ ylo=yy[i]; ilo=i; } if (yy[i]>ynewlo){ ynewlo=yy[i]; ihi=i; } } // Calculate pbar for (int i=0; i<np; ++i){ zn=0.0D; for (int j=0; j<nnp; ++j){ zn += pp[i][j]; } zn -= pp[i][ihi]; pbar[i] = zn/np; } // Calculate p=(1+alpha).pbar-alpha.ph {Reflection} for (int i=0; i<np; ++i)pstar[i]=(1.0 + this.rCoeff)*pbar[i]-this.rCoeff*pp[i][ihi]; // Calculate y* ystar=this.functionValue(g, pstar); ++this.nIter; // check for y*<yi if(ystar < ylo){ // Form p**=(1+gamma).p*-gamma.pbar {Extension} for (int i=0; i<np; ++i)p2star[i]=pstar[i]*(1.0D + this.eCoeff)-this.eCoeff*pbar[i]; // Calculate y** y2star=this.functionValue(g, p2star); ++this.nIter; if(y2star < ylo){ // Replace ph by p** for (int i=0; i<np; ++i)pp[i][ihi] = p2star[i]; yy[ihi] = y2star; } else{ //Replace ph by p* for (int i=0; i<np; ++i)pp[i][ihi]=pstar[i]; yy[ihi]=ystar; } } else{ // Check y*>yi, i!=h ln=0; for (int i=0; i<nnp; ++i)if (i!=ihi && ystar > yy[i]) ++ln; if (ln==np ){ // y*>= all yi; Check if y*>yh if(ystar<=yy[ihi]){ // Replace ph by p* for (int i=0; i<np; ++i)pp[i][ihi]=pstar[i]; yy[ihi]=ystar; } // Calculate p** =beta.ph+(1-beta)pbar {Contraction} for (int i=0; i<np; ++i)p2star[i]=this.cCoeff*pp[i][ihi] + (1.0 - this.cCoeff)*pbar[i]; // Calculate y** y2star=this.functionValue(g, p2star); ++this.nIter; // Check if y**>yh if(y2star>yy[ihi]){ //Replace all pi by (pi+pl)/2 for (int j=0; j<nnp; ++j){ for (int i=0; i<np; ++i){ pp[i][j]=0.5*(pp[i][j] + pp[i][ilo]); pmin[i]=pp[i][j]; } yy[j]=this.functionValue(g, pmin); } this.nIter += nnp; } else{ // Replace ph by p** for (int i=0; i<np; ++i)pp[i][ihi] = p2star[i]; yy[ihi] = y2star; } } else{ // replace ph by p* for (int i=0; i<np; ++i)pp[i][ihi]=pstar[i]; yy[ihi]=ystar; } } // test for convergence // calculte sd of simplex and minimum point sumnm=0.0; ynewlo=yy[0]; ilo=0; for (int i=0; i<nnp; ++i){ sumnm += yy[i]; if(ynewlo>yy[i]){ ynewlo=yy[i]; ilo=i; } } sumnm /= (double)(nnp); summnm=0.0; for (int i=0; i<nnp; ++i){ zn=yy[i]-sumnm; summnm += zn*zn; } curMin=Math.sqrt(summnm/np); // test simplex sd switch(this.minTest){ case 0: if(curMin<fTol)test=false; break; } this.minimum=ynewlo; if(!test){ // store parameter values for (int i=0; i<np; ++i)pmin[i]=pp[i][ilo]; yy[nnp-1]=ynewlo; // store simplex sd this.simplexSd = curMin; // test for restart --jcount; if(jcount>0){ test=true; for (int j=0; j<np; ++j){ pmin[j]=pmin[j]+step[j]; for (int i=0; i<np; ++i)pp[i][j]=pmin[i]; yy[j]=this.functionValue(g, pmin); pmin[j]=pmin[j]-step[j]; } } } if(test && this.nIter>this.nMax){ if(!this.supressNoConvergenceMessage){ System.out.println("Maximum iteration number reached, in Minimisation.simplex(...)"); System.out.println("without the convergence criterion being satisfied"); System.out.println("Current parameter estimates and sfunction value returned"); } this.convStatus = false; // store current estimates for (int i=0; i<np; ++i)pmin[i]=pp[i][ilo]; yy[nnp-1]=ynewlo; test=false; } } for (int i=0; i<np; ++i){ pmin[i] = pp[i][ihi]; paramValue[i] = pmin[i]/this.scale[i]; } this.minimum=ynewlo; this.kRestart=this.konvge-jcount; } // Nelder and Mead simplex // Default maximum iterations public void nelderMead(MinimisationFunction g, double[] start, double[] step, double fTol){ int nMaxx = this.nMax; this.nelderMead(g, start, step, fTol, nMaxx); } // Nelder and Mead simplex // Default tolerance public void nelderMead(MinimisationFunction g, double[] start, double[] step, int nMax){ double fToll = this.fTol; this.nelderMead(g, start, step, fToll, nMax); } // Nelder and Mead simplex // Default tolerance // Default maximum iterations public void nelderMead(MinimisationFunction g, double[] start, double[] step){ double fToll = this.fTol; int nMaxx = this.nMax; this.nelderMead(g, start, step, fToll, nMaxx); } // Nelder and Mead simplex // Default step option - all step[i] = dStep public void nelderMead(MinimisationFunction g, double[] start, double fTol, int nMax){ int n=start.length; double[] stepp = new double[n]; for(int i=0; i<n;i++)stepp[i]=this.dStep*start[i]; this.nelderMead(g, start, stepp, fTol, nMax); } // Nelder and Mead simplex // Default maximum iterations // Default step option - all step[i] = dStep public void nelderMead(MinimisationFunction g, double[] start, double fTol){ int n=start.length; int nMaxx = this.nMax; double[] stepp = new double[n]; for(int i=0; i<n;i++)stepp[i]=this.dStep*start[i]; this.nelderMead(g, start, stepp, fTol, nMaxx); } // Nelder and Mead simplex // Default tolerance // Default step option - all step[i] = dStep public void nelderMead(MinimisationFunction g, double[] start, int nMax){ int n=start.length; double fToll = this.fTol; double[] stepp = new double[n]; for(int i=0; i<n;i++)stepp[i]=this.dStep*start[i]; this.nelderMead(g, start, stepp, fToll, nMax); } // Nelder and Mead simplex // Default tolerance // Default maximum iterations // Default step option - all step[i] = dStep public void nelderMead(MinimisationFunction g, double[] start){ int n=start.length; int nMaxx = this.nMax; double fToll = this.fTol; double[] stepp = new double[n]; for(int i=0; i<n;i++)stepp[i]=this.dStep*start[i]; this.nelderMead(g, start, stepp, fToll, nMaxx); } // Calculate the function value for minimisation private double functionValue(MinimisationFunction g, double[] x){ double funcVal = -3.0D; double[] param = new double[this.nParam]; // rescale for(int i=0; i<this.nParam; i++)param[i]=x[i]/scale[i]; // single parameter penalty functions double tempFunctVal = this.lastFunctValNoCnstrnt; boolean test=true; if(this.penalty){ int k=0; for(int i=0; i<this.nConstraints; i++){ k = this.penaltyParam[i]; if(this.penaltyCheck[i]==-1){ if(param[k]<constraints[i]){ funcVal = tempFunctVal + this.penaltyWeight*Fmath.square(param[k]-constraints[i]); test=false; } } if(this.penaltyCheck[i]==1){ if(param[k]>constraints[i]){ funcVal = tempFunctVal + this.penaltyWeight*Fmath.square(param[k]-constraints[i]); test=false; } } } } // multiple parameter penalty functions if(this.sumPenalty){ int kk = 0; int pSign = 0; double sumPenaltySum = 0.0D; for(int i=0; i<this.nSumConstraints; i++){ for(int j=0; j<this.sumPenaltyNumber[i]; j++){ kk = this.sumPenaltyParam[i][j]; pSign = this.sumPlusOrMinus[i][j]; sumPenaltySum += param[kk]*pSign; } if(this.sumPenaltyCheck[i]==-1){ if(sumPenaltySum<sumConstraints[i]){ funcVal = tempFunctVal + this.penaltyWeight*Fmath.square(sumPenaltySum-sumConstraints[i]); test=false; } } if(this.sumPenaltyCheck[i]==1){ if(sumPenaltySum>sumConstraints[i]){ funcVal = tempFunctVal + this.penaltyWeight*Fmath.square(sumPenaltySum-sumConstraints[i]); test=false; } } } } if(test){ funcVal = g.function(param); this.lastFunctValNoCnstrnt = funcVal; } return funcVal; } // add a single parameter constraint boundary for the minimisation public void addConstraint(int paramIndex, int conDir, double constraint){ this.penalty=true; // First element reserved for method number if other methods than 'cliff' are added later if(this.penalties.isEmpty())this.penalties.addElement(new Integer(this.constraintMethod)); // add constraint if(penalties.size()==1){ this.penalties.addElement(new Integer(1)); } else{ int nPC = ((Integer)this.penalties.elementAt(1)).intValue(); nPC++; this.penalties.setElementAt(new Integer(nPC), 1); } this.penalties.addElement(new Integer(paramIndex)); this.penalties.addElement(new Integer(conDir)); this.penalties.addElement(new Double(constraint)); } // add a multiple parameter constraint boundary for the minimisation public void addConstraint(int[] paramIndices, int[] plusOrMinus, int conDir, double constraint){ int nCon = paramIndices.length; int nPorM = plusOrMinus.length; if(nCon!=nPorM)throw new IllegalArgumentException("num of parameters, " + nCon + ", does not equal number of parameter signs, " + nPorM); this.sumPenalty=true; // First element reserved for method number if other methods than 'cliff' are added later if(this.sumPenalties.isEmpty())this.sumPenalties.addElement(new Integer(this.constraintMethod)); // add constraint if(sumPenalties.size()==1){ this.sumPenalties.addElement(new Integer(1)); } else{ int nPC = ((Integer)this.sumPenalties.elementAt(1)).intValue(); nPC++; this.sumPenalties.setElementAt(new Integer(nPC), 1); } this.sumPenalties.addElement(new Integer(nCon)); this.sumPenalties.addElement(paramIndices); this.sumPenalties.addElement(plusOrMinus); this.sumPenalties.addElement(new Integer(conDir)); this.sumPenalties.addElement(new Double(constraint)); } // Set constraint method public void setConstraintMethod(int conMeth){ this.constraintMethod = conMeth; if(!this.penalties.isEmpty())this.penalties.setElementAt(new Integer(this.constraintMethod),0); } // remove all constraint boundaries for the minimisation public void removeConstraints(){ // check if single parameter constraints already set if(!this.penalties.isEmpty()){ int m=this.penalties.size(); // remove single parameter constraints for(int i=m-1; i>=0; i--){ this.penalties.removeElementAt(i); } } this.penalty = false; this.nConstraints = 0; // check if mutiple parameter constraints already set if(!this.sumPenalties.isEmpty()){ int m=this.sumPenalties.size(); // remove multiple parameter constraints for(int i=m-1; i>=0; i--){ this.sumPenalties.removeElementAt(i); } } this.sumPenalty = false; this.nSumConstraints = 0; } // Print the results of the minimisation // File name provided // prec = truncation precision public void print(String filename, int prec){ this.prec = prec; this.print(filename); } // Print the results of the minimisation // No file name provided // prec = truncation precision public void print(int prec){ this.prec = prec; String filename="MinimisationOutput.txt"; this.print(filename); } // Print the results of the minimisation // File name provided // prec = truncation precision public void print(String filename){ if(filename.indexOf('.')==-1)filename = filename+".txt"; FileOutput fout = new FileOutput(filename, 'n'); fout.dateAndTimeln(filename); fout.println(" "); fout.println("Simplex minimisation, using the method of Nelder and Mead,"); fout.println("of the function y = f(c[0], c[1], c[2] . . .)"); this.paraName = new String[this.nParam]; for(int i=0;i<this.nParam;i++)this.paraName[i]="c["+i+"]"; fout.println(); if(!this.convStatus){ fout.println("Convergence criterion was not satisfied"); fout.println("The following results are the current estimates on exiting the minimisation method"); fout.println(); } fout.println("Value of parameters at the minimum"); fout.println(" "); fout.printtab(" ", this.field); fout.printtab("Value at", this.field); fout.printtab("Initial", this.field); fout.println("Initial"); fout.printtab(" ", this.field); fout.printtab("mimium", this.field); fout.printtab("estimate", this.field); fout.println("step"); for(int i=0; i<this.nParam; i++){ fout.printtab(this.paraName[i], this.field); fout.printtab(Fmath.truncate(paramValue[i],this.prec), this.field); fout.printtab(Fmath.truncate(this.startH[i],this.prec), this.field); fout.println(Fmath.truncate(this.step[i],this.prec)); } fout.println(); fout.println(" "); fout.printtab("Number of paramaters"); fout.println(this.nParam); fout.printtab("Number of iterations taken"); fout.println(this.nIter); fout.printtab("Maximum number of iterations allowed"); fout.println(this.nMax); fout.printtab("Number of restarts taken"); fout.println(this.kRestart); fout.printtab("Maximum number of restarts allowed"); fout.println(this.konvge); fout.printtab("Standard deviation of the simplex at the minimum"); fout.println(Fmath.truncate(this.simplexSd, this.prec)); fout.printtab("Convergence tolerance"); fout.println(this.fTol); switch(minTest){ case 0: if(this.convStatus){ fout.println("simplex sd < the tolerance"); } else{ fout.println("NOTE!!! simplex sd > the tolerance"); } break; } fout.println(); fout.println("End of file"); fout.close(); } // Print the results of the minimisation // No file name provided public void print(){ String filename="MinimisationOutput.txt"; this.print(filename); } // Get the minimisation status // true if convergence was achieved // false if convergence not achieved before maximum number of iterations // current values then returned public boolean getConvStatus(){ return this.convStatus; } // Reset scaling factors (scaleOpt 0 and 1, see below for scaleOpt 2) public void setScale(int n){ if(n<0 || n>1)throw new IllegalArgumentException("The argument must be 0 (no scaling) 1(initial estimates all scaled to unity) or the array of scaling factors"); this.scaleOpt=n; } // Reset scaling factors (scaleOpt 2, see above for scaleOpt 0 and 1) public void setScale(double[] sc){ this.scale=sc; this.scaleOpt=2; } // Get scaling factors public double[] getScale(){ return this.scale; } // Reset the minimisation convergence test option public void setMinTest(int n){ if(n<0 || n>1)throw new IllegalArgumentException("minTest must be 0 or 1"); this.minTest=n; } // Get the minimisation convergence test option public int getMinTest(){ return this.minTest; } // Get the simplex sd at the minimum public double getSimplexSd(){ return this.simplexSd; } // Get the values of the parameters at the minimum public double[] getParamValues(){ return this.paramValue; } // Get the function value at minimum public double getMinimum(){ return this.minimum; } // Get the number of iterations in Nelder and Mead public int getNiter(){ return this.nIter; } // Set the maximum number of iterations allowed in Nelder and Mead public void setNmax(int nmax){ this.nMax = nmax; } // Get the maximum number of iterations allowed in Nelder and Mead public int getNmax(){ return this.nMax; } // Get the number of restarts in Nelder and Mead public int getNrestarts(){ return this.kRestart; } // Set the maximum number of restarts allowed in Nelder and Mead public void setNrestartsMax(int nrs){ this.konvge = nrs; } // Get the maximum number of restarts allowed in Nelder amd Mead public int getNrestartsMax(){ return this.konvge; } // Reset the Nelder and Mead reflection coefficient [alpha] public void setNMreflect(double refl){ this.rCoeff = refl; } // Get the Nelder and Mead reflection coefficient [alpha] public double getNMreflect(){ return this.rCoeff; } // Reset the Nelder and Mead extension coefficient [beta] public void setNMextend(double ext){ this.eCoeff = ext; } // Get the Nelder and Mead extension coefficient [beta] public double getNMextend(){ return this.eCoeff; } // Reset the Nelder and Mead contraction coefficient [gamma] public void setNMcontract(double con){ this.cCoeff = con; } // Get the Nelder and Mead contraction coefficient [gamma] public double getNMcontract(){ return cCoeff; } // Set the minimisation tolerance public void setTolerance(double tol){ this.fTol = tol; } // Get the minimisation tolerance public double getTolerance(){ return this.fTol; } }
Java
import java.io.File; import java.lang.Math; import java.util.*; /** * This class computes the ionization percentage * simple model with r^-2 dependence * * */ public class SurvivalProbability { public static double Ms = 2 * Math.pow(10,30); public static double G = 6.67 * Math.pow(10,-11); public static double AU = 1.5* Math.pow(10,11); public double v0, q, beta0, r0, r1, theta0, theta1, tempTheta1, thetaPrime, mu; // psi = angle swept out , p = Angular Momentum / mass, v0 = vinfinity of Moebius/Rucinski // see Wu & Judge 1979 APJ public SurvivalProbability(double lossRate1AU, double _mu) { beta0 = lossRate1AU; //average loss rate at 1AU mu = _mu; } /** * THis routine computes the fraction of ions that will be left given point / trajectory * NOTE: parameters of distribution must be given in coordinates * relative to inflow direction * * Taken from Judge&Wu 1979 */ public double compute(double r, double theta, double vr, double vt) { //System.out.println("trying lossRate.compute"); // Wu & Judge 1979 APJ - - - // this stuff is to figure out theta prime, the angle swept out by // particle on way in from infinity q = Math.sqrt((1-mu)*G*Ms/r); v0 = Math.sqrt((vr*vr)+(vt*vt)-(2*q*q)); r0 = r*vt*vt/(q*q); r1 = q*q*r/(v0*v0); theta0 = Math.PI/2 + Math.atan(-v0*vt/(q*q)); // pi/2 < theta0 < pi if (((theta0)>Math.PI)|((theta0)<Math.PI/2)) { System.out.println("theta0 out of range!! (sp) " + theta0); } tempTheta1 = Math.atan(Math.sqrt(r0/r1 + 2*r0/r - r0*r0/(r*r)) / (r0/r - 1)); // but we want 0 < theta1 < pi ... if (tempTheta1 >= 0) theta1 = tempTheta1; else theta1 = tempTheta1 + Math.PI; if ((theta1>Math.PI)|(theta1<0)) System.out.println("theta1 out of range!! (sp)"); if (vr > 0) { thetaPrime = theta0 + theta1; } else if (vr < 0) { thetaPrime = theta0 - theta1; } else if (vr == 0) { thetaPrime = theta0; } if (thetaPrime<0) System.out.println("thetaPrime out of range!!"); //System.out.println("almost done sp.comute"); // we have thetaPrime- now it's just an exponential return Math.exp(-beta0*AU*AU*thetaPrime/Math.abs(r*vt)); } /** * This one gives the survival probablility, given the angle swept out in it's orbit * * calculation of this angle must be done elsewhere in this routine. * */ public double compute(double thetaPrime, double L) { return 0; //return Math.exp(-bet0*AU*AU*tetaPrime/ } /* * For testing only */ public static void main(String [] args) { SurvivalProbability sp = new SurvivalProbability(.1,0.0); System.out.println(""+sp.compute(2*AU, 2, 100000, 100000)); } }
Java
import java.util.StringTokenizer; import java.util.Random; public class Benford2 { public file inFile, outFile; public int[][] digitTallies; //public double[] factors = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; // last one placeholder public int skipLines, dataColumn; public StringTokenizer st; public Random r; public Benford2(String[] args) { r=new Random(); try { skipLines = Integer.parseInt(args[1]); dataColumn = Integer.parseInt(args[2]); digitTallies = new int[10][2]; o("datacolumn: " + dataColumn + " skiplines: " + skipLines ); // set all digit tallies to zero for (int i=0; i<2; i++) { for (int j=0; j<10; j++) { digitTallies[j][i]=0; } } inFile = new file(args[0]); inFile.initRead(); String line = ""; for (int i=0; i<skipLines; i++) line=inFile.readLine(); o("made it here 2"); double max = -Double.MAX_VALUE; double min = Double.MAX_VALUE; // lets go through and find max and min of the data double avg = 0.0; int index = 0; while ((line=inFile.readLine())!=null) { String numString = ""; st = new StringTokenizer(line); for (int j=0; j<dataColumn; j++) { numString = st.nextToken(); } double theNumber = Double.parseDouble(numString); if (theNumber!=-1) { if (theNumber<min) min=theNumber; if (theNumber>max) max=theNumber; avg+=theNumber; index++; } } avg/=(double)index; inFile.closeRead(); o("max: " + max); o("min: " + min); o("avg: " + avg); inFile = new file(args[0]); inFile.initRead(); for (int i=0; i<skipLines; i++) line=inFile.readLine(); while ((line=inFile.readLine())!=null) { String numString = ""; st = new StringTokenizer(line); for (int j=0; j<dataColumn; j++) { numString = st.nextToken(); } double theNumber = Double.parseDouble(numString); if (theNumber != -1) { //o("numstring: " + numString); for (int i=0; i<2; i++) { if (i==1) theNumber = (theNumber-avg); if (theNumber!=0.0) { //o("thenumber " + theNumber); int theDigit = getDigit(theNumber); digitTallies[theDigit][i]++; } } } } o("made it here 3"); // we have the tallies -- lets generate a nice data file outFile = new file("benford_results2.txt"); outFile.initWrite(false); for (int j=0; j<10; j++) { line = ""; for (int i=0; i<2; i++) { line += digitTallies[j][i]+"\t"; } outFile.write(line+"\n"); } outFile.closeWrite(); // done? } catch (Exception e) { o("Format: java Benford filename.ext numLinesToSkip dataColumn_start_with_1"); e.printStackTrace(); } } public int getDigit(double d) { if (d<0) d*=-1.0; while (d<=1.0) d*=10.0; while (d>=10.0) d/=10.0; return (int)(Math.floor(d)); } public static final void main(String[] args) { Benford2 b = new Benford2(args); } public static void o(String s) { System.out.println(s); } }
Java
import java.util.StringTokenizer; import java.util.Date; import java.util.*; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Ephemeris info here! * Position of Earth, pointing of IBEX, position of IBEX based on DOY input * * Orbit info also */ public class EarthIBEX { // read these in J2000 coordinates public double[] rx,ry,rz; public double[] vx,vy,vz; public Date[] orbStarts, orbEnds; public Date[] dates; public HelioVector[] pointings; public Date startDate; public long currentDate; public file inFile; public file orbFile = new file("orbit_times.txt"); public StringTokenizer st; public int nn = 24*120; // total amount of entries in earth info file, 1 per hour for 120 days public int norbs = 120; // number of orbits in orbit times file public TimeZone tz = TimeZone.getTimeZone("UTC"); public Calendar c; public SimpleDateFormat sdf; public String line; public EarthIBEX(int year) { // read the orbit times orbStarts = new Date[norbs]; orbEnds = new Date[norbs]; orbFile.initRead(); String pattern = "yyyy/MM:dd:HH:ss z"; sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); //String test = "2010/06:26:17:44"; //try { // Date dt = sdf.parse(test + " UTC"); // System.out.println("should be 2010/06:26:17:44 " + dt.toGMTString()); //} //catch (Exception e) { // e.printStackTrace(); //} try { line = orbFile.readLine(); // header for (int i=0; i<norbs; i++) { line = orbFile.readLine(); st = new StringTokenizer(line); String garbage = st.nextToken(); orbStarts[i] = sdf.parse(st.nextToken()+ " UTC"); System.out.println("read orbit date: " + i + " = " +orbStarts[i].toGMTString()); } orbFile.closeRead(); } catch (Exception e) { e.printStackTrace(); } // done reading orbit times // now lets read the pointing information from the ECLIPJ2000 idl output pointings = new HelioVector[100]; System.out.println(" trying to read pointing information "); file f = new file("ibex_point.txt"); f.initRead(); line = f.readLine(); line = f.readLine(); // throw away header for (int i=6; i<93; i++) { line = f.readLine(); st = new StringTokenizer(line); int oo = (int)Double.parseDouble(st.nextToken()); double phi = Double.parseDouble(st.nextToken()); double theta = Double.parseDouble(st.nextToken()); System.out.println("pointing for " + oo + " " + phi + " " + theta); pointings[oo]=new HelioVector(HelioVector.SPHERICAL,1.0,phi*Math.PI/180.0,theta*Math.PI/180.0); } f.closeRead(); // done reading pointing info!! // read the earth pos. and velocity data from the file made by IDL rx = new double[nn]; ry = new double[nn]; rz = new double[nn]; vx = new double[nn]; vy = new double[nn]; vz = new double[nn]; dates = new Date[nn]; if (year==2009) { inFile = new file("earth_pos_09.txt"); c = Calendar.getInstance(); c.setTimeZone(tz); c.set(Calendar.YEAR, 2009); c.set(Calendar.MONTH, 1); c.set(Calendar.DAY_OF_YEAR, 1); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); startDate = c.getTime(); System.out.println("start date: " + startDate.toString()); currentDate = startDate.getTime(); } if (year==2010) { inFile = new file("earth_pos_10.txt"); c = Calendar.getInstance(); c.setTimeZone(tz); c.set(Calendar.YEAR, 2010); c.set(Calendar.MONTH, 1); c.set(Calendar.DAY_OF_YEAR, 1); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); startDate = c.getTime(); System.out.println("start date: " + startDate.toString()); currentDate = startDate.getTime(); } inFile.initRead(); line = ""; // skip the header for (int i=0; i<2; i++) line=inFile.readLine(); // read all the data // these are hourly datas for (int i=0; i<nn; i++) { dates[i]=new Date(currentDate); line = inFile.readLine(); // garbage line = inFile.readLine(); // r st = new StringTokenizer(line); rx[i]=Double.parseDouble(st.nextToken()); ry[i]=Double.parseDouble(st.nextToken()); rz[i]=Double.parseDouble(st.nextToken()); line = inFile.readLine(); // v st = new StringTokenizer(line); vx[i]=Double.parseDouble(st.nextToken()); vy[i]=Double.parseDouble(st.nextToken()); vz[i]=Double.parseDouble(st.nextToken()); currentDate+=3600*1000; } } /** * Return the Earth's position on that day in Heliospheric coords * * could be much faster with a hashtable but this is not our limiting routine * so we do it the hack way */ public HelioVector getEarthPosition(Date d) { long dd = d.getTime(); int ourIndex = 0; for (int i=0; i<nn; i++) { if (dd<dates[i].getTime()) { ourIndex=i; i=nn; } } return new HelioVector(HelioVector.CARTESIAN, rx[ourIndex]*1000, ry[ourIndex]*1000, rz[ourIndex]*1000); } /** * Return the point direction of IBEX spin axis. This should be toward the sun * */ public HelioVector getIbexPointing(Date d) { int orbit1 = getOrbitNumber(d); return getIbexPointing(orbit1); } /** * Return the point direction of IBEX spin axis. This should be toward the sun * */ public HelioVector getIbexPointing(int orb) { if (orb<6 | orb>93) { System.out.println(" IbexPointing not available!! "); return new HelioVector(); } return pointings[orb]; } /** * Return the velocity vector of Earth moving about the sun * */ public HelioVector getEarthVelocity(Date d) { long dd = d.getTime(); int ourIndex = 0; for (int i=0; i<nn; i++) { if (dd<dates[i].getTime()) { ourIndex=i; i=nn; } } return new HelioVector(HelioVector.CARTESIAN, vx[ourIndex]*1000, vy[ourIndex]*1000, vz[ourIndex]*1000); } /** * Get the orbit number for a date * */ public int getOrbitNumber(Date d) { long dd = d.getTime(); int ourIndex = 0; for (int i=0; i<nn-1; i++) { if (dd>orbStarts[i].getTime() & dd<orbStarts[i+1].getTime()) { ourIndex=i+1; i=nn; } } //System.out.println(" orbit number for " +d.toString()+" is " + ourIndex); return ourIndex; } public Date getDate(double doy, int year) { int day = (int)doy; double hour = (doy-day)*24.0; //System.out.println("doy: " + doy + " day+ " + day + " hour " + hour); c = Calendar.getInstance(); c.setTimeZone(tz); c.set(Calendar.YEAR, year); c.set(Calendar.DAY_OF_YEAR, (int)doy); c.set(Calendar.HOUR_OF_DAY, (int)(hour)); c.set(Calendar.MINUTE, getMinute(hour)); c.set(Calendar.SECOND, getSecond(hour)); //352.97629630 2008 = 913591566 Date d = c.getTime(); return d; } public static int getMinute(double hour) { double minutes = hour*60.0; // subtract hours double iHour = (double)(int)(hour)*60.0; minutes = minutes - iHour; //System.out.println("hour " + hour + " minutes" + minutes); return (int)(minutes); } public static int getSecond(double hour) { double seconds = hour*3600.0; double iHour = (int)(hour)*3600.0; double iMinute = getMinute(hour)*60.0; // subtract hours and minutes seconds = seconds - iHour - iMinute; //System.out.println("rem: "+ rem); return (int)(seconds); } /** * For testing */ public static final void main(String[] args) { try { String pattern = "yyyy/MM:dd:HH:ss z"; SimpleDateFormat sdf2 = new SimpleDateFormat(pattern); sdf2.setLenient(false); EarthIBEX ei = new EarthIBEX(2009); Date d = sdf2.parse("2009/01:31:23:44 UTC"); System.out.println("earth pos: " + ei.getEarthPosition(d).toAuString()); System.out.println("earth vel: " + ei.getEarthVelocity(d).toKmString()); System.out.println("ibex point: " + ei.getIbexPointing(d).toString()); // now we output position and pointing (longitude j2000 ecliptic) (day 10 - 120) file ff = new file("fig_1_2009.txt"); ff.initWrite(false); double step = 1.0/24.0; // step by 1 hour for (double doy=10.0; doy<120; doy+=step) { HelioVector pos = ei.getEarthPosition(ei.getDate(doy,2009)); HelioVector point = ei.getIbexPointing(ei.getDate(doy,2009)); ff.write(doy + "\t" + pos.getPhi()*180.0/Math.PI + "\t" + point.getPhi()*180.0/Math.PI+"\n"); } ff.closeWrite(); // test get date System.out.println(ei.getDate(2.1, 2009).toString()); System.out.println(ei.getDate(2.15, 2010).toString()); System.out.println(ei.getDate(3.5, 2010).toString()); System.out.println(ei.getDate(2.6, 2010).toString()); System.out.println(ei.getDate(2.7, 2010).toString()); System.out.println(ei.getDate(2.8, 2010).toString()); } catch(Exception e) { e.printStackTrace(); } } } /* We need to keep track of Earth's Vernal Equinox and use J2000 Ecliptic Coordinates!!! March 2009 20 11:44 2010 20 17:32 2011 20 23:21 2012 20 05:14 2013 20 11:02 2014 20 16:57 2015 20 22:45 2016 20 04:30 2017 20 10:28 This gives the location of the current epoch zero ecliptic longitude.. However /* /* Earth peri and aphelion perihelion aphelion 2007 January 3 20:00 July 7 00:00 2008 January 3 00:00 July 4 08:00 2009 January 4 15:00 July 4 02:00 2010 January 3 00:00 July 6 12:00 2011 January 3 19:00 July 4 15:00 2012 January 5 01:00 July 5 04:00 2013 January 2 05:00 July 5 15:00 2014 January 4 12:00 July 4 00:00 2015 January 4 07:00 July 6 20:00 2016 January 2 23:00 July 4 16:00 2017 January 4 14:00 July 3 20:00 2018 January 3 06:00 July 6 17:00 2019 January 3 05:00 July 4 22:00 2020 January 5 08:00 July 4 12:00 */
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating that this parameter CANNOT be null. */ @Retention(RetentionPolicy.SOURCE) @Target( { ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD } ) public @interface NonNull { }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating the visibility of the method has been * relaxed so that we can access it in unit tests. */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) public @interface PublicForTesting { }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating that this parameter can be null. */ @Retention(RetentionPolicy.SOURCE) @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE }) public @interface Null { }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. */ public abstract class GCMBaseIntentService extends IntentService { public static final String TAG = "GCMBaseIntentService"; // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour // token used to check intent origin private static final String TOKEN = Long.toBinaryString(sRandom.nextLong()); private static final String EXTRA_TOKEN = "token"; /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); Log.v(TAG, "Intent service name: " + name); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); Log.v(TAG, "Received deleted messages " + "notification: " + total); onDeletedMessages(context, total); } catch (NumberFormatException e) { Log.e(TAG, "GCM returned invalid number of " + "deleted messages: " + sTotal); } } } else { // application is not using the latest GCM library Log.e(TAG, "Received unknown special message: " + messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { // make sure intent was generated by this class, not by a // malicious app. Log.e(TAG, "Received invalid token: " + token); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { Log.v(TAG, "Releasing wakelock"); sWakeLock.release(); } else { // should never happen during normal workflow Log.e(TAG, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } Log.v(TAG, "Acquiring wakelock"); sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; Log.d(TAG, "Registration error: " + error); // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.putExtra(EXTRA_TOKEN, TOKEN); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { Log.d(TAG, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. */ public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ private static GCMBroadcastReceiver sRetryReceiver; private static String sRetryReceiverClassName; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value GCMConstants#PERMISSION_GCM_INTENTS} permission. * <li>The {@link BroadcastReceiver}(s) handles the 3 GCM intents * ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE}, * {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}, * and {@value GCMConstants#INTENT_FROM_GCM_LIBRARY_RETRY}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length); } Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Found " + receivers.size() + " receivers for action " + action); } // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); Log.v(TAG, "Registering app " + context.getPackageName() + " of senders " + flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { Log.v(TAG, "Unregistering receiver"); context.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; } } static void internalUnregister(Context context) { Log.v(TAG, "Unregistering app " + context.getPackageName()); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); context.startService(intent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen Log.e(TAG, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { Log.e(TAG, "Could not create instance of " + sRetryReceiverClassName + ". Using " + GCMBroadcastReceiver.class.getName() + " directly."); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); // must use a permission that is defined on manifest for sure String permission = category + ".permission.C2D_MESSAGE"; Log.v(TAG, "Registering receiver"); context.registerReceiver(sRetryReceiver, filter, permission, null); } } /** * Sets the name of the retry receiver class. */ static void setRetryReceiverClassName(String className) { Log.v(TAG, "Setting the name of retry receiver class to " + className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { Log.v(TAG, "App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id"); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); Log.v(TAG, "Saving regId on app version " + appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putBoolean(PROPERTY_ON_SERVER, flag); // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; Log.v(TAG, "Setting registeredOnServer status as " + flag + " until " + new Timestamp(expirationTime)); editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { Log.d(TAG, "resetting backoff for " + context.getPackageName()); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. */ public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to indicate the sender * account (a Google email) that owns the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to get the application * id. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * an error when the registration fails. See constants starting with ERROR_ * for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the {@link #INTENT_FROM_GCM_MESSAGE} intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@link #VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. */ public class GCMBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "GCMBroadcastReceiver"; private static boolean mReceiverSet = false; @Override public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; String myClass = getClass().getName(); if (!myClass.equals(GCMBroadcastReceiver.class.getName())) { GCMRegistrar.setRetryReceiverClassName(myClass); } } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.rdrrlabs.example.timer2app.R; /** * An activity representing a single Event detail screen. This activity is only * used on handset devices. On tablet-size devices, item details are presented * side-by-side with a list of items in a {@link EventListActivity}. * <p> * This activity is mostly just a 'shell' activity containing nothing more than * a {@link EventDetailFragment}. */ public class EventDetailActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_detail); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. Bundle arguments = new Bundle(); arguments.putString(EventDetailFragment.ARG_ITEM_ID, getIntent() .getStringExtra(EventDetailFragment.ARG_ITEM_ID)); EventDetailFragment fragment = new EventDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.event_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpTo(this, new Intent(this, EventListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.rdrrlabs.example.timer2app.R; public class MainActivityImpl extends FragmentActivity { @Override protected void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_intro); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.GCMHelper; import com.rdrrlabs.example.timer2app.core.GlobalContext; /** * An activity representing a list of Events. This activity has different * presentations for handset and tablet-size devices. On handsets, the activity * presents a list of items, which when touched, lead to a * {@link EventDetailActivity} representing item details. On tablets, the * activity presents the list of items and item details side-by-side using two * vertical panes. * <p> * The activity makes heavy use of fragments. The list of items is a * {@link EventListFragment} and the item details (if present) is a * {@link EventDetailFragment}. * <p> * This activity also implements the required * {@link EventListFragment.Callbacks} interface to listen for item selections. */ public class EventListActivity extends FragmentActivity implements EventListFragment.Callbacks { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean mTwoPane; private GCMHelper mGCMMixing; public EventListActivity() { mGCMMixing = new GCMHelper(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GlobalContext.getContext().onAppStart(this); setContentView(R.layout.activity_event_list); setupActionBar(); if (findViewById(R.id.event_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the // 'activated' state when touched. ((EventListFragment) getSupportFragmentManager().findFragmentById( R.id.event_list)).setActivateOnItemClick(true); } // TODO: If exposing deep links into your app, handle intents here. //--RM DEBUG--mGCMMixing.onCreate(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (MainActivity.sStartClass != this.getClass()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // // TODO: If Settings has multiple levels, Up should navigate up // that hierarchy. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** * Callback method from {@link EventListFragment.Callbacks} indicating that * the item with the given ID was selected. */ @Override public void onItemSelected(String id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle arguments = new Bundle(); arguments.putString(EventDetailFragment.ARG_ITEM_ID, id); EventDetailFragment fragment = new EventDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.event_detail_container, fragment) .commit(); } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, EventDetailActivity.class); detailIntent.putExtra(EventDetailFragment.ARG_ITEM_ID, id); startActivity(detailIntent); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.RingtonePreference; import android.text.TextUtils; import android.view.MenuItem; import android.support.v4.app.NavUtils; import java.util.List; import com.rdrrlabs.example.timer2app.R; /** * A {@link PreferenceActivity} that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * <p> * See <a href="http://developer.android.com/design/patterns/settings.html"> * Android Design: Settings</a> for design guidelines and the <a * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide</a> for more information on developing a Settings UI. */ public class SettingsActivity extends PreferenceActivity { /** * Determines whether to always show the simplified settings UI, where * settings are presented in a single list. When false, settings are shown * as a master/detail two-pane view on tablets. When true, a single pane is * shown on tablets. */ private static final boolean ALWAYS_SIMPLE_PREFS = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // // TODO: If Settings has multiple levels, Up should navigate up // that hierarchy. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } /** * Shows the simplified settings UI if the device configuration if the * device configuration dictates that a simplified, single-pane UI should be * shown. */ @SuppressWarnings("deprecation") private void setupSimplePreferencesScreen() { if (!isSimplePreferences(this)) { return; } // In the simplified UI, fragments are not used at all and we instead // use the older PreferenceActivity APIs. // Add 'general' preferences. addPreferencesFromResource(R.xml.pref_general); // Add 'notifications' preferences, and a corresponding header. PreferenceCategory fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_notifications); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_notification); // Add 'data and sync' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_data_sync); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_data_sync); // Bind the summaries of EditText/List/Dialog/Ringtone preferences to // their values. When their values change, their summaries are updated // to reflect the new value, per the Android Design guidelines. bindPreferenceSummaryToValue(findPreference("example_text")); bindPreferenceSummaryToValue(findPreference("example_list")); bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); bindPreferenceSummaryToValue(findPreference("sync_frequency")); } /** {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isXLargeTablet(this) && !isSimplePreferences(this); } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Determines whether the simplified settings UI should be shown. This is * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device * doesn't have newer APIs like {@link PreferenceFragment}, or the device * doesn't have an extra-large screen. In these cases, a single-pane * "simplified" settings UI should be shown. */ private static boolean isSimplePreferences(Context context) { return ALWAYS_SIMPLE_PREFS || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || !isXLargeTablet(context); } /** {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<Header> target) { if (!isSimplePreferences(this)) { loadHeadersFromResource(R.xml.pref_headers, target); } } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null); } else if (preference instanceof RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent); } else { Ringtone ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)); if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null); } else { // Set the summary to reflect the new ringtone display // name. String name = ringtone .getTitle(preference.getContext()); preference.setSummary(name); } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange( preference, PreferenceManager.getDefaultSharedPreferences( preference.getContext()).getString( preference.getKey(), "")); } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class GeneralPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_general); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")); bindPreferenceSummaryToValue(findPreference("example_list")); } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class NotificationPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_notification); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class DataSyncPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_data_sync); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.rdrrlabs.example.timer2app.R; public class IntroFragment extends Fragment { private TextView mTextSignInfo; private Button mBtnSignInOut; private Button mBtnEvents; private Button mBtnSettings; @Override public void onCreate(Bundle state) { super.onCreate(state); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle state) { View root = inflater.inflate(R.layout.fragment_intro, container, false); mTextSignInfo = (TextView) root.findViewById(R.id.textAccountName); mBtnSignInOut = (Button) root.findViewById(R.id.btnSignInOut); mBtnEvents = (Button) root.findViewById(R.id.btnEvents); mBtnSettings = (Button) root.findViewById(R.id.btnSettings); mBtnSignInOut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SignInDialog.showSignInDialog(getActivity()); } }); mBtnEvents.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickProfiles(); } }); mBtnSettings.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickSettings(); } }); return root; } @Override public void onResume() { super.onResume(); mTextSignInfo.setText(R.string.intro__not_logged); } protected void onClickProfiles() { startActivity(new Intent(getActivity(), EventListActivity.class)); } protected void onClickSettings() { startActivity(new Intent(getActivity(), SettingsActivity.class)); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import java.util.ArrayList; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.rdrrlabs.example.liblabs.app.Bus; import com.rdrrlabs.example.liblabs.app.Bus.Register; import com.rdrrlabs.example.liblabs.app.IBusListener; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.BusConstants; import com.rdrrlabs.example.timer2app.core.GAEHelper; import com.rdrrlabs.example.timer2app.core.GAEHelper.State; import com.rdrrlabs.example.timer2app.core.GlobalContext; public class SignInDialog extends DialogFragment implements IBusListener { @SuppressWarnings("unused") private static final String TAG = SignInDialog.class.getSimpleName(); static void showSignInDialog(FragmentActivity activity) { // based on http://developer.android.com/reference/android/app/DialogFragment.html FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog"); if (prev != null) ft.remove(prev); ft.addToBackStack(null); SignInDialog df = new SignInDialog(); df.show(ft, "dialog"); } // ----------- private static final int RESULT_SYNC_SETTINGS = Activity.RESULT_FIRST_USER + 1; private static final int MODE_SELECT_ACCOUNT = 0; private static final int MODE_AUTH_TOKEN = 1; private Button mBtnNext; private TextView mTextExplanation; private ListView mListView; private ProgressBar mProgress; private AccountManager mAccMan; private int mMode = MODE_SELECT_ACCOUNT; private OnAccountsUpdateListener mAccListener; private final State mState = new State(); private final ArrayList<AccountWrapper> mAccountWrappers = new ArrayList<SignInDialog.AccountWrapper>(); private Register<SignInDialog> mBusReg; @Override public void onCreate(Bundle state) { super.onCreate(state); mAccMan = AccountManager.get(getActivity()); mBusReg = Bus.register(this, GlobalContext.getContext().getBus()); if (mAccListener == null) { mAccListener = new OnAccountsUpdateListener() { @Override public void onAccountsUpdated(Account[] accounts) { updateAccountList(); } }; } mAccMan.addOnAccountsUpdatedListener(mAccListener, null/*handler*/, false/*updateImmediately*/); } @Override public void onDestroy() { super.onDestroy(); if (mAccListener != null) mAccMan.removeOnAccountsUpdatedListener(mAccListener); mAccMan = null; mAccountWrappers.clear(); mBusReg.deregister(); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle state) { View root = inflater.inflate(R.layout.fragment_signin, container, false); getDialog().setTitle("Sign In"); mBtnNext = (Button) root.findViewById(R.id.btnNext); mTextExplanation = (TextView) root.findViewById(R.id.txtExplanation); mListView = (ListView) root.findViewById(R.id.listAccounts); mListView.setEmptyView(root.findViewById(android.R.id.empty)); mProgress = (ProgressBar) root.findViewById(R.id.progressBar1); displayList(true); Button btnCancel = (Button) root.findViewById(R.id.btnCancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Dismiss the dialog. SignInDialog.this.dismiss(); } }); Button btnCreate = (Button) root.findViewById(android.R.id.empty); btnCreate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT); //-- doesn't seem to work. //-- i.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { "com.google" }); startActivityForResult(i, RESULT_SYNC_SETTINGS); } }); mBtnNext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Object o = v.getTag(); if (o instanceof AccountWrapper) { authenticateAccount(((AccountWrapper) o).getAccount()); } else { mListView.clearChoices(); } } }); setupAccountList(root); mBtnNext.setEnabled(false); return root; } private void displayList(boolean displayList) { mListView.setVisibility(displayList ? View.VISIBLE : View.GONE); mProgress.setVisibility(displayList ? View.GONE : View.VISIBLE); mProgress.setIndeterminate(!displayList); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_SYNC_SETTINGS) { updateAccountList(); } } private void setupAccountList(View root) { mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object o = parent.getItemAtPosition(position); if (o instanceof AccountWrapper) { mBtnNext.setEnabled(true); mBtnNext.setTag(o); } } }); updateAccountList(); } private void updateAccountList() { if (mMode != MODE_SELECT_ACCOUNT) return; if (mListView == null) return; // this should not happen. mAccountWrappers.clear(); for (Account account : mAccMan.getAccountsByType("com.google")) { mAccountWrappers.add(new AccountWrapper(account)); } if (mAccountWrappers.isEmpty()) { mTextExplanation.setText("No Google accounts available."); //FIXME res string } else { mTextExplanation.setText("Select a Google account:"); //FIXME res string } ArrayAdapter<AccountWrapper> adapter = new ArrayAdapter<AccountWrapper>( getActivity(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, mAccountWrappers) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); return view; } }; mListView.setAdapter(adapter); mListView.clearChoices(); } /** Adapts an Account to be a list entry by providing its adequate string description. */ private static class AccountWrapper { private final Account mAccount; public AccountWrapper(Account account) { mAccount = account; } public Account getAccount() { return mAccount; } @Override public String toString() { return mAccount.name; } } //----- private void authenticateAccount(Account account) { mMode = MODE_AUTH_TOKEN; mBtnNext.setEnabled(false); displayList(false); mTextExplanation.setText("Authenticating. This may take a few minutes."); GAEHelper ah = GlobalContext.getContext().getGAEHelper(); mState.mAccountName = account.name; ah.getAuthToken(getActivity(), account, mState); } @Override public void onBusMessage(int what, Object object) { if (what == BusConstants.GAE_ACCOUNT_STATE_CHANGED && object == mState) { mTextExplanation.post(new Runnable() { @Override public void run() { String info = mState.mDetail; if (info == null) { switch(mState.mState) { case State.NO_ACCOUNT: // This shouldn't really happen here. info = "Please select an account to sign-in."; break; case State.INVALID_ACCOUNT: // This shouldn't really happen here. info = "Invalid account, please select another account to sign-in."; break; case State.AUTH_TOKEN_FAILED: case State.AUTH_COOKIE_FAILED: info = "Failed to authenticate. Try again or change account."; break; case State.SUCCESS: info = "Success"; break; default: info = ""; } } mTextExplanation.setText(info); if (mState.mState != State.PENDING) { mProgress.setIndeterminate(false); mProgress.setProgress(mProgress.getMax()); } if (mState.mState == State.SUCCESS) { GAEHelper ah = GlobalContext.getContext().getGAEHelper(); ah.useAccount(getActivity(), mState.mAccountName, mState.mGAECookie); // Auto-close mTextExplanation.postDelayed(new Runnable() { @Override public void run() { SignInDialog.this.dismiss(); } }, 250 /*ms*/); } } }); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.dummy.DummyContent; /** * A fragment representing a single Event detail screen. This fragment is either * contained in a {@link EventListActivity} in two-pane mode (on tablets) or a * {@link EventDetailActivity} on handsets. */ public class EventDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; /** * The dummy content this fragment is presenting. */ private DummyContent.DummyItem mItem; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public EventDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. mItem = DummyContent.ITEM_MAP.get(getArguments().getString( ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_event_detail, container, false); // Show the dummy content as text in a TextView. if (mItem != null) { ((TextView) rootView.findViewById(R.id.event_detail)) .setText(mItem.content); } return rootView; } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.SpannableString; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.rdrrlabs.example.liblabs.app.Bus; import com.rdrrlabs.example.liblabs.app.Bus.Register; import com.rdrrlabs.example.liblabs.app.IBusListener; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.BusConstants; import com.rdrrlabs.example.timer2app.core.GAEHelper; import com.rdrrlabs.example.timer2app.core.GlobalContext; import com.rdrrlabs.example.timer2app.core.GAEHelper.State; import com.rdrrlabs.example.timer2app.dummy.DummyContent; /** * A list fragment representing a list of Events. This fragment also supports * tablet devices by allowing list items to be given an 'activated' state upon * selection. This helps indicate which item is currently being viewed in a * {@link EventDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class EventListFragment extends ListFragment // FIXME use Timeriffic ListFragment2 implements IBusListener { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; private Button mBtnSignIn; private TextView mTextSignName; private TextView mTextSignInfo; private TextView mLinkSignIn; private Register<EventListFragment> mBusReg; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(String id); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(String id) { } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public EventListFragment() { } @Override public void onCreate(Bundle state) { super.onCreate(state); mBusReg = Bus.register(this, GlobalContext.getContext().getBus()); // TODO: replace with a real list adapter. setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(), android.R.layout.simple_list_item_1, //FIXME API 11 simple_list_item_activated_1 android.R.id.text1, DummyContent.ITEMS)); } @Override public void onDestroy() { super.onDestroy(); mBusReg.deregister(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { //-- Disabled: do not call super since it creates a view root hierarchy that //-- we do not need. //-- return super.onCreateView(inflater, container, state); View root = inflater.inflate(R.layout.fragment_event_master, null /*root*/, false /*attachToRoot*/); // On start, the list view should have the focus, if possible. final View listView = root.findViewById(android.R.id.list); listView.requestFocus(); mTextSignName = (TextView) root.findViewById(R.id.textAccountName); mTextSignInfo = (TextView) root.findViewById(R.id.textInfo); mBtnSignIn = (Button) root.findViewById(R.id.btnSignIn); if (mBtnSignIn != null) { mBtnSignIn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SignInDialog.showSignInDialog(getActivity()); } }); } mLinkSignIn = (TextView) root.findViewById(R.id.linkSignIn); if (mLinkSignIn != null) { // get current text CharSequence t = mLinkSignIn.getText(); // make it a spannable SpannableString s = new SpannableString(t); // create a clickable span ClickableSpan cs = new ClickableSpan() { @Override public void onClick(View widget) { listView.requestFocus(); // TODO change focus only on success SignInDialog.showSignInDialog(getActivity()); } }; // attach the span to the spannable s.setSpan(cs, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mLinkSignIn.setMovementMethod(LinkMovementMethod.getInstance()); mLinkSignIn.setText(s); } // Start the GAE check 250ms after startup mTextSignName.postDelayed(new Runnable() { @Override public void run() { GAEHelper ah = GlobalContext.getContext().getGAEHelper(); updateSignInfo(ah); ah.onActivityStartedCheck(getActivity()); } }, 250 /*ms*/); return root; } @Override public void onViewCreated(View view, Bundle state) { super.onViewCreated(view, state); // Restore the previously serialized activated item position. if (state != null && state.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(state.getInt(STATE_ACTIVATED_POSITION)); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException( "Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. getListView().setChoiceMode( activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } // --------------- @Override public void onBusMessage(int what, Object object) { final GAEHelper ah = GlobalContext.getContext().getGAEHelper(); if (what == BusConstants.GAE_ACCOUNT_STATE_CHANGED && object == ah.getCurrentState()) { mTextSignName.post(new Runnable() { @Override public void run() { updateSignInfo(ah); } }); } } private void updateSignInfo(final GAEHelper ah) { State state = ah.getCurrentState(); String name = state.mAccountName; if (name != null) { mTextSignName.setText(name); } else { mTextSignName.setText(getString(R.string.intro__not_logged)); } String info = state.mDetail; if (info == null) { switch(state.mState) { case State.NO_ACCOUNT: info = "Please <select an account> to sign-in."; break; case State.INVALID_ACCOUNT: info = "Invalid account, please <select another account> to sign-in."; break; case State.AUTH_TOKEN_FAILED: case State.AUTH_COOKIE_FAILED: info = "Failed to authenticate. <Try again> or <change account>."; break; default: info = ""; } } mTextSignInfo.setText(info); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { public static Class<?> sStartClass = null; @Override protected void onCreate(Bundle state) { super.onCreate(state); // Check prefs to decide on which to start with sStartClass = MainActivityImpl.class; sStartClass = EventListActivity.class; Intent i = new Intent(this, sStartClass); startActivity(i); finish(); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.pub.ui.EventListActivity; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; //----------------------------------------------- /** * GCM Intent Service -- this class MUST remain at the root of the package. */ public class GCMIntentServiceImpl extends GCMBaseIntentService { private static final String TAG = GCMIntentServiceImpl.class.getSimpleName(); public static final String SENDER_ID = "265050972334"; // FIXME store in CoreStrings public GCMIntentServiceImpl() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); GCMServerUtilities.displayMessage(context, "gcm_registered"); //--getString(R.string.gcm_registered)); GCMServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); GCMServerUtilities.displayMessage(context, "gcm_unregistered"); //--getString(R.string.gcm_unregistered)); if (GCMRegistrar.isRegisteredOnServer(context)) { GCMServerUtilities.unregister(context, registrationId); } else { // This callback results from the call to unregister made on // GCMServerUtilities when the registration to the server failed. Log.i(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String message = "gcm_message"; //--getString(R.string.gcm_message); GCMServerUtilities.displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = "gcm_deleted"; //-- getString(R.string.gcm_deleted, total); GCMServerUtilities.displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); GCMServerUtilities.displayMessage(context, "gcm_error: " + errorId); //--getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); GCMServerUtilities.displayMessage(context, "gcm_recoverable_error: " + errorId); //--getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ @SuppressWarnings("deprecation") private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, EventListActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rdrrlabs.example.timer2app.gcm; import com.google.android.gcm.GCMRegistrar; import com.rdrrlabs.example.timer2app.core.GAEHelper; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class GCMServerUtilities { private static final String TAG = GCMServerUtilities.class.getSimpleName(); //--public static final String URL_AH_SERVER = "http://10.0.2.2:8080"; // FIXME detect for emulator (by Build Model=sdk) public static final String URL_SERVER_HTTP = GAEHelper.sGAEBaseURL; //-- "http://myserver.appspot.com" ; // FIXME detect for emulator (by Build Model=sdk) public static final String URL_SERVER_HTTPS = URL_SERVER_HTTP.replace("http", "https"); private static final String URL_TIMER_GCM = URL_SERVER_HTTP + "/timer_gcm"; // FIXME detect for emulator (by Build Model=sdk) private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * * @return whether the registration succeeded or not. */ static boolean register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = URL_TIMER_GCM + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, "registering " + i); //-- context.getString(R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = "server_registered"; //--context.getString(R.string.server_registered); displayMessage(context, message); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } String message = "server_register_error"; //--context.getString(R.string.server_register_error, MAX_ATTEMPTS); displayMessage(context, message); return false; } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = URL_TIMER_GCM + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = "server_unregistered"; //--context.getString(R.string.server_unregistered); displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = "server_unregister_error"; //--context.getString(R.string.server_unregister_error, e.getMessage()); displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(BACKOFF_MILLI_SECONDS); // RM added conn.setReadTimeout(BACKOFF_MILLI_SECONDS); // RM added conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Toast.makeText(context, "GCM: " + message, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.dummy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helper class for providing sample content for user interfaces created by * Android template wizards. * <p> * TODO: Replace all uses of this class before publishing your app. */ public class DummyContent { /** * An array of sample (dummy) items. */ public static List<DummyItem> ITEMS = new ArrayList<DummyItem>(); /** * A map of sample (dummy) items, by ID. */ public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>(); static { // Add fake items. for (int i = 0; i < 20; i++) { addItem(new DummyItem("" + i, "Event " + i)); } } private static void addItem(DummyItem item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } /** * A dummy item representing a piece of content. */ public static class DummyItem { public String id; public String content; public DummyItem(String id, String content) { this.id = id; this.content = content; } @Override public String toString() { return content; } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; //----------------------------------------------- public abstract class BusConstants { public final static int GAE_ACCOUNT_STATE_CHANGED = 1; }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import com.rdrrlabs.example.annotations.NonNull; import com.rdrrlabs.example.liblabs.utils.Utils; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.TimeUnit; //----------------------------------------------- /** * Holds our helper to connect our GAE instance. * It keeps the context of the current user account to use, the current * app engine cookie and can do authenticated POSTs. */ public class GAEHelper { private static final String TAG = GAEHelper.class.getSimpleName(); private static final boolean DEBUG = true; private static final boolean USE_DEV_SERVER = Utils.isEmulator(); /** Pref to store GAE account name. Type: String. */ private static final String PREFS_KEY_GAE_ACCOUNT = "gae_account"; /** Base GAE url without a final / */ public static final String sGAEBaseURL = USE_DEV_SERVER ? "http://10.0.2.2:8080" : "http://myserver.appspot.com"; // TODO change private static final String sGAEAuthCookie = USE_DEV_SERVER ? "dev_appserver_login" : "ACSID"; private static final GAEHelper sInstance = new GAEHelper(); private CookieManager mCookieMan; private final State mCurrentState = new State(); public static GAEHelper getInstance() { return sInstance; } private GAEHelper() { // Setup our own cookie manager mCookieMan = new CookieManager(); CookieHandler.setDefault(mCookieMan); } @NonNull public State getCurrentState() { return mCurrentState; } public CookieManager getCookieManager() { return mCookieMan; } /** * Initialization when main activity gets started. * If the account name isn't present, try to read it from prefs. * If there is no auth cookie, try to get one. * * @param activity The calling activity. Needed by the account manager to ask for * user permission to access App Engine, if not already granted. */ public void onActivityStartedCheck(Activity activity) { if (DEBUG) Log.d(TAG, String.format("onActivityStartedCheck: %s", mCurrentState)); if (mCurrentState.mAccountName == null) { // Read initial name from prefs GlobalContext gc = GlobalContext.getContext(); PrefsStorage ps = gc.getPrefsStorage(); mCurrentState.mAccountName = ps.getString(PREFS_KEY_GAE_ACCOUNT, null); mCurrentState.setState( mCurrentState.mAccountName == null ? State.NO_ACCOUNT : State.SUCCESS); } if (mCurrentState.mAccountName != null && mCurrentState.mGAECookie == null) { Account account = validateAccount(activity, mCurrentState); if (account != null) { getAuthToken(activity, account, mCurrentState); } } } /** * Validate that the account exists in the Account Manager. * If there is no account name, sets the state to no-account and returns null. * If found, it returns the {@link Account} and sets the state to success. * If not found, it returns null and sets the state to invalid-account. * <p/> * This should typically be followed by a call to {@link #getAuthToken}. * * @return The {@link Account} found matching the {@link State} account name, * or null if not found. */ public Account validateAccount(Activity activity, State state) { if (DEBUG) Log.d(TAG, String.format("validateAccount: %s", state)); state.setState(State.PENDING, "Validating account."); if (state.mAccountName == null || state.mAccountName.isEmpty()) { state.setState(State.NO_ACCOUNT); return null; } AccountManager am = AccountManager.get(activity); for (Account account : am.getAccountsByType("com.google")) { if (mCurrentState.mAccountName.equals(account.name)) { state.setState(State.SUCCESS); return account; } } state.setState(State.INVALID_ACCOUNT); return null; } public void getAuthToken(final Activity activity, Account account, final State state) { if (DEBUG) Log.d(TAG, String.format("getAuthToken: %s", state)); state.setState(State.PENDING, "Authenticating..."); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { // Runs from the main thread @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle result = future.getResult(120, TimeUnit.SECONDS); GetCookieTask t = new GetCookieTask(state); t.execute(result.getString(AccountManager.KEY_AUTHTOKEN)); } catch (OperationCanceledException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Authentication cancelled."); } catch (AuthenticatorException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Authentication failed."); } catch (IOException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Network error."); } } }; AccountManager am = AccountManager.get(activity); am.getAuthToken( account, "ah", // authTokenType, null, // options, activity, // activity, callback , null); // handler } private class GetCookieTask extends AsyncTask<String, Void, Void> { private final State mState; public GetCookieTask(State state) { mState = state; } @Override protected Void doInBackground(String... params) { String authToken = params[0]; if (DEBUG) Log.d(TAG, String.format("getAuthCookie: %s", mState)); mState.setState(State.PENDING, "Authenticating with server..."); // Note: The _ah/login request must match the protocol we'll use later, // either http or https. Cookies are ACSID vs SACSID and aren't interchangeable. String urlStr = sGAEBaseURL + "/_ah/login?"; if (USE_DEV_SERVER) { urlStr += "email=test@example.com&action=Login&"; } urlStr += "continue=" + sGAEBaseURL + "/&auth=" + authToken; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(120*1000); conn.setReadTimeout(5*1000); conn.setInstanceFollowRedirects(false); conn.connect(); int status = conn.getResponseCode(); // We expect a 302 redirect on success. if (status != 302) { if (DEBUG) Log.d(TAG, "GetCookieTask invalid HTTP status " + status); mState.setState(State.AUTH_COOKIE_FAILED); return null; } CookieStore st = mCookieMan.getCookieStore(); for (HttpCookie cookie : st.getCookies()) { if (sGAEAuthCookie.equals(cookie.getName())) { // Success, we found our cookie mState.mGAECookie = (HttpCookie) cookie.clone(); mState.setState(State.SUCCESS); return null; } } // If we reach here, we didn't get the right cookie. if (DEBUG) Log.d(TAG, "GetCookieTask -- cookie not found"); mState.setState(State.AUTH_COOKIE_FAILED, "Authentication not supported by server."); } catch (Throwable tr) { // Probably a network error if (DEBUG) Log.d(TAG, "GetCookieTask", tr); mState.setState(State.AUTH_COOKIE_FAILED, "Network error."); } return null; } } /** * A new account has been choosen, with its cookie to be used for this session. * Save the info in the app prefs. * * Notify bus listeners that the account name has changed, if it did. * * @param context An android context * @param accountName The account name. * @param cookie The new auth cookie. */ public void useAccount(Context context, String accountName, HttpCookie cookie) { if (DEBUG) { Log.d(TAG, "useAccount: " + accountName + ", cookie: " + cookie.toString()); } mCurrentState.mGAECookie = cookie; if ((accountName == null && mCurrentState.mAccountName != null) || !accountName.equals(mCurrentState.mAccountName)) { mCurrentState.mAccountName = accountName; GlobalContext gc = GlobalContext.getContext(); PrefsStorage ps = gc.getPrefsStorage(); ps.putString(PREFS_KEY_GAE_ACCOUNT, accountName); ps.beginWriteAsync(context); } mCurrentState.setState(State.SUCCESS); } private static void busSend(int code, State state) { GlobalContext.getContext().getBus().send(code, state); } public static class State { public static final int PENDING = 0; public static final int NO_ACCOUNT = 10; public static final int INVALID_ACCOUNT = 11; public static final int AUTH_TOKEN_FAILED = 12; public static final int AUTH_COOKIE_FAILED = 13; public static final int SUCCESS = 42; public int mState; public String mDetail; public String mAccountName; public HttpCookie mGAECookie; /** Change the state and send a bus notification if it has actually changed. */ public void setState(int state) { this.setState(state, null); } /** Change the state and send a bus notification if it has actually changed. */ public void setState(int state, String detail) { if (mState != state || (detail == null && mDetail != null) || (detail != null && !detail.equals(mDetail))) { mState = state; mDetail = detail; busSend(BusConstants.GAE_ACCOUNT_STATE_CHANGED, this); } } @Override public String toString() { return "<GAE.State [" + mState + "] name: " + mAccountName + ", cookie: " + mGAECookie + ", detail: " + mDetail + ">"; } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import com.rdrrlabs.example.liblabs.app.Bus; import android.content.Context; //----------------------------------------------- /** A singleton using shared structures of the app. * <p/> * This singleton must NEVER store an object that directly or indirectly holds * an Android context such as an activity or a fragment. * */ public class GlobalContext { private static GlobalContext sContext = new GlobalContext(); // TODO change override during test private final Bus mBus = new Bus(); private final PrefsStorage mPrefsStorage = new PrefsStorage("prefs"); private final GAEHelper mGAEHelper = GAEHelper.getInstance(); private boolean mAppStartDone; private GlobalContext() { } public static GlobalContext getContext() { return sContext; } public PrefsStorage getPrefsStorage() { return mPrefsStorage; } public GAEHelper getGAEHelper() { return mGAEHelper; } public Bus getBus() { return mBus; } /** Initialize a few things once. */ public void onAppStart(Context androidContext) { if (!mAppStartDone) { mAppStartDone = true; // Reads the pref storage async, since eventually we'll need it. mPrefsStorage.beginReadAsync(androidContext); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import android.app.Activity; import android.util.Log; import com.rdrrlabs.example.timer2app.GCMIntentService; import com.google.android.gcm.GCMRegistrar; //----------------------------------------------- public class GCMHelper { private static final String TAG = GCMHelper.class.getSimpleName(); private final Activity mActivity; public GCMHelper(Activity activity) { mActivity = activity; } public void onCreate() { GCMRegistrar.checkDevice(mActivity); GCMRegistrar.checkManifest(mActivity); final String regId = GCMRegistrar.getRegistrationId(mActivity); if (regId.equals("")) { GCMRegistrar.register(mActivity, GCMIntentService.SENDER_ID); } else { Log.v(TAG, "Already registered"); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import com.rdrrlabs.example.liblabs.prefs.BasePrefsStorage; //----------------------------------------------- public class PrefsStorage extends BasePrefsStorage { public PrefsStorage(String filename) { super(filename); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app; import com.rdrrlabs.example.timer2app.gcm.GCMIntentServiceImpl; //----------------------------------------------- /** * GCM Intent Service -- this class MUST remain at the root of the package. */ public class GCMIntentService extends GCMIntentServiceImpl { public GCMIntentService() { super(); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import android.util.Log; import com.rdrrlabs.example.annotations.Null; import com.rdrrlabs.example.liblabs.utils.Utils; //----------------------------------------------- /** * A simplistic message-based notifier. * <p/> * In its most basic implementation, the "bus" sends messages. * Listeners listen to the messages and are notified when a message is sent. * <p/> * Messages are objects (typically strings or integers). * * Messages are not queued like a Handler: posted messages are sent right away and deliver * to whoever is currently listening. There is no fancy thread handling like in a Handler * either: messages are posted and received on the sender's thread. If you want the facilities * of a Handler then use a Handler. * <p/> * Listeners can choose to listen to any kind of message, specific message * objects or just a given Class of message (e.g. Strings, or whatever custom type.) */ public class Bus { private static final String TAG = Bus.class.getSimpleName(); private static final boolean DEBUG = Utils.isEmulator(); public static final int NO_WHAT = -1; /** * Listeners. A map filter-type => listener list. * Access to the map must synchronized on the map itself. * Access to the lists must synchronized on the lists themselves. */ private final HashMap<Class<?>, List<BusAdapter>> mListeners = new HashMap<Class<?>, List<BusAdapter>>(); public Bus() { } // ----- public void send(int what) { this.send(what, null); } public void send(Object object) { this.send(NO_WHAT, null); } public void send(int what, Object object) { Class<?> filter = object == null ? Void.class : object.getClass(); if (DEBUG) { Log.d(TAG, String.format("Bus.send: what: %d, obj: %s", what, object)); } List<BusAdapter> list0 = null; // list of listeners with null. List<BusAdapter> list1 = null; // list of typed listeners, including Void.class synchronized (mListeners) { list0 = mListeners.get(null); list1 = mListeners.get(filter); } sendInternal(list0, what, object); if (list1 != list0) { sendInternal(list1, what, object); } } private void sendInternal(List<BusAdapter> list, int what, Object object) { if (list != null) { synchronized (list) { for (BusAdapter listener : list) { try { listener.onBusMessage(what, object); } catch(Throwable tr) { Log.d(TAG, listener.getClass().getSimpleName() + ".onBusMessage failed", tr); } } } } } // ----- public BusAdapter addListener(BusAdapter listener) { if (listener == null) return listener; Class<?> filter = listener.getClassFilter(); List<BusAdapter> list = null; synchronized (mListeners) { list = mListeners.get(filter); if (list == null) { list = new LinkedList<BusAdapter>(); mListeners.put(filter, list); } } synchronized (list) { if (!list.contains(listener)) { list.add(listener); } } return listener; } public BusAdapter removeListener(BusAdapter listener) { if (listener == null) return listener; Class<?> filter = listener.getClassFilter(); List<BusAdapter> list = null; synchronized (mListeners) { list = mListeners.get(filter); } if (list != null) { synchronized (list) { list.remove(listener); } } return listener; } // ----- /** * Registers a BusListener with no class filter. * * @param receiver A receiver object implement {@link IBusListener}. * @param bus The {@link Bus} instance on which to register. * @return A new {@link Register} object; caller must call {@link Register#deregister()} later. */ public static <B extends IBusListener> Register<B> register(B receiver, Bus bus) { return register(null, receiver, bus); } /** * Registers a BusListener with a specific class filter. * * @param classFilter The object class to filter. Can be null to receive everything (any kind * of object, including null) or the {@link Void} class to filter on message with null * objects. * @param receiver A receiver object implement {@link IBusListener}. * @param bus The {@link Bus} instance on which to register. * @return A new {@link Register} object; caller must call {@link Register#deregister()} later. */ public static <B extends IBusListener> Register<B> register(@Null Class<?> classFilter, B receiver, Bus bus) { Register<B> m = new Register<B>(classFilter, receiver, bus); bus.addListener(m); return m; } /** * Helper to add/remove a bus listener on an existing class. * Usage: * <pre> * public class MyActivity extends Activity implements BusListener { * private Bus.Register<MyActivity> mBusReg; * public void onCreate(...) { * mBusReg = Bus.Register.register(this, globals.getBus()); * } * public void onDestroy() { * mBusReg.deregister(); * } * public void onBusMessage(int what, Object object) { ... } * public void foo() { * mBusReg.getBus().send(42); * } * } * </pre> * * This class only keeps weak references on the listener (typically an activity) and the bus. */ public static class Register<T extends IBusListener> extends BusAdapter { private WeakReference<Bus> mBusRef; private WeakReference<T> mReceiverRef; private Register(@Null Class<?> classFilter, T receiver, Bus bus) { mReceiverRef = new WeakReference<T>(receiver); mBusRef = new WeakReference<Bus>(bus); } @Null public Bus getBus() { return mBusRef.get(); } public void deregister() { if (mBusRef == null) return; Bus bus = mBusRef.get(); if (bus != null) bus.removeListener(this); mBusRef.clear(); mBusRef = null; if (mReceiverRef != null) { synchronized (this) { mReceiverRef.clear(); mReceiverRef = null; } } } @Override public void onBusMessage(int what, Object object) { T receiver = null; synchronized (this) { if (mReceiverRef != null) receiver = mReceiverRef.get(); } if (receiver != null) receiver.onBusMessage(what, object); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import com.rdrrlabs.example.annotations.Null; //----------------------------------------------- public abstract class BusAdapter implements com.rdrrlabs.example.liblabs.app.IBusListener { private final Class<?> mClassFilter; /** Creates a bus listener that receives all type of data. */ public BusAdapter() { this(null); } /** * Creates a bus listener that receives only object data of that type. * * @param classFilter The object class to filter. Can be null to receive everything. */ public BusAdapter(@Null Class<?> classFilter) { mClassFilter = classFilter; } public Class<?> getClassFilter() { return mClassFilter; } @Override public abstract void onBusMessage(int what, Object object); }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import com.rdrrlabs.example.annotations.Null; //----------------------------------------------- /** * Listen to {@link Bus} notifications. */ public interface IBusListener { /** * Callback invoked when a message matching the {@link BusAdapter} class filter * is received. * <p/> * Users must be aware that there is no thread specification -- the callback is * invoked on the sender's thread, which may or may not be the UI thread. * * @param what The integer "what" portion of the message. {@link Bus#NO_WHAT} if not specified. * @param object A potentially null message object. */ public abstract void onBusMessage(int what, @Null Object object); }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import android.util.Log; public class Utils { public static final String TAG = Utils.class.getSimpleName(); public static final boolean DEBUG = true; private static int sSdkInt = 0; /** Returns current API level. The API level value is then cached. */ @SuppressWarnings("deprecation") public static int getApiLevel() { if (sSdkInt > 0) return sSdkInt; // Build.SDK_INT is only in API 4 and we're still compatible with API 3 try { int n = Integer.parseInt(Build.VERSION.SDK); sSdkInt = n; return n; } catch (Exception e) { Log.d(TAG, "Failed to parse Build.VERSION.SDK=" + Build.VERSION.SDK, e); return 3; } } /** Returns true if current API Level is equal or greater than {@code minApiLevel}. */ public static boolean checkMinApiLevel(int minApiLevel) { return getApiLevel() >= minApiLevel; } /** * Indicates whether the current platform reasonably looks like an emulator. * This could break if the emulator reported different values or if a custom * ROM was providing these values (e.g. one based on an emulator image.) */ public static boolean isEmulator() { // On the emulator: // Build.BRAND = generic // Build.DEVICE = generic // Build.MODEL = sdk // Build.PRODUCT = sdk or google_sdk (for the addon) // Build.MANUFACTURER = unknown -- API 4+ // Build.HARDWARE = goldfish -- API 8+ String b = Build.BRAND; String d = Build.DEVICE; String p = Build.PRODUCT; String h = null; //--ApiHelper.get().Build_HARDWARE(); if ("generic".equals(b) && "generic".equals(d) && (h == null || "goldfish".equals(h)) && ("sdk".equals(p) || "google_sdk".equals(p))) { Log.w(TAG, "Emulator Detected. Stats disabled."); return true; } return false; } // My debug key signature is // 30820255308201bea00302010202044a88ef41300d06092a864886f70d0101050500306f310b30090603550406130255533110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e310d300b060355040a130452616c663110300e060355040b1307556e6b6e6f776e311b301906035504031312416e64726f69642052616c66204465627567301e170d3039303831373035343834395a170d3337303130323035343834395a306f310b30090603550406130255533110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e310d300b060355040a130452616c663110300e060355040b1307556e6b6e6f776e311b301906035504031312416e64726f69642052616c6620446562756730819f300d06092a864886f70d010101050003818d0030818902818100aafbaa519b7a0cb0accb5cc37b6138b99bde072a952b291fb90cdb067e1f7c1980aac7152aee0304da0eb400d10dd7fef09e9e13f07ea09a3e500c86ba9fb93b5792003817cfd1639a9bffd085aa479521593d5ea516836e2eec5312c9044bafed29cf1339d4960ed96968fcbafd7ddd921b140b0de62f0576afa912789462630203010001300d06092a864886f70d01010505000381810027e6f99c4ef8c02d4dde0d1ec92bad13ea9ce85609e5d5e042e9800aca1e8472563be4fe6463ed1e12a72ff2780599d79ce03130925e345a196316b7ccab9b8941979c41e56c233d1a0a17f342cc74474615e7fde1340aac02c850b6119a708774973487250cd9d32e8c23ec8ed99d0a7ff07046c3ba53d387aa07805f6a8389 // hash = 1746973045 0x6820b175 // (to update this, empty first field and look in the log for the printed signature to match.) private static final String DEBUG_KEY_START = "30820255308201bea00302010202044"; private static final String DEBUG_KEY_END = "e8c23ec8ed99d0a7ff07046c3ba53d387aa07805f6a8389"; /** * Returns true if the current app is signed with my specific debug key. */ public static boolean isUsingDebugKey(Context context) { try { PackageInfo pi = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_SIGNATURES); Signature[] sigs = pi.signatures; if (sigs == null || sigs.length != 1) { return false; } Signature sig = pi.signatures[0]; String str = sig.toCharsString(); if (DEBUG_KEY_START.length() == 0) { int hash = sig.hashCode(); Log.d(TAG, String.format("Sig [%08x]: %s", hash, str)); } else if (str != null && str.startsWith(DEBUG_KEY_START) && str.endsWith(DEBUG_KEY_END)) { Log.d(TAG, "Using Debug Key"); return true; } } catch (Exception e) { Log.e(TAG, "UsingKey exception: " + e.toString()); } return false; } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; import android.util.Log; //----------------------------------------------- public abstract class ThreadLoop extends Thread { public static final String TAG = ThreadLoop.class.getSimpleName(); protected boolean mContinue = true; public ThreadLoop(String name) { super(name); } public ThreadLoop(String name, int priorityBoost) { this(name); this.setPriority(Thread.currentThread().getPriority() + priorityBoost); } /** * Called by the main activity when it's time to stop. * <p/> * Requirement: this MUST be called from another thread, not from GLBaseThread. * The activity thread is supposed to called this. * <p/> * This lets the thread complete it's render loop and wait for it * to fully stop using a join. */ public void threadWaitForStop() { // Not synchronized. Setting one boolean is assumed to be atomic. mContinue = false; try { assert Thread.currentThread() != this; threadWakeUp(); join(); } catch (InterruptedException e) { Log.e(TAG, "Thread.join failed", e); } } /** * Starts the thread if it wasn't already started. * Does nothing if started. */ @Override public synchronized void start() { if (getState() == State.NEW) { super.start(); } } // ----------------- /** * Base implementation of the thread loop. * Derived classes can re-implement this, as long as they follow this * contract: * - the loop must continue whilst mContinue is true * - each iteration must invoke threadRunIteration() when not paused. * - [deprecated] the loop must pause when mIsPaused is true by first * waiting for the pause barrier and do a waitForALongTime() until * mIsPaused is released. */ @Override public void run() { try { threadStartRun(); while (mContinue) { threadRunIteration(); } } catch (Exception e) { Log.e(TAG, "Run-Loop Exception, stopping thread", e); } finally { threadEndRun(); } } protected void threadStartRun() {} /** * Performs one iteration of the thread run loop. * Implementations must implement this and not throw exceptions from it. */ protected abstract void threadRunIteration(); protected void threadEndRun() {} public void threadSetCompleted() { mContinue = false; } public void threadWakeUp() { this.interrupt(); } public void threadWaitFor(long time_ms) { try { synchronized(this) { if (time_ms > 0) wait(time_ms); // TODO use SystemClock.sleep } } catch (InterruptedException e) { // pass } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; /** * A generic pair of 2 objects. * <p/> * (Note: Amusingly there's a similar class in android.util.Pair) */ public class Pair<U, V> { private final U mFirst; private final V mSecond; public Pair(U first, V second) { mFirst = first; mSecond = second; } public U getFirst() { return mFirst; } public V getSecond() { return mSecond; } // Java Tip: due to type erasure, the static create() X and Y types have // really nothing to do with the U & V types of the non-static Pair class. // Using different letters for the generic types makes this more obvious. // More details at http://stackoverflow.com/questions/936377/static-method-in-a-generic-class public static <X, Y> Pair<X, Y> create(X first, Y second) { return new Pair<X, Y>(first, second); } @SuppressWarnings("unchecked") public static <X, Y> Pair<X, Y>[] newArray(int size) { return new Pair[size]; } @Override public String toString() { return "Pair<" + (mFirst == null ? "(null)" : mFirst.toString()) + ", " + (mSecond == null ? "(null)" : mSecond.toString()) + ">"; } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.prefs; import com.rdrrlabs.example.annotations.PublicForTesting; import com.rdrrlabs.example.liblabs.serial.SerialKey; import com.rdrrlabs.example.liblabs.serial.SerialReader; import com.rdrrlabs.example.liblabs.serial.SerialWriter; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import android.util.SparseArray; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.Arrays; /** * Wrapper around {@link SerialWriter} and {@link SerialReader} to deal with app prefs. * <p/> * Supported types are the minimal required for our needs: boolean, string and int. * Callers need to ensure that only one instance exists for the same file. * <p/> * Caller initial cycle should be: * - begingReadAsync * - endReadAsync ... this waits for the read the finish. * - read, add or modify data. * - modifying data generates a delayed write (or delays an existing one) * - flushSync must be called by the owner at least once, typically when an activity/app * is paused or about to finish. It forces a write or wait for an existing one to finish. * <p/> * Values cannot be null. * Affecting a value to null is equivalent to removing it from the storage map. */ public class BasePrefsStorage { /* * All prefs key constants used. * IMPORTANT: once set, value must NOT be changed. */ /** Issue (feedback report) number count. Type: integer. Strictly incremental. */ public final static String ISSUES_NUM_COUNT = "iss_id_count"; /** User-specific issue ID. Used to identify this user in feedback reports. Type: String. */ public final static String ISSUE_ID = "issue_id"; /** System wall time of last daily ping sent. Type: long. */ public final static String DAILY_PING_LAST_TS = "daily_ping_last_ts"; /** System wall time of next daily ping to send. Type: long. */ public final static String DAILY_PING_NEXT_TS = "daily_ping_next_ts"; private static final boolean DEBUG = true; public static final String TAG = BasePrefsStorage.class.getSimpleName(); /** * Special flag to rethrow exceptions when loading/saving fails. * In normal usage, callers will not see exceptions but load/save will just * return false in case of error, to not interrupt normal workflow. However * during unit tests we want hard errors. */ public static boolean THROW_EXCEPTIONS_WHEN_TESTING = false; /** * File header. Formatted to be 8 bytes (hoping it will help alignment). * The C identifies this is for 24 *C*lock. * The 1 can serve has a format version number in case we want to have future versions. */ private static final byte[] HEADER = new byte[] { 'P', 'R', 'E', 'F', '-', 'C', '1', '\0'}; private final SerialKey mKeyer = new SerialKey(); private final SparseArray<Object> mData = new SparseArray<Object>(); private final String mFilename; private volatile boolean mDataChanged; private volatile Thread mLoadThread; private volatile Thread mSaveThread; private volatile boolean mLoadResult; private volatile boolean mSaveResult; /** * Opens a serial prefs for "filename.sprefs" in the app's dir. * Caller must still read the file before anything happens. * * @param filename The end leaf filename. Must not be null or empty. * Must not contain any path separator. * This is not an absolute path -- the actual path will depend on the application package. */ public BasePrefsStorage(String filename) { mFilename = filename; } /** * Returns the filename that was given to the constructor. * This is not an absolute path -- the actual path will depend on the application package. */ public String getFilename() { return mFilename; } /** * Returns true if internal data has changed and it's worth * calling {@link #beginWriteAsync(Context)}. */ public boolean hasDataChanged() { return mDataChanged; } /** * Returns the absolute file path where the preference file is located. * It depends on the given context. * <p/> * This method is mostly useful for unit tests. Normal usage should have no use for that. */ public File getAbsoluteFile(Context context) { final Context appContext = context.getApplicationContext(); return appContext.getFileStreamPath(mFilename); } /** * Starts reading an existing prefs file asynchronously. * Callers <em>must</em> call {@link #endReadAsync()}. * * @param context The {@link Context} to use. */ public void beginReadAsync(Context context) { final Context appContext = context.getApplicationContext(); Thread t = new Thread() { @Override public void run() { FileInputStream fis = null; try { fis = appContext.openFileInput(mFilename); mLoadResult = loadChannel(fis.getChannel()); } catch (FileNotFoundException e) { // This is an expected error. if (DEBUG) Log.d(TAG, "fileNotFound"); mLoadResult = true; } catch (Exception e) { if (DEBUG) Log.e(TAG, "endReadAsync failed", e); } finally { try { if (fis != null) fis.close(); } catch (IOException ignore) {} } } }; synchronized(this) { Thread curr = mLoadThread; if (curr != null) { if (DEBUG) Log.d(TAG, "Load already pending."); return; } else { mLoadThread = t; t.start(); } } } /** * Makes sure the asynchronous read has finished. * Callers must call this at least once before they access * the underlying storage. * @return The result from the last load operation: * True if the file was correctly read OR if the file doesn't exist. * False if the false exists and wasn't correctly read. */ public boolean endReadAsync() { Thread t = null; synchronized(this) { t = mLoadThread; if (t != null) mLoadThread = null; } if (t != null) { try { t.join(); } catch (InterruptedException e) { if (DEBUG) Log.w(TAG, e); } } return mLoadResult; } /** * Saves the prefs if they have changed. * * @param context The app context. * @return True if prefs could be written, false otherwise. */ public boolean writeSync(Context context) { if (!mDataChanged) { return true; } beginWriteAsync(context); return endWriteAsync(); } /** * Starts saving an existing prefs file asynchronously. * Nothing happens if there's no data changed and there's already a pending save operation. * * @param context The {@link Context} to use. */ public void beginWriteAsync(Context context) { if (!mDataChanged) { return; } final Context appContext = context.getApplicationContext(); Thread t = new Thread() { @Override public void run() { FileOutputStream fos = null; try { fos = appContext.openFileOutput(mFilename, Context.MODE_PRIVATE); synchronized(mData) { saveChannel(fos.getChannel()); mDataChanged = false; } try { // Notify the backup manager that data might have changed //--new BackupWrapper(appContext).dataChanged(); } catch(Exception ignore) {} mSaveResult = true; } catch (Throwable t) { mSaveResult = false; if (DEBUG) Log.e(TAG, "flushSync failed", t); if (THROW_EXCEPTIONS_WHEN_TESTING) throw new RuntimeException(t); } finally { synchronized(BasePrefsStorage.this) { mSaveThread = null; } try { if (fos != null) fos.close(); } catch (IOException ignore) {} } } }; synchronized(this) { Thread curr = mSaveThread; if (curr != null) { if (DEBUG) Log.d(TAG, "Save already pending."); return; } else { mSaveThread = t; t.start(); } } } /** * Makes sure the asynchronous save has finished. * * @return The result from the last save operation: * True if the file was correctly saved. */ public boolean endWriteAsync() { Thread t = null; synchronized(this) { t = mSaveThread; } if (t != null) { try { t.join(); } catch (InterruptedException e) { if (DEBUG) Log.w(TAG, e); } } return mSaveResult; } // --- put public void putInt(String key, int value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Integer newVal = Integer.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putLong(String key, long value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Long newVal = Long.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putBool(String key, boolean value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Boolean newVal = Boolean.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putString(String key, String value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Object curVal = mData.get(intKey); if ((value == null && curVal != null) || (value != null && !value.equals(curVal))) { mData.put(intKey, value); mDataChanged = true; } } } // --- has public boolean hasKey(String key) { synchronized(mData) { return mData.indexOfKey(mKeyer.encodeKey(key)) >= 0; } } public boolean hasInt(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Integer; } public boolean hasLong(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Long; } public boolean hasBool(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Boolean; } public boolean hasString(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof String; } // --- get public int getInt(String key, int defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof Integer) { return ((Integer) o).intValue(); } else if (o != null) { throw new TypeMismatchException(key, "int", o); } } return defValue; } public long getLong(String key, long defValue) { return getLong(key, defValue, true); // default is to convert int-to-long } public long getLong(String key, long defValue, boolean convertIntToLong) { if (endReadAsync()) { Object o = null; int intKey = mKeyer.encodeKey(key); synchronized(mData) { o = mData.get(intKey); } if (o instanceof Long) { return ((Long) o).longValue(); } else if (o instanceof Integer && convertIntToLong) { return ((Integer) o).intValue(); } else if (o != null) { throw new TypeMismatchException(key, "int or long", o); } } return defValue; } public boolean getBool(String key, boolean defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else if (o != null) { throw new TypeMismatchException(key, "boolean", o); } } return defValue; } public String getString(String key, String defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof String) { return (String) o; } else if (o != null) { throw new TypeMismatchException(key, "String", o); } } return defValue; } // ---- @SuppressLint("NewApi") // Lint incorrectly flags ByteBuffer.array() as API 9+, but it's really 1+. @PublicForTesting protected boolean loadChannel(FileChannel fileChannel) throws IOException { // Size should be a multiple of 4. Always. // assert (Integer.SIZE / 8) == 4; long n = fileChannel.size(); if (n < HEADER.length || (n & 0x03) != 0) { Log.d(TAG, "Invalid file size, should be multiple of 4."); return false; } assert (HEADER.length & 0x03) == 0; ByteBuffer header = ByteBuffer.allocate(HEADER.length); header.order(ByteOrder.LITTLE_ENDIAN); int r = fileChannel.read(header); if (r != HEADER.length || !Arrays.equals(HEADER, header.array())) { Log.d(TAG, "Invalid file format, wrong header."); return false; } n -= r; header = null; if (n > Integer.MAX_VALUE) { Log.d(TAG, "Invalid file size, file is too large."); return false; } // read all data ByteBuffer bytes = ByteBuffer.allocateDirect((int) n); bytes.order(ByteOrder.LITTLE_ENDIAN); r = fileChannel.read(bytes); if (r != n) { Log.d(TAG, "Failed to read all data."); return false; } // convert to an int buffer int[] data = new int[bytes.capacity() / 4]; bytes.position(0); // rewind and read bytes.asIntBuffer().get(data); SerialReader sr = new SerialReader(data); synchronized(mData) { mData.clear(); for (SerialReader.Entry entry : sr) { mData.append(entry.getKey(), entry.getValue()); } mDataChanged = false; } return true; } @PublicForTesting protected void saveChannel(FileChannel fileChannel) throws IOException { BufferedWriter bw = null; try { ByteBuffer header = ByteBuffer.wrap(HEADER); header.order(ByteOrder.LITTLE_ENDIAN); if (fileChannel.write(header) != HEADER.length) { throw new IOException("Failed to write header."); } SerialWriter sw = new SerialWriter(); for (int n = mData.size(), i = 0; i < n; i++) { int key = mData.keyAt(i); Object value = mData.valueAt(i); // no need to store null values. if (value == null) continue; if (value instanceof Integer) { sw.addInt(key, ((Integer) value).intValue()); } else if (value instanceof Long) { sw.addLong(key, ((Long) value).longValue()); } else if (value instanceof Boolean) { sw.addBool(key, ((Boolean) value).booleanValue()); } else if (value instanceof String) { sw.addString(key, (String) value); } else { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " does not support type " + value.getClass().getSimpleName()); } } int[] data = sw.encodeAsArray(); ByteBuffer bytes = ByteBuffer.allocateDirect(data.length * 4); bytes.order(ByteOrder.LITTLE_ENDIAN); bytes.asIntBuffer().put(data); fileChannel.write(bytes); } finally { if (bw != null) { try { bw.close(); } catch (IOException ignore) {} } } } public static class TypeMismatchException extends RuntimeException { private static final long serialVersionUID = -6386235026748640081L; public TypeMismatchException(String key, String expected, Object actual) { super(String.format("Key '%1$s' excepted type %2$s, got %3$s", key, expected, actual.getClass().getSimpleName())); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.prefs; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.Log; public class BasePrefsValues { protected final SharedPreferences mPrefs; public BasePrefsValues(Context context) { mPrefs = PreferenceManager.getDefaultSharedPreferences(context); } public BasePrefsValues(SharedPreferences prefs) { mPrefs = prefs; } public SharedPreferences getPrefs() { return mPrefs; } public Object editLock() { return BasePrefsValues.class; } /** Returns a shared pref editor. Must call endEdit() later. */ public Editor startEdit() { return mPrefs.edit(); } /** Commits an open editor. */ public boolean endEdit(Editor e, String tag) { boolean b = e.commit(); if (!b) Log.w(tag, "Prefs.edit.commit failed"); return b; } public boolean isIntroDismissed() { return mPrefs.getBoolean("dismiss_intro", false); } public void setIntroDismissed(boolean dismiss) { synchronized (editLock()) { mPrefs.edit().putBoolean("dismiss_intro", dismiss).commit(); } } public int getLastIntroVersion() { return mPrefs.getInt("last_intro_vers", 0); } public void setLastIntroVersion(int lastIntroVers) { synchronized (editLock()) { mPrefs.edit().putInt("last_intro_vers", lastIntroVers).commit(); } } public String getLastExceptions() { return mPrefs.getString("last_exceptions", null); } public void setLastExceptions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_exceptions", s).commit(); } } public String getLastActions() { return mPrefs.getString("last_actions", null); } public void setLastActions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_actions", s).commit(); } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import java.util.zip.CRC32; import com.rdrrlabs.example.liblabs.serial.SerialKey.DuplicateKey; /** * Encoder/decoder for typed data. * Extracted from NerdkillAndroid. * <p/> * * A {@link SerialWriter} serialized typed key/values to an int array. * Each key is identified by a name -- however <em>only</em> the hashcode * of the key string is used as an id, not the exact string itself. <br/> * An exception {@link DuplicateKey} is thrown when trying to add a key * that has the same string hashcode than an already present key. <br/> * The assumption is made that string hashcodes are stable for a given * interpreting machine (e.g. JVM or Dalvik). * <p/> * * <p/> * Supported types: <br/> * - integer <br/> * - long <br/> * - bool <br/> * - float <br/> * - double <br/> * - string <br/> * - {@link SerialWriter} * <p/> * * The type {@link SerialWriter} can be used to embedded a struct within * a struct. * <p/> * * Users of the serialized data can either directly process the int[] array * using {@link #encodeAsArray()} or can transform it to a semi-compact hexa * string using {@link #encodeAsString()}. Both can later be decoded using * {@link SerialReader}. * <p/> * * A typical strategy is for a serializable struct to contain a * <code>saveInto(SerialWriter)</code> method. Whatever code that does * the saving can thus first create a {@link SerialWriter} and pass it * to the struct so that it can save itself into the given writer. * <br/> * Another strategy is for the struct to have a method that creates the * {@link SerialWriter}, adds all the fields and then return the writer. * <br/> * Both approaches are valid. The former is useful if the outer and inner * methods are working in collaboration, the later is useful if both sides * should be agnostic to each other. * <p/> * * Format of the encoded int array: * The serialized data starts with a header describing the data size, * followed by one entry per field added in the order of the addXyz() calls. * Finally there's a CRC and an EOF marker. * * <pre> * - header: * - 1 int: number of ints to follow (including this and CRC + EOF marker) * - entries: * - 1 int: type, ascii for I L B F D S or Z * - 1 int: key * - int, bool, float: 1 int, value * - long, double: 2 int value (MSB + LSB) * - string: 1 int = number of chars following, then int = c1 | c2 (0 padding as needed) * - serializer: (self, starting with number of ints to follow) * - 1 int: CRC (of all previous ints including header, excluding this and EOF) * - 1 int: EOF * </pre> */ public class SerialWriter { public static class CantAddData extends RuntimeException { private static final long serialVersionUID = 8074293730213951679L; public CantAddData(String message) { super(message); } } private final SerialKey mKeyer = new SerialKey(); private int[] mData; private int mSize; private boolean mCantAdd; static final int TYPE_INT = 1; static final int TYPE_LONG = 2; static final int TYPE_BOOL = 3; static final int TYPE_FLOAT = 4; static final int TYPE_DOUBLE = 5; static final int TYPE_STRING = 6; static final int TYPE_SERIAL = 7; static final int EOF = 0x0E0F; public SerialWriter() { } public int[] encodeAsArray() { close(); // Resize the array to be of its exact size if (mData.length > mSize) { int[] newArray = new int[mSize]; System.arraycopy(mData, 0, newArray, 0, mSize); mData = newArray; } return mData; } public String encodeAsString() { int[] a = encodeAsArray(); int n = a.length; char[] cs = new char[n * 9]; int j = 0; for (int i = 0; i < n; i++) { int v = a[i]; // Write nibbles in MSB-LSB order, skipping leading zeros boolean skipZero = true; for (int k = 0; k < 8; k++) { int b = (v >> 28) & 0x0F; v = v << 4; if (skipZero) { if (b == 0) { if (k < 7) { continue; } } else { skipZero = false; } } char c = b < 0x0A ? (char)('0' + b) : (char)('A' - 0x0A + b); cs[j++] = c; } cs[j++] = ' '; } return new String(cs, 0, j); } //-- /** * @throws DuplicateKey if the key had already been registered. */ public void addInt(String name, int intValue) { addInt(mKeyer.encodeUniqueKey(name), intValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addLong(String name, long longValue) { addLong(mKeyer.encodeUniqueKey(name), longValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addBool(String name, boolean boolValue) { addBool(mKeyer.encodeUniqueKey(name), boolValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addFloat(String name, float floatValue) { addFloat(mKeyer.encodeUniqueKey(name), floatValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addDouble(String name, double doubleValue) { addDouble(mKeyer.encodeUniqueKey(name), doubleValue); } /** Add a string. Doesn't add a null value. * @throws DuplicateKey if the key had already been registered. */ public void addString(String name, String strValue) { addString(mKeyer.encodeUniqueKey(name), strValue); } /** Add a Serial. Doesn't add a null value. */ public void addSerial(String name, SerialWriter serialValue) { addSerial(mKeyer.encodeUniqueKey(name), serialValue); } //-- public void addInt(int key, int intValue) { _addInt(key, TYPE_INT, intValue); } public void addLong(int key, long longValue) { _addLong(key, TYPE_LONG, longValue); } public void addBool(int key, boolean boolValue) { _addInt(key, TYPE_BOOL, boolValue ? 1 : 0); } public void addFloat(int key, float floatValue) { _addInt(key, TYPE_FLOAT, Float.floatToIntBits(floatValue)); } public void addDouble(int key, double doubleValue) { _addLong(key, TYPE_DOUBLE, Double.doubleToLongBits(doubleValue)); } /** Add a string. Doesn't add a null value. */ public void addString(int key, String strValue) { if (strValue == null) return; int n = strValue.length(); int m = (n + 1) / 2; int pos = alloc(2 + m + 1); mData[pos++] = TYPE_STRING; mData[pos++] = key; mData[pos++] = n; for (int i = 0; i < n;) { char c1 = strValue.charAt(i++); char c2 = i >= n ? 0 : strValue.charAt(i++); int j = (c1 << 16) | (c2 & 0x0FFFF); mData[pos++] = j; } mSize = pos; } /** Add a Serial. Doesn't add a null value. */ public void addSerial(int key, SerialWriter serialValue) { if (serialValue == null) return; int[] a = serialValue.encodeAsArray(); int n = a.length; int pos = alloc(2 + n); mData[pos++] = TYPE_SERIAL; mData[pos++] = key; System.arraycopy(a, 0, mData, pos, n); pos += n; mSize = pos; } //--- private int alloc(int numInts) { if (mCantAdd) { throw new CantAddData("Serial data has been closed by a call to encode(). Can't add anymore."); } if (mData == null) { // Reserve the header int mData = new int[numInts + 1]; mSize = 1; return mSize; } int s = mSize; int n = s + numInts; if (mData.length < n) { // need to realloc int[] newArray = new int[s+n]; System.arraycopy(mData, 0, newArray, 0, s); mData = newArray; } return mSize; } private void _addInt(int key, int type, int value) { int pos = alloc(2+1); mData[pos++] = type; mData[pos++] = key; mData[pos++] = value; mSize = pos; } private void _addLong(int key, int type, long value) { int pos = alloc(2+2); mData[pos++] = type; mData[pos++] = key; // MSB first mData[pos++] = (int) (value >> 32); // LSB next mData[pos++] = (int) (value & 0xFFFFFFFF); mSize = pos; } /** Closing the array adds the CRC and the EOF. Can't add anymore once this is done. */ private void close() { // can't close the array twice if (mCantAdd) return; int pos = alloc(2); // write the header, the first int is the full size in ints mData[0] = pos + 2; // write the CRC and EOF footer mData[pos ] = computeCrc(mData, 0, pos); mData[pos+1] = EOF; mSize += 2; mCantAdd = true; } /* This is static so that we can reuse it as-is in the reader class. */ static int computeCrc(int[] data, int offset, int length) { CRC32 crc = new CRC32(); for (; length > 0; length--) { int v = data[offset++]; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); } return (int) crc.getValue(); } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import java.util.Iterator; import android.util.SparseArray; /** * Encoder/decoder for typed data. * Extracted from NerdkillAndroid. * * See {@link SerialWriter} for implementations details. */ public class SerialReader implements Iterable<SerialReader.Entry> { public static final String TAG = SerialReader.class.getSimpleName(); public class Entry { private final int mKey; private final Object mValue; public Entry(int key, Object value) { mKey = key; mValue = value; } public int getKey() { return mKey; } public Object getValue() { return mValue; } } public static class DecodeError extends RuntimeException { private static final long serialVersionUID = -8603565615795418588L; public DecodeError(String message) { super(message); } } static final int TYPE_INT = SerialWriter.TYPE_INT; static final int TYPE_LONG = SerialWriter.TYPE_LONG; static final int TYPE_BOOL = SerialWriter.TYPE_BOOL; static final int TYPE_FLOAT = SerialWriter.TYPE_FLOAT; static final int TYPE_DOUBLE = SerialWriter.TYPE_DOUBLE; static final int TYPE_STRING = SerialWriter.TYPE_STRING; static final int TYPE_SERIAL = SerialWriter.TYPE_SERIAL; static final int EOF = SerialWriter.EOF; private final SparseArray<Object> mData = new SparseArray<Object>(); private final SerialKey mKeyer = new SerialKey(); public SerialReader(String data) { decodeString(data); } public SerialReader(int[] data, int offset, int length) { decodeArray(data, offset, length); } public SerialReader(int[] data) { this(data, 0, data.length); } /** * A shortcut around {@link SerialReader#SerialReader(int[])} useful for unit tests. */ public SerialReader(SerialWriter sw) { this(sw.encodeAsArray()); } public int size() { return mData.size(); } public boolean hasName(String name) { int id = mKeyer.encodeKey(name); return mData.indexOfKey(id) >= 0; } public int getInt(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Integer) return ((Integer) d).intValue(); throw new ClassCastException("Int expected, got " + d.getClass().getSimpleName()); } public long getLong(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Long) return ((Long) d).longValue(); throw new ClassCastException("Long expected, got " + d.getClass().getSimpleName()); } public boolean getBool(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return false; if (d instanceof Boolean) return ((Boolean) d).booleanValue(); throw new ClassCastException("Bool expected, got " + d.getClass().getSimpleName()); } public float getFloat(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Float) return ((Float) d).floatValue(); throw new ClassCastException("Float expected, got " + d.getClass().getSimpleName()); } public double getDouble(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Double) return ((Double) d).doubleValue(); throw new ClassCastException("Double expected, got " + d.getClass().getSimpleName()); } public String getString(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return null; if (d instanceof String) return (String) d; throw new ClassCastException("String expected, got " + d.getClass().getSimpleName()); } public SerialReader getSerial(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return null; if (d instanceof SerialReader) return (SerialReader) d; throw new ClassCastException("SerialReader expected, got " + d.getClass().getSimpleName()); } @Override public Iterator<Entry> iterator() { return new Iterator<Entry>() { final int n = mData.size(); int index = 0; @Override public boolean hasNext() { return index < n; } @Override public Entry next() { Entry e = new Entry(mData.keyAt(index), mData.valueAt(index)); index++; return e; } @Override public void remove() { throw new UnsupportedOperationException( "Remove is not supported by " + SerialReader.class.getSimpleName()); } }; } //--- private static class IntArray { public int[] a = new int[16]; public int n = 0; public void add(long i) { if (n == a.length) { int[] newArray = new int[2 * a.length]; System.arraycopy(a, 0, newArray, 0, n); a = newArray; } int j = (int) (i & 0x0FFFFFFFFL); a[n++] = j; } } private void decodeString(String data) { IntArray a = new IntArray(); if (data == null || data.length() == 0) { throw new DecodeError("No data to decode."); } // Read a bunch of hexa numbers separated by non-hex chars char[] cs = data.toCharArray(); int cn = cs.length; int size = 0; long i = -1; for (int k = 0; k < cn; k++) { char c = cs[k]; if (c >= '0' && c <= '9') { if (i == -1) i = 0; i = (i << 4) + c - '0'; } else if (c >= 'a' && c <= 'f') { if (i == -1) i = 0; i = (i << 4) + c - 'a' + 0x0A; } else if (c >= 'A' && c <= 'F') { if (i == -1) i = 0; i = (i << 4) + c - 'A' + 0x0A; } else if (i >= 0) { a.add(i); i = -1; // The first int indicates how many ints we needed to read. // There's no need to try to read any more than that, we wouldn't // use it anyway. if (a.n == 1) { size = a.a[0]; } else if (a.n >= size) { break; } } } if (i >= 0) a.add(i); decodeArray(a.a, 0, a.n); } private void decodeArray(int[] data, int offset, int length) { // get the size in ints int size = data.length > offset ? data[offset] : 0; int end = size + offset; // An empty message has at least 3 ints. if (size < 3 || end > data.length || offset + length > data.length) { throw new DecodeError("Message too short. Not enough data found."); } if (data[end - 1] != EOF) { throw new DecodeError("Missing EOF."); } // Compute the CRC without the 2-int footer int crc = SerialWriter.computeCrc(data, offset, size - 2); if (data[end - 2] != crc) { throw new DecodeError("Invalid CRC."); } // Nothing to do if this is an empty message. if (size == 3) return; // disregard the ending CRC and EOF now end -= 2; // skip the size int offset++; while (offset < end) { // The smallest type needs 3 ints: type, id, 1 int if (offset + 3 > end) { throw new DecodeError("Not enough data to decode short primitive."); } int type = data[offset++]; int id = data[offset++]; int i1, i2; switch(type) { case TYPE_INT: i1 = data[offset++]; mData.put(id, Integer.valueOf(i1)); break; case TYPE_BOOL: i1 = data[offset++]; boolean b = i1 != 0; mData.put(id, Boolean.valueOf(b)); break; case TYPE_FLOAT: i1 = data[offset++]; float f = Float.intBitsToFloat(i1); mData.put(id, Float.valueOf(f)); break; case TYPE_LONG: case TYPE_DOUBLE: if (offset + 2 > end) throw new DecodeError("Not enough data to decode long primitive."); i1 = data[offset++]; i2 = data[offset++]; long L = ((long)i1) << 32; long L2 = i2; L |= L2 & 0x0FFFFFFFFL; if (type == TYPE_LONG) { mData.put(id, new Long(L)); } else { double d = Double.longBitsToDouble(L); mData.put(id, Double.valueOf(d)); } break; case TYPE_STRING: int char_size = data[offset++]; int m = (char_size + 1) / 2; if (offset + m > end) throw new DecodeError("Not enough data to decode string type."); char[] cs = new char[char_size]; for (int i = 0; i < char_size; ) { i1 = data[offset++]; char c = (char) ((i1 >> 16) & 0x0FFFF); cs[i++] = c; if (i < char_size) { c = (char) (i1 & 0x0FFFF); cs[i++] = c; } } String s = new String(cs); mData.put(id, s); break; case TYPE_SERIAL: // The next int must be the header of the serial data, which conveniently // starts with its own size. int sub_size = data[offset]; if (offset + sub_size > end) { throw new DecodeError("Not enough data to decode sub-serial type."); } else if (data[offset + sub_size - 1] != EOF) { throw new DecodeError("Missing EOF in sub-serial type."); } SerialReader sr = new SerialReader(data, offset, sub_size); mData.put(id, sr); offset += sub_size; break; } } } }
Java
/* * Copyright (C) 2013 rdrrlabs gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import android.util.SparseArray; /** * Encode keys used by {@link SerialWriter}. * <p/> * Keys are transformed in a unique integer. * In case of collision, {@link DuplicateKey} is thrown. */ public class SerialKey { public static class DuplicateKey extends RuntimeException { private static final long serialVersionUID = -1735763023714511003L; public DuplicateKey(String message) { super(message); } } private SparseArray<String> mUsedKeys = null; /** * Encode a key name into an integer. * <p/> * There's a risk of collision when adding keys: different names can map to * the same encoded integer. If this is the case and the key is different * then a {@link DuplicateKey} is thrown. It is ok to register twice the * same key name, which will result in the same value being returned. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. * @throws DuplicateKey if the key collides with a different one. */ public int encodeNewKey(String name) { if (mUsedKeys == null) mUsedKeys = new SparseArray<String>(); int key = encodeKey(name); int index = mUsedKeys.indexOfKey(key); if (index >= 0) { String previous = mUsedKeys.valueAt(index); if (!name.equals(previous)) { throw new DuplicateKey( String.format("Key name collision: '%1$s' has the same hash than previously used '%2$s'", name, previous)); } } else { mUsedKeys.put(key, name); } return key; } /** * Encode a key name into an integer and makes sure the key name is unique * and has never be registered before. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. * @throws DuplicateKey if the key had already been registered. */ public int encodeUniqueKey(String name) { if (mUsedKeys == null) mUsedKeys = new SparseArray<String>(); int key = encodeKey(name); int index = mUsedKeys.indexOfKey(key); if (index >= 0) { String previous = mUsedKeys.valueAt(index); throw new DuplicateKey( String.format("Key name collision: '%1$s' has the same hash than previously used '%2$s'", name, previous)); } mUsedKeys.put(key, name); return key; } /** * Encode a key name into an integer. * <p/> * Unlike {@link #encodeNewKey(String)}, this does not check whether the key has already * been used. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. */ public int encodeKey(String name) { int key = name.hashCode(); return key; } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; public class UpdateService extends Service { public static final String TAG = UpdateService.class.getSimpleName(); private static final boolean DEBUG = false; @Override public IBinder onBind(Intent intent) { // pass return null; } //---- @Override public void onStart(Intent intent, int startId) { if (DEBUG) Log.d(TAG, "Start service"); ExceptionHandler handler = new ExceptionHandler(this); try { super.onStart(intent, startId); Core core = TimerifficApp.getInstance(this).getCore(); core.getUpdateService().onStart(this, intent, startId); } finally { handler.detach(); if (DEBUG) Log.d(TAG, "Stopping service"); stopSelf(); } } @Override public void onDestroy() { Core core = TimerifficApp.getInstance(this).getCore(); core.getUpdateService().onDestroy(this); super.onDestroy(); } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import java.io.IOException; import java.lang.reflect.Method; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.FileBackupHelper; import android.app.backup.SharedPreferencesBackupHelper; import android.content.Context; import android.os.ParcelFileDescriptor; import android.preference.PreferenceManager; import android.util.Log; import com.rdrrlabs.example.timer1app.core.app.BackupWrapper; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; /** * Backup agent to backup/restore both preferences and main database. * Used only with Froyo (Android API level 8) and above. * <p/> * This class is never referenced directly except by a class name reference * in the &lt;application&gt; tag of the manifest. * <p/> * Implementation detail: since {@link TimerifficBackupAgent} depends * on the BackupAgent class, it is not available on platform < API 8. * This means any direct access to this class must be avoided. E.g. to * get the lock, callers must use the {@link BackupWrapper} instead. * <p/> * TODO exclude from Proguard */ public class TimerifficBackupAgent extends BackupAgentHelper { /* * References for understanding this: * * - BackupAgent: * http://d.android.com/reference/android/app/backup/BackupAgent.html * * - FileHelperExampleAgent.java in the BackupRestore sample for * the Froyo/2.2 Samples. */ public static final String TAG = TimerifficBackupAgent.class.getSimpleName(); private static final String KEY_DEFAULT_SHARED_PREFS = "default_shared_prefs"; private static final String KEY_PROFILES_DB = "profiles_db"; private static final String KEY_PREFS_STORAGE = "prefs_storage_"; @Override public void onCreate() { super.onCreate(); // --- shared prefs backup --- // The sharedPreferencesBackupHelper wants the name of the shared pref, // however the "default" name is not given by any public API. Try // to retrieve it via reflection. This may fail if the method changes // in future Android APIs. String sharedPrefsName = null; try { Method m = PreferenceManager.class.getMethod( "getDefaultSharedPreferencesName", new Class<?>[] { Context.class } ); Object v = m.invoke(null /*receiver*/, (Context) this); if (v instanceof String) { sharedPrefsName = (String) v; } } catch (Exception e) { // ignore } if (sharedPrefsName == null) { // In case the API call fails, we implement it naively ourselves // like it used to be done in Android 1.6 (API Level 4) sharedPrefsName = this.getPackageName() + "_preferences"; } if (sharedPrefsName != null) { SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, sharedPrefsName); addHelper(KEY_DEFAULT_SHARED_PREFS, helper); Log.d(TAG, "Register backup 1 for " + sharedPrefsName); } // --- pref storage backup --- // Use the backup helper for the new app's pref storage. PrefsStorage ps = TimerifficApp.getInstance(this).getPrefsStorage(); if (ps != null) { String name = ps.getFilename(); FileBackupHelper helper = new FileBackupHelper(this, name); addHelper(KEY_PREFS_STORAGE + name, helper); Log.d(TAG, "Register backup 2 for " + name); } // --- profiles db backup --- // Use the backup helper for the profile database. // The FileBackupHelper defaults to a file under getFilesDir() // so we need to trim the full database path. String filesPath = getFilesDir().getAbsolutePath(); String dbPath = ProfilesDB.getDatabaseFile(this).getAbsolutePath(); if (filesPath != null && dbPath != null) { dbPath = relativePath(filesPath, dbPath); FileBackupHelper helper = new FileBackupHelper(this, dbPath); addHelper(KEY_PROFILES_DB, helper); Log.d(TAG, "Register backup 3 for " + dbPath); } } @Override public void onBackup( ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { // Hold the lock while the helper performs the backup operation synchronized (BackupWrapper.getBackupLock()) { super.onBackup(oldState, data, newState); Log.d(TAG, "onBackup"); } } @Override public void onRestore( BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { // Hold the lock while the helper restores the file from // the data provided here. synchronized (BackupWrapper.getBackupLock()) { super.onRestore(data, appVersionCode, newState); Log.d(TAG, "onRestore"); } } /** * Computes a relative path from source to dest. * e.g. if source is A/B and dest is A/C/D, the relative path is ../C/D * <p/> * Source and dest are expected to be absolute unix-like, e.g. /a/b/c */ private String relativePath(String source, String dest) { // Implementation: we're working with unix-like stuff that is absolute // so /a/b/c => { "", "a", "b", "c" } // // In our use-case we can't have source==dest, so we don't handle it. String[] s = source.split("/"); String[] d = dest.split("/"); // Find common root part and ignore it. int common = 0; while (common < s.length && common < d.length && s[common].equals(d[common])) { common++; } // Now we need as many ".." as dirs left in source to go back to the // common root. String result = ""; for (int i = common; i < s.length; i++) { if (result.length() > 0) result += "/"; result += ".."; } // Finally add whatever is not a common root from the dest for (int i = common; i < d.length; i++) { if (result.length() > 0) result += "/"; result += d[i]; } return result; } }
Java
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; public class TimerifficAppBase extends TimerifficApp { public TimerifficAppBase() { super(); } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; public class PhoneStateService extends Service { private MyPhoneStateListener mPSListener; @Override public IBinder onBind(Intent intent) { // pass return null; } @Override public void onCreate() { Context context = getApplicationContext(); TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (mPSListener == null) { mPSListener = new MyPhoneStateListener(); } telephony.listen(mPSListener, PhoneStateListener.LISTEN_CALL_STATE); super.onCreate(); } @Override public void onDestroy() { if (mPSListener != null) { Context context = getApplicationContext(); TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(mPSListener, PhoneStateListener.LISTEN_NONE); mPSListener = null; } super.onDestroy(); } private class MyPhoneStateListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; public class UpdateReceiver extends BroadcastReceiver { public final static String TAG = UpdateReceiver.class.getSimpleName(); private final static boolean DEBUG = false; /** Name of intent to broadcast to activate this receiver when doing * alarm-based apply-state. */ public final static String ACTION_APPLY_STATE = "com.rdrrlabs.intent.action.APPLY_STATE"; /** Name of intent to broadcast to activate this receiver when triggering * a check from the UI. */ public final static String ACTION_UI_CHECK = "com.rdrrlabs.intent.action.UI_CHECK"; /** Name of an extra int: how we should display a toast for next event. */ public final static String EXTRA_TOAST_NEXT_EVENT = "toast-next"; public final static int TOAST_NONE = 0; public final static int TOAST_IF_CHANGED = 1; public final static int TOAST_ALWAYS = 2; /** * Starts the {@link UpdateService}. * Code should be at its minimum. No logging or DB access here. */ @Override public void onReceive(Context context, Intent intent) { ExceptionHandler handler = new ExceptionHandler(context); WakeLock wl = null; try { try { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TimerifficReceiver"); wl.acquire(); } catch (Exception e) { // Hmm wake lock failed... not sure why. Continue anyway. Log.w(TAG, "WakeLock.acquire failed"); } if (DEBUG) Log.d(TAG, "UpdateService requested"); Core core = TimerifficApp.getInstance(context).getCore(); core.getUpdateService().startFromReceiver(context, intent, wl); wl = null; } finally { if (wl != null) { try { wl.release(); } catch (Exception e) { // ignore } } handler.detach(); } } }
Java
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Application; import android.content.Context; import com.rdrrlabs.example.timer1app.core.app.AppId; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; public class TimerifficApp extends Application { @SuppressWarnings("unused") private static final String TAG = TimerifficApp.class.getSimpleName(); private boolean mFirstStart = true; private Runnable mDataListener; private final Core mCore; private final PrefsStorage mPrefsStorage = new PrefsStorage("prefs"); /** Base constructor with a default core. */ public TimerifficApp() { mCore = new Core(); } /** Derived constructor, to override the core. */ public TimerifficApp(Core core) { mCore = core; } @Override public void onCreate() { super.onCreate(); mPrefsStorage.beginReadAsync(getApplicationContext()); } /** * Returns the {@link TimerifficApp} instance using the * {@link Context#getApplicationContext()}. * * Returns null if context doesn't correctly, which is not supposed * to happen in normal behavior. */ public static TimerifficApp getInstance(Context context) { Context app = context.getApplicationContext(); if (app instanceof TimerifficApp) { return (TimerifficApp) app; } return null; } //--------------------- public boolean isFirstStart() { return mFirstStart; } public void setFirstStart(boolean firstStart) { mFirstStart = firstStart; } //--------------------- public void setDataListener(Runnable listener) { mDataListener = listener; } public void invokeDataListener() { if (mDataListener != null) mDataListener.run(); } public PrefsStorage getPrefsStorage() { return mPrefsStorage; } public String getIssueId() { return AppId.getIssueId(this, mPrefsStorage); } public Core getCore() { return mCore; } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.error; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.ui.ErrorReporterUI; public class ExceptionHandler { /** Exception Notification ID. 'ExcH' as an int. */ private static final int EXCEPTION_NOTIF_ID = 'E' << 24 + 'x' << 16 + 'c' << 8 + 'H'; public static final String TAG = ExceptionHandler.class.getSimpleName(); public static final String SEP_START = "{[ "; public static final String SEP_END = "} /*end*/ \n"; private Context mAppContext; private Handler mHandler; private static DateFormat sDateFormat; static { sDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); } // ----- public static int getNumExceptionsInLog(Context context) { try { PrefsValues pv = new PrefsValues(context); String curr = pv.getLastExceptions(); if (curr == null) { return 0; } int count = -1; int pos = -1; do { count++; pos = curr.indexOf(SEP_END, pos + 1); } while (pos >= 0); return count; } catch (Exception e) { Log.d(TAG, "getNumExceptionsInLog failed", e); } return 0; } // ----- public ExceptionHandler(Context context) { // Context is never supposed to be null if (context == null) return; // We only set our handler if there's no current handler or it is // not our -- we don't override our own handler. UncaughtExceptionHandler h = Thread.currentThread().getUncaughtExceptionHandler(); if (h == null || !(h instanceof Handler)) { mAppContext = context.getApplicationContext(); mHandler = new Handler(h); Thread.currentThread().setUncaughtExceptionHandler(mHandler); } } public void detach() { if (mAppContext != null) { Thread.currentThread().setUncaughtExceptionHandler(mHandler.getOldHanlder()); mHandler = null; mAppContext = null; } } private class Handler implements Thread.UncaughtExceptionHandler { private final UncaughtExceptionHandler mOldHanlder; public Handler(UncaughtExceptionHandler oldHanlder) { mOldHanlder = oldHanlder; } public UncaughtExceptionHandler getOldHanlder() { return mOldHanlder; } public void uncaughtException(Thread t, Throwable e) { try { PrefsValues pv = new PrefsValues(mAppContext); addToLog(pv, e); createNotification(); } catch (Throwable t2) { // ignore, or we'll get into an infinite loop } try { // chain the calls to any previous handler that is not one of ours UncaughtExceptionHandler h = mOldHanlder; while (h != null && h instanceof Handler) { h = ((Handler) h).getOldHanlder(); } if (h != null) { mOldHanlder.uncaughtException(t, e); } else { // If we couldn't find any old handler, log the error // to the console if this is an emulator if ("sdk".equals(Build.MODEL)) { Log.e(TAG, "Exception caught in Timeriffic", e); } } } catch (Throwable t3) { // ignore } } }; public synchronized static void addToLog(PrefsValues pv, Throwable e) { // get a trace of the exception StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); // store the exception String currEx = pv.getLastExceptions(); if (currEx == null) currEx = ""; // trim the string if it gets too big. if (currEx.length() > 4096) { int pos = currEx.indexOf(SEP_END); int p = pos + SEP_END.length(); if (pos > 0) { if (p < currEx.length()) { currEx = currEx.substring(p); } else { currEx = ""; } } } String d = sDateFormat.format(new Date(System.currentTimeMillis())); currEx += SEP_START + d + " ]\n"; currEx += sw.toString() + "\n"; currEx += SEP_END; pv.setLastExceptions(currEx); } private void createNotification() { NotificationManager ns = (NotificationManager) mAppContext.getSystemService(Context.NOTIFICATION_SERVICE); if (ns == null) return; Notification notif = new Notification( R.drawable.app_icon, // icon "Timeriffic Crashed!", // tickerText System.currentTimeMillis() // when ); notif.flags |= Notification.FLAG_AUTO_CANCEL; notif.defaults = Notification.DEFAULT_ALL; Intent i = new Intent(mAppContext, ErrorReporterUI.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(mAppContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); notif.setLatestEventInfo(mAppContext, "Oh no! Timeriffic Crashed!", // contentTitle "Please click here to report this error.", // contentText pi // contentIntent ); ns.notify(EXCEPTION_NOTIF_ID, notif); } }
Java
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * 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, either version 3 of the License, or * (at your option) any later version. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; /** * The holder for a timed action row. */ public class TimedActionHolder extends BaseHolder { private static boolean DEBUG = false; public static final String TAG = TimedActionHolder.class.getSimpleName(); public TimedActionHolder(ProfilesUiImpl activity, View view) { super(activity, view); } @Override public void setUiData() { ColIndexes colIndexes = mActivity.getColIndexes(); Cursor cursor = mActivity.getCursor(); super.setUiData(cursor.getString(colIndexes.mDescColIndex), getDotColor(cursor.getInt(colIndexes.mEnableColIndex))); } private Drawable getDotColor(int actionMark) { switch (actionMark) { case Columns.ACTION_MARK_PREV: return mActivity.getGreenDot(); case Columns.ACTION_MARK_NEXT: return mActivity.getPurpleDot(); default: return mActivity.getGrayDot(); } } @Override public void onCreateContextMenu(ContextMenu menu) { menu.setHeaderTitle(R.string.timedactioncontextmenu_title); menu.add(0, R.string.menu_insert_action, 0, R.string.menu_insert_action); menu.add(0, R.string.menu_delete, 0, R.string.menu_delete); menu.add(0, R.string.menu_edit, 0, R.string.menu_edit); } @Override public void onItemSelected() { // trigger edit if (DEBUG) Log.d(TAG, "action - edit"); editAction(mActivity.getCursor()); } @Override public void onContextMenuSelected(MenuItem item) { switch (item.getItemId()) { case R.string.menu_insert_action: if (DEBUG) Log.d(TAG, "action - insert_action"); insertNewAction(mActivity.getCursor()); break; case R.string.menu_delete: if (DEBUG) Log.d(TAG, "action - delete"); deleteTimedAction(mActivity.getCursor()); break; case R.string.menu_edit: if (DEBUG) Log.d(TAG, "action - edit"); editAction(mActivity.getCursor()); break; default: break; } } }
Java