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