Move burn settings into a class
[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         private static Logger log = Logger.getLogger(Burn.class);\r
34         \r
35         /**\r
36          * A class representing all the settigns one can change on a burn\r
37          * @author bkuker\r
38          */\r
39         public static class BurnSettings {\r
40                 private BurnSettings(){};\r
41 \r
42                 public enum BurnVolumeMethod {\r
43                         DeltaVolume,\r
44                         SurfaceTimesRegression;\r
45                 }\r
46                 \r
47                 private BurnVolumeMethod volumeMethod = BurnVolumeMethod.SurfaceTimesRegression;\r
48                 private double regStepIncreaseFactor = 1.01;\r
49                 private double regStepDecreaseFactor = .5;\r
50                 private Amount<Pressure> chamberPressureMaxDelta = Amount.valueOf(.5, SI.MEGA(SI.PASCAL));\r
51                 private Amount<Pressure> endPressure = Amount.valueOf(.1, RocketScience.PSI);\r
52                 \r
53                 public void setVolumeMethod(BurnVolumeMethod volumeMethod) {\r
54                         this.volumeMethod = volumeMethod;\r
55                 }\r
56                 public BurnVolumeMethod getVolumeMethod() {\r
57                         return volumeMethod;\r
58                 }\r
59                 public double getRegStepIncreaseFactor() {\r
60                         return regStepIncreaseFactor;\r
61                 }\r
62                 public void setRegStepIncreaseFactor(double regStepIncreaseFactor) {\r
63                         this.regStepIncreaseFactor = regStepIncreaseFactor;\r
64                 }\r
65                 public double getRegStepDecreaseFactor() {\r
66                         return regStepDecreaseFactor;\r
67                 }\r
68                 public void setRegStepDecreaseFactor(double regStepDecreaseFactor) {\r
69                         this.regStepDecreaseFactor = regStepDecreaseFactor;\r
70                 }\r
71                 public Amount<Pressure> getChamberPressureMaxDelta() {\r
72                         return chamberPressureMaxDelta;\r
73                 }\r
74                 public void setChamberPressureMaxDelta(Amount<Pressure> chamberPressureMaxDelta) {\r
75                         this.chamberPressureMaxDelta = chamberPressureMaxDelta;\r
76                 }\r
77                 public Amount<Pressure> getEndPressure() {\r
78                         return endPressure;\r
79                 }\r
80                 public void setEndPressure(Amount<Pressure> endPressure) {\r
81                         this.endPressure = endPressure;\r
82                 }\r
83         }\r
84         \r
85         protected final Motor motor;\r
86         \r
87         private boolean burning = false;\r
88         private boolean done = false;\r
89         \r
90         public interface BurnProgressListener{\r
91                 public void setProgress(float p);\r
92                 public void burnComplete();\r
93         }\r
94         \r
95 \r
96         \r
97         public static final BurnSettings settings = new BurnSettings();\r
98         \r
99         private Set<BurnProgressListener> bpls = new HashSet<Burn.BurnProgressListener>();\r
100         \r
101         private static final Amount<Pressure> atmosphereicPressure = Amount.valueOf(101000, SI.PASCAL);\r
102         \r
103         public class Interval{\r
104                 public Amount<Duration> time;\r
105                 public Amount<Duration> dt;\r
106                 public Amount<Length> regression;\r
107                 public Amount<Pressure> chamberPressure;\r
108                 Amount<Mass> chamberProduct;\r
109                 public Amount<Force> thrust;\r
110 \r
111                 public String toString(){\r
112                         return time + " " + dt + " " + regression + " " + chamberPressure + " " + chamberProduct;\r
113                 }\r
114         }\r
115         \r
116         protected SortedMap<Amount<Duration>,Interval> data = new TreeMap<Amount<Duration>, Interval>();\r
117         \r
118         public SortedMap<Amount<Duration>,Interval> getData(){\r
119                 if ( !done )\r
120                         throw new IllegalStateException("Burn not complete!");\r
121                 return data;\r
122         }\r
123         \r
124         public Motor getMotor(){\r
125                 return motor;\r
126         }\r
127 \r
128         public Amount<Duration> burnTime(){\r
129                 return getData().lastKey();\r
130         }\r
131         \r
132         public Burn(Motor m){\r
133                 try {\r
134                         m.validate();\r
135                 } catch (ValidationException e) {\r
136                         throw new IllegalArgumentException("Invalid Motor: " + e.getMessage());\r
137                 }\r
138                 motor = m;\r
139         }\r
140         \r
141         public void addBurnProgressListener( BurnProgressListener bpl ){\r
142                 bpls.add(bpl);\r
143                 if ( done )\r
144                         bpl.burnComplete();\r
145         }\r
146         \r
147         public void burn(){\r
148                 synchronized(this){\r
149                         if ( burning )\r
150                                 throw new IllegalStateException("Already burning!");\r
151                         burning = true;\r
152                 }\r
153                 log.info("Starting burn...");\r
154                 for (BurnProgressListener bpl : bpls ){\r
155                         bpl.setProgress(0);\r
156                 }\r
157                 \r
158                 int endPressureSteps = 0;\r
159                 long start = new Date().getTime();\r
160                 \r
161                 Amount<Length> regStep = Amount.valueOf(0.01, SI.MILLIMETER);\r
162 \r
163                 Interval initial = new Interval();\r
164                 initial.time = Amount.valueOf(0, SI.SECOND);\r
165                 initial.dt = Amount.valueOf(0, SI.SECOND);\r
166                 initial.regression = Amount.valueOf(0, SI.MILLIMETER);\r
167                 initial.chamberPressure = atmosphereicPressure;\r
168                 initial.chamberProduct = Amount.valueOf(0, SI.KILOGRAM);\r
169                 initial.thrust = Amount.valueOf(0, SI.NEWTON);\r
170                 \r
171                 data.put(Amount.valueOf(0, SI.SECOND), initial);\r
172                 \r
173                 step:\r
174                 for ( int i = 0; i < 5000; i++ ) {\r
175                         assert(positive(regStep));\r
176                         regStep = regStep.times(settings.getRegStepIncreaseFactor());\r
177                         \r
178                         Interval prev = data.get(data.lastKey());\r
179                         log.debug(prev);\r
180                         log.debug("Step " + i + " ==============================");\r
181                         Interval next = new Interval();\r
182                         \r
183                         Amount<Velocity> burnRate = motor.getFuel().burnRate(prev.chamberPressure);\r
184                         assert(positive(burnRate));\r
185                         \r
186                         log.debug("Burn Rate: " + burnRate);\r
187                         \r
188                         Amount<Duration> dt = regStep.divide(burnRate).to(Duration.UNIT);\r
189                         assert(positive(dt));\r
190                         next.dt = dt;\r
191                         \r
192 \r
193                         \r
194                         log.debug("Dt: " + dt);\r
195                         \r
196                         next.regression = prev.regression.plus(regStep);\r
197                         assert(positive(next.regression));\r
198                         \r
199                         log.debug("Regression: " + next.regression);\r
200                         \r
201                         //Update BurnProgressListeners\r
202                         Amount<Dimensionless> a = next.regression.divide(motor.getGrain().webThickness()).to(Dimensionless.UNIT);\r
203                         for (BurnProgressListener bpl : bpls ){\r
204                                 bpl.setProgress((float)a.doubleValue(Dimensionless.UNIT));\r
205                         }\r
206 \r
207                         \r
208                         next.time = prev.time.plus(dt);\r
209                         \r
210                         //log.debug("Vold: " + motor.getGrain().volume(prev.regression).to(SI.MILLIMETER.pow(3)));\r
211                         \r
212                         //log.debug("Vnew: " + motor.getGrain().volume(next.regression).to(SI.MILLIMETER.pow(3)));\r
213                         \r
214                         Amount<Volume> volumeBurnt;\r
215                         if ( settings.getVolumeMethod() == BurnSettings.BurnVolumeMethod.DeltaVolume ){\r
216                                 volumeBurnt = motor.getGrain().volume(prev.regression).minus(motor.getGrain().volume(next.regression));\r
217                         } else {\r
218                                 volumeBurnt = motor.getGrain().surfaceArea(prev.regression).times(regStep).to(Volume.UNIT);\r
219                         }\r
220                         assert(positive(volumeBurnt));\r
221                         //log.info("Volume Burnt: " + volumeBurnt.to(SI.MILLIMETER.pow(3)));\r
222                         \r
223                         Amount<MassFlowRate> mGenRate = volumeBurnt.times(motor.getFuel().getIdealDensity().times(motor.getFuel().getDensityRatio())).divide(dt).to(MassFlowRate.UNIT);\r
224                         assert(positive(mGenRate));\r
225                         \r
226                         //log.debug("Mass Gen Rate: " + mGenRate);\r
227                         \r
228                         //Calculate specific gas constant\r
229                         Amount<?> specificGasConstant = Constants.R.divide(motor.getFuel().getCombustionProduct().getEffectiveMolarWeight());\r
230                         //This unit conversion helps JScience to convert nozzle flow rate to\r
231                         //kg/s a little later on I verified the conversion by hand and\r
232                         //JScience checks it too.\r
233                         specificGasConstant = convertSpecificGasConstantUnits(specificGasConstant);\r
234                         \r
235                         //Calculate chamber temperature\r
236                         Amount<Temperature> chamberTemp = motor.getFuel().getCombustionProduct().getIdealCombustionTemperature().times(motor.getFuel().getCombustionEfficiency());\r
237                         \r
238                         Amount<MassFlowRate> mNozzle;\r
239                         {\r
240                                 Amount<Pressure> pDiff = prev.chamberPressure.minus(atmosphereicPressure);\r
241                                 //log.debug("Pdiff: " + pDiff);\r
242                                 Amount<Area> aStar = motor.getNozzle().throatArea();\r
243                                 double k = motor.getFuel().getCombustionProduct().getRatioOfSpecificHeats();\r
244                                 double kSide = Math.sqrt(k) * Math.pow((2/(k+1)) , (((k+1)/2)/(k-1)));\r
245                                 Amount<?> sqrtPart = specificGasConstant.times(chamberTemp).sqrt();\r
246                                 mNozzle = pDiff.times(aStar).times(kSide).divide(sqrtPart).to(MassFlowRate.UNIT);\r
247                                 //log.debug("Mass Exit Rate: " + mNozzle.to(MassFlowRate.UNIT));                \r
248                         }\r
249                         assert(positive(mNozzle));\r
250                         \r
251                         Amount<MassFlowRate> massStorageRate = mGenRate.minus(mNozzle);\r
252                         \r
253                         //log.debug("Mass Storage Rate: " + massStorageRate);\r
254 \r
255                         next.chamberProduct = prev.chamberProduct.plus(massStorageRate.times(dt));\r
256                         \r
257                         //Product can not go negative!\r
258                         if ( !positive(next.chamberProduct) ){\r
259                                 log.warn("ChamberProduct Negative on step " + i + "!, Adjusting regstep down and repeating step!");\r
260                                 regStep = regStep.times(settings.getRegStepDecreaseFactor());\r
261                                 continue step;\r
262                         }\r
263                         assert(positive(next.chamberProduct));\r
264                         if ( next.chamberProduct.isLessThan(Amount.valueOf(0, SI.KILOGRAM)) )\r
265                                 next.chamberProduct = Amount.valueOf(0, SI.KILOGRAM);\r
266                         \r
267                         //log.debug("Chamber Product: " + next.chamberProduct);\r
268                         \r
269                         Amount<VolumetricDensity> combustionProductDensity = next.chamberProduct.divide(motor.getChamber().chamberVolume().minus(motor.getGrain().volume(next.regression))).to(VolumetricDensity.UNIT);\r
270                         \r
271                         log.debug("Product Density: " + combustionProductDensity);\r
272                         \r
273                         next.chamberPressure = combustionProductDensity.times(specificGasConstant).times(chamberTemp).plus(atmosphereicPressure).to(Pressure.UNIT);\r
274                         assert(positive(next.chamberPressure));\r
275                         \r
276                         next.chamberPressure = Amount.valueOf(\r
277                                         next.chamberPressure.doubleValue(SI.PASCAL),\r
278                                         SI.PASCAL);\r
279                         \r
280                         Amount<Pressure> dp = next.chamberPressure.minus(prev.chamberPressure);\r
281                         if ( dp.abs().isGreaterThan(settings.getChamberPressureMaxDelta())){\r
282                                 log.warn("DP " + dp + " too big!, Adjusting regstep down and repeating step!");\r
283                                 regStep = regStep.times(settings.getRegStepDecreaseFactor());\r
284                                 continue step;\r
285                         }\r
286                         \r
287                         next.thrust = motor.getNozzle().thrust(next.chamberPressure, atmosphereicPressure, atmosphereicPressure, motor.getFuel().getCombustionProduct().getRatioOfSpecificHeats2Phase());\r
288                         assert(positive(next.thrust));\r
289                         \r
290                         if ( i > 100 && next.chamberPressure.minus(atmosphereicPressure).abs().isLessThan(settings.getEndPressure())){\r
291                                 log.info("Pressure at ~Patm on step " + i);\r
292                                 endPressureSteps++;\r
293                                 if ( endPressureSteps > 5 )\r
294                                         break;\r
295                         }\r
296                         \r
297                         data.put(data.lastKey().plus(dt), next);\r
298                 }\r
299 \r
300                 long time = new Date().getTime() - start;\r
301                 log.info("Burn took " + time + " millis.");\r
302                 done = true;\r
303                 for (BurnProgressListener bpl : bpls ){\r
304                         bpl.burnComplete();\r
305                 }\r
306         }\r
307         \r
308         @SuppressWarnings("unchecked")\r
309         /*\r
310          * This converts the units of this constant to something JScience is able\r
311          * to work from. This conversion is unchecked at compile time, but\r
312          * JScience keeps me honest at runtime.\r
313          */\r
314         private Amount convertSpecificGasConstantUnits(Amount a){\r
315                 return a.to(\r
316                                 SI.METER.pow(2).divide(SI.SECOND.pow(2).times(SI.KELVIN)));\r
317         }\r
318         \r
319         public Amount<Pressure> pressure(Amount<Duration> time){\r
320                 return getData().get(time).chamberPressure;\r
321         }\r
322         \r
323         public Amount<Force> thrust(Amount<Duration> time){\r
324                 return getData().get(time).thrust;\r
325         }\r
326         \r
327         public Amount<Dimensionless> kn(Amount<Length> regression){\r
328                 return motor.getGrain().surfaceArea(regression).divide(motor.getNozzle().throatArea()).to(Dimensionless.UNIT);\r
329         }\r
330         \r
331         \r
332         private <Q extends Quantity> boolean positive(Amount<Q> a){\r
333                 return ( a.isGreaterThan(a.minus(a)) || a.equals(a.minus(a)));\r
334         }\r
335 \r
336 }\r