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