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