Debian Codegraph @

src/dr/inference/model/Parameter.java

raw symbols SCIP
1 /*
2 * Parameter.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.inference.model;
27
28 import dr.inference.parallel.MPIServices;
29 import dr.xml.Reportable;
30 import org.w3c.dom.Document;
31 import org.w3c.dom.Element;
32
33 import java.util.*;
34
35 /**
36 * Represents a multi-dimensional continuous parameter.
37 *
38 * @author Alexei Drummond
39 * @version $Id: Parameter.java,v 1.22 2005/06/08 11:23:25 alexei Exp $
40 */
41 public interface Parameter extends Statistic, Variable<Double> {
42
43 /**
44 * @param dim the index of the parameter dimension of interest
45 * @return the parameter's scalar value in the given dimension
46 */
47 double getParameterValue(int dim);
48
49 /**
50 * @return the parameter's values (may be modified, as this is a copy)
51 */
52 double[] getParameterValues();
53
54 /**
55 * sets the scalar value in the given dimension of this parameter
56 *
57 * @param dim the index of the dimension to set
58 * @param value the value to set
59 */
60 void setParameterValue(int dim, double value);
61
62 /**
63 * sets the scalar value in the given dimension of this parameter to val, without firing any events
64 *
65 * @param dim the index of the dimension to set
66 * @param value the value to set
67 */
68 void setParameterValueQuietly(int dim, double value);
69
70
71 /**
72 * sets the scalar value in the given dimension of this parameter to val,
73 * and notifies that values in all dimension have been changed
74 *
75 * @param dim the index of the dimension to set
76 * @param value the value to set
77 */
78 void setParameterValueNotifyChangedAll(int dim, double value);
79
80 /**
81 * @return the name of this parameter
82 */
83 String getParameterName();
84
85 /**
86 * adds a parameter listener that is notified when this parameter changes.
87 *
88 * @param listener the listener
89 */
90 void addParameterListener(VariableListener listener);
91
92 /**
93 * removes a parameter listener.
94 *
95 * @param listener the listener
96 */
97 void removeParameterListener(VariableListener listener);
98
99 /**
100 * stores the state of this parameter for subsequent restore
101 */
102 void storeParameterValues();
103
104 /**
105 * restores the stored state of this parameter
106 */
107 void restoreParameterValues();
108
109 /**
110 * accepts the stored state of this parameter
111 */
112 void acceptParameterValues();
113
114 /**
115 * adopt the state of the source parameter
116 *
117 * @param source the parameter to adopt values from
118 */
119 void adoptParameterValues(Parameter source);
120
121 /**
122 * @return true if values in all dimensions are within their bounds
123 */
124 boolean isWithinBounds();
125
126 /**
127 * Can be called before store is called. If it results in new
128 * dimensions, then the value of the first dimension is copied into the new dimensions.
129 *
130 * @param dim new dimension
131 */
132 void setDimension(int dim);
133
134 /**
135 * Adds new bounds to this parameter
136 *
137 * @param bounds to add
138 */
139 void addBounds(Bounds<Double> bounds);
140
141 /**
142 * @return the intersection of all bounds added to this parameter
143 */
144 Bounds<Double> getBounds();
145
146 /**
147 * Adds an extra dimension at the given index
148 *
149 * @param index Index of the dimension to add
150 * @param value value to save at end of new array
151 */
152 void addDimension(int index, double value);
153
154 /**
155 * Removes the specified dimension from parameter
156 *
157 * @param index Index of dimension to lose
158 * @return the value of the dimension removed
159 */
160 double removeDimension(int index);
161
162 void fireParameterChangedEvent();
163
164 void fireParameterChangedEvent(int index, Parameter.ChangeType type);
165
166 boolean isUsed();
167
168 Set<Parameter> FULL_PARAMETER_SET = new LinkedHashSet<Parameter>();
169 Set<Parameter> CONNECTED_PARAMETER_SET = new LinkedHashSet<Parameter>();
170
171 /**
172 * Abstract base class for parameters
173 */
174 abstract class Abstract extends Statistic.Abstract implements Parameter, Reportable {
175
176 protected Abstract() {
177 FULL_PARAMETER_SET.add(this);
178 }
179
180 protected Abstract(final String name) {
181 super(name);
182 FULL_PARAMETER_SET.add(this);
183 }
184
185 // **************************************************************
186 // MPI IMPLEMENTATION
187 // **************************************************************
188
189
190 void sendState(int toRank) {
191 double[] value = getParameterValues();
192 MPIServices.sendDoubleArray(value, toRank);
193 }
194
195 void receiveState(int fromRank) {
196 final int length = getDimension();
197 double[] values = MPIServices.receiveDoubleArray(fromRank, length);
198 for (int i = 0; i < length; i++)
199 setParameterValueQuietly(i, values[i]);
200 this.fireParameterChangedEvent();
201 }
202
203 public int getDimension() {
204 return 1;
205 }
206
207 /**
208 * Fired when all dimensions of the parameter have changed
209 */
210 public void fireParameterChangedEvent() {
211 fireParameterChangedEvent(-1, Parameter.ChangeType.VALUE_CHANGED);
212 }
213
214 /**
215 * Fired when a single dimension of the parameter has changed
216 *
217 * @param index which dimension changed
218 * @param type the type of parameter change event
219 */
220 public void fireParameterChangedEvent(int index, Parameter.ChangeType type) {
221 if (listeners != null) {
222 for (VariableListener listener : listeners) {
223 listener.variableChangedEvent(this, index, type);
224 }
225 }
226 }
227
228 public final void addParameterListener(VariableListener listener) {
229 if (listeners == null) {
230 listeners = new ArrayList<VariableListener>();
231 }
232 listeners.add(listener);
233 }
234
235 public final void removeParameterListener(VariableListener listener) {
236 if (listeners != null) {
237 listeners.remove(listener);
238 }
239 }
240
241 public final String getStatisticName() {
242 return getParameterName();
243 }
244
245 public final double getStatisticValue(int dim) {
246 return getParameterValue(dim);
247 }
248
249 @Override
250 public String getDimensionName(int dim) {
251 if (dimensionNames == null) {
252 return super.getDimensionName(dim);
253 }
254 return dimensionNames[dim];
255 }
256
257 public final void setDimensionNames(String[] names) {
258 if (names != null && names.length != getDimension()) {
259 throw new IllegalArgumentException("Length of dimension name array doesn't match the number of dimensions");
260 }
261 dimensionNames = names;
262 }
263
264 public void setDimension(int dim) {
265 throw new UnsupportedOperationException();
266 }
267
268 /**
269 * Defensively returns copy of parameter array.
270 *
271 * @return a copy of the parameter values
272 */
273 public double[] getParameterValues() {
274
275 double[] copyOfValues = new double[getDimension()];
276 for (int i = 0; i < copyOfValues.length; i++) {
277 copyOfValues[i] = getParameterValue(i);
278 }
279 return copyOfValues;
280 }
281
282
283 public final void storeParameterValues() {
284 if (isValid) {
285 storeValues();
286
287 isValid = false;
288 }
289 }
290
291 public final void restoreParameterValues() {
292 if (!isValid) {
293 restoreValues();
294
295 isValid = true;
296 }
297 }
298
299 public final void acceptParameterValues() {
300 if (!isValid) {
301 acceptValues();
302
303 isValid = true;
304 }
305 }
306
307 public final void adoptParameterValues(Parameter source) {
308
309 adoptValues(source);
310
311 isValid = true;
312 }
313
314 public boolean isWithinBounds() {
315 Bounds<Double> bounds = getBounds();
316 for (int i = 0; i < getDimension(); i++) {
317 final double value = getParameterValue(i);
318 if (value < bounds.getLowerLimit(i) || value > bounds.getUpperLimit(i)) {
319 return false;
320 }
321 }
322 return true;
323 }
324
325 // --------------------------------------------------------------------
326 // IMPLEMENT VARIABLE
327 // --------------------------------------------------------------------
328
329 /**
330 * @return the name of this variable.
331 */
332 public final String getVariableName() {
333 return getParameterName();
334 }
335
336 public final Double getValue(int index) {
337 return getParameterValue(index);
338 }
339
340 public final void setValue(int index, Double value) {
341 setParameterValue(index, value);
342 }
343
344 public Double[] getValues() {
345 Double[] copyOfValues = new Double[getDimension()];
346 for (int i = 0; i < getDimension(); i++) {
347 copyOfValues[i] = getValue(i);
348 }
349 return copyOfValues;
350 }
351
352 /**
353 * @return the size of this variable - i.e. the length of the vector
354 */
355 public int getSize() {
356 return getDimension();
357 }
358
359 /**
360 * adds a parameter listener that is notified when this parameter changes.
361 *
362 * @param listener the listener
363 */
364 public final void addVariableListener(VariableListener listener) {
365 addParameterListener(listener);
366 }
367
368 /**
369 * removes a parameter listener.
370 *
371 * @param listener the listener
372 */
373 public final void removeVariableListener(VariableListener listener) {
374 removeParameterListener(listener);
375 }
376
377 /**
378 * stores the state of this parameter for subsequent restore
379 */
380 public void storeVariableValues() {
381 storeParameterValues();
382 }
383
384 /**
385 * restores the stored state of this parameter
386 */
387 public void restoreVariableValues() {
388 restoreParameterValues();
389 }
390
391 /**
392 * accepts the stored state of this parameter
393 */
394 public void acceptVariableValues() {
395 acceptParameterValues();
396 }
397
398 public boolean isUsed() {
399 return listeners != null && listeners.size() > 0;
400 }
401
402 // --------------------------------------------------------------------
403
404 protected abstract void storeValues();
405
406 protected abstract void restoreValues();
407
408 protected abstract void acceptValues();
409
410 protected abstract void adoptValues(Parameter source);
411
412 public String toString() {
413 StringBuilder buffer = new StringBuilder(String.valueOf(getParameterValue(0)));
414 Bounds bounds = null;
415 try {
416 bounds = getBounds();
417 } catch (NullPointerException e) {
418 //
419 }
420 final String id = getId();
421 if (id != null) buffer.append(", ").append(id);
422 if (bounds != null) {
423 buffer.append("=[").append(String.valueOf(bounds.getLowerLimit(0)));
424 buffer.append(", ").append(String.valueOf(bounds.getUpperLimit(0))).append("]");
425 }
426
427 for (int i = 1; i < getDimension(); i++) {
428 buffer.append(", ").append(String.valueOf(getParameterValue(i)));
429 if (bounds != null) {
430 buffer.append("[").append(String.valueOf(bounds.getLowerLimit(i)));
431 buffer.append(", ").append(String.valueOf(bounds.getUpperLimit(i))).append("]");
432 }
433 }
434 return buffer.toString();
435 }
436
437 public String getReport() {
438 StringBuilder sb = new StringBuilder();
439 Bounds bounds = null;
440 try {
441 bounds = getBounds();
442 } catch (NullPointerException e) {
443 // Do nothing
444 }
445
446 for (int i = 0; i < getDimension(); ++i) {
447 if (getDimensionName(i) != null) {
448 sb.append(getDimensionName(i)).append("=");
449 }
450 sb.append(String.valueOf(getParameterValue(i)));
451
452 if (bounds != null) {
453 sb.append("[");
454 try {
455 sb.append(String.valueOf(bounds.getLowerLimit(i)));
456 sb.append(", ").append(String.valueOf(bounds.getUpperLimit(i)));
457 } catch (NullPointerException npe) {
458 sb.append("no bounds");
459 }
460 sb.append("]");
461 }
462
463 if (i < getDimension() - 1) {
464 sb.append(", ");
465 }
466 }
467
468 return sb.toString();
469 }
470
471 public Element createElement(Document document) {
472 throw new IllegalArgumentException();
473 }
474
475 private boolean isValid = true;
476
477 private ArrayList<VariableListener> listeners;
478
479 private String[] dimensionNames = null;
480 }
481
482
483 /**
484 * A class that implements the Parameter interface.
485 */
486 class Default extends Abstract {
487
488 public Default(String id, int dimension) {
489 this(dimension);
490 setId(id);
491 }
492
493 public Default(String id) {
494 this(1); // dimension
495 setId(id);
496 }
497
498 public Default(int dimension) {
499 this(dimension, 1.0);
500 }
501
502 public Default(String id, double initialValue) {
503 this(initialValue);
504 setId(id);
505 }
506
507 public Default(double initialValue) {
508 values = new double[1];
509 values[0] = initialValue;
510 this.bounds = null;
511 }
512
513 /**
514 * @param id a unique id for this parameter
515 * @param initialValue the initial value for this parameter
516 * @param lower the lower bound on this parameter
517 * @param upper the upper bound on this parameter
518 */
519 public Default(String id, double initialValue, double lower, double upper) {
520 this(initialValue);
521 setId(id);
522 addBounds(new DefaultBounds(upper, lower, 1));
523 }
524
525 public Default(int dimension, double initialValue) {
526 values = new double[dimension];
527 for (int i = 0; i < dimension; i++) {
528 values[i] = initialValue;
529 }
530 this.bounds = null;
531 }
532
533 public Default(String id, double[] values) {
534 this(values);
535 setId(id);
536 }
537
538 public Default(double[] values) {
539 this.values = new double[values.length];
540 System.arraycopy(values, 0, this.values, 0, values.length);
541 }
542
543 public Default(String id, int dimension, double initialValue) {
544 this(dimension, initialValue);
545 setId(id);
546 }
547
548 public void addBounds(Bounds<Double> boundary) {
549 if (bounds == null) {
550 bounds = boundary;
551 } else {
552 if (!(bounds instanceof IntersectionBounds)) {
553 IntersectionBounds newBounds = new IntersectionBounds(getDimension());
554 newBounds.addBounds(bounds);
555 bounds = newBounds;
556 }
557
558 ((IntersectionBounds) bounds).addBounds(boundary);
559 }
560
561 // can't change dimension after bounds are added!
562 //hasBeenStored = true;
563 }
564
565 //********************************************************************
566 // GETTERS
567 //********************************************************************
568
569 public final int getDimension() {
570 return values.length;
571 }
572
573 public final int getSize() {
574 return getDimension();
575 }
576
577 public final double getParameterValue(int i) {
578 return values[i];
579 }
580
581 /**
582 * Defensively returns copy of parameter array.
583 *
584 * @return a copy of the parameter values
585 */
586 public final double[] getParameterValues() {
587
588 double[] copyOfValues = new double[values.length];
589 System.arraycopy(values, 0, copyOfValues, 0, copyOfValues.length);
590 return copyOfValues;
591 }
592
593 /**
594 * Do not write to the returned array directly!!
595 *
596 * @return the parameter values
597 */
598 public final double[] inspectParameterValues() {
599 return values;
600 }
601
602 public Bounds<Double> getBounds() {
603 if (bounds == null) {
604 throw new NullPointerException(getParameterName() + " parameter: Bounds not set");
605 }
606 return bounds;
607 }
608
609 public String getParameterName() {
610 return getId();
611 }
612
613 //********************************************************************
614 // SETTERS
615 //********************************************************************
616
617 /**
618 * Can only be called before store is called. If it results in new
619 * dimensions, then the value of the first dimension is copied into the new dimensions.
620 */
621 public void setDimension(int dim) {
622 final int oldDim = getDimension();
623 if (oldDim == dim) {
624 return;
625 }
626
627 assert storedValues == null :
628 "Can't change dimension after store has been called! storedValues=" +
629 Arrays.toString(storedValues) + " bounds=" + bounds;
630
631
632 double[] newValues = new double[dim];
633 // copy over new values, min in case new dim is smaller
634 System.arraycopy(values, 0, newValues, 0, Math.min(oldDim, dim));
635 // fill new values with first item
636 for (int i = oldDim; i < dim; i++) {
637 newValues[i] = values[0];
638 }
639 values = newValues;
640
641 if (bounds != null) {
642 //assert oldDim < dim : "Can't decrease dimension when bounds are set";
643 for (int k = 1; k < oldDim; ++k) {
644 assert ((double) bounds.getLowerLimit(k) == bounds.getLowerLimit(0)) &&
645 ((double) bounds.getUpperLimit(k) == bounds.getUpperLimit(0)) :
646 "Can't change dimension when bounds are not all equal";
647 }
648 final double low = bounds.getLowerLimit(0);
649 final double high = bounds.getUpperLimit(0);
650 bounds = null;
651 addBounds(low, high);
652 }
653 }
654
655 /**
656 * Adds an extra dimension to the end of values
657 *
658 * @param value value to save at end of new array
659 */
660 public void addDimension(int index, double value) {
661 assert bounds == null;
662
663 final int n = values.length;
664 double[] newValues = new double[n + 1];
665 System.arraycopy(values, 0, newValues, 0, index);
666 newValues[index] = value;
667 System.arraycopy(values, index, newValues, index + 1, n - index);
668 values = newValues;
669 fireParameterChangedEvent(index, Parameter.ChangeType.ADDED);
670 }
671
672
673 /**
674 * Removes a single dimension from value array
675 *
676 * @param index Index of dimension to lose
677 */
678 public double removeDimension(int index) {
679 assert bounds == null;
680
681 final int n = values.length;
682 final double value = values[index];
683
684 final double[] newValues = new double[n - 1];
685 System.arraycopy(values, 0, newValues, 0, index);
686 System.arraycopy(values, index, newValues, index - 1, n - index);
687 values = newValues;
688 fireParameterChangedEvent(index, Parameter.ChangeType.REMOVED);
689 return value;
690 }
691
692
693 public void setParameterValue(int i, double val) {
694 values[i] = val;
695 fireParameterChangedEvent(i, Parameter.ChangeType.VALUE_CHANGED);
696 }
697
698 /**
699 * Sets the value of the parameter without firing a changed event.
700 *
701 * @param dim the index of the parameter dimension
702 * @param value the value to set
703 */
704 public void setParameterValueQuietly(int dim, double value) {
705 values[dim] = value;
706 }
707
708
709 /**
710 * Sets the values of the parameter and notify that all values of the parameter have changed.
711 *
712 * @param i index of the value
713 * @param val to value to set
714 */
715 public void setParameterValueNotifyChangedAll(int i, double val) {
716 values[i] = val;
717 fireParameterChangedEvent(-1, Parameter.ChangeType.ALL_VALUES_CHANGED);
718 }
719
720 protected final void storeValues() {
721 // no need to pay a price in a very common call for one-time rare usage
722 //hasBeenStored = true;
723 if (storedValues == null || storedValues.length != values.length) {
724 storedValues = new double[values.length];
725 }
726 System.arraycopy(values, 0, storedValues, 0, storedValues.length);
727 }
728
729 protected final void restoreValues() {
730
731 //swap the arrays
732 double[] temp = storedValues;
733 storedValues = values;
734 values = temp;
735
736 //if (storedValues != null) {
737 // System.arraycopy(storedValues, 0, values, 0, values.length);
738 //} else throw new RuntimeException("restore called before store!");
739 }
740
741 /**
742 * Nothing to do
743 */
744 protected final void acceptValues() {
745 }
746
747 protected final void adoptValues(Parameter source) {
748 // todo bug ? bounds not adopted?
749
750 if (getDimension() != source.getDimension()) {
751 throw new RuntimeException("The two parameters don't have the same number of dimensions");
752 }
753
754 for (int i = 0, n = getDimension(); i < n; i++) {
755 values[i] = source.getParameterValue(i);
756 }
757 }
758
759 private double[] values;
760
761 private double[] storedValues;
762
763 // same as !storedValues && !bounds
764 //private boolean hasBeenStored = false;
765 private Bounds<Double> bounds = null;
766
767 public void addBounds(double lower, double upper) {
768 addBounds(new DefaultBounds(upper, lower, getDimension()));
769 }
770 }
771
772 class DefaultBounds implements Bounds<Double> {
773
774 public DefaultBounds(double upper, double lower, int dimension) {
775
776 this.uppers = new double[dimension];
777 this.lowers = new double[dimension];
778 for (int i = 0; i < dimension; i++) {
779 uppers[i] = upper;
780 lowers[i] = lower;
781 }
782 }
783 //
784 // public DefaultBounds(ArrayList<java.lang.Double> upperList, ArrayList<java.lang.Double> lowerList) {
785 //
786 // final int length = upperList.size();
787 // if (length != lowerList.size()) {
788 // throw new IllegalArgumentException("upper and lower limits must be defined on the same number of dimensions.");
789 // }
790 // uppers = new double[length];
791 // lowers = new double[length];
792 // for (int i = 0; i < uppers.length; i++) {
793 // uppers[i] = upperList.get(i);
794 // lowers[i] = lowerList.get(i);
795 // }
796 // }
797
798 public DefaultBounds(double[] uppers, double[] lowers) {
799
800 if (uppers.length != lowers.length) {
801 throw new IllegalArgumentException("upper and lower limits must be defined on the same number of dimensions.");
802 }
803 this.uppers = uppers;
804 this.lowers = lowers;
805 }
806
807 public Double getUpperLimit(int i) {
808 return uppers[i];
809 }
810
811 public Double getLowerLimit(int i) {
812 return lowers[i];
813 }
814
815 public int getBoundsDimension() {
816 return uppers.length;
817 }
818
819 public boolean isConstant() {
820 return true;
821 }
822
823 private final double[] uppers, lowers;
824 }
825
826 }