motor selection enhancements
[debian/openrocket] / src / net / sf / openrocket / motor / ThrustCurveMotor.java
1 package net.sf.openrocket.motor;
2
3 import java.text.Collator;
4 import java.util.Arrays;
5 import java.util.Locale;
6
7 import net.sf.openrocket.logging.LogHelper;
8 import net.sf.openrocket.models.atmosphere.AtmosphericConditions;
9 import net.sf.openrocket.startup.Application;
10 import net.sf.openrocket.util.BugException;
11 import net.sf.openrocket.util.Coordinate;
12 import net.sf.openrocket.util.Inertia;
13 import net.sf.openrocket.util.MathUtil;
14
15
16 public class ThrustCurveMotor implements Motor, Comparable<ThrustCurveMotor> {
17         private static final LogHelper log = Application.getLogger();
18         
19         public static final double MAX_THRUST = 10e6;
20         
21         //  Comparators:
22         private static final Collator COLLATOR = Collator.getInstance(Locale.US);
23         static {
24                 COLLATOR.setStrength(Collator.PRIMARY);
25         }
26         private static final DesignationComparator DESIGNATION_COMPARATOR = new DesignationComparator();
27         
28
29
30         private final Manufacturer manufacturer;
31         private final String designation;
32         private final String description;
33         private final Motor.Type type;
34         private final double[] delays;
35         private final double diameter;
36         private final double length;
37         private final double[] time;
38         private final double[] thrust;
39         private final Coordinate[] cg;
40         
41         private double maxThrust;
42         private double burnTime;
43         private double averageThrust;
44         private double totalImpulse;
45         
46         
47         /**
48          * Sole constructor.  Sets all the properties of the motor.
49          * 
50          * @param manufacturer  the manufacturer of the motor.
51          * @param designation   the designation of the motor.
52          * @param description   extra description of the motor.
53          * @param type                  the motor type
54          * @param delays                the delays defined for this thrust curve
55          * @param diameter      diameter of the motor.
56          * @param length        length of the motor.
57          * @param time          the time points for the thrust curve.
58          * @param thrust        thrust at the time points.
59          * @param cg            cg at the time points.
60          */
61         public ThrustCurveMotor(Manufacturer manufacturer, String designation, String description,
62                         Motor.Type type, double[] delays, double diameter, double length,
63                         double[] time, double[] thrust, Coordinate[] cg) {
64                 
65                 // Check argument validity
66                 if ((time.length != thrust.length) || (time.length != cg.length)) {
67                         throw new IllegalArgumentException("Array lengths do not match, " +
68                                         "time:" + time.length + " thrust:" + thrust.length +
69                                         " cg:" + cg.length);
70                 }
71                 if (time.length < 2) {
72                         throw new IllegalArgumentException("Too short thrust-curve, length=" +
73                                         time.length);
74                 }
75                 for (int i = 0; i < time.length - 1; i++) {
76                         if (time[i + 1] < time[i]) {
77                                 throw new IllegalArgumentException("Time goes backwards, " +
78                                                 "time[" + i + "]=" + time[i] + " " +
79                                                 "time[" + (i + 1) + "]=" + time[i + 1]);
80                         }
81                 }
82                 if (!MathUtil.equals(time[0], 0)) {
83                         throw new IllegalArgumentException("Curve starts at time " + time[0]);
84                 }
85                 if (!MathUtil.equals(thrust[0], 0)) {
86                         throw new IllegalArgumentException("Curve starts at thrust " + thrust[0]);
87                 }
88                 if (!MathUtil.equals(thrust[thrust.length - 1], 0)) {
89                         throw new IllegalArgumentException("Curve ends at thrust " +
90                                         thrust[thrust.length - 1]);
91                 }
92                 for (double t : thrust) {
93                         if (t < 0) {
94                                 throw new IllegalArgumentException("Negative thrust.");
95                         }
96                         if (t > MAX_THRUST || Double.isNaN(t)) {
97                                 throw new IllegalArgumentException("Invalid thrust " + t);
98                         }
99                 }
100                 for (Coordinate c : cg) {
101                         if (c.isNaN()) {
102                                 throw new IllegalArgumentException("Invalid CG " + c);
103                         }
104                         if (c.x < 0 || c.x > length) {
105                                 throw new IllegalArgumentException("Invalid CG position " + c.x);
106                         }
107                         if (c.weight < 0) {
108                                 throw new IllegalArgumentException("Negative mass " + c.weight);
109                         }
110                 }
111                 
112                 if (type != Motor.Type.SINGLE && type != Motor.Type.RELOAD &&
113                                 type != Motor.Type.HYBRID && type != Motor.Type.UNKNOWN) {
114                         throw new IllegalArgumentException("Illegal motor type=" + type);
115                 }
116                 
117
118                 this.manufacturer = manufacturer;
119                 this.designation = designation;
120                 this.description = description;
121                 this.type = type;
122                 this.delays = delays.clone();
123                 this.diameter = diameter;
124                 this.length = length;
125                 this.time = time.clone();
126                 this.thrust = thrust.clone();
127                 this.cg = cg.clone();
128                 
129                 computeStatistics();
130         }
131         
132         
133
134         /**
135          * Get the manufacturer of this motor.
136          * 
137          * @return the manufacturer
138          */
139         public Manufacturer getManufacturer() {
140                 return manufacturer;
141         }
142         
143         
144         /**
145          * Return the array of time points for this thrust curve.
146          * @return      an array of time points where the thrust is sampled
147          */
148         public double[] getTimePoints() {
149                 return time.clone();
150         }
151         
152         /**
153          * Returns the array of thrust points for this thrust curve.
154          * @return      an array of thrust samples
155          */
156         public double[] getThrustPoints() {
157                 return thrust.clone();
158         }
159         
160         /**
161          * Returns the array of CG points for this thrust curve.
162          * @return      an array of CG samples
163          */
164         public Coordinate[] getCGPoints() {
165                 return cg.clone();
166         }
167         
168         /**
169          * Return a list of standard delays defined for this motor.
170          * @return      a list of standard delays
171          */
172         public double[] getStandardDelays() {
173                 return delays.clone();
174         }
175         
176         
177         /**
178          * {@inheritDoc}
179          * <p>
180          * NOTE: In most cases you want to examine the motor type of the ThrustCurveMotorSet,
181          * not the ThrustCurveMotor itself.
182          */
183         @Override
184         public Type getMotorType() {
185                 return type;
186         }
187         
188         
189         @Override
190         public String getDesignation() {
191                 return designation;
192         }
193         
194         @Override
195         public String getDesignation(double delay) {
196                 return designation + "-" + getDelayString(delay);
197         }
198         
199         
200         @Override
201         public String getDescription() {
202                 return description;
203         }
204         
205         @Override
206         public double getDiameter() {
207                 return diameter;
208         }
209         
210         @Override
211         public double getLength() {
212                 return length;
213         }
214         
215         
216         @Override
217         public MotorInstance getInstance() {
218                 return new ThrustCurveMotorInstance();
219         }
220         
221         
222         @Override
223         public Coordinate getLaunchCG() {
224                 return cg[0];
225         }
226         
227         @Override
228         public Coordinate getEmptyCG() {
229                 return cg[cg.length - 1];
230         }
231         
232         
233
234
235         @Override
236         public double getBurnTimeEstimate() {
237                 return burnTime;
238         }
239         
240         @Override
241         public double getAverageThrustEstimate() {
242                 return averageThrust;
243         }
244         
245         @Override
246         public double getMaxThrustEstimate() {
247                 return maxThrust;
248         }
249         
250         @Override
251         public double getTotalImpulseEstimate() {
252                 return totalImpulse;
253         }
254         
255         
256
257         /**
258          * Compute the general statistics of this motor.
259          */
260         private void computeStatistics() {
261                 
262                 // Maximum thrust
263                 maxThrust = 0;
264                 for (double t : thrust) {
265                         if (t > maxThrust)
266                                 maxThrust = t;
267                 }
268                 
269
270                 // Burn start time
271                 double thrustLimit = maxThrust * MARGINAL_THRUST;
272                 double burnStart, burnEnd;
273                 
274                 int pos;
275                 for (pos = 1; pos < thrust.length; pos++) {
276                         if (thrust[pos] >= thrustLimit)
277                                 break;
278                 }
279                 if (pos >= thrust.length) {
280                         throw new BugException("Could not compute burn start time, maxThrust=" + maxThrust +
281                                         " limit=" + thrustLimit + " thrust=" + Arrays.toString(thrust));
282                 }
283                 if (MathUtil.equals(thrust[pos - 1], thrust[pos])) {
284                         // For safety
285                         burnStart = (time[pos - 1] + time[pos]) / 2;
286                 } else {
287                         burnStart = MathUtil.map(thrustLimit, thrust[pos - 1], thrust[pos], time[pos - 1], time[pos]);
288                 }
289                 
290
291                 // Burn end time
292                 for (pos = thrust.length - 2; pos >= 0; pos--) {
293                         if (thrust[pos] >= thrustLimit)
294                                 break;
295                 }
296                 if (pos < 0) {
297                         throw new BugException("Could not compute burn end time, maxThrust=" + maxThrust +
298                                         " limit=" + thrustLimit + " thrust=" + Arrays.toString(thrust));
299                 }
300                 if (MathUtil.equals(thrust[pos], thrust[pos + 1])) {
301                         // For safety
302                         burnEnd = (time[pos] + time[pos + 1]) / 2;
303                 } else {
304                         burnEnd = MathUtil.map(thrustLimit, thrust[pos], thrust[pos + 1],
305                                         time[pos], time[pos + 1]);
306                 }
307                 
308
309                 // Burn time
310                 burnTime = Math.max(burnEnd - burnStart, 0);
311                 
312
313                 // Total impulse and average thrust
314                 totalImpulse = 0;
315                 averageThrust = 0;
316                 
317                 for (pos = 0; pos < time.length - 1; pos++) {
318                         double t0 = time[pos];
319                         double t1 = time[pos + 1];
320                         double f0 = thrust[pos];
321                         double f1 = thrust[pos + 1];
322                         
323                         totalImpulse += (t1 - t0) * (f0 + f1) / 2;
324                         
325                         if (t0 < burnStart && t1 > burnStart) {
326                                 double fStart = MathUtil.map(burnStart, t0, t1, f0, f1);
327                                 averageThrust += (fStart + f1) / 2 * (t1 - burnStart);
328                         } else if (t0 >= burnStart && t1 <= burnEnd) {
329                                 averageThrust += (f0 + f1) / 2 * (t1 - t0);
330                         } else if (t0 < burnEnd && t1 > burnEnd) {
331                                 double fEnd = MathUtil.map(burnEnd, t0, t1, f0, f1);
332                                 averageThrust += (f0 + fEnd) / 2 * (burnEnd - t0);
333                         }
334                 }
335                 
336                 if (burnTime > 0) {
337                         averageThrust /= burnTime;
338                 } else {
339                         averageThrust = 0;
340                 }
341                 
342         }
343         
344         
345         //////////  Static methods
346         
347         /**
348          * Return a String representation of a delay time.  If the delay is {@link #PLUGGED},
349          * returns "P".
350          *  
351          * @param delay         the delay time.
352          * @return                      the <code>String</code> representation.
353          */
354         public static String getDelayString(double delay) {
355                 return getDelayString(delay, "P");
356         }
357         
358         /**
359          * Return a String representation of a delay time.  If the delay is {@link #PLUGGED},
360          * <code>plugged</code> is returned.
361          *   
362          * @param delay         the delay time.
363          * @param plugged       the return value if there is no ejection charge.
364          * @return                      the String representation.
365          */
366         public static String getDelayString(double delay, String plugged) {
367                 if (delay == PLUGGED)
368                         return plugged;
369                 delay = Math.rint(delay * 10) / 10;
370                 if (MathUtil.equals(delay, Math.rint(delay)))
371                         return "" + ((int) delay);
372                 return "" + delay;
373         }
374         
375         
376
377         ////////  Motor instance implementation  ////////
378         private class ThrustCurveMotorInstance implements MotorInstance {
379                 
380                 private int position;
381                 
382                 // Previous time step value
383                 private double prevTime;
384                 
385                 // Average thrust during previous step
386                 private double stepThrust;
387                 // Instantaneous thrust at current time point
388                 private double instThrust;
389                 
390                 // Average CG during previous step
391                 private Coordinate stepCG;
392                 // Instantaneous CG at current time point
393                 private Coordinate instCG;
394                 
395                 private final double unitRotationalInertia;
396                 private final double unitLongitudalInertia;
397                 
398                 private int modID = 0;
399                 
400                 public ThrustCurveMotorInstance() {
401                         log.debug("ThrustCurveMotor:  Creating motor instance of " + ThrustCurveMotor.this);
402                         position = 0;
403                         prevTime = 0;
404                         instThrust = 0;
405                         stepThrust = 0;
406                         instCG = cg[0];
407                         stepCG = cg[0];
408                         unitRotationalInertia = Inertia.filledCylinderRotational(getDiameter() / 2);
409                         unitLongitudalInertia = Inertia.filledCylinderLongitudal(getDiameter() / 2, getLength());
410                 }
411                 
412                 @Override
413                 public double getTime() {
414                         return prevTime;
415                 }
416                 
417                 @Override
418                 public Coordinate getCG() {
419                         return stepCG;
420                 }
421                 
422                 @Override
423                 public double getLongitudalInertia() {
424                         return unitLongitudalInertia * stepCG.weight;
425                 }
426                 
427                 @Override
428                 public double getRotationalInertia() {
429                         return unitRotationalInertia * stepCG.weight;
430                 }
431                 
432                 @Override
433                 public double getThrust() {
434                         return stepThrust;
435                 }
436                 
437                 @Override
438                 public boolean isActive() {
439                         return prevTime < time[time.length - 1];
440                 }
441                 
442                 @Override
443                 public void step(double nextTime, double acceleration, AtmosphericConditions cond) {
444                         
445                         if (!(nextTime >= prevTime)) {
446                                 // Also catches NaN
447                                 throw new IllegalArgumentException("Stepping backwards in time, current=" +
448                                                 prevTime + " new=" + nextTime);
449                         }
450                         if (MathUtil.equals(prevTime, nextTime)) {
451                                 return;
452                         }
453                         
454                         modID++;
455                         
456                         if (position >= time.length - 1) {
457                                 // Thrust has ended
458                                 prevTime = nextTime;
459                                 stepThrust = 0;
460                                 instThrust = 0;
461                                 stepCG = cg[cg.length - 1];
462                                 return;
463                         }
464                         
465
466                         // Compute average & instantaneous thrust
467                         if (nextTime < time[position + 1]) {
468                                 
469                                 // Time step between time points
470                                 double nextF = MathUtil.map(nextTime, time[position], time[position + 1],
471                                                 thrust[position], thrust[position + 1]);
472                                 stepThrust = (instThrust + nextF) / 2;
473                                 instThrust = nextF;
474                                 
475                         } else {
476                                 
477                                 // Portion of previous step
478                                 stepThrust = (instThrust + thrust[position + 1]) / 2 * (time[position + 1] - prevTime);
479                                 
480                                 // Whole steps
481                                 position++;
482                                 while ((position < time.length - 1) && (nextTime >= time[position + 1])) {
483                                         stepThrust += (thrust[position] + thrust[position + 1]) / 2 *
484                                                                         (time[position + 1] - time[position]);
485                                         position++;
486                                 }
487                                 
488                                 // End step
489                                 if (position < time.length - 1) {
490                                         instThrust = MathUtil.map(nextTime, time[position], time[position + 1],
491                                                         thrust[position], thrust[position + 1]);
492                                         stepThrust += (thrust[position] + instThrust) / 2 *
493                                                                         (nextTime - time[position]);
494                                 } else {
495                                         // Thrust ended during this step
496                                         instThrust = 0;
497                                 }
498                                 
499                                 stepThrust /= (nextTime - prevTime);
500                                 
501                         }
502                         
503                         // Compute average and instantaneous CG (simple average between points)
504                         Coordinate nextCG;
505                         if (position < time.length - 1) {
506                                 nextCG = MathUtil.map(nextTime, time[position], time[position + 1],
507                                                 cg[position], cg[position + 1]);
508                         } else {
509                                 nextCG = cg[cg.length - 1];
510                         }
511                         stepCG = instCG.add(nextCG).multiply(0.5);
512                         instCG = nextCG;
513                         
514                         // Update time
515                         prevTime = nextTime;
516                 }
517                 
518                 @Override
519                 public MotorInstance clone() {
520                         try {
521                                 return (MotorInstance) super.clone();
522                         } catch (CloneNotSupportedException e) {
523                                 throw new BugException("CloneNotSupportedException", e);
524                         }
525                 }
526                 
527                 @Override
528                 public int getModID() {
529                         return modID;
530                 }
531         }
532         
533         
534
535         @Override
536         public int compareTo(ThrustCurveMotor other) {
537                 
538                 int value;
539                 
540                 // 1. Manufacturer
541                 value = COLLATOR.compare(this.manufacturer.getDisplayName(),
542                                 ((ThrustCurveMotor) other).manufacturer.getDisplayName());
543                 if (value != 0)
544                         return value;
545                 
546                 // 2. Designation
547                 value = DESIGNATION_COMPARATOR.compare(this.getDesignation(), other.getDesignation());
548                 if (value != 0)
549                         return value;
550                 
551                 // 3. Diameter
552                 value = (int) ((this.getDiameter() - other.getDiameter()) * 1000000);
553                 if (value != 0)
554                         return value;
555                 
556                 // 4. Length
557                 value = (int) ((this.getLength() - other.getLength()) * 1000000);
558                 return value;
559                 
560         }
561         
562
563 }