code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
public class MakeTanAngle135Array {
public static void main(String[] args) {
VIonBulk vib;
file myFile;
double AU = 1.5* Math.pow(10,11);
myFile = new file("135array.txt");
myFile.initWrite(false);
for (int v0=20000; v0<40000; v0=v0+1000) {
vib = new VIonBulk(AU, 28000, 135*3.14159/180);
double ourAngle = Math.atan(vib.Vr()/vib.Vperp());
myFile.write(v0+" "+ourAngle+System.getProperty("line.separator"));
}
myFile.closeWrite();
}
}
| 0lism | trunk/java/MakeTanAngle135Array.java | Java | gpl3 | 483 |
/**
* A basic power law in ENERGY
*
*/
public class PowerLawVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double power, density, lim1, lim2, norm, ee;
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);
/**
* Construct a power law VLISM
*/
public PowerLawVLISM(HelioVector _vBulk, double _density, double _power, double _ll, double _hh) {
vBulk = _vBulk;
power = _power;
density = _density;
lim1 = _ll;
lim2 = _hh;
// calculate normalization
norm = density/4/Math.PI/ (Math.pow(lim2,power+3.0)- Math.pow(lim1,power+3.0))*(power+3.0);
norm=norm;
System.out.println("norm: " + norm);
}
/**
*
* 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;
}
/**
* 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 PowerLawVLISM gvli = new PowerLawVLISM(new HelioVector(HelioVector.CARTESIAN,
-20000.0,0.0,0.0), 1.0, -4.0, 1000.0, 300000.0);
System.out.println("Created PLVLISM" );
//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);
}
}
| 0lism | trunk/java/PowerLawVLISM.java | Java | gpl3 | 3,615 |
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);
}
}
| 0lism | trunk/java/Integration_old.java | Java | gpl3 | 2,726 |
import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
/** This class computes the pickup distribution as a function of
* vr, vt, ( and r, theta)
*/
public class 2DVelocityDistribution {
// 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 NeutralDistribution nd; // this is our neutral helium distribution
public SurvivalProbability sp; // % of neutral ions still left at r,v
public 2DVelocityDistribution(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);
nd = new NeutralDistribution(Vb, phi0, theta0,
Temp, N, mu);
}
public double N(double r, double theta, double vr, 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);
}
// 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 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
}
}
} | 0lism | trunk/java/2DVelocityDistribution.java | Java | gpl3 | 3,475 |
import java.util.StringTokenizer;
import java.util.Vector;
/*
* 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(double[] qdays, double[] qrates) {
days = qdays;
rates = qrates;
}
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;
}
} | 0lism | trunk/java/FitData.java | Java | gpl3 | 1,273 |
/*
* Interface MinimisationFunction
*
* This interface provides the abstract method for the function to be
* minimised by the methods in the class, Minimisation
*
* WRITTEN BY: Dr Michael Thomas Flanagan
*
* DATE: April 2003
* MODIFIED: April 2004
*
* DOCUMENTATION:
* See Michael Thomas Flanagan's Java library on-line web page:
* Minimisation.html
*
* Copyright (c) April 2004
*
* 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.
*
****************************************************************************************/
// Interface for Minimisation class
// Calculates value of function to be minimised
public interface MinimisationFunction{
double function(double[]param);
} | 0lism | trunk/java/MinimisationFunction.java | Java | gpl3 | 1,292 |
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 gov.noaa.pmel.sgt.dm.SimpleGrid;
import gov.noaa.pmel.sgt.dm.*;
import gov.noaa.pmel.sgt.SGLabel;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.image.*;
//import net.jmge.gif.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
/**
* Let's use this to take a look at 3D data with color...
*
* Put new code in makeGraph() routine
*
* Added to:
* @author Donald Denbo
* @version $Revision: 1.8 $, $Date: 2001/02/05 23:28:46 $
* @since 2.0
*
* Lukas Saul summer 2002
*/
public class JColorGraph extends PrintableDialog implements ActionListener{
public JPlotLayout rpl_;
public JPane gridKeyPane;
private GridAttribute gridAttr_;
JButton edit_;
JButton space_ = null;
JButton tree_;
JButton print_;
JButton save_;
JButton color_;
JPanel main;
Range2D datar;
ContourLevels clevels;
ColorMap cmap;
SGTData newData;
public String fileName ="test";
public String xLabel1, xLabel2, yLabel1, yLabel2;
// defaults
private String unitString = "log sqare error";
private String label1 = "University of Bern";
private String label2 = "Neutralizer";
public double[] xValues;
public double[] yValues;
public double[] zValues;
public float xMax, xMin, yMax, yMin, zMax, zMin;
public float cMin, cMax, cDelta;
public boolean b_color;
public JColorGraph() {
b_color = true;
}
public JColorGraph(double[] x, double[] y, double[] z) {
this(x,y,z,true);
}
public JColorGraph(double[] x, double[] y, double[] z, boolean b) {
b_color = b;
xValues=x;
yValues=y;
zValues=z;
// assume here we are going to have input the data already
xMax = (float)xValues[0]; xMin = (float)xValues[0];
yMax = (float)yValues[0]; yMin = (float)yValues[0];
zMax = (float)zValues[0]; zMin = (float)zValues[0];
//o("xMin: " + xMin);
for (int i=0; i<xValues.length; i++) {
if (xValues[i]<xMin) xMin = (float)xValues[i];
if (xValues[i]>xMax) xMax = (float)xValues[i];
}
for (int i=0; i<yValues.length; i++) {
if (yValues[i]<yMin) yMin = (float)yValues[i];
if (yValues[i]>yMax) yMax = (float)yValues[i];
}
for (int i=0; i<zValues.length; i++) {
if (zValues[i]<zMin) zMin = (float)zValues[i];
if (zValues[i]>zMax) zMax = (float)zValues[i];
}
o("xmin: " + xMin);
o("xmax: " + xMax);
o("ymin: " + yMin);
o("ymax: " + yMax);
cMin = zMin; cMax = zMax; cDelta = (zMax-zMin)/2;
datar = new Range2D(zMin, zMax, cDelta);
clevels = ContourLevels.getDefault(datar);
gridAttr_ = new GridAttribute(clevels);
if (b_color == true) cmap = createColorMap(datar);
else cmap = createMonochromeMap(datar);
gridAttr_.setColorMap(cmap);
gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
}
private JPanel makeButtonPanel(boolean mark) {
JPanel button = new JPanel();
button.setLayout(new FlowLayout());
tree_ = new JButton("Tree View");
//MyAction myAction = new MyAction();
tree_.addActionListener(this);
button.add(tree_);
edit_ = new JButton("Edit GridAttribute");
edit_.addActionListener(this);
button.add(edit_);
print_= new JButton("Print");
print_.addActionListener(this);
button.add(print_);
save_= new JButton("Save");
save_.addActionListener(this);
button.add(save_);
color_= new JButton("Colors...");
color_.addActionListener(this);
button.add(color_);
// Optionally leave the "mark" button out of the button panel
if(mark) {
space_ = new JButton("Add Mark");
space_.addActionListener(this);
button.add(space_);
}
return button;
}
/**
* more hacking here
*/
public void showIt() {
frame.setVisible(true);
try {
Thread.sleep(3000);
BufferedImage ii = getImage();
//String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(fileName+".png"));
//System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
}
}
private JFrame frame = null;
public void run() {
/*
* Create a new JFrame to contain the demo.
*/
frame = new JFrame("Grid Demo");
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);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
/*
* Create button panel with "mark" button
*/
JPanel button = 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_ = makeGraph();
rpl_.setBatch(true);
/*
* Layout the plot, key, and buttons.
*/
main.add(rpl_, BorderLayout.CENTER);
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();
}
/**
* 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.
*/
private JPlotLayout makeGraph() {
o("inside makeGraph");
//SimpleGrid sg;
SimpleGrid sg;
//TestData td;
JPlotLayout rpl;
//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();
sg = new SimpleGrid(zValues, xValues, yValues, "Quantar");
sg.setXMetaData(new SGTMetaData(xLabel1, xLabel2));
sg.setYMetaData(new SGTMetaData(yLabel1, yLabel2));
//sg.setXMetaData(new SGTMetaData("Interstellar He Wind Temperature", "deg K"));
//sg.setYMetaData(new SGTMetaData("Interstellar He Bulk Speed", "km/s"));
sg.setZMetaData(new SGTMetaData(unitString, ""));
// newData.setKeyTitle(new SGLabel("a","test",new Point2D.Double(0.0,0.0)) );
// newData.setTimeArray(GeoDate[] tloc)
// newData.setTimeEdges(GeoDate[] edge);
sg.setTitle("tttest");
// newData.setXEdges(double[] edge);
// newData.setYEdges(double[] edge);
newData = sg;
//newData = sg.copy();
//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.
//datar = new Range2D(zMin, zMax, (zMax-zMin)/6);
//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_, "Diff. EFlux (1/cm^2/s/sr)");
rpl.addData(newData, gridAttr_, unitString);
// rpl.addData(newData);
/*
* Change the layout's three title lines.
*/
rpl.setTitles(label1,label2,"");
/*
* 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;
}
private ColorMap createColorMap(Range2D datar) {
int[] red =
{ 255, 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 =
{ 255, 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 =
{ 255,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;
}
/**
* here's a simpler map...
*/
private ColorMap createMonochromeMap(Range2D datar) {
int[] red = new int[200];
int[] green = new int [200];
int[] blue = new int [200];
red[0]=255; //red[1]=255;
green[0]=255; ///green[1]=255;
blue[0]=255; //lue[1]=255;
for (int i=1; i<red.length; i++) {
red[i]=230-i;
green[i]=230-i;
blue[i]=230-i;
}
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if(obj == save_) {
try {
BufferedImage ii = getImage();
String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(s+".png"));
//File outputFile = new File("gifOutput_" +1+".gif");
//FileOutputStream fos = new FileOutputStream(outputFile);
//o("starting to write animated gif...");
////writeAnimatedGIF(ii,"CTOF He+", true, 3.0, fos);
//writeNormalGIF(ii, "MFI PSD", -1, false, fos);
//fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (obj == print_) {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
o("printing...");
job.print();
o("done...");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
else if (obj == color_) {
try {
System.out.println("changing color scale");
rpl_.setVisible(false);
rpl_.clear();
cMin = Float.parseFloat(
JOptionPane.showInputDialog(this,"Min. Color Value: ",cMin+""));
cMax = Float.parseFloat(
JOptionPane.showInputDialog(this,"Max. Color Value: ",cMax+""));
cDelta = Float.parseFloat(
JOptionPane.showInputDialog(this,"Delta. Color Value: ",cDelta+""));
rpl_.addData(newData, gridAttr_, "EFlux");
rpl_.setVisible(true);
}
catch (Exception e) {e.printStackTrace();}
}
}
private static void o(String s) {
System.out.println(s);
}
/*private void writeNormalGIF(Image img,
String annotation,
int transparent_index, // pass -1 for none
boolean interlaced,
OutputStream out) throws IOException {
Gif89Encoder gifenc = new Gif89Encoder(img);
gifenc.setComments(annotation);
gifenc.setTransparentIndex(transparent_index);
gifenc.getFrameAt(0).setInterlaced(interlaced);
gifenc.encode(out);
}*/
/**
* Use this to set the labels that will appear on the graph when you call "run()".
*
* This first is the big title, second subtitle, third units on color scale (z axis)
*/
public void setLabels(String l1, String l2, String l3) {
unitString = l3;
label1 = l1;
label2 = l2;
}
public void setXAxisLabels(String l1, String l2) {
xLabel1 = l1;
xLabel2 = l2;
}
public void setYAxisLabels(String l1, String l2) {
yLabel1 = l1;
yLabel2 = l2;
}
public BufferedImage getImage() {
//Image ii = rpl_.getIconImage();
//if (ii==null) {
// System.out.println ("lpl ain't got no image");
//}
//else {
//ImageIcon i = new ImageIcon(ii);
// return ii;
//}
try {
//show();
//setDefaultSizes();
//rpl.setAutoRange(false,false);
//rpl.setRange(new Domain(new Range2D(1.3, 4.0), new Range2D(0.0, 35000.0)));
rpl_.draw();
//show();
Robot r = new Robot();
Point p = main.getLocationOnScreen();
Dimension d = new Dimension(main.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;
}
}
}
// some code from original below
/*
public static void main(String[] args) {
// Create the demo as an application
JColorGraph gd = new JColorGraph();
// 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);
}
*/
/* class MyAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
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());
}
}*/
/*
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);
}
*/ | 0lism | trunk/java/JColorGraph.java | Java | gpl3 | 19,601 |
import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
import drasys.or.nonlinear.*;
public class BofTheta {
public static double Ms = 2 * Math.pow(10,30);
public static double G = 667 * Math.pow(10,-13);
public static double AU = 15* Math.pow(10,12);
private double r, v0;
private Simpsons s;
private EquationSolution es;
public BofTheta(double r, double v0) {
this.r = r; this.v0 = v0;
System.out.println("r= " + r);
s = new Simpsons(); s.setEpsilon(.001);
es = new EquationSolution(); es.setAccuracy(1); es.setMaxIterations(100);
System.out.println(es.getAccuracy() + " is accurate?");
System.out.println("r= " + r);
System.out.println(es.getMaxIterations()+"");
}
class DThetaDr implements FunctionI {
private double b = 0;
public DThetaDr(double b) {
this.b = b;
}
public double function(double rV) {
//System.out.println("Called function- "+b+ " " + r + " " +rV);
return v0*b/(rV*rV)*Math.sqrt(2*Ms*G/rV - v0*v0*b*b/(rV*rV) + v0*v0);
}
}
class ThetaOfB implements FunctionI {
public double function(double b) {
//System.out.println("Calling ThetaOfB");
DThetaDr dthDr = new DThetaDr(b);
//System.out.println("trying integral..." + dthDr.b);
try {
double q = s.integrate(dthDr, 1000*AU, r);
System.out.println("Theta= " + q);
return q;
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
public double calculate(double theta) {
ThetaOfB tob = new ThetaOfB();
try {
double bLimit = Math.sqrt(2*Ms*G*r/(v0*v0) + r*r);
return es.solve(tob, -bLimit, bLimit, theta);
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
| 0lism | trunk/java/BofTheta.java | Java | gpl3 | 1,738 |
/*
* 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]);
}
}
| 0lism | trunk/java/MaximFunct.java | Java | gpl3 | 2,980 |
import java.util.StringTokenizer;
import java.util.Random;
public class Benford {
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 Benford(String[] args) {
r=new Random();
try {
skipLines = Integer.parseInt(args[1]);
dataColumn = Integer.parseInt(args[2]);
digitTallies = new int[10][factors.length];
o("datacolumn: " + dataColumn + " skiplines: " + skipLines );
// set all digit tallies to zero
for (int i=0; i<factors.length; 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");
while ((line=inFile.readLine())!=null) {
String numString = "";
st = new StringTokenizer(line);
for (int j=0; j<dataColumn; j++) {
numString = st.nextToken();
}
//o("numstring: " + numString);
for (int i=0; i<factors.length; i++) {
double theNumber = Double.parseDouble(numString);
if (theNumber!=0.0) {
//o("thenumber " + theNumber);
if (i==factors.length-1) factors[9]=1+r.nextInt(9);
theNumber = theNumber*factors[i];
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_results.txt");
outFile.initWrite(false);
for (int j=0; j<10; j++) {
line = "";
for (int i=0; i<factors.length; 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) {
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) {
Benford b = new Benford(args);
}
public static void o(String s) {
System.out.println(s);
}
} | 0lism | trunk/java/Benford.java | Java | gpl3 | 2,305 |
/*
* Class Fmath
*
* USAGE: Mathematical class that supplements java.lang.Math and contains:
* the main physical constants
* trigonemetric functions absent from java.lang.Math
* some useful additional mathematical functions
* some conversion functions
*
* WRITTEN BY: Dr Michael Thomas Flanagan
*
* DATE: June 2002
* AMENDED: 6 January 2006, 12 April 2006, 5 May 2006, 28 July 2006, 27 December 2006,
* 29 March 2007, 29 April 2007
*
* DOCUMENTATION:
* See Michael Thomas Flanagan's Java library on-line web pages:
* http://www.ee.ucl.ac.uk/~mflanaga/java/
* http://www.ee.ucl.ac.uk/~mflanaga/java/Fmath.html
*
* Copyright (c) june 2002, April 2007
*
* 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.Vector;
public class Fmath{
// PHYSICAL CONSTANTS
public static final double N_AVAGADRO = 6.0221419947e23; /* mol^-1 */
public static final double K_BOLTZMANN = 1.380650324e-23; /* J K^-1 */
public static final double H_PLANCK = 6.6260687652e-34; /* J s */
public static final double H_PLANCK_RED = H_PLANCK/(2*Math.PI); /* J s */
public static final double C_LIGHT = 2.99792458e8; /* m s^-1 */
public static final double R_GAS = 8.31447215; /* J K^-1 mol^-1 */
public static final double F_FARADAY = 9.6485341539e4; /* C mol^-1 */
public static final double T_ABS = -273.15; /* Celsius */
public static final double Q_ELECTRON = -1.60217646263e-19; /* C */
public static final double M_ELECTRON = 9.1093818872e-31; /* kg */
public static final double M_PROTON = 1.6726215813e-27; /* kg */
public static final double M_NEUTRON = 1.6749271613e-27; /* kg */
public static final double EPSILON_0 = 8.854187817e-12; /* F m^-1 */
public static final double MU_0 = Math.PI*4e-7; /* H m^-1 (N A^-2) */
// MATHEMATICAL CONSTANTS
public static final double EULER_CONSTANT_GAMMA = 0.5772156649015627;
public static final double PI = Math.PI; /* 3.141592653589793D */
public static final double E = Math.E; /* 2.718281828459045D */
// METHODS
// LOGARITHMS
// Log to base 10 of a double number
public static double log10(double a){
return Math.log(a)/Math.log(10.0D);
}
// Log to base 10 of a float number
public static float log10(float a){
return (float) (Math.log((double)a)/Math.log(10.0D));
}
// Base 10 antilog of a double
public static double antilog10(double x){
return Math.pow(10.0D, x);
}
// Base 10 antilog of a float
public static float antilog10(float x){
return (float)Math.pow(10.0D, (double)x);
}
// Log to base e of a double number
public static double log(double a){
return Math.log(a);
}
// Log to base e of a float number
public static float log(float a){
return (float)Math.log((double)a);
}
// Base e antilog of a double
public static double antilog(double x){
return Math.exp(x);
}
// Base e antilog of a float
public static float antilog(float x){
return (float)Math.exp((double)x);
}
// Log to base 2 of a double number
public static double log2(double a){
return Math.log(a)/Math.log(2.0D);
}
// Log to base 2 of a float number
public static float log2(float a){
return (float) (Math.log((double)a)/Math.log(2.0D));
}
// Base 2 antilog of a double
public static double antilog2(double x){
return Math.pow(2.0D, x);
}
// Base 2 antilog of a float
public static float antilog2(float x){
return (float)Math.pow(2.0D, (double)x);
}
// Log to base b of a double number and double base
public static double log10(double a, double b){
return Math.log(a)/Math.log(b);
}
// Log to base b of a double number and int base
public static double log10(double a, int b){
return Math.log(a)/Math.log((double)b);
}
// Log to base b of a float number and flaot base
public static float log10(float a, float b){
return (float) (Math.log((double)a)/Math.log((double)b));
}
// Log to base b of a float number and int base
public static float log10(float a, int b){
return (float) (Math.log((double)a)/Math.log((double)b));
}
// Square of a double number
public static double square(double a){
return a*a;
}
// Square of a float number
public static float square(float a){
return a*a;
}
// Square of an int number
public static int square(int a){
return a*a;
}
// factorial of n
// argument and return are integer, therefore limited to 0<=n<=12
// see below for long and double arguments
public static int factorial(int n){
if(n<0)throw new IllegalArgumentException("n must be a positive integer");
if(n>12)throw new IllegalArgumentException("n must less than 13 to avoid integer overflow\nTry long or double argument");
int f = 1;
for(int i=2; i<=n; i++)f*=i;
return f;
}
// factorial of n
// argument and return are long, therefore limited to 0<=n<=20
// see below for double argument
public static long factorial(long n){
if(n<0)throw new IllegalArgumentException("n must be a positive integer");
if(n>20)throw new IllegalArgumentException("n must less than 21 to avoid long integer overflow\nTry double argument");
long f = 1;
long iCount = 2L;
while(iCount<=n){
f*=iCount;
iCount += 1L;
}
return f;
}
// factorial of n
// Argument is of type double but must be, numerically, an integer
// factorial returned as double but is, numerically, should be an integer
// numerical rounding may makes this an approximation after n = 21
public static double factorial(double n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 1.0D;
double iCount = 2.0D;
while(iCount<=n){
f*=iCount;
iCount += 1.0D;
}
return f;
}
// log to base e of the factorial of n
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(int n){
if(n<0 || (n-(int)n)!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
for(int i=2; i<=n; i++)f+=Math.log(i);
return f;
}
// log to base e of the factorial of n
// Argument is of type double but must be, numerically, an integer
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(long n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
long iCount = 2L;
while(iCount<=n){
f+=Math.log(iCount);
iCount += 1L;
}
return f;
}
// log to base e of the factorial of n
// Argument is of type double but must be, numerically, an integer
// log[e](factorial) returned as double
// numerical rounding may makes this an approximation
public static double logFactorial(double n){
if(n<0 || (n-Math.floor(n))!=0)throw new IllegalArgumentException("\nn must be a positive integer\nIs a Gamma funtion [Fmath.gamma(x)] more appropriate?");
double f = 0.0D;
double iCount = 2.0D;
while(iCount<=n){
f+=Math.log(iCount);
iCount += 1.0D;
}
return f;
}
// Maximum of a 1D array of doubles, aa
public static double maximum(double[] aa){
int n = aa.length;
double aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of floats, aa
public static float maximum(float[] aa){
int n = aa.length;
float aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of ints, aa
public static int maximum(int[] aa){
int n = aa.length;
int aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Maximum of a 1D array of longs, aa
public static long maximum(long[] aa){
long n = aa.length;
long aamax=aa[0];
for(int i=1; i<n; i++){
if(aa[i]>aamax)aamax=aa[i];
}
return aamax;
}
// Minimum of a 1D array of doubles, aa
public static double minimum(double[] aa){
int n = aa.length;
double aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of floats, aa
public static float minimum(float[] aa){
int n = aa.length;
float aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of ints, aa
public static int minimum(int[] aa){
int n = aa.length;
int aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Minimum of a 1D array of longs, aa
public static long minimum(long[] aa){
long n = aa.length;
long aamin=aa[0];
for(int i=1; i<n; i++){
if(aa[i]<aamin)aamin=aa[i];
}
return aamin;
}
// Reverse the order of the elements of a 1D array of doubles, aa
public static double[] reverseArray(double[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of floats, aa
public static float[] reverseArray(float[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of ints, aa
public static int[] reverseArray(int[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of longs, aa
public static long[] reverseArray(long[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// Reverse the order of the elements of a 1D array of char, aa
public static char[] reverseArray(char[] aa){
int n = aa.length;
char[] bb = new char[n];
for(int i=0; i<n; i++){
bb[i] = aa[n-1-i];
}
return bb;
}
// return absolute values of an array of doubles
public static double[] arrayAbs(double[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of floats
public static float[] arrayAbs(float[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of long
public static long[] arrayAbs(long[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// return absolute values of an array of int
public static int[] arrayAbs(int[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = Math.abs(aa[i]);
}
return bb;
}
// multiple all elements by a constant double[] by double -> double[]
public static double[] arrayMultByConstant(double[] aa, double constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[i]*constant;
}
return bb;
}
// multiple all elements by a constant int[] by double -> double[]
public static double[] arrayMultByConstant(int[] aa, double constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i]*constant;
}
return bb;
}
// multiple all elements by a constant double[] by int -> double[]
public static double[] arrayMultByConstant(double[] aa, int constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = aa[i]*(double)constant;
}
return bb;
}
// multiple all elements by a constant int[] by int -> double[]
public static double[] arrayMultByConstant(int[] aa, int constant){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)(aa[i]*constant);
}
return bb;
}
// finds the value of nearest element value in array to the argument value
public static double nearestElementValue(double[] array, double value){
double diff = Math.abs(array[0] - value);
double nearest = array[0];
for(int i=1; i<array.length; i++){
if(Math.abs(array[i] - value)<diff){
diff = Math.abs(array[i] - value);
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest element value in array to the argument value
public static int nearestElementIndex(double[] array, double value){
double diff = Math.abs(array[0] - value);
int nearest = 0;
for(int i=1; i<array.length; i++){
if(Math.abs(array[i] - value)<diff){
diff = Math.abs(array[i] - value);
nearest = i;
}
}
return nearest;
}
// finds the value of nearest lower element value in array to the argument value
public static double nearestLowerElementValue(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
double nearest = 0.0D;
int ii = 0;
boolean test = true;
double min = array[0];
while(test){
if(array[ii]<min)min = array[ii];
if((value - array[ii])>=0.0D){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = min;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest lower element value in array to the argument value
public static int nearestLowerElementIndex(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
int nearest = 0;
int ii = 0;
boolean test = true;
double min = array[0];
int minI = 0;
while(test){
if(array[ii]<min){
min = array[ii];
minI = ii;
}
if((value - array[ii])>=0.0D){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = minI;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest higher element value in array to the argument value
public static double nearestHigherElementValue(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
double nearest = 0.0D;
int ii = 0;
boolean test = true;
double max = array[0];
while(test){
if(array[ii]>max)max = array[ii];
if((array[ii] - value )>=0.0D){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = max;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest higher element value in array to the argument value
public static int nearestHigherElementIndex(double[] array, double value){
double diff0 = 0.0D;
double diff1 = 0.0D;
int nearest = 0;
int ii = 0;
boolean test = true;
double max = array[0];
int maxI = 0;
while(test){
if(array[ii]>max){
max = array[ii];
maxI = ii;
}
if((array[ii] - value )>=0.0D){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = maxI;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0.0D && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest element value in array to the argument value
public static int nearestElementValue(int[] array, int value){
int diff = (int) Math.abs(array[0] - value);
int nearest = array[0];
for(int i=1; i<array.length; i++){
if((int) Math.abs(array[i] - value)<diff){
diff = (int)Math.abs(array[i] - value);
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest element value in array to the argument value
public static int nearestElementIndex(int[] array, int value){
int diff = (int) Math.abs(array[0] - value);
int nearest = 0;
for(int i=1; i<array.length; i++){
if((int) Math.abs(array[i] - value)<diff){
diff = (int)Math.abs(array[i] - value);
nearest = i;
}
}
return nearest;
}
// finds the value of nearest lower element value in array to the argument value
public static int nearestLowerElementValue(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int min = array[0];
while(test){
if(array[ii]<min)min = array[ii];
if((value - array[ii])>=0){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = min;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest lower element value in array to the argument value
public static int nearestLowerElementIndex(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int min = array[0];
int minI = 0;
while(test){
if(array[ii]<min){
min = array[ii];
minI = ii;
}
if((value - array[ii])>=0){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = minI;
diff0 = min - value;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = value - array[i];
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// finds the value of nearest higher element value in array to the argument value
public static int nearestHigherElementValue(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int max = array[0];
while(test){
if(array[ii]>max)max = array[ii];
if((array[ii] - value )>=0){
diff0 = value - array[ii];
nearest = array[ii];
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = max;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = array[i];
}
}
return nearest;
}
// finds the index of nearest higher element value in array to the argument value
public static int nearestHigherElementIndex(int[] array, int value){
int diff0 = 0;
int diff1 = 0;
int nearest = 0;
int ii = 0;
boolean test = true;
int max = array[0];
int maxI = 0;
while(test){
if(array[ii]>max){
max = array[ii];
maxI = ii;
}
if((array[ii] - value )>=0){
diff0 = value - array[ii];
nearest = ii;
test = false;
}
else{
ii++;
if(ii>array.length-1){
nearest = maxI;
diff0 = value - max;
test = false;
}
}
}
for(int i=0; i<array.length; i++){
diff1 = array[i]- value;
if(diff1>=0 && diff1<diff0 ){
diff0 = diff1;
nearest = i;
}
}
return nearest;
}
// Sum of all array elements - double array
public static double arraySum(double[]array){
double sum = 0.0D;
for(double i:array)sum += i;
return sum;
}
// Sum of all array elements - float array
public static float arraySum(float[]array){
float sum = 0.0F;
for(float i:array)sum += i;
return sum;
}
// Sum of all array elements - int array
public static int arraySum(int[]array){
int sum = 0;
for(int i:array)sum += i;
return sum;
}
// Sum of all array elements - long array
public static long arraySum(long[]array){
long sum = 0L;
for(long i:array)sum += i;
return sum;
}
// Product of all array elements - double array
public static double arrayProduct(double[]array){
double product = 1.0D;
for(double i:array)product *= i;
return product;
}
// Product of all array elements - float array
public static float arrayProduct(float[]array){
float product = 1.0F;
for(float i:array)product *= i;
return product;
}
// Product of all array elements - int array
public static int arrayProduct(int[]array){
int product = 1;
for(int i:array)product *= i;
return product;
}
// Product of all array elements - long array
public static long arrayProduct(long[]array){
long product = 1L;
for(long i:array)product *= i;
return product;
}
// Concatenate two double arrays
public static double[] concatenate(double[] aa, double[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
double[] cc = new double[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two float arrays
public static float[] concatenate(float[] aa, float[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
float[] cc = new float[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two int arrays
public static int[] concatenate(int[] aa, int[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
int[] cc = new int[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// Concatenate two long arrays
public static long[] concatenate(long[] aa, long[] bb){
int aLen = aa.length;
int bLen = bb.length;
int cLen = aLen + bLen;
long[] cc = new long[cLen];
for(int i=0; i<aLen; i++)cc[i] = aa[i];
for(int i=0; i<bLen; i++)cc[i+aLen] = bb[i];
return cc;
}
// recast an array of float as doubles
public static double[] floatTOdouble(float[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of int as double
public static double[] intTOdouble(int[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of int as float
public static float[] intTOfloat(int[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of int as long
public static long[] intTOlong(int[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of long as double
// BEWARE POSSIBLE LOSS OF PRECISION
public static double[] longTOdouble(long[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of long as float
// BEWARE POSSIBLE LOSS OF PRECISION
public static float[] longTOfloat(long[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of short as double
public static double[] shortTOdouble(short[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (double)aa[i];
}
return bb;
}
// recast an array of short as float
public static float[] shortTOfloat(short[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of short as long
public static long[] shortTOlong(short[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of short as int
public static int[] shortTOint(short[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as double
public static double[] byteTOdouble(byte[] aa){
int n = aa.length;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as float
public static float[] byteTOfloat(byte[] aa){
int n = aa.length;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i] = (float)aa[i];
}
return bb;
}
// recast an array of byte as long
public static long[] byteTOlong(byte[] aa){
int n = aa.length;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i] = (long)aa[i];
}
return bb;
}
// recast an array of byte as int
public static int[] byteTOint(byte[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// recast an array of byte as short
public static short[] byteTOshort(byte[] aa){
int n = aa.length;
short[] bb = new short[n];
for(int i=0; i<n; i++){
bb[i] = (short)aa[i];
}
return bb;
}
// recast an array of double as int
// BEWARE OF LOSS OF PRECISION
public static int[] doubleTOint(double[] aa){
int n = aa.length;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i] = (int)aa[i];
}
return bb;
}
// print an array of doubles to screen
// No line returns except at the end
public static void print(double[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of doubles to screen
// with line returns
public static void println(double[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of floats to screen
// No line returns except at the end
public static void print(float[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of floats to screen
// with line returns
public static void println(float[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of ints to screen
// No line returns except at the end
public static void print(int[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of ints to screen
// with line returns
public static void println(int[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of longs to screen
// No line returns except at the end
public static void print(long[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of longs to screen
// with line returns
public static void println(long[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of char to screen
// No line returns except at the end
public static void print(char[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of char to screen
// with line returns
public static void println(char[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// print an array of String to screen
// No line returns except at the end
public static void print(String[] aa){
for(int i=0; i<aa.length; i++){
System.out.print(aa[i]+" ");
}
System.out.println();
}
// print an array of Strings to screen
// with line returns
public static void println(String[] aa){
for(int i=0; i<aa.length; i++){
System.out.println(aa[i]+" ");
}
}
// sort elements in an array of doubles into ascending order
// using selection sort method
// returns Vector containing the original array, the sorted array
// and an array of the indices of the sorted array
public static Vector<Object> selectSortVector(double[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double holdb = 0.0D;
int holdi = 0;
double[] bb = new double[n];
int[] indices = new int[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
Vector<Object> vec = new Vector<Object>();
vec.addElement(aa);
vec.addElement(bb);
vec.addElement(indices);
return vec;
}
// sort elements in an array of doubles into ascending order
// using selection sort method
public static double[] selectionSort(double[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double hold = 0.0D;
double[] bb = new double[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of floats into ascending order
// using selection sort method
public static float[] selectionSort(float[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
float hold = 0.0F;
float[] bb = new float[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of ints into ascending order
// using selection sort method
public static int[] selectionSort(int[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int hold = 0;
int[] bb = new int[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of longs into ascending order
// using selection sort method
public static long[] selectionSort(long[] aa){
int index = 0;
int lastIndex = -1;
int n = aa.length;
long hold = 0L;
long[] bb = new long[n];
for(int i=0; i<n; i++){
bb[i]=aa[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
hold=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=hold;
}
return bb;
}
// sort elements in an array of doubles into ascending order
// using selection sort method
// returns Vector containing the original array, the sorted array
// and an array of the indices of the sorted array
public static void selectionSort(double[] aa, double[] bb, int[] indices){
int index = 0;
int lastIndex = -1;
int n = aa.length;
double holdb = 0.0D;
int holdi = 0;
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
}
// sort the elements of an array into ascending order with matching switches in an array of the length
// using selection sort method
// array determining the order is the first argument
// matching array is the second argument
// sorted arrays returned as third and fourth arguments resopectively
public static void selectionSort(double[] aa, double[] bb, double[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(float[] aa, float[] bb, float[] cc, float[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
float holdx = 0.0F;
float holdy = 0.0F;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, long[] bb, long[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, int[] bb, int[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(double[] aa, long[] bb, double[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, double[] bb, long[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(double[] aa, int[] bb, double[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
double holdx = 0.0D;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, double[] bb, int[] cc, double[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
double holdy = 0.0D;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(long[] aa, int[] bb, long[] cc, int[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
long holdx = 0L;
int holdy = 0;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
public static void selectionSort(int[] aa, long[] bb, int[] cc, long[] dd){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(n!=m)throw new IllegalArgumentException("First argument array, aa, (length = " + n + ") and the second argument array, bb, (length = " + m + ") should be the same length");
int nn = cc.length;
if(nn<n)throw new IllegalArgumentException("The third argument array, cc, (length = " + nn + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int mm = dd.length;
if(mm<m)throw new IllegalArgumentException("The fourth argument array, dd, (length = " + mm + ") should be at least as long as the second argument array, bb, (length = " + m + ")");
int holdx = 0;
long holdy = 0L;
for(int i=0; i<n; i++){
cc[i]=aa[i];
dd[i]=bb[i];
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(cc[i]<cc[index]){
index=i;
}
}
lastIndex++;
holdx=cc[index];
cc[index]=cc[lastIndex];
cc[lastIndex]=holdx;
holdy=dd[index];
dd[index]=dd[lastIndex];
dd[lastIndex]=holdy;
}
}
// sort elements in an array of doubles (first argument) into ascending order
// using selection sort method
// returns the sorted array as second argument
// and an array of the indices of the sorted array as the third argument
public static void selectSort(double[] aa, double[] bb, int[] indices){
int index = 0;
int lastIndex = -1;
int n = aa.length;
int m = bb.length;
if(m<n)throw new IllegalArgumentException("The second argument array, bb, (length = " + m + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
int k = indices.length;
if(m<n)throw new IllegalArgumentException("The third argument array, indices, (length = " + k + ") should be at least as long as the first argument array, aa, (length = " + n + ")");
double holdb = 0.0D;
int holdi = 0;
for(int i=0; i<n; i++){
bb[i]=aa[i];
indices[i]=i;
}
while(lastIndex != n-1){
index = lastIndex+1;
for(int i=lastIndex+2; i<n; i++){
if(bb[i]<bb[index]){
index=i;
}
}
lastIndex++;
holdb=bb[index];
bb[index]=bb[lastIndex];
bb[lastIndex]=holdb;
holdi=indices[index];
indices[index]=indices[lastIndex];
indices[lastIndex]=holdi;
}
}
/* returns -1 if x < 0 else returns 1 */
// double version
public static double sign(double x){
if (x<0.0){
return -1.0;
}
else{
return 1.0;
}
}
/* returns -1 if x < 0 else returns 1 */
// float version
public static float sign(float x){
if (x<0.0F){
return -1.0F;
}
else{
return 1.0F;
}
}
/* returns -1 if x < 0 else returns 1 */
// int version
public static int sign(int x){
if (x<0){
return -1;
}
else{
return 1;
}
}
/* returns -1 if x < 0 else returns 1 */
// long version
public static long sign(long x){
if (x<0){
return -1;
}
else{
return 1;
}
}
// UNIT CONVERSIONS
// Converts radians to degrees
public static double radToDeg(double rad){
return rad*180.0D/Math.PI;
}
// Converts degrees to radians
public static double degToRad(double deg){
return deg*Math.PI/180.0D;
}
// Converts electron volts(eV) to corresponding wavelength in nm
public static double evToNm(double ev){
return 1e+9*C_LIGHT/(-ev*Q_ELECTRON/H_PLANCK);
}
// Converts wavelength in nm to matching energy in eV
public static double nmToEv(double nm)
{
return C_LIGHT/(-nm*1e-9)*H_PLANCK/Q_ELECTRON;
}
// Converts moles per litre to percentage weight by volume
public static double molarToPercentWeightByVol(double molar, double molWeight){
return molar*molWeight/10.0D;
}
// Converts percentage weight by volume to moles per litre
public static double percentWeightByVolToMolar(double perCent, double molWeight){
return perCent*10.0D/molWeight;
}
// Converts Celsius to Kelvin
public static double celsiusToKelvin(double cels){
return cels-T_ABS;
}
// Converts Kelvin to Celsius
public static double kelvinToCelsius(double kelv){
return kelv+T_ABS;
}
// Converts Celsius to Fahrenheit
public static double celsiusToFahren(double cels){
return cels*(9.0/5.0)+32.0;
}
// Converts Fahrenheit to Celsius
public static double fahrenToCelsius(double fahr){
return (fahr-32.0)*5.0/9.0;
}
// Converts calories to Joules
public static double calorieToJoule(double cal){
return cal*4.1868;
}
// Converts Joules to calories
public static double jouleToCalorie(double joule){
return joule*0.23884;
}
// Converts grams to ounces
public static double gramToOunce(double gm){
return gm/28.3459;
}
// Converts ounces to grams
public static double ounceToGram(double oz){
return oz*28.3459;
}
// Converts kilograms to pounds
public static double kgToPound(double kg){
return kg/0.4536;
}
// Converts pounds to kilograms
public static double poundToKg(double pds){
return pds*0.4536;
}
// Converts kilograms to tons
public static double kgToTon(double kg){
return kg/1016.05;
}
// Converts tons to kilograms
public static double tonToKg(double tons){
return tons*1016.05;
}
// Converts millimetres to inches
public static double millimetreToInch(double mm){
return mm/25.4;
}
// Converts inches to millimetres
public static double inchToMillimetre(double in){
return in*25.4;
}
// Converts feet to metres
public static double footToMetre(double ft){
return ft*0.3048;
}
// Converts metres to feet
public static double metreToFoot(double metre){
return metre/0.3048;
}
// Converts yards to metres
public static double yardToMetre(double yd){
return yd*0.9144;
}
// Converts metres to yards
public static double metreToYard(double metre){
return metre/0.9144;
}
// Converts miles to kilometres
public static double mileToKm(double mile){
return mile*1.6093;
}
// Converts kilometres to miles
public static double kmToMile(double km){
return km/1.6093;
}
// Converts UK gallons to litres
public static double gallonToLitre(double gall){
return gall*4.546;
}
// Converts litres to UK gallons
public static double litreToGallon(double litre){
return litre/4.546;
}
// Converts UK quarts to litres
public static double quartToLitre(double quart){
return quart*1.137;
}
// Converts litres to UK quarts
public static double litreToQuart(double litre){
return litre/1.137;
}
// Converts UK pints to litres
public static double pintToLitre(double pint){
return pint*0.568;
}
// Converts litres to UK pints
public static double litreToPint(double litre){
return litre/0.568;
}
// Converts UK gallons per mile to litres per kilometre
public static double gallonPerMileToLitrePerKm(double gallPmile){
return gallPmile*2.825;
}
// Converts litres per kilometre to UK gallons per mile
public static double litrePerKmToGallonPerMile(double litrePkm){
return litrePkm/2.825;
}
// Converts miles per UK gallons to kilometres per litre
public static double milePerGallonToKmPerLitre(double milePgall){
return milePgall*0.354;
}
// Converts kilometres per litre to miles per UK gallons
public static double kmPerLitreToMilePerGallon(double kmPlitre){
return kmPlitre/0.354;
}
// Converts UK fluid ounce to American fluid ounce
public static double fluidOunceUKtoUS(double flOzUK){
return flOzUK*0.961;
}
// Converts American fluid ounce to UK fluid ounce
public static double fluidOunceUStoUK(double flOzUS){
return flOzUS*1.041;
}
// Converts UK pint to American liquid pint
public static double pintUKtoUS(double pintUK){
return pintUK*1.201;
}
// Converts American liquid pint to UK pint
public static double pintUStoUK(double pintUS){
return pintUS*0.833;
}
// Converts UK quart to American liquid quart
public static double quartUKtoUS(double quartUK){
return quartUK*1.201;
}
// Converts American liquid quart to UK quart
public static double quartUStoUK(double quartUS){
return quartUS*0.833;
}
// Converts UK gallon to American gallon
public static double gallonUKtoUS(double gallonUK){
return gallonUK*1.201;
}
// Converts American gallon to UK gallon
public static double gallonUStoUK(double gallonUS){
return gallonUS*0.833;
}
// Converts UK pint to American cup
public static double pintUKtoCupUS(double pintUK){
return pintUK/0.417;
}
// Converts American cup to UK pint
public static double cupUStoPintUK(double cupUS){
return cupUS*0.417;
}
// Calculates body mass index (BMI) from height (m) and weight (kg)
public static double calcBMImetric(double height, double weight){
return weight/(height*height);
}
// Calculates body mass index (BMI) from height (ft) and weight (lbs)
public static double calcBMIimperial(double height, double weight){
height = Fmath.footToMetre(height);
weight = Fmath.poundToKg(weight);
return weight/(height*height);
}
// Calculates weight (kg) to give a specified BMI for a given height (m)
public static double calcWeightFromBMImetric(double bmi, double height){
return bmi*height*height;
}
// Calculates weight (lbs) to give a specified BMI for a given height (ft)
public static double calcWeightFromBMIimperial(double bmi, double height){
height = Fmath.footToMetre(height);
double weight = bmi*height*height;
weight = Fmath.kgToPound(weight);
return weight;
}
// ADDITIONAL TRIGONOMETRIC FUNCTIONS
// Returns the length of the hypotenuse of a and b
// i.e. sqrt(a*a+b*b) [without unecessary overflow or underflow]
// double version
public static double hypot(double aa, double bb){
double amod=Math.abs(aa);
double bmod=Math.abs(bb);
double cc = 0.0D, ratio = 0.0D;
if(amod==0.0){
cc=bmod;
}
else{
if(bmod==0.0){
cc=amod;
}
else{
if(amod>=bmod){
ratio=bmod/amod;
cc=amod*Math.sqrt(1.0 + ratio*ratio);
}
else{
ratio=amod/bmod;
cc=bmod*Math.sqrt(1.0 + ratio*ratio);
}
}
}
return cc;
}
// Returns the length of the hypotenuse of a and b
// i.e. sqrt(a*a+b*b) [without unecessary overflow or underflow]
// float version
public static float hypot(float aa, float bb){
return (float) hypot((double) aa, (double) bb);
}
// Angle (in radians) subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double angle(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double ccos = Fmath.cos(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.acos(ccos);
}
// Angle (in radians) between sides sideA and sideB given all side lengths of a triangle
public static double angle(double sideAC, double sideBC, double sideAB){
double ccos = Fmath.cos(sideAC, sideBC, sideAB);
return Math.acos(ccos);
}
// Sine of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double sin(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double angle = Fmath.angle(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.sin(angle);
}
// Sine of angle between sides sideA and sideB given all side lengths of a triangle
public static double sin(double sideAC, double sideBC, double sideAB){
double angle = Fmath.angle(sideAC, sideBC, sideAB);
return Math.sin(angle);
}
// Sine given angle in radians
// for completion - returns Math.sin(arg)
public static double sin(double arg){
return Math.sin(arg);
}
// Inverse sine
// Fmath.asin Checks limits - Java Math.asin returns NaN if without limits
public static double asin(double a){
if(a<-1.0D && a>1.0D) throw new IllegalArgumentException("Fmath.asin argument (" + a + ") must be >= -1.0 and <= 1.0");
return Math.asin(a);
}
// Cosine of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double cos(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double sideAC = Fmath.hypot(xAtA - xAtC, yAtA - yAtC);
double sideBC = Fmath.hypot(xAtB - xAtC, yAtB - yAtC);
double sideAB = Fmath.hypot(xAtA - xAtB, yAtA - yAtB);
return Fmath.cos(sideAC, sideBC, sideAB);
}
// Cosine of angle between sides sideA and sideB given all side lengths of a triangle
public static double cos(double sideAC, double sideBC, double sideAB){
return 0.5D*(sideAC/sideBC + sideBC/sideAC - (sideAB/sideAC)*(sideAB/sideBC));
}
// Cosine given angle in radians
// for completion - returns Java Math.cos(arg)
public static double cos(double arg){
return Math.cos(arg);
}
// Inverse cosine
// Fmath.asin Checks limits - Java Math.asin returns NaN if without limits
public static double acos(double a){
if(a<-1.0D || a>1.0D) throw new IllegalArgumentException("Fmath.acos argument (" + a + ") must be >= -1.0 and <= 1.0");
return Math.acos(a);
}
// Tangent of angle subtended at coordinate C
// given x, y coordinates of all apices, A, B and C, of a triangle
public static double tan(double xAtA, double yAtA, double xAtB, double yAtB, double xAtC, double yAtC){
double angle = Fmath.angle(xAtA, yAtA, xAtB, yAtB, xAtC, yAtC);
return Math.tan(angle);
}
// Tangent of angle between sides sideA and sideB given all side lengths of a triangle
public static double tan(double sideAC, double sideBC, double sideAB){
double angle = Fmath.angle(sideAC, sideBC, sideAB);
return Math.tan(angle);
}
// Tangent given angle in radians
// for completion - returns Math.tan(arg)
public static double tan(double arg){
return Math.tan(arg);
}
// Inverse tangent
// for completion - returns Math.atan(arg)
public static double atan(double a){
return Math.atan(a);
}
// Inverse tangent - ratio numerator and denominator provided
// for completion - returns Math.atan2(arg)
public static double atan2(double a, double b){
return Math.atan2(a, b);
}
// Cotangent
public static double cot(double a){
return 1.0D/Math.tan(a);
}
// Inverse cotangent
public static double acot(double a){
return Math.atan(1.0D/a);
}
// Inverse cotangent - ratio numerator and denominator provided
public static double acot2(double a, double b){
return Math.atan2(b, a);
}
// Secant
public static double sec(double a){
return 1.0/Math.cos(a);
}
// Inverse secant
public static double asec(double a){
if(a<1.0D && a>-1.0D) throw new IllegalArgumentException("asec argument (" + a + ") must be >= 1 or <= -1");
return Math.acos(1.0/a);
}
// Cosecant
public static double csc(double a){
return 1.0D/Math.sin(a);
}
// Inverse cosecant
public static double acsc(double a){
if(a<1.0D && a>-1.0D) throw new IllegalArgumentException("acsc argument (" + a + ") must be >= 1 or <= -1");
return Math.asin(1.0/a);
}
// Exsecant
public static double exsec(double a){
return (1.0/Math.cos(a)-1.0D);
}
// Inverse exsecant
public static double aexsec(double a){
if(a<0.0D && a>-2.0D) throw new IllegalArgumentException("aexsec argument (" + a + ") must be >= 0.0 and <= -2");
return Math.asin(1.0D/(1.0D + a));
}
// Versine
public static double vers(double a){
return (1.0D - Math.cos(a));
}
// Inverse versine
public static double avers(double a){
if(a<0.0D && a>2.0D) throw new IllegalArgumentException("avers argument (" + a + ") must be <= 2 and >= 0");
return Math.acos(1.0D - a);
}
// Coversine
public static double covers(double a){
return (1.0D - Math.sin(a));
}
// Inverse coversine
public static double acovers(double a){
if(a<0.0D && a>2.0D) throw new IllegalArgumentException("acovers argument (" + a + ") must be <= 2 and >= 0");
return Math.asin(1.0D - a);
}
// Haversine
public static double hav(double a){
return 0.5D*Fmath.vers(a);
}
// Inverse haversine
public static double ahav(double a){
if(a<0.0D && a>1.0D) throw new IllegalArgumentException("ahav argument (" + a + ") must be >= 0 and <= 1");
return 0.5D*Fmath.vers(a);
}
// Sinc
public static double sinc(double a){
if(Math.abs(a)<1e-40){
return 1.0D;
}
else{
return Math.sin(a)/a;
}
}
//Hyperbolic sine of a double number
public static double sinh(double a){
return 0.5D*(Math.exp(a)-Math.exp(-a));
}
// Inverse hyperbolic sine of a double number
public static double asinh(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
return sgn*Math.log(a+Math.sqrt(a*a+1.0D));
}
//Hyperbolic cosine of a double number
public static double cosh(double a){
return 0.5D*(Math.exp(a)+Math.exp(-a));
}
// Inverse hyperbolic cosine of a double number
public static double acosh(double a){
if(a<1.0D) throw new IllegalArgumentException("acosh real number argument (" + a + ") must be >= 1");
return Math.log(a+Math.sqrt(a*a-1.0D));
}
//Hyperbolic tangent of a double number
public static double tanh(double a){
return sinh(a)/cosh(a);
}
// Inverse hyperbolic tangent of a double number
public static double atanh(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
if(a>1.0D) throw new IllegalArgumentException("atanh real number argument (" + sgn*a + ") must be >= -1 and <= 1");
return 0.5D*sgn*(Math.log(1.0D + a)-Math.log(1.0D - a));
}
//Hyperbolic cotangent of a double number
public static double coth(double a){
return 1.0D/tanh(a);
}
// Inverse hyperbolic cotangent of a double number
public static double acoth(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
if(a<1.0D) throw new IllegalArgumentException("acoth real number argument (" + sgn*a + ") must be <= -1 or >= 1");
return 0.5D*sgn*(Math.log(1.0D + a)-Math.log(a - 1.0D));
}
//Hyperbolic secant of a double number
public static double sech(double a){
return 1.0D/cosh(a);
}
// Inverse hyperbolic secant of a double number
public static double asech(double a){
if(a>1.0D || a<0.0D) throw new IllegalArgumentException("asech real number argument (" + a + ") must be >= 0 and <= 1");
return 0.5D*(Math.log(1.0D/a + Math.sqrt(1.0D/(a*a) - 1.0D)));
}
//Hyperbolic cosecant of a double number
public static double csch(double a){
return 1.0D/sinh(a);
}
// Inverse hyperbolic cosecant of a double number
public static double acsch(double a){
double sgn = 1.0D;
if(a<0.0D){
sgn = -1.0D;
a = -a;
}
return 0.5D*sgn*(Math.log(1.0/a + Math.sqrt(1.0D/(a*a) + 1.0D)));
}
// MANTISSA ROUNDING (TRUNCATING)
// returns a value of xDouble truncated to trunc decimal places
public static double truncate(double xDouble, int trunc){
double xTruncated = xDouble;
if(!Fmath.isNaN(xDouble)){
if(!Fmath.isPlusInfinity(xDouble)){
if(!Fmath.isMinusInfinity(xDouble)){
if(xDouble!=0.0D){
String xString = ((new Double(xDouble)).toString()).trim();
xTruncated = Double.parseDouble(truncateProcedure(xString, trunc));
}
}
}
}
return xTruncated;
}
// returns a value of xFloat truncated to trunc decimal places
public static float truncate(float xFloat, int trunc){
float xTruncated = xFloat;
if(!Fmath.isNaN(xFloat)){
if(!Fmath.isPlusInfinity(xFloat)){
if(!Fmath.isMinusInfinity(xFloat)){
if(xFloat!=0.0D){
String xString = ((new Float(xFloat)).toString()).trim();
xTruncated = Float.parseFloat(truncateProcedure(xString, trunc));
}
}
}
}
return xTruncated;
}
// private method for truncating a float or double expressed as a String
private static String truncateProcedure(String xValue, int trunc){
String xTruncated = xValue;
String xWorking = xValue;
String exponent = " ";
String first = "+";
int expPos = xValue.indexOf('E');
int dotPos = xValue.indexOf('.');
int minPos = xValue.indexOf('-');
if(minPos!=-1){
if(minPos==0){
xWorking = xWorking.substring(1);
first = "-";
dotPos--;
expPos--;
}
}
if(expPos>-1){
exponent = xWorking.substring(expPos);
xWorking = xWorking.substring(0,expPos);
}
String xPreDot = null;
String xPostDot = "0";
String xDiscarded = null;
String tempString = null;
double tempDouble = 0.0D;
if(dotPos>-1){
xPreDot = xWorking.substring(0,dotPos);
xPostDot = xWorking.substring(dotPos+1);
int xLength = xPostDot.length();
if(trunc<xLength){
xDiscarded = xPostDot.substring(trunc);
tempString = xDiscarded.substring(0,1) + ".";
if(xDiscarded.length()>1){
tempString += xDiscarded.substring(1);
}
else{
tempString += "0";
}
tempDouble = Math.round(Double.parseDouble(tempString));
if(trunc>0){
if(tempDouble>=5.0){
int[] xArray = new int[trunc+1];
xArray[0] = 0;
for(int i=0; i<trunc; i++){
xArray[i+1] = Integer.parseInt(xPostDot.substring(i,i+1));
}
boolean test = true;
int iCounter = trunc;
while(test){
xArray[iCounter] += 1;
if(iCounter>0){
if(xArray[iCounter]<10){
test = false;
}
else{
xArray[iCounter]=0;
iCounter--;
}
}
else{
test = false;
}
}
int preInt = Integer.parseInt(xPreDot);
preInt += xArray[0];
xPreDot = (new Integer(preInt)).toString();
tempString = "";
for(int i=1; i<=trunc; i++){
tempString += (new Integer(xArray[i])).toString();
}
xPostDot = tempString;
}
else{
xPostDot = xPostDot.substring(0, trunc);
}
}
else{
if(tempDouble>=5.0){
int preInt = Integer.parseInt(xPreDot);
preInt++;
xPreDot = (new Integer(preInt)).toString();
}
xPostDot = "0";
}
}
xTruncated = first + xPreDot.trim() + "." + xPostDot.trim() + exponent;
}
return xTruncated.trim();
}
// Returns true if x is infinite, i.e. is equal to either plus or minus infinity
// x is double
public static boolean isInfinity(double x){
boolean test=false;
if(x==Double.POSITIVE_INFINITY || x==Double.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is infinite, i.e. is equal to either plus or minus infinity
// x is float
public static boolean isInfinity(float x){
boolean test=false;
if(x==Float.POSITIVE_INFINITY || x==Float.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is plus infinity
// x is double
public static boolean isPlusInfinity(double x){
boolean test=false;
if(x==Double.POSITIVE_INFINITY)test=true;
return test;
}
// Returns true if x is plus infinity
// x is float
public static boolean isPlusInfinity(float x){
boolean test=false;
if(x==Float.POSITIVE_INFINITY)test=true;
return test;
}
// Returns true if x is minus infinity
// x is double
public static boolean isMinusInfinity(double x){
boolean test=false;
if(x==Double.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is minus infinity
// x is float
public static boolean isMinusInfinity(float x){
boolean test=false;
if(x==Float.NEGATIVE_INFINITY)test=true;
return test;
}
// Returns true if x is 'Not a Number' (NaN)
// x is double
public static boolean isNaN(double x){
boolean test=false;
if(x!=x)test=true;
return test;
}
// Returns true if x is 'Not a Number' (NaN)
// x is float
public static boolean isNaN(float x){
boolean test=false;
if(x!=x)test=true;
return test;
}
// Returns true if x equals y
// x and y are double
// x may be float within range, PLUS_INFINITY, NEGATIVE_INFINITY, or NaN
// NB!! This method treats two NaNs as equal
public static boolean isEqual(double x, double y){
boolean test=false;
if(Fmath.isNaN(x)){
if(Fmath.isNaN(y))test=true;
}
else{
if(Fmath.isPlusInfinity(x)){
if(Fmath.isPlusInfinity(y))test=true;
}
else{
if(Fmath.isMinusInfinity(x)){
if(Fmath.isMinusInfinity(y))test=true;
}
else{
if(x==y)test=true;
}
}
}
return test;
}
// Returns true if x equals y
// x and y are float
// x may be float within range, PLUS_INFINITY, NEGATIVE_INFINITY, or NaN
// NB!! This method treats two NaNs as equal
public static boolean isEqual(float x, float y){
boolean test=false;
if(Fmath.isNaN(x)){
if(Fmath.isNaN(y))test=true;
}
else{
if(Fmath.isPlusInfinity(x)){
if(Fmath.isPlusInfinity(y))test=true;
}
else{
if(Fmath.isMinusInfinity(x)){
if(Fmath.isMinusInfinity(y))test=true;
}
else{
if(x==y)test=true;
}
}
}
return test;
}
// Returns true if x equals y
// x and y are int
public static boolean isEqual(int x, int y){
boolean test=false;
if(x==y)test=true;
return test;
}
// Returns true if x equals y
// x and y are char
public static boolean isEqual(char x, char y){
boolean test=false;
if(x==y)test=true;
return test;
}
// Returns true if x equals y
// x and y are Strings
public static boolean isEqual(String x, String y){
boolean test=false;
if(x.equals(y))test=true;
return test;
}
// Returns true if x is an even number, false if x is an odd number
// x is int
public static boolean isEven(int x){
boolean test=false;
if(x%2 == 0.0D)test=true;
return test;
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are double
public static int compare(double x, double y){
Double X = new Double(x);
Double Y = new Double(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are int
public static int compare(int x, int y){
Integer X = new Integer(x);
Integer Y = new Integer(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are long
public static int compare(long x, long y){
Long X = new Long(x);
Long Y = new Long(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are float
public static int compare(float x, float y){
Float X = new Float(x);
Float Y = new Float(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are short
public static int compare(byte x, byte y){
Byte X = new Byte(x);
Byte Y = new Byte(y);
return X.compareTo(Y);
}
// Returns 0 if x == y
// Returns -1 if x < y
// Returns 1 if x > y
// x and y are short
public static int compare(short x, short y){
Short X = new Short(x);
Short Y = new Short(y);
return X.compareTo(Y);
}
// Returns true if x is an even number, false if x is an odd number
// x is float but must hold an integer value
public static boolean isEven(float x){
double y=Math.floor(x);
if(((double)x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=false;
y=Math.floor(x/2.0F);
if(((double)(x/2.0F)-y) == 0.0D)test=true;
return test;
}
// Returns true if x is an even number, false if x is an odd number
// x is double but must hold an integer value
public static boolean isEven(double x){
double y=Math.floor(x);
if((x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=false;
y=Math.floor(x/2.0F);
if((x/2.0D-y) == 0.0D)test=true;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is int
public static boolean isOdd(int x){
boolean test=true;
if(x%2 == 0.0D)test=false;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is float but must hold an integer value
public static boolean isOdd(float x){
double y=Math.floor(x);
if(((double)x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=true;
y=Math.floor(x/2.0F);
if(((double)(x/2.0F)-y) == 0.0D)test=false;
return test;
}
// Returns true if x is an odd number, false if x is an even number
// x is double but must hold an integer value
public static boolean isOdd(double x){
double y=Math.floor(x);
if((x - y)!= 0.0D)throw new IllegalArgumentException("the argument is not an integer");
boolean test=true;
y=Math.floor(x/2.0F);
if((x/2.0D-y) == 0.0D)test=false;
return test;
}
// Returns true if year (argument) is a leap year
public static boolean leapYear(int year){
boolean test = false;
if(year%4 != 0){
test = false;
}
else{
if(year%400 == 0){
test=true;
}
else{
if(year%100 == 0){
test=false;
}
else{
test=true;
}
}
}
return test;
}
// Returns milliseconds since 0 hours 0 minutes 0 seconds on 1 Jan 1970
public static long dateToJavaMilliS(int year, int month, int day, int hour, int min, int sec){
long[] monthDays = {0L, 31L, 28L, 31L, 30L, 31L, 30L, 31L, 31L, 30L, 31L, 30L, 31L};
long ms = 0L;
long yearDiff = 0L;
int yearTest = year-1;
while(yearTest>=1970){
yearDiff += 365;
if(Fmath.leapYear(yearTest))yearDiff++;
yearTest--;
}
yearDiff *= 24L*60L*60L*1000L;
long monthDiff = 0L;
int monthTest = month -1;
while(monthTest>0){
monthDiff += monthDays[monthTest];
if(Fmath.leapYear(year))monthDiff++;
monthTest--;
}
monthDiff *= 24L*60L*60L*1000L;
ms = yearDiff + monthDiff + day*24L*60L*60L*1000L + hour*60L*60L*1000L + min*60L*1000L + sec*1000L;
return ms;
}
}
| 0lism | trunk/java/Fmath.java | Java | gpl3 | 100,209 |
import java.util.StringTokenizer;
public class ParamPlotter {
public ParamPlotter() {
file f = new file("lVSv_6000_86p5_200k.txt");
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
// we are going to set the x and y graph params by hand here..
// easier than reading from a file because we created the x and y with code previously
// get the params from IBEXWind.java :
double 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 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 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;
for (int i=0; i<30; i++) {
x[i]=lamdaMin + i*lamdaDelta;
y[i]=vMin + i*vDelta;
}
String line = "";
f.initRead();
int zIndex = 0;
while ((line=f.readLine())!=null) {
StringTokenizer st = new StringTokenizer(line);
String garb = st.nextToken();
garb = st.nextToken();
try {
z[zIndex]=Math.log(Double.parseDouble(st.nextToken()));
}
catch (Exception e) {
e.printStackTrace();
}
zIndex++;
}
System.out.println("going to throw up a plot now ");
JColorGraph jcg;
//jcg = new JColorGraph(x,y,z,false);
jcg = new JColorGraph(x,y,z);
String unitString = "log sum of squares difference";
jcg.setLabels("IBEX-LO","2010",unitString);
jcg.setXAxisLabels("Interstellar He Longitude", "deg");
jcg.setYAxisLabels("Interstellar He Temperature", "deg K");
// sg.setXMetaData(new SGTMetaData("Interstellar He Wind Longitude", "deg"));
// sg.setYMetaData(new SGTMetaData("Interstellar He Wind Temperature", "deg K"));
jcg.run();
jcg.showIt();
}
public static final void main(String[] args) {
ParamPlotter pp = new ParamPlotter();
}
} | 0lism | trunk/java/ParamPlotter.java | Java | gpl3 | 2,320 |
import java.lang.Math;
import java.util.Date;
import java.util.Random;
import flanagan.integration.*;
//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) !!
*
* Testing in jan 2008 again..
*
* 16 points seems to work well enough for 4 digit precision of 3D gaussian integral in < 20ms
*/
public class MultipleIntegration {
public static double PLUS_INFINITY = Double.POSITIVE_INFINITY;
public static double MINUS_INFINITY = Double.NEGATIVE_INFINITY;
private double result;
public int npoints=128;
public int lastNP = 0;
public double smartMin = 0.0000000001;
Random r;
/**
* 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() {
r=new Random();
r.setSeed((new Date()).getTime());
counter = 0;
counter2 = 0;
result = 0.0;
}
/**
* sets counter to zero
*/
public void reset() {
counter = 0;
}
public void reset2() {
counter2 = 0;
}
/**
* Set accuracy of integration
*/
public void setEpsilon(double d) {
//s.setErrMax(d);
}
/**
* Deal with infinit limits here and call Flanagan gaussian quadrature for numeric integration
*
*/
public double gaussQuad(final FunctionI fI, final double min_l, final double max_l, final int np) {
try{ // if inifinite limits, replace arg x by x/1-x and integrate -1 to 1
if (min_l!=MINUS_INFINITY && max_l!=PLUS_INFINITY)
return Integration.gaussQuad(fI, min_l, max_l, np);
else if (min_l==MINUS_INFINITY && max_l==PLUS_INFINITY) {
// lets try recursion instead...
return
gaussQuad(fI, min_l, -10000.0, np/4) +
gaussQuad(fI, -10000.0, 0.0, np/4) +
gaussQuad(fI, 0.0, 10000.0, np/4) +
gaussQuad(fI, 10000.0, max_l, np/4);
/*FunctionI newFI = new FunctionI () {
public double function(double x) {
return (fI.function((1.0-x)/x)+fI.function((-1.0+x)/x))/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
*/
}
else if (min_l==MINUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return fI.function(max_l-(1.0-x)/x)/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
}
else if (max_l==PLUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return fI.function(min_l+(1.0-x)/x)/x/x;
}
};
return Integration.gaussQuad(newFI,0.0,1.0,np);
}
}
catch (Exception e) {
e.printStackTrace();
return 0.0;
}
return 0.0;
}
/**
* 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, final int np) {
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;
FunctionI funcII = new FunctionI () {
public double function(double x) {
return integrate(f.getFunctionII(2,x), nextLimits, np);
}
};
result = gaussQuad(funcII,limits[0],limits[1],np);
return result;
}
/**
* Here's the goods, for 2D integrations
*/
public double integrate(final FunctionII f, final double[] limits, final int np) {
FunctionI f1 = new FunctionI() {
public double function(double x) {
return integrate(f.getFunction(1,x),limits[2],limits[3], np);
}
};
result = gaussQuad(f1, limits[0], limits[1], np);
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 FunctionI f, double lowLimit, double highLimit, int np) {
//System.out.println("Called 1D integrator");
counter2++;
counter++;
//if (counter%10000==1) System.out.println("Counter: " + counter);
//s.setInterval(lowLimit,highLimit);
//return s.getResult(f);
return gaussQuad(f,lowLimit,highLimit,np);
//return
}
/**
* Monte-Carlo 1D Integration (not a good idea but for test)
*/
public double mcIntegrate(final FunctionI f, double lowLimit, double highLimit, int np) {
if (lowLimit == MINUS_INFINITY && highLimit == PLUS_INFINITY) {
FunctionI newFI = new FunctionI () {
public double function(double x) {
return (f.function((1.0-x)/x)+f.function((-1.0+x)/x))/x/x;
}
};
return mcIntegrate(newFI, 0.0, 1.0, np);
}
else {
r.setSeed((new Date()).getTime());
double tbr = 0.0;
for (int i=0; i<np; i++) {
// select random point
double point = r.nextGaussian()*(highLimit-lowLimit) + lowLimit;
tbr += f.function(point);
}
tbr*=(highLimit-lowLimit);
tbr/=np;
return tbr;
}
}
/**
* Monte-Carlo 2D Integration (not a good idea but for test)
*/
public double mcIntegrate(final FunctionII f, double[] limits, int np) {
r.setSeed((new Date()).getTime());
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double tbr = 0.0;
double xpoint,ypoint;
System.out.println("widths: " + w1 + " " + w2);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
tbr += f.function2(xpoint,ypoint);
}
tbr*=w1*w2;
tbr=tbr/(double)np;
return tbr;
}
/**
* Monte carlo 3D integral
*/
public double mcIntegrate(final FunctionIII f, double[] limits, int np) {
if (limits[0] == MINUS_INFINITY && limits[1] == PLUS_INFINITY &&
limits[2] == MINUS_INFINITY && limits[3] == PLUS_INFINITY &&
limits[4] == MINUS_INFINITY && limits[5] == PLUS_INFINITY) {
System.out.println("doing infinite MC");
FunctionIII newFI = new FunctionIII () {
public double function(double x,double y, double z) {
double xp = (1.0-x)/x;
double yp = (1.0-y)/y;
double zp = (1.0-z)/z;
return (f.function3(xp,yp,zp)+f.function3(-xp,yp,zp)+
f.function3(xp,-yp,zp)+f.function3(-xp,-yp,zp)+
f.function3(xp,yp,-zp)+f.function3(-xp,yp,-zp)+
f.function3(xp,-yp,-zp)+f.function3(-xp,-yp,-zp))/x/x/y/y/z/z;
}
};
double [] newLims = {0.0,1.0, 0.0,1.0, 0.0,1.0};
return mcIntegrate(newFI, newLims, np);
}
else {
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double w3 = limits[5]-limits[4];
double tbr = 0.0;
double xpoint,ypoint,zpoint;
// System.out.println("widths: " + w1 + " " + w2 + " " + w3);
for (int i=0; i<np; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
}
tbr*=w1*w2*w3;
tbr=tbr/(double)np;
return tbr;
}
}
/**
* Monte carlo 3D integral - this time with a certain number of threads
*/
public double mcIntegrate(final FunctionIII f, double[] limits, int np, int threads) {
double tbr = 0.0; // this is the total tbr, not the to be returned for a single thread
// set up the threads
int numPerThread = np/threads;
MCThread theMCs[] = new MCThread[threads];
for (int i=0; i<threads; i++) theMCs[i]=new MCThread(f, limits, numPerThread);
System.out.println("doing numPerThread: " + numPerThread);
// start them all
for (int i=0; i<threads; i++) theMCs[i].start();
// wait for them to finish
boolean allDone = false;
while (!allDone) {
boolean tempDone = true;
for (int i=0; i<threads; i++) {
if (!theMCs[i].finished) {
try { Thread.sleep(1000);} catch (Exception e) { e.printStackTrace(); }
tempDone = false;
}
}
if (tempDone) allDone=true;
}
// add their results
for (int i=0; i<threads; i++) tbr+= theMCs[i].tbr;
double w1 = limits[1]-limits[0];
double w2 = limits[3]-limits[2];
double w3 = limits[5]-limits[4];
tbr*=w1*w2*w3;
tbr=tbr/(double)np;
return tbr;
}
/**
* Make a smart estimate at the proper number of iterations to perform
*
*/
public double mcIntegrateS(final FunctionIII f, double[] limits, int max_np) {
int currentNP=100;
double result1 = 0;
double result2 = 1;
while(Math.abs(result2-result1)>Math.abs(0.05*result2) && currentNP<max_np) {
//System.out.println("trying np: " + currentNP);
result1=mcIntegrate(f,limits,currentNP);
currentNP*=2;
result2=mcIntegrate(f,limits,currentNP);
}
lastNP = currentNP;
return result2;
}
/**
* Monte carlo 3D integral - take 3, implement smart functionality inside integration routine
* without losing any time here!!
*/
public double mcIntegrateSS(final FunctionIII f, double[] limits, int maxNp) {
currentNP = 100;
tbr = 0.0; // running total!
tbrLast = 100.0;
tbrNew = 0.0;
numDone = 0;
w1 = limits[1]-limits[0];
w2 = limits[3]-limits[2];
w3 = limits[5]-limits[4];
while (Math.abs(tbrLast-tbrNew)>Math.abs(acc*tbrLast) & numDone<maxNp & Math.abs(tbrLast)>smartMin) {
tbrNew = tbrLast;
for (int i=numDone; i<currentNP; i++) {
// select random point
xpoint = r.nextDouble()*w1 + limits[0];
ypoint = r.nextDouble()*w2 + limits[2];
zpoint = r.nextDouble()*w3 + limits[4];
tbr += f.function3(xpoint,ypoint,zpoint);
numDone++;
}
tbrLast = tbr;
tbrLast*=w1*w2*w3;
tbrLast=tbrLast/(double)numDone;
currentNP = currentNP*2;
}
lastNP = numDone;
return tbrLast;
}
// VARIABLES FOR ABOVE ROUTINE HERE:
int currentNP = 100;
double acc=0.01;
double tbr = 0.0; // running total!
double tbrLast = 100.0;
double tbrNew = 0.0;
int numDone = 0;
double xpoint,ypoint,zpoint;
double w1, w2, w3;
/**
* 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!!
FunctionI testf1 = new FunctionI() {
public double function(double x) {
return Math.exp(-(x+20.0)*(x+20.0));
}
};
FunctionIII testf3 = new FunctionIII () {
public double function3(double x, double y, double z) {
return (Math.exp(-(x*x+y*y+z*z)));
}
};
FunctionIII testf4 = new FunctionIII () {
public double function3(double r, double p, double t) {
return r*r*Math.sin(t);
}
};
System.out.println("f1 gauss: "+mi.integrate(testf1,MINUS_INFINITY,PLUS_INFINITY,10000));
System.out.println("f1 gauss mc: "+mi.mcIntegrate(testf1,MINUS_INFINITY,PLUS_INFINITY,1000000));
System.out.println("sqrt pi: "+ Math.sqrt(Math.PI));
//System.out.println(""+mi.integrate(testf1,MINUS_INFINITY,0.0,512));
//System.out.println(""+mi.integrate(testf1,-100.0,0.0,512));
double[] lims = {MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY};
double[] lims2 = {-10.0,10.0,-10.0,10.0,-10.0,10.0};
double test3 = mi.integrate(testf3,lims2,64);
double test32 = mi.mcIntegrate(testf3,lims,1000000);
double test323 = mi.mcIntegrate(testf3,lims2,1000000);
System.out.println("test3 reg to 10: " + test3);
System.out.println("test3 mc: " + test32);
System.out.println("test3 mc to 10: " + test323);
System.out.println("pi to 3/2: "+ Math.pow(Math.PI,3.0/2.0));
System.out.println("new test");
double[] newLims = {0.0,2.0,0.0,2*Math.PI,0.0,Math.PI};
double newAns = mi.mcIntegrate(testf4,newLims,10000000);
System.out.println("answer new: " + newAns);
System.out.println("sphere volume " + (4.0/3.0*Math.PI*8.0));
double newAns2 = mi.mcIntegrateS(testf4,newLims,10000000);
System.out.println("answer new again: "+newAns2);
double newAns3 = mi.mcIntegrateSS(testf4,newLims,10000000);
System.out.println("answer new again SS: "+newAns3);
System.out.println("lastNP: " + mi.lastNP);
/*
// FOR TESTING 3D INTEGRALS
file f = new file("int_test.txt");
f.initWrite(false);
for (int i=1; i<256; i*=2) {
//System.out.println("lim: " + i);
Date d1 = new Date();
double test1 = mi.integrate(testf1, -100,100,i);
Date d2 = new Date();
//System.out.println("1D integrations: " + mi.counter);
double[] lims = {MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY, MINUS_INFINITY, PLUS_INFINITY};
double test3 = mi.integrate(testf3,lims,i);
Date d3 = new Date();
//System.out.println("3D integrations: " + mi.counter);
//System.out.println("Answer single gauss: " + test1);
//System.out.println("Answer trip gauss: " + test3);
//System.out.println("took: " + (d2.getTime()-d1.getTime()));
//System.out.println("took 3: " + (d3.getTime()-d2.getTime()));
f.write(i+"\t"+test3+"\t"+(d3.getTime()-d2.getTime()) + "\n");
}
f.closeWrite();
*/
/*
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));
*/
}
} | 0lism | trunk/java/MultipleIntegration.java | Java | gpl3 | 16,411 |
public class MyDouble {
public double value;
public MyDouble(double d) {
value=d;
}
} | 0lism | trunk/java/MyDouble.java | Java | gpl3 | 103 |
import java.lang.Math;
import java.util.Date;
/**
* Lukas Saul - March 27, 2001
* Taken from C routine Four1, from Numerical Recipes
*/
public class JFFT {
public double[] dOutReal;
public double[] dOutImaginary;
private double[] dInReal;
//private long nn;
//private int iSign;
//private double wr, wi, wpr, wpi, wtemp, theta;
// for testing here...
public static void main(String[] args) {
double[] testData = new double[10000];
for (int m=0; m<testData.length; m++) {
testData[m]=m*m+2*m+3; // random function
}
JFFT j = new JFFT(testData);
//for (int q=0; q<testData.length; q++) {
// System.out.println(j.dOutReal[q] + " " + j.dOutImaginary[q]);
//}
}
public JFFT(double[] _dIn) {
Date d1 = new Date();
dInReal = _dIn;
int size = dInReal.length;
System.out.println(size);
// what if dIn.length is not a power of 2?
int test=1;
int i = 0;
while (test != 0) {
i++;
test = size >> i; // divide by 2^i (binary shift)
//System.out.println("test = " + test);
}
i=i-1;
System.out.println("final i = " + i);
int dif = size - (int)Math.pow(2,i);
System.out.println("dif = " + dif);
if (dif > 0) { // In this case we need to pad the array with zeroes
double[] dIn2 = new double[(int)Math.pow(2.0,i+1)]; //this could be faster
//copy by hand
for (int k=0; k<dInReal.length; k++) {
dIn2[k]=dInReal[k];
}
for (int j=dInReal.length; j<dIn2.length; j++) {
dIn2[j]=0;
}
// the new data:
dInReal = dIn2;
System.out.println("new size " + dInReal.length);
}
Date d2 = new Date();
System.out.println("setup took: " + (d2.getTime() - d1.getTime()) );
// Set up our discrete complex array
double[] ourData = new double[dInReal.length*2];
for (int j=0; j<dInReal.length; j++) {
ourData[2*j] = dInReal[j];
ourData[2*j+1] = 0; // set imaginary part to zero
}
// Ok, let's do the FFT on the ourData array:
four1(ourData, dInReal.length, 1);
dOutReal = new double[dInReal.length];
dOutImaginary = new double[dInReal.length];
for (int j=0; j<dInReal.length; j++) {
dOutReal[j] = ourData[2*j];
dOutImaginary[j] = ourData[2*j+1];
}
Date d3 = new Date();
System.out.println("fft took: " + (d3.getTime() - d1.getTime()) );
}
public void four1(double[] data, int nn, int isign) {
System.out.println("computing fft with args: " + data.length + " " + nn);
long n, mmax, m, j, istep, i;
double wtemp, wr, wpr, wpi, wi, theta;
float tempr, tempi;
n = nn/2;
System.out.println("compare " + n + " " + nn + " " + nn/2);
j=1;
for (i=1; i<n; i+=2) {
if (j>i) {
swap(data[(int)j], data[(int)i]);
swap(data[(int)j+1], data[(int)i+1]);
}
m=n/2;
while (m >= 2 && j>m) {
j -= m;
m=m/2;
}
j += m;
}
// Here begins Danielson-Lanczos section of routine
mmax=2;
while (n > mmax) {
istep = mmax << 1;
theta = isign*(6.28318530717959/mmax);
wtemp = Math.sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi = Math.sin(theta);
wr=1.0;
wi=0.0;
for (m=1; m<mmax; m+=2) {
for (i=m; i<=n; i+=istep) {
j=i+mmax;
tempr = (float)(wr*data[(int)j] -
wi*data[(int)j+1]);
tempi = (float)(wr*data[(int)j+1] - wi*data[(int)j]);
data[(int)j] = data[(int)i] - tempr;
data[(int)j+1] = data[(int)i+1] - tempi;
data[(int)i] += tempr;
data[(int)i+1] += tempi;
}
wr = (wtemp=wr)*wpr - wi*wpi + wr;
wi = wi*wpr + wtemp*wpi + wi;
}
mmax = istep;
}
}
private void swap(double a, double b) {
double temp = a;
a=b;
b=temp;
}
} | 0lism | trunk/java/JFFT.java | Java | gpl3 | 3,708 |
/**
* A basic power law in ENERGY
*
*/
public class PowerLawVLISM extends InterstellarMedium {
public HelioVector vBulk;
public double power, density, lim1, lim2, norm, ee;
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);
/**
* Construct a power law VLISM
*/
public PowerLawVLISM(HelioVector _vBulk, double _density, double _power, double _ll, double _hh) {
vBulk = _vBulk;
power = _power;
density = _density;
lim1 = _ll;
lim2 = _hh;
// calculate normalization
norm = density/4/Math.PI/ (Math.pow(lim2,power+3.0)- Math.pow(lim1,power+3.0))*(power+3.0);
norm=norm;
System.out.println("norm: " + norm);
}
/**
*
* 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;
}
/**
* 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 PowerLawVLISM gvli = new PowerLawVLISM(new HelioVector(HelioVector.CARTESIAN,
-20000.0,0.0,0.0), 1.0, -4.0, 1000.0, 300000.0);
System.out.println("Created PLVLISM" );
//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);
}
}
| 0lism | trunk/java/KappaDistribution.java | Java | gpl3 | 3,615 |
/**
* 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 )
*/
public abstract class FunctionII {
/**
* Override this for the function needed!!
*
*/
public double function2(double x, double y) {
return 0;
}
/**
*
* This returns a one dimensional function, given one of the values fixed
*
*/
protected final Function getFunction(final int index, final double value) {
if (index == 0) return new Function() {
public double function(double x) {
return function2(value,x);
}
};
else if (index == 1) return new Function() {
public double function(double x) {
return function2(x,value);
}
};
else {
System.out.println("index out of range in FunctionII.getFunction");
return null;
}
}
}
| 0lism | trunk/java/FunctionIIoldo.java | Java | gpl3 | 879 |
/**
* Simulating response at IBEX_LO with this class
*
* Create interstellar medium and perform integration
*
*/
public class IBEXLO {
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 startPerp = 260.0*3.14/180.0; // FALL
//public double endPerp = 340.0*3.14/180.0; // FALL
public double he_ion_rate = 1.0*Math.pow(10,-7);
public double o_ion_rate = 8.0*Math.pow(10,-7);
// 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; // in square meters now!!
public file outF;
public MultipleIntegration mi;
/*
8.8 23.2
17.6 46.4
35.75 94.25
74.25 195.75
153.45 404.55
330.55 871.45
663.3 1748.7
1298.55 3423.45
he_S 73.7 194.3
he_F 4.4 11.6
o_S 293.7 774.3
o_F 18.15 47.85
*/
/**
*
*
*
*/
public IBEXLO() {
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];
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 = Math.PI/2;
//double finalPos = 1.5*Math.PI;
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 wet take smaller integration timest than an orbit.. current: 12 hours
//determine entrance velocity vector and integration range
double midPhi = initPos-Math.PI/2.0;
double midThe = Math.PI/2.0;
for (double pos = initPos; pos<finalPos; pos+= step) {
// inner loop moves pos2
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;
//int hrmn
//if (pos>downWind) {
// midPhi = pos + Math.PI/2.0;
// 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 il = new IBEXLO();
}
public static void o(String s) {
System.out.println(s);
}
}
| 0lism | trunk/java/IBEXLO.java | Java | gpl3 | 11,639 |
/**
*
*
*/
public abstract class Distribution {
} | 0lism | trunk/java/Distribution.java | Java | gpl3 | 54 |
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 gov.noaa.pmel.sgt.dm.SimpleGrid;
import gov.noaa.pmel.sgt.dm.*;
import gov.noaa.pmel.sgt.SGLabel;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.image.*;
import net.jmge.gif.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
/**
* Let's use this to take a look at 3D data with color...
*
* Put new code in makeGraph() routine
*
* Added to:
* @author Donald Denbo
* @version $Revision: 1.8 $, $Date: 2001/02/05 23:28:46 $
* @since 2.0
*
* Lukas Saul summer 2002
*/
public class JColorGraph extends PrintableDialog implements ActionListener{
public JPlotLayout rpl_;
public JPane gridKeyPane;
private GridAttribute gridAttr_;
JButton edit_;
JButton space_ = null;
JButton tree_;
JButton print_;
JButton save_;
JButton color_;
JPanel main;
Range2D datar;
ContourLevels clevels;
ColorMap cmap;
SGTData newData;
// defaults
private String unitString = "Diff. EFlux (1/cm^2/s/sr)";
private String label1 = "SOHO CTOF HE+";
private String label2 = "1996";
public double[] xValues;
public double[] yValues;
public double[] zValues;
public float xMax, xMin, yMax, yMin, zMax, zMin;
public float cMin, cMax, cDelta;
public boolean b_color;
public JColorGraph() {
b_color = true;
}
public JColorGraph(double[] x, double[] y, double[] z) {
this(x,y,z,true);
}
public JColorGraph(double[] x, double[] y, double[] z, boolean b) {
b_color = b;
xValues=x;
yValues=y;
zValues=z;
// assume here we are going to have input the data already
xMax = (float)xValues[0]; xMin = (float)xValues[0];
yMax = (float)yValues[0]; yMin = (float)yValues[0];
zMax = (float)zValues[0]; zMin = (float)zValues[0];
o("xMin: " + xMin);
for (int i=0; i<xValues.length; i++) {
if (xValues[i]<xMin) xMin = (float)xValues[i];
if (xValues[i]>xMax) xMax = (float)xValues[i];
}
for (int i=0; i<yValues.length; i++) {
if (yValues[i]<yMin) yMin = (float)yValues[i];
if (yValues[i]>yMax) yMax = (float)yValues[i];
}
for (int i=0; i<zValues.length; i++) {
if (zValues[i]<zMin) zMin = (float)zValues[i];
if (zValues[i]>zMax) zMax = (float)zValues[i];
}
o("xmin: " + xMin);
o("xmax: " + xMax);
cMin = zMin; cMax = zMax; cDelta = (zMax-zMin)/6;
datar = new Range2D(zMin, zMax, cDelta);
clevels = ContourLevels.getDefault(datar);
gridAttr_ = new GridAttribute(clevels);
if (b_color == true) cmap = createColorMap(datar);
else cmap = createMonochromeMap(datar);
gridAttr_.setColorMap(cmap);
gridAttr_.setStyle(GridAttribute.RASTER_CONTOUR);
}
private JPanel makeButtonPanel(boolean mark) {
JPanel button = new JPanel();
button.setLayout(new FlowLayout());
tree_ = new JButton("Tree View");
//MyAction myAction = new MyAction();
tree_.addActionListener(this);
button.add(tree_);
edit_ = new JButton("Edit GridAttribute");
edit_.addActionListener(this);
button.add(edit_);
print_= new JButton("Print");
print_.addActionListener(this);
button.add(print_);
save_= new JButton("Save");
save_.addActionListener(this);
button.add(save_);
color_= new JButton("Colors...");
color_.addActionListener(this);
button.add(color_);
// Optionally leave the "mark" button out of the button panel
if(mark) {
space_ = new JButton("Add Mark");
space_.addActionListener(this);
button.add(space_);
}
return button;
}
/**
* more hacking here
*/
public void showIt() {
frame.setVisible(true);
}
private JFrame frame = null;
public void run() {
/*
* Create a new JFrame to contain the demo.
*/
frame = new JFrame("Grid Demo");
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);
}
public void windowOpened(java.awt.event.WindowEvent event) {
rpl_.getKeyPane().draw();
}
});
/*
* Create button panel with "mark" button
*/
JPanel button = 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_ = makeGraph();
rpl_.setBatch(true);
/*
* Layout the plot, key, and buttons.
*/
main.add(rpl_, BorderLayout.CENTER);
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();
}
/**
* 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.
*/
private JPlotLayout makeGraph() {
o("inside makeGraph");
//SimpleGrid sg;
SimpleGrid sg;
//TestData td;
JPlotLayout rpl;
//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();
sg = new SimpleGrid(zValues, xValues, yValues, "Title");
sg.setXMetaData(new SGTMetaData("Helio Longitude", "deg"));
sg.setYMetaData(new SGTMetaData("Ecliptic Latitude", "deg"));
sg.setZMetaData(new SGTMetaData(unitString, ""));
// newData.setKeyTitle(new SGLabel("a","test",new Point2D.Double(0.0,0.0)) );
// newData.setTimeArray(GeoDate[] tloc)
// newData.setTimeEdges(GeoDate[] edge);
sg.setTitle("tttest");
// newData.setXEdges(double[] edge);
// newData.setYEdges(double[] edge);
newData = sg;
//newData = sg.copy();
//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.
//datar = new Range2D(zMin, zMax, (zMax-zMin)/6);
//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_, "Diff. EFlux (1/cm^2/s/sr)");
rpl.addData(newData, gridAttr_, unitString);
// rpl.addData(newData);
/*
* Change the layout's three title lines.
*/
rpl.setTitles(label1,label2,"");
/*
* 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;
}
private 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 =
{ 255,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;
}
/**
* here's a simpler map...
*/
private ColorMap createMonochromeMap(Range2D datar) {
int[] red = new int[200];
int[] green = new int [200];
int[] blue = new int [200];
red[0]=255; //red[1]=255;
green[0]=255; ///green[1]=255;
blue[0]=255; //lue[1]=255;
for (int i=1; i<red.length; i++) {
red[i]=230-i;
green[i]=230-i;
blue[i]=230-i;
}
IndexedColorMap cmap = new IndexedColorMap(red, green, blue);
cmap.setTransform(new LinearTransform(0.0, (double)red.length,
datar.start, datar.end));
return cmap;
}
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
else if(obj == save_) {
try {
BufferedImage ii = getImage();
String s = JOptionPane.showInputDialog("enter file name");
ImageIO.write(ii,"png",new File(s+".png"));
//File outputFile = new File("gifOutput_" +1+".gif");
//FileOutputStream fos = new FileOutputStream(outputFile);
//o("starting to write animated gif...");
////writeAnimatedGIF(ii,"CTOF He+", true, 3.0, fos);
//writeNormalGIF(ii, "MFI PSD", -1, false, fos);
//fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (obj == print_) {
System.out.println("Trying to print...");
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
if (job.printDialog()) {
try {
o("printing...");
job.print();
o("done...");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
//setCursor(Cursor.getDefaultCursor());
else if (obj == color_) {
try {
System.out.println("changing color scale");
rpl_.setVisible(false);
rpl_.clear();
cMin = Float.parseFloat(
JOptionPane.showInputDialog(this,"Min. Color Value: ",cMin+""));
cMax = Float.parseFloat(
JOptionPane.showInputDialog(this,"Max. Color Value: ",cMax+""));
cDelta = Float.parseFloat(
JOptionPane.showInputDialog(this,"Delta. Color Value: ",cDelta+""));
rpl_.addData(newData, gridAttr_, "EFlux");
rpl_.setVisible(true);
}
catch (Exception e) {e.printStackTrace();}
}
}
private static void o(String s) {
System.out.println(s);
}
private void writeNormalGIF(Image img,
String annotation,
int transparent_index, // pass -1 for none
boolean interlaced,
OutputStream out) throws IOException {
Gif89Encoder gifenc = new Gif89Encoder(img);
gifenc.setComments(annotation);
gifenc.setTransparentIndex(transparent_index);
gifenc.getFrameAt(0).setInterlaced(interlaced);
gifenc.encode(out);
}
/**
* Use this to set the labels that will appear on the graph when you call "run()".
*
* This first is the big title, second subtitle, third units on color scale (z axis)
*/
public void setLabels(String l1, String l2, String l3) {
unitString = l3;
label1 = l1;
label2 = l2;
}
public BufferedImage getImage() {
//Image ii = rpl_.getIconImage();
//if (ii==null) {
// System.out.println ("lpl ain't got no image");
//}
//else {
//ImageIcon i = new ImageIcon(ii);
// return ii;
//}
try {
//show();
//setDefaultSizes();
//rpl.setAutoRange(false,false);
//rpl.setRange(new Domain(new Range2D(1.3, 4.0), new Range2D(0.0, 35000.0)));
rpl_.draw();
//show();
Robot r = new Robot();
Point p = main.getLocationOnScreen();
Dimension d = new Dimension(main.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;
}
}
}
// some code from original below
/*
public static void main(String[] args) {
// Create the demo as an application
JColorGraph gd = new JColorGraph();
// 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);
}
*/
/* class MyAction implements java.awt.event.ActionListener {
public void actionPerformed(java.awt.event.ActionEvent event) {
Object source = event.getActionCommand();
Object obj = event.getSource();
if(obj == edit_)
edit_actionPerformed(event);
else if(obj == space_) {
System.out.println(" <<Mark>>");
}
else if(obj == tree_)
tree_actionPerformed(event);
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());
}
}*/
/*
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);
}
*/ | 0lism | trunk/java/JColorGraph_new.java | Java | gpl3 | 18,834 |
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!
*
* Uses an input distribution class to determine LISM f.
*
* Lukas Saul - Warsaw 2000
*
* Winter 2001 or so - got rid of Wu & Judge code
* Last Modified - October 2002 - moved lism distribution to separate class
* reviving - April 2004
*/
public class NeutralDistribution {
public static double Ms = 1.98892 * Math.pow(10,30); // kg
public static double G = 6.673 * Math.pow(10,-11);
public static double AU = 1.49598* Math.pow(10,11); //meters
public static double NaN = Double.NaN;
private double mu, beta, Gmod;
// 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 test2;
private HelioVector tempHV, thetaHat;
private double testX, testY, arg;
/**
* 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-mu);
// 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();
goingIn=false;
}
/**
* 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 geometry
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);
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;
// then calculate the v0 - vinf
//hpdif.setCoords(hpInflow);
//HelioVector.difference(hpdif, hpvi);
//o("hpdif: "+hpdif);
// we need to multiply by the survival probability here...
// then do the gaussian with survival probability
double answer = vlism.heliumDist(hpvi.getX(),hpvi.getY(),hpvi.getZ());
//o(""+answer);
return answer;
}
/**
* 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()"...
*
*/
private HelioVector getHPInfinity(HelioVector hpr, HelioVector hpv) {
double r = hpr.getR();
// - define orbital plane
// 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
if (hpn.getR()==0) {return null;} // problems with div. by zero if we are at the origin
else HelioVector.normalize(hpn);
// are we coming into the sun or going away?
// we need to know this for the geometry;
goingIn = false;
if (hpr.dotProduct(hpv)<0) goingIn = true;
// 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)
//hpox.setCoords(HelioVector.CARTESIAN, hpn.getY(), -hpn.getX(), 0);
hpox.setCoords(HelioVector.CARTESIAN, -hpr.getX()/r, -hpr.getY()/r, -hpr.getZ()/r);
HelioVector.normalize(hpox);
// this is the y axis in orbital plane
hpoy.setCoords(hpn);
HelioVector.crossProduct(hpoy, hpox); // hopy (Y) = hpn(Z) cross hpox (X)
o("hpoy size: " + hopy.getR());
HelioVector.normalize(hpoy);
o("hopy size: " + hopy.getR());
// we want the ++ quadrant to be where the particle came from, i.e.dtheta/dt positive
/*testY = hpr.dotProduct(hpoy);
testX = hpr.dotProduct(hpox);
if (goingIn && (testY<0)) {
HelioVector.invert(hpoy); //o("we have inverted hpoy 1...");
}
else if (!goingIn && (testY>0)) {
HelioVector.invert(hpoy); //o("we have inverted hpoy 2...");
}
if (goingIn && (testX<0)) {
HelioVector.invert(hpox); //o("we have inverted hpox 1...");
}
else if (!goingIn &&(testY>0)) {
HelioVector.invert(hpoy); //o("we have inverted hpox 2...");
}*/
// test so far
o("hpr: " + hpr.o());
o("hpv: " + hpv.o());
o("hpox: " + hpox.o());
o("hpoy: " + hpoy.o());
o("hpr dot hpox: " + hpr.dotProduct(hpox));
// ok, we have defined the orbital plane !
// now lets put the given coordinates into this plane
// they are: r, ptheta, rdot, thetadot
// Now we know ptheta, the orbital plane theta component
//ptheta = hpr.getAngle(hpox);
//if (!goingIn) ptheta = -ptheta + 2*Math.PI;
ptheta = Math.PI;
// we want rDot. This is the component of traj. parallel to our position
//
rdot = -hpv.dotProduct(hpr)/r;
// one way to get thetadot:
//
// thetadot = v_ cross r_ / r^2 ????
//
// using a temp variable to avoid "new Object()..."
//
//tempHV.setCoords(hpv);
//HelioVector.crossProduct(tempHV,hpr);
//thetadot = tempHV.getR()/r/r;
// yet a fucking nother way to get thetadot
//
// is from v = rdot rhat + r thetadot thetahat...
//
// thetadot thetahat = (v_ - rdot rhat) / r
//
// but we need the thetaHat to get the sign right
// thetaHat is just (0,-1) in our plane
// because we are sitting on the minus X axis
// thats how we chose hpox
//
thetaHat.setCoords(hpoy);
thetaHat.invert(); //we have thetahat
tempHV.setCoords(hpv);
HelioVector.product(tempHV,1.0/r);
HelioVector.difference(tempHV,hpr.product(rdot/r));
thetadot = tempHV.getR()/r;
// but what is the sign?
if (hpv.dotProduct(thetaHat),0) thetadot = -thetadot;
// test so far
o("Coords in orbital plane - r: " + hpr.getR());
o("ptheta: " + ptheta);
o("thetadot: " + thetadot);
o("rdot: " + rdot);
// 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..
L=r*r*thetadot; // ok - we know our angular momentum (/Mhe)
// NOW use the ENERGY conservation to compute
// rdoti - the velocity at infinity
//
//if ((test2=rdot*rdot - L*L/r/r + 2*Gmod*Ms/r) < 0) {
test2=hpv.dotProduct(hpv)-2*Gmod*Ms/r;
o("E= " + test2);
if (test2 < 0) {
o("discarding elipticals...");
// System.out.println("discarding elipticals");
return null;
}
o("E dif: " + ( (rdot*rdot + L*L/r/r - 2*Gmod*Ms/r) - test2 ));
rdoti=-Math.sqrt(test2);
o("rdoti: " + rdoti);
a = -Gmod*Ms/rdoti/rdoti;
// e = Math.sqrt(1+L*L*rdoti*rdoti/Gmod/Gmod/Ms/Ms);
e = Math.sqrt(1-L*L/a/Gmod/Ms);
if (e<=1) {
System.out.println("I thought we threw out ellipticals already??");
return null;
}
double maxPhi = Math.acos(1/e);
o("maxPhi: " + maxPhi);
o("e= " + e + " a= " + a);
// that pretty much defines the orbit, we need to find the angular shift
// to match with our coordinate system
arg = a*(1-e*e)/e/r - 1/e;
o("arg: " + arg);
if (arg<-1 | arg>1) {
o("problems here 9a8nv3");
//return null;
}
phi = Math.acos(arg)-maxPhi;
if (goingIn) { // we are in the +y half, ptheta<180
shift = ptheta-(Math.PI-phi);
pthetai = (Math.PI-maxPhi)+shift;
}
else {
shift = (Math.PI-phi)-(2*Math.PI-ptheta);
pthetai = (Math.PI-maxPhi)+shift;
}
o("phi: " + phi + " pthetai" + pthetai);
// now we know vinf in it's entirety. The vector, in original coordinates:
double vinfxo = rdoti*Math.cos(pthetai);
double 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.sum(answer,hpoy.product(vinfyo));
HelioVector.product(hpoy,vinfyo);
HelioVector.sum(answer,hpoy);
// that's a vector going away from the sun. Invert it
HelioVector.invert(answer);
return answer;
}
/**
* for testing only
*/
public static final void main(String[] args) {
/*parameters:
*/
Date dt3 = new Date();
NeutralDistribution nd = new NeutralDistribution(new GaussianVLISM(new HelioVector(),0.0,0.0),0.0,0.0);
Date dt4 = new Date();
o("constructor took: "+(dt4.getTime()-dt3.getTime()));
// test getHPInfinity
//HelioVector tttt = new HelioVector();
Date dt1 = new Date();
HelioVector r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,AU, 0.01);
HelioVector v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, -50000);
o("Trying r = AUy, v = -50000x");
HelioVector tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
double einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
double efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, AU,0.01,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01,-50000, 0.01);
o("Trying x axis, -50000y");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, -50000);
o("Trying z axis, -50000z");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, AU,0.01,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 50000, 0.01, 0.01);
o("Trying x axis, 50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, 50000);
o("Trying z axis, 50000z");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,AU,0.01);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 50000, 0.01);
o("Trying y axis, 50000y");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
//OK, that's 6 easy tests to see whats happening.
// to be really sure lets give her 3 more interesting cases and
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 0.01, 0.01, 0.01);
o("Trying z axis, 0v");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, 50000, 0.01, 0.01);
o("Trying z axis, 50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
r1 = new HelioVector(HelioVector.CARTESIAN, 0.01,0.01,AU);
v1 = new HelioVector(HelioVector.CARTESIAN, -50000, 0.01, 0.01);
o("Trying z axis, -50000x");
tttt = nd.getHPInfinity(r1,v1);
o("goingIN: "+ nd.goingIn);
o(tttt+"");
einit= 0.5*v1.dotProduct(v1) - Ms*nd.Gmod/Math.sqrt(r1.dotProduct(r1));
efinal= 0.5*tttt.dotProduct(tttt);
o("energy difference = " + Math.abs(efinal-einit));
o("\n\n\n");
Date dt2 = new Date();
System.out.println("9 took: "+(dt2.getTime()-dt1.getTime()));
// hello
/*
Date d0= new Date();
o("r on z axis, v on -x");
double d = nd.dist(1*AU,0,.001,0,0,0);
o(d+"\n\n\n\n\nr on x axis, v on -x");
double e = nd.dist(100*AU,0,Math.PI/2, 0,0,.001);
double f = nd.dist(100*AU,0,.001, 0,0,.001);
Date d1 = new Date();
o(e+"\n"+f+"\n3 dists took: " + (d1.getTime()-d0.getTime()) );
double dd = nd.density(AU,0,0);
o(dd+"");
Date d2 = new Date();
o((d2.getTime()-d1.getTime()));
*/
}
private static void o(String s) {
System.out.println(s);
}
} | 0lism | trunk/java/NeutralDistributionOld.java | Java | gpl3 | 14,946 |
import java.util.Date;
public class LegendreTest {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(Legendre.compute(3,3));
Date d2 = new Date();
System.out.println(d2.getTime() - d1.getTime());
Legendre l = new Legendre();
file f = new file("deltadata6.txt");
f.initWrite(false);
//double cdels[] = new double[100];
//Arrays.fill(cdels,0.0);
for (double j=-1.0; j<1.0; j+=+0.04) {
double delt=0.0;
for (int i=0; i<50; i++) {
delt += (2*i+1)/2*l.p(i,j)*l.p(i,0.0);
}
//System.out.println("testing");
System.out.println(j+"\t"+delt);
f.write(j+"\t"+delt+"\n");
}
f.closeWrite();
System.exit(0);
}
}
| 0lism | trunk/java/LegendreTest.java | Java | gpl3 | 718 |
import java.util.StringTokenizer;
public class TwoDPlot {
public CurveFitter cf;
public TwoDPlot() {
file f = new file("sp_param_65_74_6_5.txt");
f.initRead();
double[] x = new double[30];
double[] y = new double[30];
double[] z = new double[900];
for (int i=0; i<x.length; i++) x[i]=Double.parseDouble(f.readLine());
for (int i=0; i<y.length; i++) y[i]=Double.parseDouble(f.readLine());
for (int i=0; i<z.length; i++) {
String ss = f.readLine();
System.out.println(ss);
z[i]=Double.parseDouble(ss);
//z[i]=Math.log(z[i]);
}
// modify z
//for (int i=0; i<z.length; i++) z[i]=z[i]-840000.0;
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) {
TwoDPlot theMain = new TwoDPlot();
}
} | 0lism | trunk/java/TwoDPlot.java | Java | gpl3 | 1,181 |
//import cern.jet.math.Bessel;
import java.lang.Math;
import java.util.Date;
public class YadavaIntegral {
public YadavaIntegral() {
MultipleIntegration mi = new MultipleIntegration();
double[] lims2 = new double[4];
lims2[0]=0.0;
lims2[1]=Math.PI;
lims2[2]=0.0;
lims2[3]=Math.PI;
FunctionII yadavaEnergyLoss = new FunctionII () {
double R = 2.8E-15;
public double function2(double b, double theta) {
return Math.sin(theta) * (1-R*Math.sin(theta)/b) / b / Math.exp(R*Math.sin(theta)/b);
}
};
double test2 = mi.integrate(yadavaEnergyLoss,lims2);
System.out.println(test2+"");
}
public static void main(String[] args) {
YadavaIntegral yi = new YadavaIntegral();
}
}
| 0lism | trunk/java/YadavaIntegral.java | Java | gpl3 | 748 |
/**
* 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();
}
} | 0lism | trunk/java/NeutralMapMaker.java | Java | gpl3 | 1,578 |
/**
* 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);*/
}
}
| 0lism | trunk/java/GaussianOxVLISM.java | Java | gpl3 | 4,286 |
/**
* 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...+
}
| 0lism | trunk/java/InterstellarMedium.java | Java | gpl3 | 1,067 |
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) {
} | 0lism | trunk/java/PickupDistribution.java | Java | gpl3 | 2,362 |
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();}
}
} | 0lism | trunk/java/DensityDisplay.java | Java | gpl3 | 1,336 |
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();
}
} | 0lism | trunk/java/BenfordDataMaker.java | Java | gpl3 | 585 |
/**
* 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));
}
}
| 0lism | trunk/java/FunctionII.java | Java | gpl3 | 2,085 |
//
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;
}
}
| 0lism | trunk/java/Function.java | Java | gpl3 | 341 |
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);
}
} | 0lism | trunk/java/IBEX_image.java | Java | gpl3 | 4,496 |
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);
}
} | 0lism | trunk/java/HelioTrajectories.java | Java | gpl3 | 2,319 |
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;
}
}
}
| 0lism | trunk/java/VIonBulk.java | Java | gpl3 | 2,221 |
/**
*
*
*
*/
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
} | 0lism | trunk/java/MaxwellianDistribution.java | Java | gpl3 | 326 |
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() {
| 0lism | trunk/java/AI.java | Java | gpl3 | 284 |
import java.math.*;
import java.number.BigInteger;
public class JulyPonder {
public JulyPonder () {
}
public static final void main(String[] args) {
JulyPonder jp = new JulyPonder();
}
}
| 0lism | trunk/java/JulyPonder.java | Java | gpl3 | 222 |
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;
}
} | 0lism | trunk/java/PrintableDialog.java | Java | gpl3 | 1,775 |
/**
*
* 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();
*/
}
}
| 0lism | trunk/java/AdiabaticModel.java | Java | gpl3 | 3,611 |
//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()));
}
}
| 0lism | trunk/java/CurveFitterOld.java | Java | gpl3 | 23,503 |
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
}
} | 0lism | trunk/java/Sieve.java | Java | gpl3 | 4,088 |
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)) ;
}
}
} | 0lism | trunk/java/SphericalHarmonics.java | Java | gpl3 | 253 |
//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! | 0lism | trunk/java/Legendre.java | Java | gpl3 | 4,165 |
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));
}
} | 0lism | trunk/java/MultipleIntegrationOld.java | Java | gpl3 | 7,921 |
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");
}
}
| 0lism | trunk/java/BofThetaTest.java | Java | gpl3 | 450 |
//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;
}
}
}
| 0lism | trunk/java/NOAAPanelPlotFrame.java | Java | gpl3 | 8,259 |
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
*/ | 0lism | trunk/java/IBEXWind.java | Java | gpl3 | 28,523 |
/**
* 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);
}
}
| 0lism | trunk/java/Skymap.java | Java | gpl3 | 4,965 |
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);
}
} | 0lism | trunk/java/HelioVector.java | Java | gpl3 | 12,534 |
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();
}
} | 0lism | trunk/java/IbexPostFitter.java | Java | gpl3 | 3,332 |
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());*/ | 0lism | trunk/java/HelioPoint.java | Java | gpl3 | 11,046 |
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);
}
}
| 0lism | trunk/java/TestFunction.java | Java | gpl3 | 661 |
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");
}
}
| 0lism | trunk/java/ThetaOfBTest.java | Java | gpl3 | 571 |
/*
* 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]);
}
}
| 0lism | trunk/java/MaximisationExample.java | Java | gpl3 | 2,980 |
/**
* 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));
}
}
| 0lism | trunk/java/FunctionIII.java | Java | gpl3 | 2,519 |
/**
* 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();
}
} | 0lism | trunk/java/NeutralDensity.java | Java | gpl3 | 3,734 |
/*
* $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);
}
}
}
| 0lism | trunk/java/JGridDemo.java | Java | gpl3 | 9,717 |
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
}
}
} | 0lism | trunk/java/SimpleNeutralDistribution.java | Java | gpl3 | 3,637 |
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
}
}
| 0lism | trunk/java/MyDate2.java | Java | gpl3 | 5,633 |
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]);}
}
} | 0lism | trunk/java/MCAReader.java | Java | gpl3 | 1,639 |
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);
}
}
| 0lism | trunk/java/Integration_old2.java | Java | gpl3 | 2,726 |
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;
}
}
}
| 0lism | trunk/java/CurveFitter.java | Java | gpl3 | 26,948 |
/**
* 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;
} | 0lism | trunk/java/kepler_traj_code.java | Java | gpl3 | 5,825 |
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
*/ | 0lism | trunk/java/IBEXWind2.java | Java | gpl3 | 22,169 |
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);
}
}
| 0lism | trunk/java/KappaVLISM.java | Java | gpl3 | 3,916 |
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));
}
} | 0lism | trunk/java/LossRate.java | Java | gpl3 | 1,309 |
/**
* 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);
}
}
| 0lism | trunk/java/IBEXLO_super.java | Java | gpl3 | 11,280 |
public class InvertibleFunction extends FunctionI {
double inverse(double y) {
return 0.0;
}
} | 0lism | trunk/java/InvertibleFunction.java | Java | gpl3 | 104 |
// 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 ---
| 0lism | trunk/java/file.java | Java | gpl3 | 14,999 |
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();
}
}
| 0lism | trunk/java/MakeDrDtArray.java | Java | gpl3 | 455 |
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);
}
}
| 0lism | trunk/java/IBEXLO_09fit.java | Java | gpl3 | 14,690 |
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();*/
}
}
| 0lism | trunk/java/Hemispheric.java | Java | gpl3 | 6,468 |
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()+"");
}
} | 0lism | trunk/java/HelioTester.java | Java | gpl3 | 1,298 |
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);
}
} | 0lism | trunk/java/NeutralDistribution.java | Java | gpl3 | 20,780 |
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();
}
}
| 0lism | trunk/java/TestDistribution.java | Java | gpl3 | 506 |
/*
* 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;
}
}
| 0lism | trunk/java/Minimisation.java | Java | gpl3 | 34,151 |
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));
}
} | 0lism | trunk/java/SurvivalProbability.java | Java | gpl3 | 2,759 |
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);
}
} | 0lism | trunk/java/Benford2.java | Java | gpl3 | 3,074 |
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
*/ | 0lism | trunk/java/EarthIBEX.java | Java | gpl3 | 9,882 |
package Fertilizer
{
import org.flixel.FlxSprite;
/**
* ...
* @author JoeDono
*/
public class FertilizerBullet extends FlxSprite
{
public const FERTILIZER_BULLET_SPEED:Number = 400;
[Embed(source="../../asset/graphic/FertilizerShot.png")]
private var ImgFertilizerBullet:Class;
public function FertilizerBullet()
{
super(0, 0, ImgFertilizerBullet);
}
public function fireShot(x:Number, y:Number, hSpeed:Number, vSpeed:Number):void {
this.x = x - 8;
this.y = y - 8;
this.velocity.x = hSpeed * FERTILIZER_BULLET_SPEED;
this.velocity.y = vSpeed * FERTILIZER_BULLET_SPEED;
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Fertilizer/FertilizerBullet.as | ActionScript | gpl3 | 663 |
package Fertilizer
{
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class FertilizerEmitter extends FlxSprite
{
public var partEmitter:FlxEmitter;
public function FertilizerEmitter(x:Number, y:Number)
{
super(x, y);
this.makeGraphic(32, 32, 0x00000000);
this.partEmitter = new FlxEmitter(x + 16, y + 30, 30);
initializeEmitter();
partEmitter.start(false, 0.7, 0.05);
}
private function initializeEmitter():void
{
partEmitter.minParticleSpeed.x = -100;
partEmitter.maxParticleSpeed.x = 100;
partEmitter.particleDrag.x = 200;
partEmitter.minParticleSpeed.y = -10;
partEmitter.maxParticleSpeed.y = -30;
partEmitter.gravity = -200;
var particles:int = 30;
for (var i:int = 0; i < particles; i++)
{
var particle:FertilizerParticle = new FertilizerParticle();
partEmitter.add(particle);
}
}
public override function update():void
{
super.update();
partEmitter.update();
}
public override function draw():void
{
super.draw();
partEmitter.draw();
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Fertilizer/FertilizerEmitter.as | ActionScript | gpl3 | 1,146 |
package Fertilizer
{
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class FertilizerParticle extends FlxParticle
{
public function FertilizerParticle()
{
this.makeGraphic(5, 5, 0xFFFF8000);
}
public override function onEmit():void {
super.onEmit();
this.alpha = 1;
}
public override function update():void {
super.update();
this.alpha = this.lifespan * 2;
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Fertilizer/FertilizerParticle.as | ActionScript | gpl3 | 459 |
package Grow
{
/**
* ...
* @author JoeDono
*/
public final class GrowPlatformState
{
public static const GROW_INERT:int = 0;
public static const GROW_GROWING_OUT:int = 1;
public static const GROW_GROWN:int = 2;
public static const GROW_GROWING_IN:int = 3;
public static const GROW_READY_TO_GROW:int = 4;
public static const GROW_DIR_UP:int = 0;
public static const GROW_DIR_DOWN:int = 1;
public static const GROW_DIR_LEFT:int = 2;
public static const GROW_DIR_RIGHT:int = 3;
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Grow/GrowPlatformState.as | ActionScript | gpl3 | 532 |
package Grow
{
import org.flixel.FlxSprite;
/**
* ...
* @author JoeDono
*/
public class GrowPlatform extends FlxSprite
{
public static const GROW_PLATFORM_SPEED:Number = 50;
[Embed(source="../../asset/graphic/growPlatform/GrowPlatform.png")]
private static var ImgGrowPlatform:Class;
public var parent:GrowGroup;
private var dir:int;
public function GrowPlatform(parent:GrowGroup)
{
super(0, 0, ImgGrowPlatform);
this.parent = parent;
this.immovable = true;
}
public function stop():void {
this.velocity.x = 0;
this.velocity.y = 0;
}
public function retract():void {
switch(dir) {
case GrowPlatformState.GROW_DIR_UP:
this.velocity.y = GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_DOWN:
this.velocity.y = -GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_LEFT:
this.velocity.x = GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_RIGHT:
this.velocity.x = -GROW_PLATFORM_SPEED;
break;
}
}
public function setDirection(dir:int):void {
this.dir = dir;
switch(dir) {
case GrowPlatformState.GROW_DIR_UP:
this.velocity.y = -GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_DOWN:
this.velocity.y = GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_LEFT:
this.velocity.x = -GROW_PLATFORM_SPEED;
break;
case GrowPlatformState.GROW_DIR_RIGHT:
this.velocity.x = GROW_PLATFORM_SPEED;
break;
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Grow/GrowPlatform.as | ActionScript | gpl3 | 1,612 |
package Grow
{
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class GrowGroup extends FlxGroup
{
public static const GROWN_TIMER:Number = 1.5;
[Embed(source="../../asset/graphic/growPlatform/GrowUp.png")]
private static var ImgGrowSourceUp:Class;
[Embed(source="../../asset/graphic/growPlatform/GrowDown.png")]
private static var ImgGrowSourceDown:Class;
[Embed(source="../../asset/graphic/growPlatform/GrowLeft.png")]
private static var ImgGrowSourceLeft:Class;
[Embed(source="../../asset/graphic/growPlatform/GrowRight.png")]
private static var ImgGrowSourceRight:Class;
public var growSource:GrowSource;
public var growPlatforms:FlxGroup;
private var growDirection:int;
private var grownTimer:Number;
private var growLength:int;
private var isGrowSourceSpaceOpen:Boolean;
public function GrowGroup(x:int, y:int, growDirection:int, growLength:int)
{
super();
this.growDirection = growDirection;
this.growLength = growLength;
growSource = new GrowSource(x, y);
growPlatforms = new FlxGroup(32);
for (var i:int = 0; i < 32; i++)
{
var newPlatform:GrowPlatform = new GrowPlatform(this);
newPlatform.kill();
growPlatforms.add(newPlatform);
}
switch (growDirection)
{
case GrowPlatformState.GROW_DIR_UP:
growSource.loadGraphic(ImgGrowSourceUp);
break;
case GrowPlatformState.GROW_DIR_DOWN:
growSource.loadGraphic(ImgGrowSourceDown);
break;
case GrowPlatformState.GROW_DIR_LEFT:
growSource.loadGraphic(ImgGrowSourceLeft);
break;
case GrowPlatformState.GROW_DIR_RIGHT:
growSource.loadGraphic(ImgGrowSourceRight);
break;
}
this.add(growSource);
this.add(growPlatforms);
}
public override function update():void
{
switch (growSource.curState)
{
case GrowPlatformState.GROW_INERT:
break;
case GrowPlatformState.GROW_READY_TO_GROW:
grownTimer = GROWN_TIMER;
growSource.curState = GrowPlatformState.GROW_GROWING_OUT;
break;
case GrowPlatformState.GROW_GROWING_OUT:
updateGrowingOut();
break;
case GrowPlatformState.GROW_GROWN:
grownTimer -= FlxG.elapsed;
if (grownTimer <= 0)
{
startGrowingIn();
}
break;
case GrowPlatformState.GROW_GROWING_IN:
updateGrowingIn();
break;
}
super.update();
}
private function updateGrowingOut():void
{
isGrowSourceSpaceOpen = true;
FlxG.overlap(this.growSource, this.growPlatforms, checkGrowSourceOpen);
if (isGrowSourceSpaceOpen)
{
var newPlatform:GrowPlatform = growPlatforms.recycle(GrowPlatform) as GrowPlatform;
newPlatform.revive();
newPlatform.x = growSource.x;
newPlatform.y = growSource.y;
newPlatform.velocity.x = 0;
newPlatform.velocity.y = 0;
newPlatform.setDirection(this.growDirection);
}
if (growLength <= growPlatforms.countLiving())
{
grownTimer = grownTimer;
growSource.curState = GrowPlatformState.GROW_GROWN;
growPlatforms.callAll("stop");
}
}
private function checkGrowSourceOpen(growSource:GrowSource, growPlatform:GrowPlatform):void
{
isGrowSourceSpaceOpen = false;
}
private function startGrowingIn():void
{
growSource.curState = GrowPlatformState.GROW_GROWING_IN;
growPlatforms.callAll("retract");
}
private function updateGrowingIn():void
{
FlxG.overlap(growSource, growPlatforms, platformReturnsToSource);
if (growPlatforms.getFirstAlive() == null) {
growSource.curState = GrowPlatformState.GROW_INERT;
}
}
public override function draw():void
{
growPlatforms.draw();
growSource.draw();
}
private function platformReturnsToSource(growSource:GrowSource, growPlatform:GrowPlatform):void {
if (FlxU.getDistance(new FlxPoint(growSource.x, growSource.y), new FlxPoint(growPlatform.x, growPlatform.y)) < 1) {
growPlatform.kill();
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Grow/GrowGroup.as | ActionScript | gpl3 | 4,134 |
package Grow
{
import org.flixel.FlxSprite;
/**
* ...
* @author JoeDono
*/
public class GrowSource extends FlxSprite
{
public var curState:int;
public function GrowSource(x:int, y:int)
{
super(x, y);
this.immovable = true;
curState = GrowPlatformState.GROW_INERT;
}
public function hitWithFertilizer():void
{
if (curState == GrowPlatformState.GROW_INERT)
{
curState = GrowPlatformState.GROW_READY_TO_GROW;
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Grow/GrowSource.as | ActionScript | gpl3 | 505 |
package
{
import org.flixel.system.FlxPreloader;
public class Preloader extends FlxPreloader
{
public function Preloader()
{
className = "Main";
super();
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Preloader.as | ActionScript | gpl3 | 189 |
package
{
import org.flixel.FlxSprite;
/**
* ...
* @author JoeDono
*/
public class Goal extends FlxSprite
{
[Embed(source="../asset/graphic/Goal.png")]
private var ImgGoalSheet:Class;
public function Goal()
{
super();
this.loadGraphic(ImgGoalSheet, true, false, 16);
this.addAnimation("pulse", [0, 1, 2, 3], 5);
this.play("pulse");
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Goal.as | ActionScript | gpl3 | 411 |
package State
{
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class TitleState extends FlxState
{
[Embed(source="../../asset/graphic/screen/TitleScreen.png")]
private var ImgTitleScreen:Class;
private var img:FlxSprite;
public override function create():void
{
FlxG.bgColor = 0xFFFFFFC2;
img = new FlxSprite(0, 0, ImgTitleScreen);
this.add(img);
}
public override function update():void
{
if (FlxG.keys.any())
{
FlxG.switchState(new PlayState());
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/State/TitleState.as | ActionScript | gpl3 | 566 |
package State
{
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class GameEndState extends FlxState
{
[Embed(source="../../asset/graphic/screen/GameBeatenScreen.png")]
private var ImgGameBeatenScreen:Class;
private var img:FlxSprite;
public override function create():void
{
FlxG.bgColor = 0xFFFFFFC2;
img = new FlxSprite(0, 0, ImgGameBeatenScreen);
this.add(img);
}
public override function update():void
{
if (FlxG.keys.any())
{
FlxG.switchState(new TitleState());
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/State/GameEndState.as | ActionScript | gpl3 | 587 |
package State
{
import Fertilizer.*;
import org.flixel.*;
import org.flixel.system.FlxTile;
import Player.Player;
import Grow.*;
public class PlayState extends FlxState
{
[Embed(source="../../asset/graphic/Tileset.png")]
private var ImgTileset:Class;
[Embed(source="../../asset/level/level1.txt",mimeType="application/octet-stream")]
private var Level1Config:Class;
[Embed(source="../../asset/level/level2.txt",mimeType="application/octet-stream")]
private var Level2Config:Class;
[Embed(source="../../asset/level/level3.txt",mimeType="application/octet-stream")]
private var Level3Config:Class;
[Embed(source="../../asset/level/level4.txt",mimeType="application/octet-stream")]
private var Level4Config:Class;
[Embed(source="../../asset/level/level5.txt",mimeType="application/octet-stream")]
private var Level5Config:Class;
private var player:Player;
private var wallTiles:FlxTilemap;
private var fertilizerFountains:FlxGroup;
private var growSources:FlxGroup;
private var goal:Goal;
private var levelConfigs:Array = new Array();
private var curLevel:int = 0;
public override function create():void
{
FlxG.bgColor = 0xFFFFFFC2;
levelConfigs[0] = new Level1Config().toString();
levelConfigs[1] = new Level2Config().toString();
levelConfigs[2] = new Level3Config().toString();
levelConfigs[3] = new Level4Config().toString();
levelConfigs[4] = new Level5Config().toString();
player = new Player();
fertilizerFountains = new FlxGroup();
growSources = new FlxGroup();
goal = new Goal();
loadLevel(levelConfigs[curLevel]);
add(player);
add(fertilizerFountains);
add(growSources);
add(goal);
}
private function loadLevel(levelConfig:String):void
{
this.remove(wallTiles);
wallTiles = new FlxTilemap();
wallTiles.loadMap(levelConfig, ImgTileset, 32, 32);
this.add(wallTiles);
fertilizerFountains.clear();
growSources.clear();
var lines:Array = levelConfig.split("\r\n");
for (var y:int = 0; y < lines.length; y++)
{
var line:Array = lines[y].split(",");
for (var x:int = 0; x < line.length; x++)
{
var curChar:String = line[x];
var xPos:int = x * 32;
var yPos:int = y * 32;
var lengthStr:String;
var length:int;
if (curChar == "P")
{
player.x = xPos;
player.y = yPos;
player.velocity.x = 0;
player.velocity.y = 0;
player.hasFertilizer = false;
}
else if (curChar == "F")
{
fertilizerFountains.add(new FertilizerEmitter(xPos, yPos));
}
else if (curChar.indexOf("U") >= 0)
{
lengthStr = curChar.substr(1);
length = int(lengthStr);
growSources.add(new GrowGroup(xPos, yPos, GrowPlatformState.GROW_DIR_UP, length));
}
else if (curChar.indexOf("D") >= 0)
{
lengthStr = curChar.substr(1);
length = int(lengthStr);
growSources.add(new GrowGroup(xPos, yPos, GrowPlatformState.GROW_DIR_DOWN, length));
}
else if (curChar.indexOf("L") >= 0)
{
lengthStr = curChar.substr(1);
length = int(lengthStr);
growSources.add(new GrowGroup(xPos, yPos, GrowPlatformState.GROW_DIR_LEFT, length));
}
else if (curChar.indexOf("R") >= 0)
{
lengthStr = curChar.substr(1);
length = int(lengthStr);
growSources.add(new GrowGroup(xPos, yPos, GrowPlatformState.GROW_DIR_RIGHT, length));
}
else if (curChar.indexOf("G") >= 0)
{
goal.x = xPos + 8;
goal.y = yPos + 8;
}
}
}
}
public override function update():void
{
super.update();
FlxG.collide(wallTiles, player);
FlxG.collide(growSources, player);
FlxG.overlap(fertilizerFountains, player, overlapFertilizerFountainsPlayer);
FlxG.collide(wallTiles, player.fertilizerBullets, bulletHitWall);
FlxG.collide(growSources, player.fertilizerBullets, bulletHitFertilizer);
FlxG.overlap(player, goal, playerHitGoal);
}
private function overlapFertilizerFountainsPlayer(emitter:FertilizerEmitter, player:Player):void
{
player.hasFertilizer = true;
}
private function bulletHitWall(tile:FlxTilemap, bullet:FertilizerBullet):void
{
bullet.kill();
}
private function bulletHitFertilizer(other:FlxBasic, bullet:FertilizerBullet):void
{
bullet.kill();
if (other is GrowSource)
{
var other2:GrowSource = GrowSource(other);
other2.hitWithFertilizer();
}
}
private function playerHitGoal(player:Player, goal:Goal):void
{
curLevel++;
if (curLevel < 5)
{
this.loadLevel(levelConfigs[curLevel]);
}
else
{
FlxG.switchState(new GameEndState());
}
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/State/PlayState.as | ActionScript | gpl3 | 4,907 |
package
{
import org.flixel.*;
import State.*;
[SWF(width = "800", height = "608", backgroundColor = "#FFFFFF")]
[Frame(factoryClass = "Preloader")]
public class Main extends FlxGame
{
public function Main():void
{
super(800, 608, TitleState, 1);
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Main.as | ActionScript | gpl3 | 287 |
package Player
{
import Fertilizer.FertilizerBullet;
import org.flixel.*;
/**
* ...
* @author JoeDono
*/
public class Player extends FlxSprite
{
public const PLAYER_WALK_SPEED:int = 200;
public const PLAYER_JUMP_SPEED:int = 500;
public const MAX_PLAYER_FALL_SPEED:int = 500;
public const PLAYER_FALL_ACCELERATION:int = 1500;
public const WALK_ANIMATION_SPEED:int = 5;
public const SHOT_TIMER:Number = 0.2;
[Embed(source="../../asset/graphic/Player.png")]
private var ImgPlayerSheet:Class;
[Embed(source="../../asset/graphic/FertilizerShot.png")]
private var ImgHoldingBullet:Class;
private var holdingBullet:FlxSprite;
private var curPlayerState:int;
private var facingRight:Boolean;
private var shotTimer:Number;
public var hasFertilizer:Boolean;
public var fertilizerBullets:FlxGroup;
public function Player()
{
super();
initializeMotions();
initializeAnimations();
initializeBullets();
holdingBullet = new FlxSprite(0, 0, ImgHoldingBullet);
curPlayerState = PlayerState.PLAYER_STAND_RIGHT;
facingRight = true;
hasFertilizer = false;
shotTimer = SHOT_TIMER;
}
private function initializeMotions():void
{
this.maxVelocity.x = PLAYER_WALK_SPEED;
this.maxVelocity.y = MAX_PLAYER_FALL_SPEED;
this.acceleration.y = PLAYER_FALL_ACCELERATION;
}
private function initializeAnimations():void
{
this.loadGraphic(ImgPlayerSheet, true, false, 32);
this.addAnimation("idle-left", [0]);
this.addAnimation("idle-right", [2]);
this.addAnimation("walk-left", [1, 0], WALK_ANIMATION_SPEED);
this.addAnimation("walk-right", [2, 3], WALK_ANIMATION_SPEED);
this.addAnimation("jump-left", [1]);
this.addAnimation("jump-right", [3]);
this.play("idle-left");
}
private function initializeBullets():void
{
fertilizerBullets = new FlxGroup(30);
}
public override function update():void
{
this.velocity.x = 0;
if (shotTimer > 0)
{
shotTimer -= FlxG.elapsed;
}
updateMovement();
updateShoot();
fertilizerBullets.update();
super.update();
}
private function updateMovement():void
{
var onGround:Boolean = this.isTouching(FlxObject.FLOOR);
var isMoving:Boolean = false;
if (FlxG.keys.LEFT)
{
this.velocity.x = -PLAYER_WALK_SPEED;
facingRight = false;
isMoving = true;
}
if (FlxG.keys.RIGHT)
{
this.velocity.x = PLAYER_WALK_SPEED;
facingRight = true;
isMoving = true;
}
if (FlxG.keys.Z && onGround)
{
this.velocity.y = -PLAYER_JUMP_SPEED;
}
if (onGround)
{
if (facingRight)
{
if (isMoving)
{
changeState(PlayerState.PLAYER_WALK_RIGHT);
}
else
{
changeState(PlayerState.PLAYER_STAND_RIGHT);
}
}
else
{
if (isMoving)
{
changeState(PlayerState.PLAYER_WALK_LEFT);
}
else
{
changeState(PlayerState.PLAYER_STAND_LEFT);
}
}
}
else
{
if (facingRight)
{
changeState(PlayerState.PLAYER_JUMP_RIGHT);
}
else
{
changeState(PlayerState.PLAYER_JUMP_LEFT);
}
}
}
private function changeState(nextState:int):void
{
if (curPlayerState != nextState)
{
curPlayerState = nextState;
switch (curPlayerState)
{
case PlayerState.PLAYER_STAND_LEFT:
play("idle-left");
break;
case PlayerState.PLAYER_STAND_RIGHT:
play("idle-right");
break;
case PlayerState.PLAYER_WALK_LEFT:
play("walk-left");
break;
case PlayerState.PLAYER_WALK_RIGHT:
play("walk-right");
break;
case PlayerState.PLAYER_JUMP_LEFT:
play("jump-left");
break;
case PlayerState.PLAYER_JUMP_RIGHT:
play("jump-right");
break;
}
}
}
private function updateShoot():void
{
if (FlxG.keys.X && hasFertilizer && shotTimer <= 0)
{
var bullet:FertilizerBullet = fertilizerBullets.recycle(FertilizerBullet) as FertilizerBullet;
bullet.revive();
var hSpeed:Number = 0;
var vSpeed:Number = 0;
if (FlxG.keys.LEFT)
{
hSpeed = -1;
}
else if (FlxG.keys.RIGHT)
{
hSpeed = 1;
}
if (FlxG.keys.UP)
{
vSpeed = -1;
}
else if (FlxG.keys.DOWN)
{
vSpeed = 1;
}
// No keys pressed, use facingRight instead
if (hSpeed == 0 && vSpeed == 0)
{
hSpeed = facingRight ? 1 : -1;
}
// Normalize speed
if (hSpeed != 0 && vSpeed != 0)
{
hSpeed = hSpeed / Math.sqrt(hSpeed * hSpeed + vSpeed * vSpeed);
vSpeed = vSpeed / Math.sqrt(hSpeed * hSpeed + vSpeed * vSpeed);
}
bullet.fireShot(x + 16, y + 16, hSpeed, vSpeed);
shotTimer = SHOT_TIMER;
hasFertilizer = false;
}
}
public override function draw():void
{
fertilizerBullets.draw();
if (hasFertilizer)
{
holdingBullet.y = this.y - 2;
holdingBullet.x = facingRight ? this.x - 2 : this.x + 18;
holdingBullet.draw();
}
super.draw();
}
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Player/Player.as | ActionScript | gpl3 | 5,324 |
package Player
{
/**
* ...
* @author JoeDono
*/
public final class PlayerState
{
public static const PLAYER_STAND_LEFT:int = 0;
public static const PLAYER_STAND_RIGHT:int = 1;
public static const PLAYER_WALK_LEFT:int = 2;
public static const PLAYER_WALK_RIGHT:int = 3;
public static const PLAYER_JUMP_LEFT:int = 4;
public static const PLAYER_JUMP_RIGHT:int = 5;
}
} | 05-may-1gam-blocks-that-grow | trunk/src/Player/PlayerState.as | ActionScript | gpl3 | 404 |
package org.flixel
{
import flash.display.BitmapData;
import flash.text.TextField;
import flash.text.TextFormat;
/**
* Extends <code>FlxSprite</code> to support rendering text.
* Can tint, fade, rotate and scale just like a sprite.
* Doesn't really animate though, as far as I know.
* Also does nice pixel-perfect centering on pixel fonts
* as long as they are only one liners.
*
* @author Adam Atomic
*/
public class FlxText extends FlxSprite
{
/**
* Internal reference to a Flash <code>TextField</code> object.
*/
protected var _textField:TextField;
/**
* Whether the actual text field needs to be regenerated and stamped again.
* This is NOT the same thing as <code>FlxSprite.dirty</code>.
*/
protected var _regen:Boolean;
/**
* Internal tracker for the text shadow color, default is clear/transparent.
*/
protected var _shadow:uint;
/**
* Creates a new <code>FlxText</code> object at the specified position.
*
* @param X The X position of the text.
* @param Y The Y position of the text.
* @param Width The width of the text object (height is determined automatically).
* @param Text The actual text you would like to display initially.
* @param EmbeddedFont Whether this text field uses embedded fonts or nto
*/
public function FlxText(X:Number, Y:Number, Width:uint, Text:String=null, EmbeddedFont:Boolean=true)
{
super(X,Y);
makeGraphic(Width,1,0);
if(Text == null)
Text = "";
_textField = new TextField();
_textField.width = Width;
_textField.embedFonts = EmbeddedFont;
_textField.selectable = false;
_textField.sharpness = 100;
_textField.multiline = true;
_textField.wordWrap = true;
_textField.text = Text;
var format:TextFormat = new TextFormat("system",8,0xffffff);
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
if(Text.length <= 0)
_textField.height = 1;
else
_textField.height = 10;
_regen = true;
_shadow = 0;
allowCollisions = NONE;
calcFrame();
}
/**
* Clean up memory.
*/
override public function destroy():void
{
_textField = null;
super.destroy();
}
/**
* You can use this if you have a lot of text parameters
* to set instead of the individual properties.
*
* @param Font The name of the font face for the text display.
* @param Size The size of the font (in pixels essentially).
* @param Color The color of the text in traditional flash 0xRRGGBB format.
* @param Alignment A string representing the desired alignment ("left,"right" or "center").
* @param ShadowColor A uint representing the desired text shadow color in flash 0xRRGGBB format.
*
* @return This FlxText instance (nice for chaining stuff together, if you're into that).
*/
public function setFormat(Font:String=null,Size:Number=8,Color:uint=0xffffff,Alignment:String=null,ShadowColor:uint=0):FlxText
{
if(Font == null)
Font = "";
var format:TextFormat = dtfCopy();
format.font = Font;
format.size = Size;
format.color = Color;
format.align = Alignment;
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
_shadow = ShadowColor;
_regen = true;
calcFrame();
return this;
}
/**
* The text being displayed.
*/
public function get text():String
{
return _textField.text;
}
/**
* @private
*/
public function set text(Text:String):void
{
var ot:String = _textField.text;
_textField.text = Text;
if(_textField.text != ot)
{
_regen = true;
calcFrame();
}
}
/**
* The size of the text being displayed.
*/
public function get size():Number
{
return _textField.defaultTextFormat.size as Number;
}
/**
* @private
*/
public function set size(Size:Number):void
{
var format:TextFormat = dtfCopy();
format.size = Size;
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
_regen = true;
calcFrame();
}
/**
* The color of the text being displayed.
*/
override public function get color():uint
{
return _textField.defaultTextFormat.color as uint;
}
/**
* @private
*/
override public function set color(Color:uint):void
{
var format:TextFormat = dtfCopy();
format.color = Color;
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
_regen = true;
calcFrame();
}
/**
* The font used for this text.
*/
public function get font():String
{
return _textField.defaultTextFormat.font;
}
/**
* @private
*/
public function set font(Font:String):void
{
var format:TextFormat = dtfCopy();
format.font = Font;
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
_regen = true;
calcFrame();
}
/**
* The alignment of the font ("left", "right", or "center").
*/
public function get alignment():String
{
return _textField.defaultTextFormat.align;
}
/**
* @private
*/
public function set alignment(Alignment:String):void
{
var format:TextFormat = dtfCopy();
format.align = Alignment;
_textField.defaultTextFormat = format;
_textField.setTextFormat(format);
calcFrame();
}
/**
* The color of the text shadow in 0xAARRGGBB hex format.
*/
public function get shadow():uint
{
return _shadow;
}
/**
* @private
*/
public function set shadow(Color:uint):void
{
_shadow = Color;
calcFrame();
}
/**
* Internal function to update the current animation frame.
*/
override protected function calcFrame():void
{
if(_regen)
{
//Need to generate a new buffer to store the text graphic
var i:uint = 0;
var nl:uint = _textField.numLines;
height = 0;
while(i < nl)
height += _textField.getLineMetrics(i++).height;
height += 4; //account for 2px gutter on top and bottom
_pixels = new BitmapData(width,height,true,0);
frameHeight = height;
_textField.height = height*1.2;
_flashRect.x = 0;
_flashRect.y = 0;
_flashRect.width = width;
_flashRect.height = height;
_regen = false;
}
else //Else just clear the old buffer before redrawing the text
_pixels.fillRect(_flashRect,0);
if((_textField != null) && (_textField.text != null) && (_textField.text.length > 0))
{
//Now that we've cleared a buffer, we need to actually render the text to it
var format:TextFormat = _textField.defaultTextFormat;
var formatAdjusted:TextFormat = format;
_matrix.identity();
//If it's a single, centered line of text, we center it ourselves so it doesn't blur to hell
if((format.align == "center") && (_textField.numLines == 1))
{
formatAdjusted = new TextFormat(format.font,format.size,format.color,null,null,null,null,null,"left");
_textField.setTextFormat(formatAdjusted);
_matrix.translate(Math.floor((width - _textField.getLineMetrics(0).width)/2),0);
}
//Render a single pixel shadow beneath the text
if(_shadow > 0)
{
_textField.setTextFormat(new TextFormat(formatAdjusted.font,formatAdjusted.size,_shadow,null,null,null,null,null,formatAdjusted.align));
_matrix.translate(1,1);
_pixels.draw(_textField,_matrix,_colorTransform);
_matrix.translate(-1,-1);
_textField.setTextFormat(new TextFormat(formatAdjusted.font,formatAdjusted.size,formatAdjusted.color,null,null,null,null,null,formatAdjusted.align));
}
//Actually draw the text onto the buffer
_pixels.draw(_textField,_matrix,_colorTransform);
_textField.setTextFormat(new TextFormat(format.font,format.size,format.color,null,null,null,null,null,format.align));
}
//Finally, update the visible pixels
if((framePixels == null) || (framePixels.width != _pixels.width) || (framePixels.height != _pixels.height))
framePixels = new BitmapData(_pixels.width,_pixels.height,true,0);
framePixels.copyPixels(_pixels,_flashRect,_flashPointZero);
}
/**
* A helper function for updating the <code>TextField</code> that we use for rendering.
*
* @return A writable copy of <code>TextField.defaultTextFormat</code>.
*/
protected function dtfCopy():TextFormat
{
var defaultTextFormat:TextFormat = _textField.defaultTextFormat;
return new TextFormat(defaultTextFormat.font,defaultTextFormat.size,defaultTextFormat.color,defaultTextFormat.bold,defaultTextFormat.italic,defaultTextFormat.underline,defaultTextFormat.url,defaultTextFormat.target,defaultTextFormat.align);
}
}
}
| 05-may-1gam-blocks-that-grow | trunk/lib/Flixel/org/flixel/FlxText.as | ActionScript | gpl3 | 8,621 |
package org.flixel
{
import flash.geom.Rectangle;
/**
* Stores a rectangle.
*
* @author Adam Atomic
*/
public class FlxRect
{
/**
* @default 0
*/
public var x:Number;
/**
* @default 0
*/
public var y:Number;
/**
* @default 0
*/
public var width:Number;
/**
* @default 0
*/
public var height:Number;
/**
* Instantiate a new rectangle.
*
* @param X The X-coordinate of the point in space.
* @param Y The Y-coordinate of the point in space.
* @param Width Desired width of the rectangle.
* @param Height Desired height of the rectangle.
*/
public function FlxRect(X:Number=0, Y:Number=0, Width:Number=0, Height:Number=0)
{
x = X;
y = Y;
width = Width;
height = Height;
}
/**
* The X coordinate of the left side of the rectangle. Read-only.
*/
public function get left():Number
{
return x;
}
/**
* The X coordinate of the right side of the rectangle. Read-only.
*/
public function get right():Number
{
return x + width;
}
/**
* The Y coordinate of the top of the rectangle. Read-only.
*/
public function get top():Number
{
return y;
}
/**
* The Y coordinate of the bottom of the rectangle. Read-only.
*/
public function get bottom():Number
{
return y + height;
}
/**
* Instantiate a new rectangle.
*
* @param X The X-coordinate of the point in space.
* @param Y The Y-coordinate of the point in space.
* @param Width Desired width of the rectangle.
* @param Height Desired height of the rectangle.
*
* @return A reference to itself.
*/
public function make(X:Number=0, Y:Number=0, Width:Number=0, Height:Number=0):FlxRect
{
x = X;
y = Y;
width = Width;
height = Height;
return this;
}
/**
* Helper function, just copies the values from the specified rectangle.
*
* @param Rect Any <code>FlxRect</code>.
*
* @return A reference to itself.
*/
public function copyFrom(Rect:FlxRect):FlxRect
{
x = Rect.x;
y = Rect.y;
width = Rect.width;
height = Rect.height;
return this;
}
/**
* Helper function, just copies the values from this rectangle to the specified rectangle.
*
* @param Point Any <code>FlxRect</code>.
*
* @return A reference to the altered rectangle parameter.
*/
public function copyTo(Rect:FlxRect):FlxRect
{
Rect.x = x;
Rect.y = y;
Rect.width = width;
Rect.height = height;
return Rect;
}
/**
* Helper function, just copies the values from the specified Flash rectangle.
*
* @param FlashRect Any <code>Rectangle</code>.
*
* @return A reference to itself.
*/
public function copyFromFlash(FlashRect:Rectangle):FlxRect
{
x = FlashRect.x;
y = FlashRect.y;
width = FlashRect.width;
height = FlashRect.height;
return this;
}
/**
* Helper function, just copies the values from this rectangle to the specified Flash rectangle.
*
* @param Point Any <code>Rectangle</code>.
*
* @return A reference to the altered rectangle parameter.
*/
public function copyToFlash(FlashRect:Rectangle):Rectangle
{
FlashRect.x = x;
FlashRect.y = y;
FlashRect.width = width;
FlashRect.height = height;
return FlashRect;
}
/**
* Checks to see if some <code>FlxRect</code> object overlaps this <code>FlxRect</code> object.
*
* @param Rect The rectangle being tested.
*
* @return Whether or not the two rectangles overlap.
*/
public function overlaps(Rect:FlxRect):Boolean
{
return (Rect.x + Rect.width > x) && (Rect.x < x+width) && (Rect.y + Rect.height > y) && (Rect.y < y+height);
}
}
}
| 05-may-1gam-blocks-that-grow | trunk/lib/Flixel/org/flixel/FlxRect.as | ActionScript | gpl3 | 3,725 |
package org.flixel
{
/**
* This is a simple particle class that extends the default behavior
* of <code>FlxSprite</code> to have slightly more specialized behavior
* common to many game scenarios. You can override and extend this class
* just like you would <code>FlxSprite</code>. While <code>FlxEmitter</code>
* used to work with just any old sprite, it now requires a
* <code>FlxParticle</code> based class.
*
* @author Adam Atomic
*/
public class FlxParticle extends FlxSprite
{
/**
* How long this particle lives before it disappears.
* NOTE: this is a maximum, not a minimum; the object
* could get recycled before its lifespan is up.
*/
public var lifespan:Number;
/**
* Determines how quickly the particles come to rest on the ground.
* Only used if the particle has gravity-like acceleration applied.
* @default 500
*/
public var friction:Number;
/**
* Instantiate a new particle. Like <code>FlxSprite</code>, all meaningful creation
* happens during <code>loadGraphic()</code> or <code>makeGraphic()</code> or whatever.
*/
public function FlxParticle()
{
super();
lifespan = 0;
friction = 500;
}
/**
* The particle's main update logic. Basically it checks to see if it should
* be dead yet, and then has some special bounce behavior if there is some gravity on it.
*/
override public function update():void
{
//lifespan behavior
if(lifespan <= 0)
return;
lifespan -= FlxG.elapsed;
if(lifespan <= 0)
kill();
//simpler bounce/spin behavior for now
if(touching)
{
if(angularVelocity != 0)
angularVelocity = -angularVelocity;
}
if(acceleration.y > 0) //special behavior for particles with gravity
{
if(touching & FLOOR)
{
drag.x = friction;
if(!(wasTouching & FLOOR))
{
if(velocity.y < -elasticity*10)
{
if(angularVelocity != 0)
angularVelocity *= -elasticity;
}
else
{
velocity.y = 0;
angularVelocity = 0;
}
}
}
else
drag.x = 0;
}
}
/**
* Triggered whenever this object is launched by a <code>FlxEmitter</code>.
* You can override this to add custom behavior like a sound or AI or something.
*/
public function onEmit():void
{
}
}
}
| 05-may-1gam-blocks-that-grow | trunk/lib/Flixel/org/flixel/FlxParticle.as | ActionScript | gpl3 | 2,338 |
package org.flixel
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.flixel.system.FlxTile;
import org.flixel.system.FlxTilemapBuffer;
/**
* This is a traditional tilemap display and collision class.
* It takes a string of comma-separated numbers and then associates
* those values with tiles from the sheet you pass in.
* It also includes some handy static parsers that can convert
* arrays or images into strings that can be loaded.
*
* @author Adam Atomic
*/
public class FlxTilemap extends FlxObject
{
[Embed(source="data/autotiles.png")] static public var ImgAuto:Class;
[Embed(source="data/autotiles_alt.png")] static public var ImgAutoAlt:Class;
/**
* No auto-tiling.
*/
static public const OFF:uint = 0;
/**
* Good for levels with thin walls that don'tile need interior corner art.
*/
static public const AUTO:uint = 1;
/**
* Better for levels with thick walls that look better with interior corner art.
*/
static public const ALT:uint = 2;
/**
* Set this flag to use one of the 16-tile binary auto-tile algorithms (OFF, AUTO, or ALT).
*/
public var auto:uint;
/**
* Read-only variable, do NOT recommend changing after the map is loaded!
*/
public var widthInTiles:uint;
/**
* Read-only variable, do NOT recommend changing after the map is loaded!
*/
public var heightInTiles:uint;
/**
* Read-only variable, do NOT recommend changing after the map is loaded!
*/
public var totalTiles:uint;
/**
* Rendering helper, minimize new object instantiation on repetitive methods.
*/
protected var _flashPoint:Point;
/**
* Rendering helper, minimize new object instantiation on repetitive methods.
*/
protected var _flashRect:Rectangle;
/**
* Internal reference to the bitmap data object that stores the original tile graphics.
*/
protected var _tiles:BitmapData;
/**
* Internal list of buffers, one for each camera, used for drawing the tilemaps.
*/
protected var _buffers:Array;
/**
* Internal representation of the actual tile data, as a large 1D array of integers.
*/
protected var _data:Array;
/**
* Internal representation of rectangles, one for each tile in the entire tilemap, used to speed up drawing.
*/
protected var _rects:Array;
/**
* Internal, the width of a single tile.
*/
protected var _tileWidth:uint;
/**
* Internal, the height of a single tile.
*/
protected var _tileHeight:uint;
/**
* Internal collection of tile objects, one for each type of tile in the map (NOTE one for every single tile in the whole map).
*/
protected var _tileObjects:Array;
/**
* Internal, used for rendering the debug bounding box display.
*/
protected var _debugTileNotSolid:BitmapData;
/**
* Internal, used for rendering the debug bounding box display.
*/
protected var _debugTilePartial:BitmapData;
/**
* Internal, used for rendering the debug bounding box display.
*/
protected var _debugTileSolid:BitmapData;
/**
* Internal, used for rendering the debug bounding box display.
*/
protected var _debugRect:Rectangle;
/**
* Internal flag for checking to see if we need to refresh
* the tilemap display to show or hide the bounding boxes.
*/
protected var _lastVisualDebug:Boolean;
/**
* Internal, used to sort of insert blank tiles in front of the tiles in the provided graphic.
*/
protected var _startingIndex:uint;
/**
* The tilemap constructor just initializes some basic variables.
*/
public function FlxTilemap()
{
super();
auto = OFF;
widthInTiles = 0;
heightInTiles = 0;
totalTiles = 0;
_buffers = new Array();
_flashPoint = new Point();
_flashRect = null;
_data = null;
_tileWidth = 0;
_tileHeight = 0;
_rects = null;
_tiles = null;
_tileObjects = null;
immovable = true;
cameras = null;
_debugTileNotSolid = null;
_debugTilePartial = null;
_debugTileSolid = null;
_debugRect = null;
_lastVisualDebug = FlxG.visualDebug;
_startingIndex = 0;
}
/**
* Clean up memory.
*/
override public function destroy():void
{
_flashPoint = null;
_flashRect = null;
_tiles = null;
var i:uint = 0;
var l:uint = _tileObjects.length;
while(i < l)
(_tileObjects[i++] as FlxTile).destroy();
_tileObjects = null;
i = 0;
l = _buffers.length;
while(i < l)
(_buffers[i++] as FlxTilemapBuffer).destroy();
_buffers = null;
_data = null;
_rects = null;
_debugTileNotSolid = null;
_debugTilePartial = null;
_debugTileSolid = null;
_debugRect = null;
super.destroy();
}
/**
* Load the tilemap with string data and a tile graphic.
*
* @param MapData A string of comma and line-return delineated indices indicating what order the tiles should go in.
* @param TileGraphic All the tiles you want to use, arranged in a strip corresponding to the numbers in MapData.
* @param TileWidth The width of your tiles (e.g. 8) - defaults to height of the tile graphic if unspecified.
* @param TileHeight The height of your tiles (e.g. 8) - defaults to width if unspecified.
* @param AutoTile Whether to load the map using an automatic tile placement algorithm. Setting this to either AUTO or ALT will override any values you put for StartingIndex, DrawIndex, or CollideIndex.
* @param StartingIndex Used to sort of insert empty tiles in front of the provided graphic. Default is 0, usually safest ot leave it at that. Ignored if AutoTile is set.
* @param DrawIndex Initializes all tile objects equal to and after this index as visible. Default value is 1. Ignored if AutoTile is set.
* @param CollideIndex Initializes all tile objects equal to and after this index as allowCollisions = ANY. Default value is 1. Ignored if AutoTile is set. Can override and customize per-tile-type collision behavior using <code>setTileProperties()</code>.
*
* @return A pointer this instance of FlxTilemap, for chaining as usual :)
*/
public function loadMap(MapData:String, TileGraphic:Class, TileWidth:uint=0, TileHeight:uint=0, AutoTile:uint=OFF, StartingIndex:uint=0, DrawIndex:uint=1, CollideIndex:uint=1):FlxTilemap
{
auto = AutoTile;
_startingIndex = StartingIndex;
//Figure out the map dimensions based on the data string
var columns:Array;
var rows:Array = MapData.split("\n");
heightInTiles = rows.length;
_data = new Array();
var row:uint = 0;
var column:uint;
while(row < heightInTiles)
{
columns = rows[row++].split(",");
if(columns.length <= 1)
{
heightInTiles = heightInTiles - 1;
continue;
}
if(widthInTiles == 0)
widthInTiles = columns.length;
column = 0;
while(column < widthInTiles)
_data.push(uint(columns[column++]));
}
//Pre-process the map data if it's auto-tiled
var i:uint;
totalTiles = widthInTiles*heightInTiles;
if(auto > OFF)
{
_startingIndex = 1;
DrawIndex = 1;
CollideIndex = 1;
i = 0;
while(i < totalTiles)
autoTile(i++);
}
//Figure out the size of the tiles
_tiles = FlxG.addBitmap(TileGraphic);
_tileWidth = TileWidth;
if(_tileWidth == 0)
_tileWidth = _tiles.height;
_tileHeight = TileHeight;
if(_tileHeight == 0)
_tileHeight = _tileWidth;
//create some tile objects that we'll use for overlap checks (one for each tile)
i = 0;
var l:uint = (_tiles.width/_tileWidth) * (_tiles.height/_tileHeight);
if(auto > OFF)
l++;
_tileObjects = new Array(l);
var ac:uint;
while(i < l)
{
_tileObjects[i] = new FlxTile(this,i,_tileWidth,_tileHeight,(i >= DrawIndex),(i >= CollideIndex)?allowCollisions:NONE);
i++;
}
//create debug tiles for rendering bounding boxes on demand
_debugTileNotSolid = makeDebugTile(FlxG.BLUE);
_debugTilePartial = makeDebugTile(FlxG.PINK);
_debugTileSolid = makeDebugTile(FlxG.GREEN);
_debugRect = new Rectangle(0,0,_tileWidth,_tileHeight);
//Then go through and create the actual map
width = widthInTiles*_tileWidth;
height = heightInTiles*_tileHeight;
_rects = new Array(totalTiles);
i = 0;
while(i < totalTiles)
updateTile(i++);
return this;
}
/**
* Internal function to clean up the map loading code.
* Just generates a wireframe box the size of a tile with the specified color.
*/
protected function makeDebugTile(Color:uint):BitmapData
{
var debugTile:BitmapData
debugTile = new BitmapData(_tileWidth,_tileHeight,true,0);
var gfx:Graphics = FlxG.flashGfx;
gfx.clear();
gfx.moveTo(0,0);
gfx.lineStyle(1,Color,0.5);
gfx.lineTo(_tileWidth-1,0);
gfx.lineTo(_tileWidth-1,_tileHeight-1);
gfx.lineTo(0,_tileHeight-1);
gfx.lineTo(0,0);
debugTile.draw(FlxG.flashGfxSprite);
return debugTile;
}
/**
* Main logic loop for tilemap is pretty simple,
* just checks to see if visual debug got turned on.
* If it did, the tilemap is flagged as dirty so it
* will be redrawn with debug info on the next draw call.
*/
override public function update():void
{
if(_lastVisualDebug != FlxG.visualDebug)
{
_lastVisualDebug = FlxG.visualDebug;
setDirty();
}
}
/**
* Internal function that actually renders the tilemap to the tilemap buffer. Called by draw().
*
* @param Buffer The <code>FlxTilemapBuffer</code> you are rendering to.
* @param Camera The related <code>FlxCamera</code>, mainly for scroll values.
*/
protected function drawTilemap(Buffer:FlxTilemapBuffer,Camera:FlxCamera):void
{
Buffer.fill();
//Copy tile images into the tile buffer
_point.x = int(Camera.scroll.x*scrollFactor.x) - x; //modified from getScreenXY()
_point.y = int(Camera.scroll.y*scrollFactor.y) - y;
var screenXInTiles:int = (_point.x + ((_point.x > 0)?0.0000001:-0.0000001))/_tileWidth;
var screenYInTiles:int = (_point.y + ((_point.y > 0)?0.0000001:-0.0000001))/_tileHeight;
var screenRows:uint = Buffer.rows;
var screenColumns:uint = Buffer.columns;
//Bound the upper left corner
if(screenXInTiles < 0)
screenXInTiles = 0;
if(screenXInTiles > widthInTiles-screenColumns)
screenXInTiles = widthInTiles-screenColumns;
if(screenYInTiles < 0)
screenYInTiles = 0;
if(screenYInTiles > heightInTiles-screenRows)
screenYInTiles = heightInTiles-screenRows;
var rowIndex:int = screenYInTiles*widthInTiles+screenXInTiles;
_flashPoint.y = 0;
var row:uint = 0;
var column:uint;
var columnIndex:uint;
var tile:FlxTile;
var debugTile:BitmapData;
while(row < screenRows)
{
columnIndex = rowIndex;
column = 0;
_flashPoint.x = 0;
while(column < screenColumns)
{
_flashRect = _rects[columnIndex] as Rectangle;
if(_flashRect != null)
{
Buffer.pixels.copyPixels(_tiles,_flashRect,_flashPoint,null,null,true);
if(FlxG.visualDebug && !ignoreDrawDebug)
{
tile = _tileObjects[_data[columnIndex]];
if(tile != null)
{
if(tile.allowCollisions <= NONE)
debugTile = _debugTileNotSolid; //blue
else if(tile.allowCollisions != ANY)
debugTile = _debugTilePartial; //pink
else
debugTile = _debugTileSolid; //green
Buffer.pixels.copyPixels(debugTile,_debugRect,_flashPoint,null,null,true);
}
}
}
_flashPoint.x += _tileWidth;
column++;
columnIndex++;
}
rowIndex += widthInTiles;
_flashPoint.y += _tileHeight;
row++;
}
Buffer.x = screenXInTiles*_tileWidth;
Buffer.y = screenYInTiles*_tileHeight;
}
/**
* Draws the tilemap buffers to the cameras and handles flickering.
*/
override public function draw():void
{
if(_flickerTimer != 0)
{
_flicker = !_flicker;
if(_flicker)
return;
}
if(cameras == null)
cameras = FlxG.cameras;
var camera:FlxCamera;
var buffer:FlxTilemapBuffer;
var i:uint = 0;
var l:uint = cameras.length;
while(i < l)
{
camera = cameras[i];
if(_buffers[i] == null)
_buffers[i] = new FlxTilemapBuffer(_tileWidth,_tileHeight,widthInTiles,heightInTiles,camera);
buffer = _buffers[i++] as FlxTilemapBuffer;
if(!buffer.dirty)
{
_point.x = x - int(camera.scroll.x*scrollFactor.x) + buffer.x; //copied from getScreenXY()
_point.y = y - int(camera.scroll.y*scrollFactor.y) + buffer.y;
buffer.dirty = (_point.x > 0) || (_point.y > 0) || (_point.x + buffer.width < camera.width) || (_point.y + buffer.height < camera.height);
}
if(buffer.dirty)
{
drawTilemap(buffer,camera);
buffer.dirty = false;
}
_flashPoint.x = x - int(camera.scroll.x*scrollFactor.x) + buffer.x; //copied from getScreenXY()
_flashPoint.y = y - int(camera.scroll.y*scrollFactor.y) + buffer.y;
_flashPoint.x += (_flashPoint.x > 0)?0.0000001:-0.0000001;
_flashPoint.y += (_flashPoint.y > 0)?0.0000001:-0.0000001;
buffer.draw(camera,_flashPoint);
_VISIBLECOUNT++;
}
}
/**
* Fetches the tilemap data array.
*
* @param Simple If true, returns the data as copy, as a series of 1s and 0s (useful for auto-tiling stuff). Default value is false, meaning it will return the actual data array (NOT a copy).
*
* @return An array the size of the tilemap full of integers indicating tile placement.
*/
public function getData(Simple:Boolean=false):Array
{
if(!Simple)
return _data;
var i:uint = 0;
var l:uint = _data.length;
var data:Array = new Array(l);
while(i < l)
{
data[i] = ((_tileObjects[_data[i]] as FlxTile).allowCollisions > 0)?1:0;
i++;
}
return data;
}
/**
* Set the dirty flag on all the tilemap buffers.
* Basically forces a reset of the drawn tilemaps, even if it wasn'tile necessary.
*
* @param Dirty Whether to flag the tilemap buffers as dirty or not.
*/
public function setDirty(Dirty:Boolean=true):void
{
var i:uint = 0;
var l:uint = _buffers.length;
while(i < l)
(_buffers[i++] as FlxTilemapBuffer).dirty = Dirty;
}
/**
* Find a path through the tilemap. Any tile with any collision flags set is treated as impassable.
* If no path is discovered then a null reference is returned.
*
* @param Start The start point in world coordinates.
* @param End The end point in world coordinates.
* @param Simplify Whether to run a basic simplification algorithm over the path data, removing extra points that are on the same line. Default value is true.
* @param RaySimplify Whether to run an extra raycasting simplification algorithm over the remaining path data. This can result in some close corners being cut, and should be used with care if at all (yet). Default value is false.
*
* @return A <code>FlxPath</code> from the start to the end. If no path could be found, then a null reference is returned.
*/
public function findPath(Start:FlxPoint,End:FlxPoint,Simplify:Boolean=true,RaySimplify:Boolean=false):FlxPath
{
//figure out what tile we are starting and ending on.
var startIndex:uint = int((Start.y-y)/_tileHeight) * widthInTiles + int((Start.x-x)/_tileWidth);
var endIndex:uint = int((End.y-y)/_tileHeight) * widthInTiles + int((End.x-x)/_tileWidth);
//check that the start and end are clear.
if( ((_tileObjects[_data[startIndex]] as FlxTile).allowCollisions > 0) ||
((_tileObjects[_data[endIndex]] as FlxTile).allowCollisions > 0) )
return null;
//figure out how far each of the tiles is from the starting tile
var distances:Array = computePathDistance(startIndex,endIndex);
if(distances == null)
return null;
//then count backward to find the shortest path.
var points:Array = new Array();
walkPath(distances,endIndex,points);
//reset the start and end points to be exact
var node:FlxPoint;
node = points[points.length-1] as FlxPoint;
node.x = Start.x;
node.y = Start.y;
node = points[0] as FlxPoint;
node.x = End.x;
node.y = End.y;
//some simple path cleanup options
if(Simplify)
simplifyPath(points);
if(RaySimplify)
raySimplifyPath(points);
//finally load the remaining points into a new path object and return it
var path:FlxPath = new FlxPath();
var i:int = points.length - 1;
while(i >= 0)
{
node = points[i--] as FlxPoint;
if(node != null)
path.addPoint(node,true);
}
return path;
}
/**
* Pathfinding helper function, strips out extra points on the same line.
*
* @param Points An array of <code>FlxPoint</code> nodes.
*/
protected function simplifyPath(Points:Array):void
{
var deltaPrevious:Number;
var deltaNext:Number;
var last:FlxPoint = Points[0];
var node:FlxPoint;
var i:uint = 1;
var l:uint = Points.length-1;
while(i < l)
{
node = Points[i];
deltaPrevious = (node.x - last.x)/(node.y - last.y);
deltaNext = (node.x - Points[i+1].x)/(node.y - Points[i+1].y);
if((last.x == Points[i+1].x) || (last.y == Points[i+1].y) || (deltaPrevious == deltaNext))
Points[i] = null;
else
last = node;
i++;
}
}
/**
* Pathfinding helper function, strips out even more points by raycasting from one point to the next and dropping unnecessary points.
*
* @param Points An array of <code>FlxPoint</code> nodes.
*/
protected function raySimplifyPath(Points:Array):void
{
var source:FlxPoint = Points[0];
var lastIndex:int = -1;
var node:FlxPoint;
var i:uint = 1;
var l:uint = Points.length;
while(i < l)
{
node = Points[i++];
if(node == null)
continue;
if(ray(source,node,_point))
{
if(lastIndex >= 0)
Points[lastIndex] = null;
}
else
source = Points[lastIndex];
lastIndex = i-1;
}
}
/**
* Pathfinding helper function, floods a grid with distance information until it finds the end point.
* NOTE: Currently this process does NOT use any kind of fancy heuristic! It's pretty brute.
*
* @param StartIndex The starting tile's map index.
* @param EndIndex The ending tile's map index.
*
* @return A Flash <code>Array</code> of <code>FlxPoint</code> nodes. If the end tile could not be found, then a null <code>Array</code> is returned instead.
*/
protected function computePathDistance(StartIndex:uint, EndIndex:uint):Array
{
//Create a distance-based representation of the tilemap.
//All walls are flagged as -2, all open areas as -1.
var mapSize:uint = widthInTiles*heightInTiles;
var distances:Array = new Array(mapSize);
var i:int = 0;
while(i < mapSize)
{
if((_tileObjects[_data[i]] as FlxTile).allowCollisions)
distances[i] = -2;
else
distances[i] = -1;
i++;
}
distances[StartIndex] = 0;
var distance:uint = 1;
var neighbors:Array = [StartIndex];
var current:Array;
var currentIndex:uint;
var left:Boolean;
var right:Boolean;
var up:Boolean;
var down:Boolean;
var currentLength:uint;
var foundEnd:Boolean = false;
while(neighbors.length > 0)
{
current = neighbors;
neighbors = new Array();
i = 0;
currentLength = current.length;
while(i < currentLength)
{
currentIndex = current[i++];
if(currentIndex == EndIndex)
{
foundEnd = true;
neighbors.length = 0;
break;
}
//basic map bounds
left = currentIndex%widthInTiles > 0;
right = currentIndex%widthInTiles < widthInTiles-1;
up = currentIndex/widthInTiles > 0;
down = currentIndex/widthInTiles < heightInTiles-1;
var index:uint;
if(up)
{
index = currentIndex - widthInTiles;
if(distances[index] == -1)
{
distances[index] = distance;
neighbors.push(index);
}
}
if(right)
{
index = currentIndex + 1;
if(distances[index] == -1)
{
distances[index] = distance;
neighbors.push(index);
}
}
if(down)
{
index = currentIndex + widthInTiles;
if(distances[index] == -1)
{
distances[index] = distance;
neighbors.push(index);
}
}
if(left)
{
index = currentIndex - 1;
if(distances[index] == -1)
{
distances[index] = distance;
neighbors.push(index);
}
}
if(up && right)
{
index = currentIndex - widthInTiles + 1;
if((distances[index] == -1) && (distances[currentIndex-widthInTiles] >= -1) && (distances[currentIndex+1] >= -1))
{
distances[index] = distance;
neighbors.push(index);
}
}
if(right && down)
{
index = currentIndex + widthInTiles + 1;
if((distances[index] == -1) && (distances[currentIndex+widthInTiles] >= -1) && (distances[currentIndex+1] >= -1))
{
distances[index] = distance;
neighbors.push(index);
}
}
if(left && down)
{
index = currentIndex + widthInTiles - 1;
if((distances[index] == -1) && (distances[currentIndex+widthInTiles] >= -1) && (distances[currentIndex-1] >= -1))
{
distances[index] = distance;
neighbors.push(index);
}
}
if(up && left)
{
index = currentIndex - widthInTiles - 1;
if((distances[index] == -1) && (distances[currentIndex-widthInTiles] >= -1) && (distances[currentIndex-1] >= -1))
{
distances[index] = distance;
neighbors.push(index);
}
}
}
distance++;
}
if(!foundEnd)
distances = null;
return distances;
}
/**
* Pathfinding helper function, recursively walks the grid and finds a shortest path back to the start.
*
* @param Data A Flash <code>Array</code> of distance information.
* @param Start The tile we're on in our walk backward.
* @param Points A Flash <code>Array</code> of <code>FlxPoint</code> nodes composing the path from the start to the end, compiled in reverse order.
*/
protected function walkPath(Data:Array,Start:uint,Points:Array):void
{
Points.push(new FlxPoint(x + uint(Start%widthInTiles)*_tileWidth + _tileWidth*0.5, y + uint(Start/widthInTiles)*_tileHeight + _tileHeight*0.5));
if(Data[Start] == 0)
return;
//basic map bounds
var left:Boolean = Start%widthInTiles > 0;
var right:Boolean = Start%widthInTiles < widthInTiles-1;
var up:Boolean = Start/widthInTiles > 0;
var down:Boolean = Start/widthInTiles < heightInTiles-1;
var current:uint = Data[Start];
var i:uint;
if(up)
{
i = Start - widthInTiles;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(right)
{
i = Start + 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(down)
{
i = Start + widthInTiles;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(left)
{
i = Start - 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(up && right)
{
i = Start - widthInTiles + 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(right && down)
{
i = Start + widthInTiles + 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(left && down)
{
i = Start + widthInTiles - 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
if(up && left)
{
i = Start - widthInTiles - 1;
if((Data[i] >= 0) && (Data[i] < current))
{
walkPath(Data,i,Points);
return;
}
}
}
/**
* Checks to see if some <code>FlxObject</code> overlaps this <code>FlxObject</code> object in world space.
* If the group has a LOT of things in it, it might be faster to use <code>FlxG.overlaps()</code>.
* WARNING: Currently tilemaps do NOT support screen space overlap checks!
*
* @param Object The object being tested.
* @param InScreenSpace Whether to take scroll factors into account when checking for overlap.
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the two objects overlap.
*/
override public function overlaps(ObjectOrGroup:FlxBasic,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean
{
if(ObjectOrGroup is FlxGroup)
{
var results:Boolean = false;
var basic:FlxBasic;
var i:uint = 0;
var members:Array = (ObjectOrGroup as FlxGroup).members;
while(i < length)
{
basic = members[i++] as FlxBasic;
if(basic is FlxObject)
{
if(overlapsWithCallback(basic as FlxObject))
results = true;
}
else
{
if(overlaps(basic,InScreenSpace,Camera))
results = true;
}
}
return results;
}
else if(ObjectOrGroup is FlxObject)
return overlapsWithCallback(ObjectOrGroup as FlxObject);
return false;
}
/**
* Checks to see if this <code>FlxObject</code> were located at the given position, would it overlap the <code>FlxObject</code> or <code>FlxGroup</code>?
* This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size into account.
* WARNING: Currently tilemaps do NOT support screen space overlap checks!
*
* @param X The X position you want to check. Pretends this object (the caller, not the parameter) is located here.
* @param Y The Y position you want to check. Pretends this object (the caller, not the parameter) is located here.
* @param ObjectOrGroup The object or group being tested.
* @param InScreenSpace Whether to take scroll factors into account when checking for overlap. Default is false, or "only compare in world space."
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the two objects overlap.
*/
override public function overlapsAt(X:Number,Y:Number,ObjectOrGroup:FlxBasic,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean
{
if(ObjectOrGroup is FlxGroup)
{
var results:Boolean = false;
var basic:FlxBasic;
var i:uint = 0;
var members:Array = (ObjectOrGroup as FlxGroup).members;
while(i < length)
{
basic = members[i++] as FlxBasic;
if(basic is FlxObject)
{
_point.x = X;
_point.y = Y;
if(overlapsWithCallback(basic as FlxObject,null,false,_point))
results = true;
}
else
{
if(overlapsAt(X,Y,basic,InScreenSpace,Camera))
results = true;
}
}
return results;
}
else if(ObjectOrGroup is FlxObject)
{
_point.x = X;
_point.y = Y;
return overlapsWithCallback(ObjectOrGroup as FlxObject,null,false,_point);
}
return false;
}
/**
* Checks if the Object overlaps any tiles with any collision flags set,
* and calls the specified callback function (if there is one).
* Also calls the tile's registered callback if the filter matches.
*
* @param Object The <code>FlxObject</code> you are checking for overlaps against.
* @param Callback An optional function that takes the form "myCallback(Object1:FlxObject,Object2:FlxObject)", where Object1 is a FlxTile object, and Object2 is the object passed in in the first parameter of this method.
* @param FlipCallbackParams Used to preserve A-B list ordering from FlxObject.separate() - returns the FlxTile object as the second parameter instead.
* @param Position Optional, specify a custom position for the tilemap (useful for overlapsAt()-type funcitonality).
*
* @return Whether there were overlaps, or if a callback was specified, whatever the return value of the callback was.
*/
public function overlapsWithCallback(Object:FlxObject,Callback:Function=null,FlipCallbackParams:Boolean=false,Position:FlxPoint=null):Boolean
{
var results:Boolean = false;
var X:Number = x;
var Y:Number = y;
if(Position != null)
{
X = Position.x;
Y = Position.y;
}
//Figure out what tiles we need to check against
var selectionX:int = FlxU.floor((Object.x - X)/_tileWidth);
var selectionY:int = FlxU.floor((Object.y - Y)/_tileHeight);
var selectionWidth:uint = selectionX + (FlxU.ceil(Object.width/_tileWidth)) + 1;
var selectionHeight:uint = selectionY + FlxU.ceil(Object.height/_tileHeight) + 1;
//Then bound these coordinates by the map edges
if(selectionX < 0)
selectionX = 0;
if(selectionY < 0)
selectionY = 0;
if(selectionWidth > widthInTiles)
selectionWidth = widthInTiles;
if(selectionHeight > heightInTiles)
selectionHeight = heightInTiles;
//Then loop through this selection of tiles and call FlxObject.separate() accordingly
var rowStart:uint = selectionY*widthInTiles;
var row:uint = selectionY;
var column:uint;
var tile:FlxTile;
var overlapFound:Boolean;
var deltaX:Number = X - last.x;
var deltaY:Number = Y - last.y;
while(row < selectionHeight)
{
column = selectionX;
while(column < selectionWidth)
{
overlapFound = false;
tile = _tileObjects[_data[rowStart+column]] as FlxTile;
if(tile.allowCollisions)
{
tile.x = X+column*_tileWidth;
tile.y = Y+row*_tileHeight;
tile.last.x = tile.x - deltaX;
tile.last.y = tile.y - deltaY;
if(Callback != null)
{
if(FlipCallbackParams)
overlapFound = Callback(Object,tile);
else
overlapFound = Callback(tile,Object);
}
else
overlapFound = (Object.x + Object.width > tile.x) && (Object.x < tile.x + tile.width) && (Object.y + Object.height > tile.y) && (Object.y < tile.y + tile.height);
if(overlapFound)
{
if((tile.callback != null) && ((tile.filter == null) || (Object is tile.filter)))
{
tile.mapIndex = rowStart+column;
tile.callback(tile,Object);
}
results = true;
}
}
else if((tile.callback != null) && ((tile.filter == null) || (Object is tile.filter)))
{
tile.mapIndex = rowStart+column;
tile.callback(tile,Object);
}
column++;
}
rowStart += widthInTiles;
row++;
}
return results;
}
/**
* Checks to see if a point in 2D world space overlaps this <code>FlxObject</code> object.
*
* @param Point The point in world space you want to check.
* @param InScreenSpace Whether to take scroll factors into account when checking for overlap.
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
*
* @return Whether or not the point overlaps this object.
*/
override public function overlapsPoint(Point:FlxPoint,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean
{
if(!InScreenSpace)
return (_tileObjects[_data[uint(uint((Point.y-y)/_tileHeight)*widthInTiles + (Point.x-x)/_tileWidth)]] as FlxTile).allowCollisions > 0;
if(Camera == null)
Camera = FlxG.camera;
Point.x = Point.x - Camera.scroll.x;
Point.y = Point.y - Camera.scroll.y;
getScreenXY(_point,Camera);
return (_tileObjects[_data[uint(uint((Point.y-_point.y)/_tileHeight)*widthInTiles + (Point.x-_point.x)/_tileWidth)]] as FlxTile).allowCollisions > 0;
}
/**
* Check the value of a particular tile.
*
* @param X The X coordinate of the tile (in tiles, not pixels).
* @param Y The Y coordinate of the tile (in tiles, not pixels).
*
* @return A uint containing the value of the tile at this spot in the array.
*/
public function getTile(X:uint,Y:uint):uint
{
return _data[Y * widthInTiles + X] as uint;
}
/**
* Get the value of a tile in the tilemap by index.
*
* @param Index The slot in the data array (Y * widthInTiles + X) where this tile is stored.
*
* @return A uint containing the value of the tile at this spot in the array.
*/
public function getTileByIndex(Index:uint):uint
{
return _data[Index] as uint;
}
/**
* Returns a new Flash <code>Array</code> full of every map index of the requested tile type.
*
* @param Index The requested tile type.
*
* @return An <code>Array</code> with a list of all map indices of that tile type.
*/
public function getTileInstances(Index:uint):Array
{
var array:Array = null;
var i:uint = 0;
var l:uint = widthInTiles * heightInTiles;
while(i < l)
{
if(_data[i] == Index)
{
if(array == null)
array = new Array();
array.push(i);
}
i++;
}
return array;
}
/**
* Returns a new Flash <code>Array</code> full of every coordinate of the requested tile type.
*
* @param Index The requested tile type.
* @param Midpoint Whether to return the coordinates of the tile midpoint, or upper left corner. Default is true, return midpoint.
*
* @return An <code>Array</code> with a list of all the coordinates of that tile type.
*/
public function getTileCoords(Index:uint,Midpoint:Boolean=true):Array
{
var array:Array = null;
var point:FlxPoint;
var i:uint = 0;
var l:uint = widthInTiles * heightInTiles;
while(i < l)
{
if(_data[i] == Index)
{
point = new FlxPoint(x + uint(i%widthInTiles)*_tileWidth,y + uint(i/widthInTiles)*_tileHeight);
if(Midpoint)
{
point.x += _tileWidth*0.5;
point.y += _tileHeight*0.5;
}
if(array == null)
array = new Array();
array.push(point);
}
i++;
}
return array;
}
/**
* Change the data and graphic of a tile in the tilemap.
*
* @param X The X coordinate of the tile (in tiles, not pixels).
* @param Y The Y coordinate of the tile (in tiles, not pixels).
* @param Tile The new integer data you wish to inject.
* @param UpdateGraphics Whether the graphical representation of this tile should change.
*
* @return Whether or not the tile was actually changed.
*/
public function setTile(X:uint,Y:uint,Tile:uint,UpdateGraphics:Boolean=true):Boolean
{
if((X >= widthInTiles) || (Y >= heightInTiles))
return false;
return setTileByIndex(Y * widthInTiles + X,Tile,UpdateGraphics);
}
/**
* Change the data and graphic of a tile in the tilemap.
*
* @param Index The slot in the data array (Y * widthInTiles + X) where this tile is stored.
* @param Tile The new integer data you wish to inject.
* @param UpdateGraphics Whether the graphical representation of this tile should change.
*
* @return Whether or not the tile was actually changed.
*/
public function setTileByIndex(Index:uint,Tile:uint,UpdateGraphics:Boolean=true):Boolean
{
if(Index >= _data.length)
return false;
var ok:Boolean = true;
_data[Index] = Tile;
if(!UpdateGraphics)
return ok;
setDirty();
if(auto == OFF)
{
updateTile(Index);
return ok;
}
//If this map is autotiled and it changes, locally update the arrangement
var i:uint;
var row:int = int(Index/widthInTiles) - 1;
var rowLength:int = row + 3;
var column:int = Index%widthInTiles - 1;
var columnHeight:int = column + 3;
while(row < rowLength)
{
column = columnHeight - 3;
while(column < columnHeight)
{
if((row >= 0) && (row < heightInTiles) && (column >= 0) && (column < widthInTiles))
{
i = row*widthInTiles+column;
autoTile(i);
updateTile(i);
}
column++;
}
row++;
}
return ok;
}
/**
* Adjust collision settings and/or bind a callback function to a range of tiles.
* This callback function, if present, is triggered by calls to overlap() or overlapsWithCallback().
*
* @param Tile The tile or tiles you want to adjust.
* @param AllowCollisions Modify the tile or tiles to only allow collisions from certain directions, use FlxObject constants NONE, ANY, LEFT, RIGHT, etc. Default is "ANY".
* @param Callback The function to trigger, e.g. <code>lavaCallback(Tile:FlxTile, Object:FlxObject)</code>.
* @param CallbackFilter If you only want the callback to go off for certain classes or objects based on a certain class, set that class here.
* @param Range If you want this callback to work for a bunch of different tiles, input the range here. Default value is 1.
*/
public function setTileProperties(Tile:uint,AllowCollisions:uint=0x1111,Callback:Function=null,CallbackFilter:Class=null,Range:uint=1):void
{
if(Range <= 0)
Range = 1;
var tile:FlxTile;
var i:uint = Tile;
var l:uint = Tile+Range;
while(i < l)
{
tile = _tileObjects[i++] as FlxTile;
tile.allowCollisions = AllowCollisions;
tile.callback = Callback;
tile.filter = CallbackFilter;
}
}
/**
* Call this function to lock the automatic camera to the map's edges.
*
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera.
* @param Border Adjusts the camera follow boundary by whatever number of tiles you specify here. Handy for blocking off deadends that are offscreen, etc. Use a negative number to add padding instead of hiding the edges.
* @param UpdateWorld Whether to update the collision system's world size, default value is true.
*/
public function follow(Camera:FlxCamera=null,Border:int=0,UpdateWorld:Boolean=true):void
{
if(Camera == null)
Camera = FlxG.camera;
Camera.setBounds(x+Border*_tileWidth,y+Border*_tileHeight,width-Border*_tileWidth*2,height-Border*_tileHeight*2,UpdateWorld);
}
/**
* Get the world coordinates and size of the entire tilemap as a <code>FlxRect</code>.
*
* @param Bounds Optional, pass in a pre-existing <code>FlxRect</code> to prevent instantiation of a new object.
*
* @return A <code>FlxRect</code> containing the world coordinates and size of the entire tilemap.
*/
public function getBounds(Bounds:FlxRect=null):FlxRect
{
if(Bounds == null)
Bounds = new FlxRect();
return Bounds.make(x,y,width,height);
}
/**
* Shoots a ray from the start point to the end point.
* If/when it passes through a tile, it stores that point and returns false.
*
* @param Start The world coordinates of the start of the ray.
* @param End The world coordinates of the end of the ray.
* @param Result A <code>Point</code> object containing the first wall impact.
* @param Resolution Defaults to 1, meaning check every tile or so. Higher means more checks!
* @return Returns true if the ray made it from Start to End without hitting anything. Returns false and fills Result if a tile was hit.
*/
public function ray(Start:FlxPoint, End:FlxPoint, Result:FlxPoint=null, Resolution:Number=1):Boolean
{
var step:Number = _tileWidth;
if(_tileHeight < _tileWidth)
step = _tileHeight;
step /= Resolution;
var deltaX:Number = End.x - Start.x;
var deltaY:Number = End.y - Start.y;
var distance:Number = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
var steps:uint = Math.ceil(distance/step);
var stepX:Number = deltaX/steps;
var stepY:Number = deltaY/steps;
var curX:Number = Start.x - stepX - x;
var curY:Number = Start.y - stepY - y;
var tileX:uint;
var tileY:uint;
var i:uint = 0;
while(i < steps)
{
curX += stepX;
curY += stepY;
if((curX < 0) || (curX > width) || (curY < 0) || (curY > height))
{
i++;
continue;
}
tileX = curX/_tileWidth;
tileY = curY/_tileHeight;
if((_tileObjects[_data[tileY*widthInTiles+tileX]] as FlxTile).allowCollisions)
{
//Some basic helper stuff
tileX *= _tileWidth;
tileY *= _tileHeight;
var rx:Number = 0;
var ry:Number = 0;
var q:Number;
var lx:Number = curX-stepX;
var ly:Number = curY-stepY;
//Figure out if it crosses the X boundary
q = tileX;
if(deltaX < 0)
q += _tileWidth;
rx = q;
ry = ly + stepY*((q-lx)/stepX);
if((ry > tileY) && (ry < tileY + _tileHeight))
{
if(Result == null)
Result = new FlxPoint();
Result.x = rx;
Result.y = ry;
return false;
}
//Else, figure out if it crosses the Y boundary
q = tileY;
if(deltaY < 0)
q += _tileHeight;
rx = lx + stepX*((q-ly)/stepY);
ry = q;
if((rx > tileX) && (rx < tileX + _tileWidth))
{
if(Result == null)
Result = new FlxPoint();
Result.x = rx;
Result.y = ry;
return false;
}
return true;
}
i++;
}
return true;
}
/**
* Converts a one-dimensional array of tile data to a comma-separated string.
*
* @param Data An array full of integer tile references.
* @param Width The number of tiles in each row.
* @param Invert Recommended only for 1-bit arrays - changes 0s to 1s and vice versa.
*
* @return A comma-separated string containing the level data in a <code>FlxTilemap</code>-friendly format.
*/
static public function arrayToCSV(Data:Array,Width:int,Invert:Boolean=false):String
{
var row:uint = 0;
var column:uint;
var csv:String;
var Height:int = Data.length / Width;
var index:int;
while(row < Height)
{
column = 0;
while(column < Width)
{
index = Data[row*Width+column];
if(Invert)
{
if(index == 0)
index = 1;
else if(index == 1)
index = 0;
}
if(column == 0)
{
if(row == 0)
csv += index;
else
csv += "\n"+index;
}
else
csv += ", "+index;
column++;
}
row++;
}
return csv;
}
/**
* Converts a <code>BitmapData</code> object to a comma-separated string.
* Black pixels are flagged as 'solid' by default,
* non-black pixels are set as non-colliding.
* Black pixels must be PURE BLACK.
*
* @param bitmapData A Flash <code>BitmapData</code> object, preferably black and white.
* @param Invert Load white pixels as solid instead.
* @param Scale Default is 1. Scale of 2 means each pixel forms a 2x2 block of tiles, and so on.
*
* @return A comma-separated string containing the level data in a <code>FlxTilemap</code>-friendly format.
*/
static public function bitmapToCSV(bitmapData:BitmapData,Invert:Boolean=false,Scale:uint=1):String
{
//Import and scale image if necessary
if(Scale > 1)
{
var bd:BitmapData = bitmapData;
bitmapData = new BitmapData(bitmapData.width*Scale,bitmapData.height*Scale);
var mtx:Matrix = new Matrix();
mtx.scale(Scale,Scale);
bitmapData.draw(bd,mtx);
}
//Walk image and export pixel values
var row:uint = 0;
var column:uint;
var pixel:uint;
var csv:String = "";
var bitmapWidth:uint = bitmapData.width;
var bitmapHeight:uint = bitmapData.height;
while(row < bitmapHeight)
{
column = 0;
while(column < bitmapWidth)
{
//Decide if this pixel/tile is solid (1) or not (0)
pixel = bitmapData.getPixel(column,row);
if((Invert && (pixel > 0)) || (!Invert && (pixel == 0)))
pixel = 1;
else
pixel = 0;
//Write the result to the string
if(column == 0)
{
if(row == 0)
csv += pixel;
else
csv += "\n"+pixel;
}
else
csv += ", "+pixel;
column++;
}
row++;
}
return csv;
}
/**
* Converts a resource image file to a comma-separated string.
* Black pixels are flagged as 'solid' by default,
* non-black pixels are set as non-colliding.
* Black pixels must be PURE BLACK.
*
* @param ImageFile An embedded graphic, preferably black and white.
* @param Invert Load white pixels as solid instead.
* @param Scale Default is 1. Scale of 2 means each pixel forms a 2x2 block of tiles, and so on.
*
* @return A comma-separated string containing the level data in a <code>FlxTilemap</code>-friendly format.
*/
static public function imageToCSV(ImageFile:Class,Invert:Boolean=false,Scale:uint=1):String
{
return bitmapToCSV((new ImageFile).bitmapData,Invert,Scale);
}
/**
* An internal function used by the binary auto-tilers.
*
* @param Index The index of the tile you want to analyze.
*/
protected function autoTile(Index:uint):void
{
if(_data[Index] == 0)
return;
_data[Index] = 0;
if((Index-widthInTiles < 0) || (_data[Index-widthInTiles] > 0)) //UP
_data[Index] += 1;
if((Index%widthInTiles >= widthInTiles-1) || (_data[Index+1] > 0)) //RIGHT
_data[Index] += 2;
if((Index+widthInTiles >= totalTiles) || (_data[Index+widthInTiles] > 0)) //DOWN
_data[Index] += 4;
if((Index%widthInTiles <= 0) || (_data[Index-1] > 0)) //LEFT
_data[Index] += 8;
if((auto == ALT) && (_data[Index] == 15)) //The alternate algo checks for interior corners
{
if((Index%widthInTiles > 0) && (Index+widthInTiles < totalTiles) && (_data[Index+widthInTiles-1] <= 0))
_data[Index] = 1; //BOTTOM LEFT OPEN
if((Index%widthInTiles > 0) && (Index-widthInTiles >= 0) && (_data[Index-widthInTiles-1] <= 0))
_data[Index] = 2; //TOP LEFT OPEN
if((Index%widthInTiles < widthInTiles-1) && (Index-widthInTiles >= 0) && (_data[Index-widthInTiles+1] <= 0))
_data[Index] = 4; //TOP RIGHT OPEN
if((Index%widthInTiles < widthInTiles-1) && (Index+widthInTiles < totalTiles) && (_data[Index+widthInTiles+1] <= 0))
_data[Index] = 8; //BOTTOM RIGHT OPEN
}
_data[Index] += 1;
}
/**
* Internal function used in setTileByIndex() and the constructor to update the map.
*
* @param Index The index of the tile you want to update.
*/
protected function updateTile(Index:uint):void
{
var tile:FlxTile = _tileObjects[_data[Index]] as FlxTile;
if((tile == null) || !tile.visible)
{
_rects[Index] = null;
return;
}
var rx:uint = (_data[Index]-_startingIndex)*_tileWidth;
var ry:uint = 0;
if(rx >= _tiles.width)
{
ry = uint(rx/_tiles.width)*_tileHeight;
rx %= _tiles.width;
}
_rects[Index] = (new Rectangle(rx,ry,_tileWidth,_tileHeight));
}
}
}
| 05-may-1gam-blocks-that-grow | trunk/lib/Flixel/org/flixel/FlxTilemap.as | AngelScript | gpl3 | 46,682 |
package org.flixel
{
import flash.display.Graphics;
import org.flixel.plugin.DebugPathDisplay;
/**
* This is a simple path data container. Basically a list of points that
* a <code>FlxObject</code> can follow. Also has code for drawing debug visuals.
* <code>FlxTilemap.findPath()</code> returns a path object, but you can
* also just make your own, using the <code>add()</code> functions below
* or by creating your own array of points.
*
* @author Adam Atomic
*/
public class FlxPath
{
/**
* The list of <code>FlxPoint</code>s that make up the path data.
*/
public var nodes:Array;
/**
* Specify a debug display color for the path. Default is white.
*/
public var debugColor:uint;
/**
* Specify a debug display scroll factor for the path. Default is (1,1).
* NOTE: does not affect world movement! Object scroll factors take care of that.
*/
public var debugScrollFactor:FlxPoint;
/**
* Setting this to true will prevent the object from appearing
* when the visual debug mode in the debugger overlay is toggled on.
* @default false
*/
public var ignoreDrawDebug:Boolean;
/**
* Internal helper for keeping new variable instantiations under control.
*/
protected var _point:FlxPoint;
/**
* Instantiate a new path object.
*
* @param Nodes Optional, can specify all the points for the path up front if you want.
*/
public function FlxPath(Nodes:Array=null)
{
if(Nodes == null)
nodes = new Array();
else
nodes = Nodes;
_point = new FlxPoint();
debugScrollFactor = new FlxPoint(1.0,1.0);
debugColor = 0xffffff;
ignoreDrawDebug = false;
var debugPathDisplay:DebugPathDisplay = manager;
if(debugPathDisplay != null)
debugPathDisplay.add(this);
}
/**
* Clean up memory.
*/
public function destroy():void
{
var debugPathDisplay:DebugPathDisplay = manager;
if(debugPathDisplay != null)
debugPathDisplay.remove(this);
debugScrollFactor = null;
_point = null;
nodes = null;
}
/**
* Add a new node to the end of the path at the specified location.
*
* @param X X position of the new path point in world coordinates.
* @param Y Y position of the new path point in world coordinates.
*/
public function add(X:Number,Y:Number):void
{
nodes.push(new FlxPoint(X,Y));
}
/**
* Add a new node to the path at the specified location and index within the path.
*
* @param X X position of the new path point in world coordinates.
* @param Y Y position of the new path point in world coordinates.
* @param Index Where within the list of path nodes to insert this new point.
*/
public function addAt(X:Number, Y:Number, Index:uint):void
{
if(Index > nodes.length)
Index = nodes.length;
nodes.splice(Index,0,new FlxPoint(X,Y));
}
/**
* Sometimes its easier or faster to just pass a point object instead of separate X and Y coordinates.
* This also gives you the option of not creating a new node but actually adding that specific
* <code>FlxPoint</code> object to the path. This allows you to do neat things, like dynamic paths.
*
* @param Node The point in world coordinates you want to add to the path.
* @param AsReference Whether to add the point as a reference, or to create a new point with the specified values.
*/
public function addPoint(Node:FlxPoint,AsReference:Boolean=false):void
{
if(AsReference)
nodes.push(Node);
else
nodes.push(new FlxPoint(Node.x,Node.y));
}
/**
* Sometimes its easier or faster to just pass a point object instead of separate X and Y coordinates.
* This also gives you the option of not creating a new node but actually adding that specific
* <code>FlxPoint</code> object to the path. This allows you to do neat things, like dynamic paths.
*
* @param Node The point in world coordinates you want to add to the path.
* @param Index Where within the list of path nodes to insert this new point.
* @param AsReference Whether to add the point as a reference, or to create a new point with the specified values.
*/
public function addPointAt(Node:FlxPoint,Index:uint,AsReference:Boolean=false):void
{
if(Index > nodes.length)
Index = nodes.length;
if(AsReference)
nodes.splice(Index,0,Node);
else
nodes.splice(Index,0,new FlxPoint(Node.x,Node.y));
}
/**
* Remove a node from the path.
* NOTE: only works with points added by reference or with references from <code>nodes</code> itself!
*
* @param Node The point object you want to remove from the path.
*
* @return The node that was excised. Returns null if the node was not found.
*/
public function remove(Node:FlxPoint):FlxPoint
{
var index:int = nodes.indexOf(Node);
if(index >= 0)
return nodes.splice(index,1)[0];
else
return null;
}
/**
* Remove a node from the path using the specified position in the list of path nodes.
*
* @param Index Where within the list of path nodes you want to remove a node.
*
* @return The node that was excised. Returns null if there were no nodes in the path.
*/
public function removeAt(Index:uint):FlxPoint
{
if(nodes.length <= 0)
return null;
if(Index >= nodes.length)
Index = nodes.length-1;
return nodes.splice(Index,1)[0];
}
/**
* Get the first node in the list.
*
* @return The first node in the path.
*/
public function head():FlxPoint
{
if(nodes.length > 0)
return nodes[0];
return null;
}
/**
* Get the last node in the list.
*
* @return The last node in the path.
*/
public function tail():FlxPoint
{
if(nodes.length > 0)
return nodes[nodes.length-1];
return null;
}
/**
* While this doesn't override <code>FlxBasic.drawDebug()</code>, the behavior is very similar.
* Based on this path data, it draws a simple lines-and-boxes representation of the path
* if the visual debug mode was toggled in the debugger overlay. You can use <code>debugColor</code>
* and <code>debugScrollFactor</code> to control the path's appearance.
*
* @param Camera The camera object the path will draw to.
*/
public function drawDebug(Camera:FlxCamera=null):void
{
if(nodes.length <= 0)
return;
if(Camera == null)
Camera = FlxG.camera;
//Set up our global flash graphics object to draw out the path
var gfx:Graphics = FlxG.flashGfx;
gfx.clear();
//Then fill up the object with node and path graphics
var node:FlxPoint;
var nextNode:FlxPoint;
var i:uint = 0;
var l:uint = nodes.length;
while(i < l)
{
//get a reference to the current node
node = nodes[i] as FlxPoint;
//find the screen position of the node on this camera
_point.x = node.x - int(Camera.scroll.x*debugScrollFactor.x); //copied from getScreenXY()
_point.y = node.y - int(Camera.scroll.y*debugScrollFactor.y);
_point.x = int(_point.x + ((_point.x > 0)?0.0000001:-0.0000001));
_point.y = int(_point.y + ((_point.y > 0)?0.0000001:-0.0000001));
//decide what color this node should be
var nodeSize:uint = 2;
if((i == 0) || (i == l-1))
nodeSize *= 2;
var nodeColor:uint = debugColor;
if(l > 1)
{
if(i == 0)
nodeColor = FlxG.GREEN;
else if(i == l-1)
nodeColor = FlxG.RED;
}
//draw a box for the node
gfx.beginFill(nodeColor,0.5);
gfx.lineStyle();
gfx.drawRect(_point.x-nodeSize*0.5,_point.y-nodeSize*0.5,nodeSize,nodeSize);
gfx.endFill();
//then find the next node in the path
var linealpha:Number = 0.3;
if(i < l-1)
nextNode = nodes[i+1];
else
{
nextNode = nodes[0];
linealpha = 0.15;
}
//then draw a line to the next node
gfx.moveTo(_point.x,_point.y);
gfx.lineStyle(1,debugColor,linealpha);
_point.x = nextNode.x - int(Camera.scroll.x*debugScrollFactor.x); //copied from getScreenXY()
_point.y = nextNode.y - int(Camera.scroll.y*debugScrollFactor.y);
_point.x = int(_point.x + ((_point.x > 0)?0.0000001:-0.0000001));
_point.y = int(_point.y + ((_point.y > 0)?0.0000001:-0.0000001));
gfx.lineTo(_point.x,_point.y);
i++;
}
//then stamp the path down onto the game buffer
Camera.buffer.draw(FlxG.flashGfxSprite);
}
static public function get manager():DebugPathDisplay
{
return FlxG.getPlugin(DebugPathDisplay) as DebugPathDisplay;
}
}
} | 05-may-1gam-blocks-that-grow | trunk/lib/Flixel/org/flixel/FlxPath.as | ActionScript | gpl3 | 8,537 |