More reasonable end criteria
[sw/motorsim] / src / com / billkuker / rocketry / motorsim / Burn.java
1 package com.billkuker.rocketry.motorsim;\r
2 \r
3 \r
4 \r
5 import java.util.Date;\r
6 import java.util.SortedMap;\r
7 import java.util.TreeMap;\r
8 \r
9 import javax.measure.quantity.Area;\r
10 import javax.measure.quantity.Dimensionless;\r
11 import javax.measure.quantity.Duration;\r
12 import javax.measure.quantity.Force;\r
13 import javax.measure.quantity.Length;\r
14 import javax.measure.quantity.Mass;\r
15 import javax.measure.quantity.MassFlowRate;\r
16 import javax.measure.quantity.Pressure;\r
17 import javax.measure.quantity.Quantity;\r
18 import javax.measure.quantity.Temperature;\r
19 import javax.measure.quantity.Velocity;\r
20 import javax.measure.quantity.Volume;\r
21 import javax.measure.quantity.VolumetricDensity;\r
22 import javax.measure.unit.SI;\r
23 \r
24 import org.apache.log4j.Logger;\r
25 import org.jscience.physics.amount.Amount;\r
26 import org.jscience.physics.amount.Constants;\r
27 \r
28 import com.billkuker.rocketry.motorsim.Validating.ValidationException;\r
29 \r
30 public class Burn {\r
31         //Some constants to tune adaptive regression step\r
32         private static final double regStepIncreaseFactor = 1.01;\r
33         private static final double regStepDecreaseFactor = .5;\r
34         private static final Amount<Pressure> chamberPressureMaxDelta = Amount.valueOf(.5, SI.MEGA(SI.PASCAL));\r
35         \r
36         private static final Amount<Pressure> endPressure = Amount.valueOf(.1, RocketScience.PSI);\r
37         \r
38         private static Logger log = Logger.getLogger(Burn.class);\r
39         protected final Motor motor;\r
40         \r
41         public interface BurnProgressListener{\r
42                 public void setProgress(float p);\r
43         }\r
44         \r
45         private BurnProgressListener bpl = null;\r
46         \r
47         private static final Amount<Pressure> atmosphereicPressure = Amount.valueOf(101000, SI.PASCAL);\r
48         \r
49         public class Interval{\r
50                 public Amount<Duration> time;\r
51                 public Amount<Duration> dt;\r
52                 public Amount<Length> regression;\r
53                 public Amount<Pressure> chamberPressure;\r
54                 Amount<Mass> chamberProduct;\r
55                 public Amount<Force> thrust;\r
56 \r
57                 public String toString(){\r
58                         return time + " " + dt + " " + regression + " " + chamberPressure + " " + chamberProduct;\r
59                 }\r
60         }\r
61         \r
62         protected SortedMap<Amount<Duration>,Interval> data = new TreeMap<Amount<Duration>, Interval>();\r
63         \r
64         public SortedMap<Amount<Duration>,Interval> getData(){\r
65                 return data;\r
66         }\r
67         \r
68         public Motor getMotor(){\r
69                 return motor;\r
70         }\r
71 \r
72         public Amount<Duration> burnTime(){\r
73                 return data.lastKey();\r
74         }\r
75         \r
76         public Burn(Motor m){\r
77                 try {\r
78                         m.validate();\r
79                 } catch (ValidationException e) {\r
80                         throw new IllegalArgumentException("Invalid Motor: " + e.getMessage());\r
81                 }\r
82                 motor = m;\r
83                 burn();\r
84         }\r
85         \r
86         public Burn(Motor m, BurnProgressListener bpl){\r
87                 try {\r
88                         m.validate();\r
89                 } catch (ValidationException e) {\r
90                         throw new IllegalArgumentException("Invalid Motor: " + e.getMessage());\r
91                 }\r
92                 motor = m;\r
93                 this.bpl = bpl;\r
94                 burn();\r
95         }\r
96         \r
97         private void burn(){\r
98                 log.info("Starting burn...");\r
99                 int endPressureSteps = 0;\r
100                 long start = new Date().getTime();\r
101                 \r
102                 Amount<Length> regStep = Amount.valueOf(0.01, SI.MILLIMETER);\r
103 \r
104                 Interval initial = new Interval();\r
105                 initial.time = Amount.valueOf(0, SI.SECOND);\r
106                 initial.dt = Amount.valueOf(0, SI.SECOND);\r
107                 initial.regression = Amount.valueOf(0, SI.MILLIMETER);\r
108                 initial.chamberPressure = atmosphereicPressure;\r
109                 initial.chamberProduct = Amount.valueOf(0, SI.KILOGRAM);\r
110                 initial.thrust = Amount.valueOf(0, SI.NEWTON);\r
111                 \r
112                 data.put(Amount.valueOf(0, SI.SECOND), initial);\r
113                 \r
114                 step:\r
115                 for ( int i = 0; i < 5000; i++ ) {\r
116                         assert(positive(regStep));\r
117                         regStep = regStep.times(regStepIncreaseFactor);\r
118                         \r
119                         Interval prev = data.get(data.lastKey());\r
120                         log.debug(prev);\r
121                         log.debug("Step " + i + " ==============================");\r
122                         Interval next = new Interval();\r
123                         \r
124                         Amount<Velocity> burnRate = motor.getFuel().burnRate(prev.chamberPressure);\r
125                         assert(positive(burnRate));\r
126                         \r
127                         log.debug("Burn Rate: " + burnRate);\r
128                         \r
129                         Amount<Duration> dt = regStep.divide(burnRate).to(Duration.UNIT);\r
130                         assert(positive(dt));\r
131                         next.dt = dt;\r
132                         \r
133 \r
134                         \r
135                         log.debug("Dt: " + dt);\r
136                         \r
137                         next.regression = prev.regression.plus(regStep);\r
138                         assert(positive(next.regression));\r
139                         \r
140                         log.debug("Regression: " + next.regression);\r
141                         \r
142                         if ( bpl != null ){\r
143                                 Amount<Dimensionless> a = next.regression.divide(motor.getGrain().webThickness()).to(Dimensionless.UNIT);\r
144                                 bpl.setProgress((float)a.doubleValue(Dimensionless.UNIT));\r
145                         }\r
146                         \r
147                         next.time = prev.time.plus(dt);\r
148                         \r
149                         //log.debug("Vold: " + motor.getGrain().volume(prev.regression).to(SI.MILLIMETER.pow(3)));\r
150                         \r
151                         //log.debug("Vnew: " + motor.getGrain().volume(next.regression).to(SI.MILLIMETER.pow(3)));\r
152                         \r
153                         //TODO Amount<Volume> volumeBurnt = motor.getGrain().volume(prev.regression).minus(motor.getGrain().volume(next.regression));\r
154                         Amount<Volume> volumeBurnt = motor.getGrain().surfaceArea(prev.regression).times(regStep).to(Volume.UNIT);\r
155                         assert(positive(volumeBurnt));\r
156                         //log.info("Volume Burnt: " + volumeBurnt.to(SI.MILLIMETER.pow(3)));\r
157                         \r
158                         Amount<MassFlowRate> mGenRate = volumeBurnt.times(motor.getFuel().getIdealDensity().times(motor.getFuel().getDensityRatio())).divide(dt).to(MassFlowRate.UNIT);\r
159                         assert(positive(mGenRate));\r
160                         \r
161                         //log.debug("Mass Gen Rate: " + mGenRate);\r
162                         \r
163                         //Calculate specific gas constant\r
164                         Amount<?> specificGasConstant = Constants.R.divide(motor.getFuel().getCombustionProduct().getEffectiveMolarWeight());\r
165                         //This unit conversion helps JScience to convert nozzle flow rate to\r
166                         //kg/s a little later on I verified the conversion by hand and\r
167                         //JScience checks it too.\r
168                         specificGasConstant = convertSpecificGasConstantUnits(specificGasConstant);\r
169                         \r
170                         //Calculate chamber temperature\r
171                         Amount<Temperature> chamberTemp = motor.getFuel().getCombustionProduct().getIdealCombustionTemperature().times(motor.getFuel().getCombustionEfficiency());\r
172                         \r
173                         Amount<MassFlowRate> mNozzle;\r
174                         {\r
175                                 Amount<Pressure> pDiff = prev.chamberPressure.minus(atmosphereicPressure);\r
176                                 //log.debug("Pdiff: " + pDiff);\r
177                                 Amount<Area> aStar = motor.getNozzle().throatArea();\r
178                                 double k = motor.getFuel().getCombustionProduct().getRatioOfSpecificHeats();\r
179                                 double kSide = Math.sqrt(k) * Math.pow((2/(k+1)) , (((k+1)/2)/(k-1)));\r
180                                 Amount<?> sqrtPart = specificGasConstant.times(chamberTemp).sqrt();\r
181                                 mNozzle = pDiff.times(aStar).times(kSide).divide(sqrtPart).to(MassFlowRate.UNIT);\r
182                                 //log.debug("Mass Exit Rate: " + mNozzle.to(MassFlowRate.UNIT));                \r
183                         }\r
184                         assert(positive(mNozzle));\r
185                         \r
186                         Amount<MassFlowRate> massStorageRate = mGenRate.minus(mNozzle);\r
187                         \r
188                         //log.debug("Mass Storage Rate: " + massStorageRate);\r
189 \r
190                         next.chamberProduct = prev.chamberProduct.plus(massStorageRate.times(dt));\r
191                         \r
192                         //Product can not go negative!\r
193                         if ( !positive(next.chamberProduct) ){\r
194                                 log.warn("ChamberProduct Negative on step " + i + "!, Adjusting regstep down and repeating step!");\r
195                                 regStep = regStep.times(regStepDecreaseFactor);\r
196                                 continue step;\r
197                         }\r
198                         assert(positive(next.chamberProduct));\r
199                         if ( next.chamberProduct.isLessThan(Amount.valueOf(0, SI.KILOGRAM)) )\r
200                                 next.chamberProduct = Amount.valueOf(0, SI.KILOGRAM);\r
201                         \r
202                         //log.debug("Chamber Product: " + next.chamberProduct);\r
203                         \r
204                         Amount<VolumetricDensity> combustionProductDensity = next.chamberProduct.divide(motor.getChamber().chamberVolume().minus(motor.getGrain().volume(next.regression))).to(VolumetricDensity.UNIT);\r
205                         \r
206                         log.debug("Product Density: " + combustionProductDensity);\r
207                         \r
208                         next.chamberPressure = combustionProductDensity.times(specificGasConstant).times(chamberTemp).plus(atmosphereicPressure).to(Pressure.UNIT);\r
209                         assert(positive(next.chamberPressure));\r
210                         \r
211                         next.chamberPressure = Amount.valueOf(\r
212                                         next.chamberPressure.doubleValue(SI.PASCAL),\r
213                                         SI.PASCAL);\r
214                         \r
215                         Amount<Pressure> dp = next.chamberPressure.minus(prev.chamberPressure);\r
216                         if ( dp.abs().isGreaterThan(chamberPressureMaxDelta)){\r
217                                 log.warn("DP " + dp + " too big!, Adjusting regstep down and repeating step!");\r
218                                 regStep = regStep.times(regStepDecreaseFactor);\r
219                                 continue step;\r
220                         }\r
221                         \r
222                         next.thrust = motor.getNozzle().thrust(next.chamberPressure, atmosphereicPressure, atmosphereicPressure, motor.getFuel().getCombustionProduct().getRatioOfSpecificHeats2Phase());\r
223                         assert(positive(next.thrust));\r
224                         \r
225                         if ( i > 100 && next.chamberPressure.minus(atmosphereicPressure).abs().isLessThan(endPressure)){\r
226                                 log.info("Pressure at ~Patm on step " + i);\r
227                                 endPressureSteps++;\r
228                                 if ( endPressureSteps > 5 )\r
229                                         break;\r
230                         }\r
231                         \r
232                         data.put(data.lastKey().plus(dt), next);\r
233                 }\r
234 \r
235                 long time = new Date().getTime() - start;\r
236                 log.info("Burn took " + time + " millis.");\r
237         }\r
238         \r
239         @SuppressWarnings("unchecked")\r
240         /*\r
241          * This converts the units of this constant to something JScience is able\r
242          * to work from. This conversion is unchecked at compile time, but\r
243          * JScience keeps me honest at runtime.\r
244          */\r
245         private Amount convertSpecificGasConstantUnits(Amount a){\r
246                 return a.to(\r
247                                 SI.METER.pow(2).divide(SI.SECOND.pow(2).times(SI.KELVIN)));\r
248         }\r
249         \r
250         public Amount<Pressure> pressure(Amount<Duration> time){\r
251                 return data.get(time).chamberPressure;\r
252         }\r
253         \r
254         public Amount<Force> thrust(Amount<Duration> time){\r
255                 return data.get(time).thrust;\r
256         }\r
257         \r
258         public Amount<Dimensionless> kn(Amount<Length> regression){\r
259                 return motor.getGrain().surfaceArea(regression).divide(motor.getNozzle().throatArea()).to(Dimensionless.UNIT);\r
260         }\r
261         \r
262         \r
263         private <Q extends Quantity> boolean positive(Amount<Q> a){\r
264                 return ( a.isGreaterThan(a.minus(a)) || a.equals(a.minus(a)));\r
265         }\r
266 \r
267 }\r