icamodel-commits Mailing List for ICA model
Brought to you by:
lmpryor
You can subscribe to this list here.
| 2007 |
Jan
(4) |
Feb
|
Mar
(7) |
Apr
|
May
(4) |
Jun
(19) |
Jul
(6) |
Aug
(11) |
Sep
|
Oct
|
Nov
|
Dec
|
|---|
Update of /cvsroot/icamodel/icamodel/src/icamodel/framework In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv22053/src/icamodel/framework Modified Files: BusinessLine.java ModelBit.java RandomNumberGenerator.java AssetPool.java LossType.java Parameters.java Log Message: Make it possible to load a params file after another one has already been loaded Index: Parameters.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/Parameters.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Parameters.java 19 Aug 2007 17:59:55 -0000 1.4 --- Parameters.java 26 Aug 2007 11:56:23 -0000 1.5 *************** *** 128,131 **** --- 128,133 ---- kids = modelElement.getChildNodes(); ModelRoot root = ModelRoot.getInstance(); + root.clearNames(); + root.clear(); // It should have some parameters setParameters( root, kids); Index: BusinessLine.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/BusinessLine.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** BusinessLine.java 19 Aug 2007 14:39:11 -0000 1.4 --- BusinessLine.java 26 Aug 2007 11:56:23 -0000 1.5 *************** *** 408,411 **** } ! } --- 408,413 ---- } ! public void clearSpecial() { ! // do nothing ! } } Index: ModelBit.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/ModelBit.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ModelBit.java 19 Aug 2007 17:59:55 -0000 1.6 --- ModelBit.java 26 Aug 2007 11:56:23 -0000 1.7 *************** *** 161,165 **** --- 161,169 ---- allNames.put(model.getName(), model); } + + public static void clearNames() { + allNames.clear(); + } /** * Get the name of this bit. *************** *** 280,283 **** --- 284,319 ---- /******************************************************************** + * Things to do with clearing the model to reload another set of params + * clear the children and clear the params and clear the results + ********************************************************************/ + /** + * Reset this bit for the start of a realisation. + * @param rnum the realisation number + */ + public void clear() { + this.resetResults(0); + this.myParams.clear(); + this.otherChildren.clear(); + this.clearChildren(); + if (! this.isRoot()) { + myChildren.clear(); + } + this.clearSpecial(); + } + + public abstract void clearSpecial(); + /** + * clear this bit's children + **/ + private void clearChildren() { + if (myChildren != null) { + Iterator<ModelBit> it = myChildren.iterator(); + while (it.hasNext()) { + it.next().clear(); + } + } + } + + /******************************************************************** * Things to do with resetting for a realisation ********************************************************************/ Index: LossType.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/LossType.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** LossType.java 19 Aug 2007 14:39:11 -0000 1.3 --- LossType.java 26 Aug 2007 11:56:23 -0000 1.4 *************** *** 181,183 **** --- 181,186 ---- } + public void clearSpecial() { + // do nothing + } } Index: AssetPool.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/AssetPool.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** AssetPool.java 19 Aug 2007 14:39:11 -0000 1.2 --- AssetPool.java 26 Aug 2007 11:56:23 -0000 1.3 *************** *** 127,130 **** return lastValue; } ! } --- 127,133 ---- return lastValue; } ! ! public void clearSpecial() { ! // do nothing ! } } Index: RandomNumberGenerator.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/RandomNumberGenerator.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RandomNumberGenerator.java 19 Aug 2007 14:39:11 -0000 1.5 --- RandomNumberGenerator.java 26 Aug 2007 11:56:23 -0000 1.6 *************** *** 60,62 **** --- 60,66 ---- // do nothing } + + public void clearSpecial() { + // do nothing + } } |
|
From: Louise P. <lm...@us...> - 2007-08-26 11:56:24
|
Update of /cvsroot/icamodel/icamodel In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv22053 Modified Files: .cvsignore Log Message: Make it possible to load a params file after another one has already been loaded Index: .cvsignore =================================================================== RCS file: /cvsroot/icamodel/icamodel/.cvsignore,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** .cvsignore 26 Jan 2007 14:40:27 -0000 1.1.1.1 --- .cvsignore 26 Aug 2007 11:56:23 -0000 1.2 *************** *** 1,5 **** signatures build - dist - logs results --- 1,5 ---- signatures build results + logs + dist |
|
From: Louise P. <lm...@us...> - 2007-08-26 11:56:24
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/bits In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv22053/src/icamodel/bits Modified Files: Liabilities.java RandomInterestRate.java FixedInterestRate.java ModelRoot.java External.java Corporate.java Assets.java StochTotalReturn.java BusinessLogic.java Log Message: Make it possible to load a params file after another one has already been loaded Index: FixedInterestRate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/FixedInterestRate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FixedInterestRate.java 19 Aug 2007 14:39:11 -0000 1.2 --- FixedInterestRate.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 113,115 **** --- 113,118 ---- } + public void clearSpecial() { + } + } Index: BusinessLogic.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/BusinessLogic.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** BusinessLogic.java 19 Aug 2007 14:39:11 -0000 1.2 --- BusinessLogic.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 75,78 **** --- 75,82 ---- return null; } + + public void clearSpecial() { + // do nothing + } Index: ModelRoot.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/ModelRoot.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ModelRoot.java 19 Aug 2007 14:39:11 -0000 1.2 --- ModelRoot.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 237,240 **** --- 237,245 ---- return prob; } + + public void clearSpecial() { + + + } Index: Assets.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Assets.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Assets.java 19 Aug 2007 14:39:07 -0000 1.3 --- Assets.java 26 Aug 2007 11:56:22 -0000 1.4 *************** *** 130,133 **** --- 130,137 ---- return null; } + + public void clearSpecial() { + // do nothing + } Index: StochTotalReturn.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/StochTotalReturn.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** StochTotalReturn.java 19 Aug 2007 14:39:11 -0000 1.2 --- StochTotalReturn.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 164,167 **** --- 164,171 ---- return null; // no checking } + + public void clearSpecial() { + // do nothing + } private RFunction rGetReturn; Index: RandomInterestRate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/RandomInterestRate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RandomInterestRate.java 19 Aug 2007 14:39:11 -0000 1.2 --- RandomInterestRate.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 108,110 **** --- 108,114 ---- } + public void clearSpecial() { + // do nothing + } + } Index: Liabilities.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Liabilities.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Liabilities.java 19 Aug 2007 14:39:11 -0000 1.3 --- Liabilities.java 26 Aug 2007 11:56:21 -0000 1.4 *************** *** 100,103 **** --- 100,106 ---- return null; } + + public void clearSpecial() { + } Index: Corporate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Corporate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Corporate.java 19 Aug 2007 14:39:11 -0000 1.2 --- Corporate.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 74,76 **** --- 74,79 ---- return null; } + + public void clearSpecial() { + } } Index: External.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/External.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** External.java 19 Aug 2007 14:39:11 -0000 1.2 --- External.java 26 Aug 2007 11:56:22 -0000 1.3 *************** *** 169,172 **** --- 169,177 ---- return null; } + + public void clearSpecial() { + interestRate = null; + gen = null; + } } |
|
From: Louise P. <lm...@us...> - 2007-08-26 11:56:23
|
Update of /cvsroot/icamodel/icamodel/data In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv22053/data Modified Files: example-params.xml Log Message: Make it possible to load a params file after another one has already been loaded Index: example-params.xml =================================================================== RCS file: /cvsroot/icamodel/icamodel/data/example-params.xml,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** example-params.xml 24 Jun 2007 16:09:35 -0000 1.1 --- example-params.xml 26 Aug 2007 11:56:23 -0000 1.2 *************** *** 77,82 **** 1.0 </param> ! <param id="ClaimsPaymentPattern" type="listNumber"> ! 1.0, 2.0 </param> </modelBit> <!-- end of LType1 --> --- 77,83 ---- 1.0 </param> ! <param id="ClaimsPaymentPattern" type="paymentPattern"> ! <incidence>Front</incidence> ! <values>1.0,2.0</values> </param> </modelBit> <!-- end of LType1 --> *************** *** 106,111 **** 1.5, 2.1 </param> ! <param id="ClaimsPaymentPattern" type="listNumber"> ! 1.0, 1.0, 1.0, 1.0 </param> </modelBit> <!-- end of LType1 --> --- 107,113 ---- 1.5, 2.1 </param> ! <param id="ClaimsPaymentPattern" type="paymentPattern"> ! <incidence>Even</incidence> ! <values>1.0, 1.0, 1.0, 1.0</values> </param> </modelBit> <!-- end of LType1 --> |
|
From: Louise P. <lm...@us...> - 2007-08-19 18:01:06
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/utils In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv26024 Added Files: ICAModelToTreeAdaptor.java Log Message: Show tree when model is loaded --- NEW FILE: ICAModelToTreeAdaptor.java --- /* * ICAModelToTreeAdaptor.java * * Created on 19 August 2007, 18:19 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package icamodel.utils; import icamodel.bits.ModelRoot; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreePath; /** * * @author Louise */ public class ICAModelToTreeAdaptor implements javax.swing.tree.TreeModel { public Object getRoot() { return ModelRoot.getInstance(); } public Object getChild(Object parent, int index) { ModelNode node = (ModelNode) parent; return node.child(index); } public int getChildCount(Object parent) { ModelNode node = (ModelNode) parent; return node.childCount(); } public boolean isLeaf(Object node) { // Determines whether the icon shows up to the left. // Return true for any node with no children ModelNode mNode = (ModelNode) node; if (mNode.childCount() > 0) return false; return true; } public void valueForPathChanged(TreePath path, Object newValue) { // Null. We won't be making changes in the GUI // If we did, we would ensure the new value was really new, // adjust the model, and then fire a TreeNodesChanged event. } public int getIndexOfChild(Object parent, Object child) { ModelNode node = (ModelNode) parent; return node.index((ModelNode) child); } /** * Use these methods to add and remove event listeners. * (Needed to satisfy TreeModel interface, but not used.) */ public void addTreeModelListener(TreeModelListener listener) { } public void removeTreeModelListener(TreeModelListener listener) { } } |
|
From: Louise P. <lm...@us...> - 2007-08-19 17:59:57
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/framework In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv25322/src/icamodel/framework Modified Files: ModelBit.java Parameters.java Log Message: Show tree when model is loaded Index: ModelBit.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/ModelBit.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ModelBit.java 19 Aug 2007 14:39:11 -0000 1.5 --- ModelBit.java 19 Aug 2007 17:59:55 -0000 1.6 *************** *** 51,56 **** private HashMap<String, ModelParameter> myParams = new HashMap<String, ModelParameter>(); private HashMap<String, String> myValidParams= new HashMap<String, String>(); ! private List<ModelNode> otherChildren; ! private List<ModelBit> myChildren; private List<String> initProblems; private int lastUpdated; --- 51,56 ---- private HashMap<String, ModelParameter> myParams = new HashMap<String, ModelParameter>(); private HashMap<String, String> myValidParams= new HashMap<String, String>(); ! private List<ModelNode> otherChildren = new ArrayList<ModelNode>(); ! private List<ModelBit> myChildren = new ArrayList<ModelBit>(); private List<String> initProblems; private int lastUpdated; *************** *** 563,566 **** --- 563,567 ---- if (null == prob) { myParams.put(param.getName(), param); + otherChildren.add(param); // for the tree } return prob; *************** *** 765,767 **** --- 766,771 ---- } + public String toString() { + return "ModelBit: " + getName() + " ( " + this.getClass().getSimpleName() + " ) "; + } } Index: Parameters.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/Parameters.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Parameters.java 19 Aug 2007 14:39:11 -0000 1.3 --- Parameters.java 19 Aug 2007 17:59:55 -0000 1.4 *************** *** 400,407 **** } - public void viewTree() { - DOMEcho.makeFrame(paramTree); - } - private static ModelParameter makeModelParameter(String name, Element paramElt) throws InitialisationException { String paramType = paramElt.getAttribute("type"); --- 400,403 ---- *************** *** 489,541 **** return (kids.getLength() == 1); } ! ! class ICAModelToToTreeModelAdapter implements javax.swing.tree.TreeModel { ! public Object getRoot() { ! return ModelRoot.getInstance(); ! } ! ! public Object getChild(Object parent, int index) { ! ModelNode node = (ModelNode) parent; ! return node.child(index); ! } ! ! public int getChildCount(Object parent) { ! ModelNode node = (ModelNode) parent; ! return node.childCount(); ! ! } ! ! public boolean isLeaf(Object node) { ! // Determines whether the icon shows up to the left. ! // Return true for any node with no children ! ModelNode mNode = (ModelNode) node; ! if (mNode.childCount() > 0) return false; ! return true; ! ! } ! ! public void valueForPathChanged(TreePath path, Object newValue) { ! // Null. We won't be making changes in the GUI ! // If we did, we would ensure the new value was really new, ! // adjust the model, and then fire a TreeNodesChanged event. ! } ! ! public int getIndexOfChild(Object parent, Object child) { ! ModelNode node = (ModelNode) parent; ! return node.index((ModelNode) child); ! ! } ! ! /** ! * Use these methods to add and remove event listeners. ! * (Needed to satisfy TreeModel interface, but not used.) ! */ ! public void addTreeModelListener(TreeModelListener listener) { ! ! } ! public void removeTreeModelListener(TreeModelListener listener) { ! } ! ! ! } } --- 485,488 ---- return (kids.getLength() == 1); } ! } |
|
From: Louise P. <lm...@us...> - 2007-08-19 17:59:57
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/utils In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv25322/src/icamodel/utils Modified Files: ICAModelJFrame.form ICAModelJFrame.java ModelParameter.java Log Message: Show tree when model is loaded Index: ICAModelJFrame.form =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/ICAModelJFrame.form,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ICAModelJFrame.form 19 Aug 2007 14:39:12 -0000 1.1 --- ICAModelJFrame.form 19 Aug 2007 17:59:55 -0000 1.2 *************** *** 23,27 **** <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> ! <Component id="jScrollPane2" pref="565" max="32767" attributes="0"/> </Group> <Group type="102" alignment="0" attributes="0"> --- 23,27 ---- <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> ! <Component id="treeScrollPane" pref="565" max="32767" attributes="0"/> </Group> <Group type="102" alignment="0" attributes="0"> *************** *** 39,44 **** <Component id="loadButton" linkSize="1" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> - <Component id="viewButton" min="-2" pref="80" max="-2" attributes="0"/> - <EmptySpace max="-2" attributes="0"/> <Component id="runButton" min="-2" pref="80" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> --- 39,42 ---- *************** *** 77,81 **** <Component id="exitButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="runButton" alignment="3" min="-2" max="-2" attributes="0"/> - <Component id="viewButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="loadButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="browseButton" alignment="3" min="-2" max="-2" attributes="0"/> --- 75,78 ---- *************** *** 86,90 **** <Component id="statusLabel" min="-2" pref="36" max="-2" attributes="0"/> <EmptySpace min="-2" pref="20" max="-2" attributes="0"/> ! <Component id="jScrollPane2" pref="349" max="32767" attributes="0"/> <EmptySpace max="-2" attributes="0"/> </Group> --- 83,87 ---- <Component id="statusLabel" min="-2" pref="36" max="-2" attributes="0"/> <EmptySpace min="-2" pref="20" max="-2" attributes="0"/> ! <Component id="treeScrollPane" pref="349" max="32767" attributes="0"/> <EmptySpace max="-2" attributes="0"/> </Group> *************** *** 127,131 **** <Properties> <Property name="text" type="java.lang.String" value="Load"/> - <Property name="actionCommand" type="java.lang.String" value="Load"/> </Properties> </Component> --- 124,127 ---- *************** *** 141,149 **** </Properties> </Component> - <Component class="javax.swing.JButton" name="viewButton"> - <Properties> - <Property name="text" type="java.lang.String" value="View"/> - </Properties> - </Component> <Component class="javax.swing.JButton" name="exitButton"> <Properties> --- 137,140 ---- *************** *** 175,179 **** </SubComponents> </Container> ! <Container class="javax.swing.JScrollPane" name="jScrollPane2"> <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> --- 166,170 ---- </SubComponents> </Container> ! <Container class="javax.swing.JScrollPane" name="treeScrollPane"> <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> Index: ICAModelJFrame.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/ICAModelJFrame.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ICAModelJFrame.java 19 Aug 2007 14:39:12 -0000 1.1 --- ICAModelJFrame.java 19 Aug 2007 17:59:55 -0000 1.2 *************** *** 20,23 **** --- 20,24 ---- import java.util.List; import javax.swing.JFileChooser; + import javax.swing.JTree; import javax.swing.filechooser.FileNameExtensionFilter; *************** *** 63,67 **** browseButton.addActionListener(this); loadButton.addActionListener(this); - viewButton.addActionListener(this); runButton.addActionListener(this); exitButton.addActionListener(this); --- 64,67 ---- *************** *** 83,91 **** pfileStatusLabel = new javax.swing.JLabel(); runButton = new javax.swing.JButton(); - viewButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); logTextArea = new javax.swing.JTextArea(); ! jScrollPane2 = new javax.swing.JScrollPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); --- 83,90 ---- pfileStatusLabel = new javax.swing.JLabel(); runButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); logTextArea = new javax.swing.JTextArea(); ! treeScrollPane = new javax.swing.JScrollPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); *************** *** 105,109 **** loadButton.setText("Load"); - loadButton.setActionCommand("Load"); pfileStatusLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); --- 104,107 ---- *************** *** 112,117 **** runButton.setText("Run"); - viewButton.setText("View"); - exitButton.setText("Exit"); --- 110,113 ---- *************** *** 132,136 **** .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() ! .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(220, 220, 220) --- 128,132 ---- .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() ! .addComponent(treeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(220, 220, 220) *************** *** 146,151 **** .addComponent(loadButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(viewButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) --- 142,145 ---- *************** *** 178,182 **** .addComponent(exitButton) .addComponent(runButton) - .addComponent(viewButton) .addComponent(loadButton) .addComponent(browseButton)) --- 172,175 ---- *************** *** 186,190 **** .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) ! .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE) .addContainerGap()) ); --- 179,183 ---- .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) ! .addComponent(treeScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE) .addContainerGap()) ); *************** *** 202,206 **** loadButton.setText("Load"); loadButton.setEnabled(false); - viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.FILE_CHOSEN) { --- 195,198 ---- *************** *** 212,216 **** loadButton.setText("Load"); loadButton.setEnabled(true); - viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.INVALID_FILE) { --- 204,207 ---- *************** *** 223,227 **** loadButton.setText("Reload"); loadButton.setEnabled(true); - viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.INVALID_MODEL) { --- 214,217 ---- *************** *** 233,237 **** logTextArea.setText(""); if (allProblems == null) { ! logTextArea.setText(currentProblem); } else { setProblems(allProblems); --- 223,227 ---- logTextArea.setText(""); if (allProblems == null) { ! logTextArea.setText(currentProblem); } else { setProblems(allProblems); *************** *** 239,243 **** loadButton.setText("Reload"); loadButton.setEnabled(true); - viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.PARAMS_LOADED) { --- 229,232 ---- *************** *** 250,254 **** loadButton.setText("Reload"); loadButton.setEnabled(true); - viewButton.setEnabled(true); runButton.setEnabled(true); } else if (myState == ModelState.RUNNING) { --- 239,242 ---- *************** *** 260,264 **** loadButton.setText("Reload"); loadButton.setEnabled(false); - viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.RUN_PROBLEM) { --- 248,251 ---- *************** *** 269,273 **** loadButton.setText("Reload"); loadButton.setEnabled(true); - viewButton.setEnabled(true); runButton.setEnabled(true); } else if (myState == ModelState.DONE) { --- 256,259 ---- *************** *** 278,282 **** loadButton.setText("Reload"); loadButton.setEnabled(true); - viewButton.setEnabled(true); runButton.setEnabled(true); } --- 264,267 ---- *************** *** 318,323 **** } else if ("Load".equals(e.getActionCommand())) { doLoadParamFile(); - } else if ("View".equals(e.getActionCommand())) { - theParams.viewTree(); } else if ("Run".equals(e.getActionCommand())) { doRunModel(); --- 303,306 ---- *************** *** 352,355 **** --- 335,341 ---- List<String> probs = theRoot.getAllInitProblems(); if (probs.size() < 1) { + JTree tree = new JTree(new ICAModelToTreeAdaptor()); + treeScrollPane.setViewportView(tree); + setStatus("Model tree built"); setState(ModelState.PARAMS_LOADED); *************** *** 408,412 **** private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; - private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton loadButton; private javax.swing.JTextArea logTextArea; --- 394,397 ---- *************** *** 415,419 **** private javax.swing.JLabel statusLabel; private javax.swing.JLabel titleLabel; ! private javax.swing.JButton viewButton; // End of variables declaration//GEN-END:variables --- 400,404 ---- private javax.swing.JLabel statusLabel; private javax.swing.JLabel titleLabel; ! private javax.swing.JScrollPane treeScrollPane; // End of variables declaration//GEN-END:variables Index: ModelParameter.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/ModelParameter.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ModelParameter.java 19 Aug 2007 14:39:12 -0000 1.1 --- ModelParameter.java 19 Aug 2007 17:59:55 -0000 1.2 *************** *** 98,100 **** --- 98,116 ---- } + public String toString() { + String ans = "param: " + name ; + if ("integer".equals(type) || + "number".equals(type) || + "paymentPattern".equals(type)) { + ans += " ( " + value.toString() + " ) "; + } else if ("listNumber".equals(type)) { + ans += RFunction.glueArgs((double[]) value); + } else if ( "listInteger".equals(type)) { + ans += RFunction.glueArgs((int[]) value); + } else if ("listString".equals(type)) { + ans += RFunction.glueArgs((String[]) value); + } + + return ans; + } } |
|
From: Louise P. <lm...@us...> - 2007-08-19 14:56:10
|
Update of /cvsroot/icamodel/WrapR/src/wrapr In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv18488/wrapr Modified Files: RFunction.java Log Message: Changes for GUI interface. Includes making parameters more abstract. Prepartory steps for being able to show tree. Index: RFunction.java =================================================================== RCS file: /cvsroot/icamodel/WrapR/src/wrapr/RFunction.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RFunction.java 13 Jul 2007 08:46:00 -0000 1.2 --- RFunction.java 19 Aug 2007 14:56:07 -0000 1.3 *************** *** 250,253 **** --- 250,273 ---- b.append(','); } + } /** + * Joins separate aruments together into a single string. + * @param args any number of parameters matching the function's parameter list + * @return params with brackets and commas + */ + public static String glueArgs(final int[] args) { + if (args == null) + return "()"; + int iMax = args.length - 1; + if (iMax == -1) + return "()"; + + StringBuilder b = new StringBuilder(); + b.append('('); + for (int i = 0; ; i++) { + b.append(String.valueOf(args[i])); + if (i == iMax) + return b.append(')').toString(); + b.append(','); + } } |
|
From: Louise P. <lm...@us...> - 2007-08-19 14:39:37
|
Update of /cvsroot/icamodel/icamodel/src/icamodel In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11829/src/icamodel Modified Files: ICAModel.java Log Message: Changes for GUI interface. Includes making parameters more abstract. Prepartory steps for being able to show tree. Index: ICAModel.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/ICAModel.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ICAModel.java 24 Jun 2007 16:09:35 -0000 1.7 --- ICAModel.java 19 Aug 2007 14:39:06 -0000 1.8 *************** *** 66,144 **** // set up its basic structure theRoot.initialise(); ! setParameters(); ! List<String> probs = theRoot.getAllInitProblems(); ! if (! probs.isEmpty()) { ! // there are problems, so tell the user what they are ! // TO DO use logger ! System.out.println("Initialisation problems:"); ! for (Iterator<String> it = probs.iterator(); it.hasNext();) { ! String msg = it.next(); ! System.out.println(msg); ! } ! System.exit(1); ! } else { ! // no problems, so go ahead and run the simulations ! // first, show the user what the model consists of ! System.out.println("ModelBits:"); ! List<String> bits = theRoot.getAllModelBits(); ! for (Iterator<String> it = bits.iterator(); it.hasNext();) { ! String msg = it.next(); ! System.out.println(msg); ! } ! PrintWriter bw; ! // do the right number of realisations ! for (int rnum = 1; rnum <= ModelRoot.getInstance().getTotalRealisations(); rnum++) { ! theRoot.reset(rnum); ! // and in each realisation, do the right number of time periods ! for (int tnum = 1; tnum <= ModelRoot.getInstance().getTimePeriodsPerRealisation(); tnum++) { ! theRoot.update(rnum, tnum); ! } ! // and at the end of the realisation, write the results ! bw = theRoot.getResultWriter(rnum); ! if (bw != null) { ! theRoot.writeResults(bw); ! } ! } ! } } catch (ModelException ex) { ex.printStackTrace(); System.exit(2); ! } catch (IOException ex) { ! ex.printStackTrace(); ! System.exit(2); ! } ! ! // we're done. let's go ! System.exit(0); ! ! } ! ! /* ! * Set up the parameters by hand. Change this to change the parameters. ! * TODO: allow user to specify which parameter file to use ! */ ! private static void setParameters() throws ModelException { ! ! // Look for the parameter file. Should be data/params.xml ! String fileName = "params.xml"; ! String dirName = "data"; ! File paramFile = new File(dirName + File.separator + fileName); ! ! System.out.println("Reading parameter file " + fileName); ! Parameters theParams = Parameters.getInstance(); ! theParams.readParamFile(paramFile); ! ! // We now have a DOM Document containing all the parameters. ! // we could look at it, but the viewer isn't that helpful ! // Also, it disappears when the program exits ! // TODO: different option for running the system, just lets you view ! // the model set up. ! // TODO: improve the viewer so you can actually see the model structure ! // TODO: extend the viewer so you can edit the param file? ! // DOMEcho.makeFrame(theParams.getParamTree()); - theParams.buildModel(); - - // TODO: give user a record of all the parameters } --- 66,75 ---- // set up its basic structure theRoot.initialise(); ! new ICAModelJFrame().setVisible(true); } catch (ModelException ex) { ex.printStackTrace(); System.exit(2); ! } } |
|
From: Louise P. <lm...@us...> - 2007-08-19 14:39:16
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/bits In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11829/src/icamodel/bits Modified Files: Assets.java BusinessLineConstant.java BusinessLogic.java CashPool.java Corporate.java External.java FixedInterestRate.java Liabilities.java LossTypeConstant.java LossTypeRange.java ModelRoot.java RandomInterestRate.java StochTotalReturn.java Log Message: Changes for GUI interface. Includes making parameters more abstract. Prepartory steps for being able to show tree. Index: StochTotalReturn.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/StochTotalReturn.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** StochTotalReturn.java 11 Jun 2007 20:56:25 -0000 1.1 --- StochTotalReturn.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 11,14 **** --- 11,15 ---- package icamodel.bits; + import icamodel.utils.ModelParameter; import wrapr.*; *************** *** 37,48 **** public StochTotalReturn(String name) { super(name); isDirty = true; // all R functions are in one source file RFunction rf = new RFunction(this); rf.declare(); ! rf = new RFunction(this, "setTimePeriodsPerYear"); rf.call((double) ModelRoot.getInstance().getTimePeriodsPerYear()); ! rGetReturn = new RFunction(this, "createPortfolioReturn"); } --- 38,53 ---- public StochTotalReturn(String name) { super(name); + addValidParameter("Names", "listString"); + addValidParameter("Means", "listNumber"); + addValidParameter("Mixes", "listNumber"); + addValidParameter("Corrs", "listNumber"); isDirty = true; // all R functions are in one source file RFunction rf = new RFunction(this); rf.declare(); ! rf = new RFunction(this, "setTimePeriodsPerYear"); rf.call((double) ModelRoot.getInstance().getTimePeriodsPerYear()); ! rGetReturn = new RFunction(this, "createPortfolioReturn"); } *************** *** 55,59 **** return calcRate(); } ! /** * Get the current rate per time period for the specified term --- 60,64 ---- return calcRate(); } ! /** * Get the current rate per time period for the specified term *************** *** 64,70 **** return calcRate(); } ! ! /** ! * get the rate per time period for specified time period in this realisation, * for the specified term * @param tnum time period --- 69,75 ---- return calcRate(); } ! ! /** ! * get the rate per time period for specified time period in this realisation, * for the specified term * @param tnum time period *************** *** 75,123 **** return calcRate(); } ! ! public String[] getNames() { ! return names; ! } ! ! public void setNames(String[] names) { ! isDirty = true; ! this.names = names; ! RFunction rf = new RFunction(this, "setNames"); ! rf.call("c" + RFunction.glueArgs(names)); ! } ! ! public double[] getMeans() { ! return means; ! } ! ! public void setMeans(double[] means) { ! isDirty = true; ! this.means = means; ! RFunction rf = new RFunction(this, "setMeans"); ! rf.call("c" + RFunction.glueArgs(means)); ! } ! ! public double[] getMixes() { ! return mixes; ! } ! ! public void setMixes(double[] mixes) { ! isDirty = true; ! this.mixes = mixes; ! RFunction rf = new RFunction(this, "setMixes"); ! rf.call("c" + RFunction.glueArgs(mixes)); ! } ! ! public double[] getCorrs() { ! return corrs; ! } ! ! public void setCorrs(double[] corr) { ! isDirty = true; ! this.corrs = corr; ! RFunction rf = new RFunction(this, "setCorrs"); ! rf.call("c" + RFunction.glueArgs(corr)); } /** * Find out if this ModelBit has been initialised correctly --- 80,101 ---- return calcRate(); } ! ! /** ! * override so as to set the param in the R code ! */ ! public String setParameter(ModelParameter param) { ! String prob = super.setParameter(param); ! if (prob == null) { ! // OK so go ahead ! String pName = param.getName(); ! String args = null; ! isDirty = true; ! RFunction rf = new RFunction(this, "set" + pName); ! rf.call("c" + param.getGluedValue()); ! } ! return prob; } + /** * Find out if this ModelBit has been initialised correctly *************** *** 125,134 **** protected void checkForInitProblems() { super.checkForInitProblems(); ! if (names == null) addInitProblem("Names must be set"); ! if (mixes == null) addInitProblem("Mixes must be set"); ! if (means == null) addInitProblem("Means must be set"); ! if (corrs == null) addInitProblem("Correlations must be set"); } ! /** * do things before the children are reset at the start of a realisation --- 103,112 ---- protected void checkForInitProblems() { super.checkForInitProblems(); ! if (! this.isParameter("Names")) addInitProblem("Names must be set"); ! if (! this.isParameter("Mixes")) addInitProblem("Mixes must be set"); ! if (! this.isParameter("Means")) addInitProblem("Means must be set"); ! if (! this.isParameter("Corrs")) addInitProblem("Correlations must be set"); } ! /** * do things before the children are reset at the start of a realisation *************** *** 138,142 **** isDirty = true; } ! /** * do things after the children are reset at the start of a realisation --- 116,120 ---- isDirty = true; } ! /** * do things after the children are reset at the start of a realisation *************** *** 145,149 **** protected void endReset(int rnum) { } ! /** * do things before the children are updated for a time period --- 123,127 ---- protected void endReset(int rnum) { } ! /** * do things before the children are updated for a time period *************** *** 154,158 **** isDirty = true; } ! /** * do things after the children are updated for a time period --- 132,136 ---- isDirty = true; } ! /** * do things after the children are updated for a time period *************** *** 162,166 **** protected void endUpdate(int rnum, int tnum) { } ! /** * do things when adding a child --- 140,144 ---- protected void endUpdate(int rnum, int tnum) { } ! /** * do things when adding a child *************** *** 183,193 **** } private RFunction rGetReturn; private boolean isDirty; private double rate; ! private String[] names; ! private double[] means; ! private double[] mixes; ! private double[] corrs; } --- 161,172 ---- } + protected String checkParameterValue(ModelParameter param) { + return null; // no checking + } + private RFunction rGetReturn; private boolean isDirty; private double rate; ! } Index: BusinessLineConstant.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/BusinessLineConstant.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** BusinessLineConstant.java 26 Jan 2007 14:40:29 -0000 1.1.1.1 --- BusinessLineConstant.java 19 Aug 2007 14:39:10 -0000 1.2 *************** *** 13,16 **** --- 13,17 ---- import icamodel.framework.BusinessLine; import icamodel.utils.InitialisationException; + import icamodel.utils.ModelParameter; /** *************** *** 20,26 **** public class BusinessLineConstant extends BusinessLine { - private double exposureUnits = -1; - private double premiumRate = -1; - /** * Creates a new instance of BusinessLineConstant --- 21,24 ---- *************** *** 29,32 **** --- 27,32 ---- public BusinessLineConstant(String name) { super(name); + addValidParameter("ExposureUnits", "number"); + addValidParameter("PremiumRate", "number"); } *************** *** 36,43 **** protected void checkForInitProblems() { super.checkForInitProblems(); ! if (exposureUnits == -1) { addInitProblem("Exposure units must be set"); } ! if (premiumRate == -1) { addInitProblem("Premium rate must be set"); } --- 36,43 ---- protected void checkForInitProblems() { super.checkForInitProblems(); ! if (! isParameter("ExposureUnits")) { addInitProblem("Exposure units must be set"); } ! if (! isParameter("PremiumRate")) { addInitProblem("Premium rate must be set"); } *************** *** 45,48 **** --- 45,66 ---- /** + *checks on parameter values + */ + protected String checkParameterValue(ModelParameter param) { + String prob = null; + if (param.getName().equals("ExposureUnits")) { + Double eu = (Double) param.getValue(); + if (eu.doubleValue()<0) { + prob = "ExposureUnits can't be negative: " + eu; + } + } else if (param.getName().equals("PremiumRate")) { + Double pr = (Double) param.getValue(); + if (pr.doubleValue()<0) { + prob = "PremiumRate can't be negative: " + pr; + } + } + return prob; + } + /** * Calculate the units of exposure for the specified time period * @param rnum number of the realisation *************** *** 51,55 **** */ protected double calcExposureUnits(int rnum, int tnum) { ! return exposureUnits; } --- 69,74 ---- */ protected double calcExposureUnits(int rnum, int tnum) { ! Double eu = (Double) getParameterValue("ExposureUnits"); ! return eu.doubleValue(); } *************** *** 61,65 **** */ protected double calcPremiumRate(int rnum, int tnum) { ! return premiumRate; } --- 80,85 ---- */ protected double calcPremiumRate(int rnum, int tnum) { ! Double pr = (Double) getParameterValue("PremiumRate"); ! return pr.doubleValue(); } *************** *** 86,110 **** } - /** - * Set the constant number of exposure units - * @param exposureUnits the number of exposure units - */ - public void setExposureUnits(double exposureUnits) { - if (exposureUnits < 0) { - throw new InitialisationException("Exposure units must be non-negative, not " + exposureUnits); - } - this.exposureUnits = exposureUnits; - } - - /** - * Set the constant premium rate - * @param premiumRate the constant premium rate - */ - public void setPremiumRate(double premiumRate) { - if (premiumRate < 0) { - throw new InitialisationException("Premium rate must be non-negative, not " + premiumRate); - } - this.premiumRate = premiumRate; - } - } --- 106,108 ---- Index: BusinessLogic.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/BusinessLogic.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** BusinessLogic.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- BusinessLogic.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 12,15 **** --- 12,16 ---- import icamodel.framework.ModelBit; + import icamodel.utils.ModelParameter; /** *************** *** 69,72 **** --- 70,78 ---- protected void endUpdate(int rnum, int tnum) { } + + protected String checkParameterValue(ModelParameter param) { + // no parameters, so no checking to do. + return null; + } Index: ModelRoot.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/ModelRoot.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ModelRoot.java 26 Jan 2007 14:40:31 -0000 1.1.1.1 --- ModelRoot.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 14,17 **** --- 14,18 ---- import icamodel.utils.Doer; import icamodel.utils.ModelException; + import icamodel.utils.ModelParameter; import java.io.BufferedWriter; import java.io.File; *************** *** 26,35 **** public class ModelRoot extends ModelBit { ! private static ModelRoot theRoot; // the only instance that is allowed ! ! private int totalRealisations; ! private int timePeriodsPerRealisation; ! private int timePeriodsPerYear; private int lastWriter = 0; private PrintWriter resultWriter; --- 27,36 ---- public class ModelRoot extends ModelBit { ! private static ModelRoot theOnlyRoot; // the only instance that is allowed + // private int totalRealisations; + // private int timePeriodsPerRealisation; + // private int timePeriodsPerYear; + // private int lastWriter = 0; private PrintWriter resultWriter; *************** *** 41,44 **** --- 42,48 ---- private ModelRoot() { super("Root"); + addValidParameter("TotalRealisations", "integer"); + addValidParameter("TimePeriodsPerRealisation", "integer"); + addValidParameter("TimePeriodsPerYear", "integer"); } /** *************** *** 59,76 **** */ public static synchronized ModelRoot getInstance() { ! if (theRoot == null) { ! theRoot = new ModelRoot(); } ! return theRoot; } protected void checkForInitProblems() { ! if (totalRealisations == 0) { addInitProblem("The total number of Realisations must be set"); } ! if (timePeriodsPerRealisation == 0) { addInitProblem("The number of time Periods per Realisation must be set"); } ! if (timePeriodsPerYear == 0) { addInitProblem("The number of time Periods per year must be set"); } --- 63,80 ---- */ public static synchronized ModelRoot getInstance() { ! if (theOnlyRoot == null) { ! theOnlyRoot = new ModelRoot(); } ! return theOnlyRoot; } protected void checkForInitProblems() { ! if (! isParameter("TotalRealisations")) { addInitProblem("The total number of Realisations must be set"); } ! if (! isParameter("TimePeriodsPerRealisation")) { addInitProblem("The number of time Periods per Realisation must be set"); } ! if (! isParameter("TimePeriodsPerYear")) { addInitProblem("The number of time Periods per year must be set"); } *************** *** 164,176 **** */ public int getTotalRealisations() { ! return totalRealisations; ! } ! ! /** ! * Set the number of realisations that we'll be running ! * @param totalRealisations the number of realisations we will run ! */ ! public void setTotalRealisations(int totalRealisations) { ! this.totalRealisations = totalRealisations; } --- 168,173 ---- */ public int getTotalRealisations() { ! Integer tr = (Integer) this.getParameterValue("TotalRealisations"); ! return tr.intValue(); } *************** *** 180,193 **** */ public int getTimePeriodsPerRealisation() { ! return timePeriodsPerRealisation; } - /** - * set the number of time periods per realisation - * @param timePeriodsPerRealisation time periods in each realisation - */ - public void setTimePeriodsPerRealisation(int timePeriodsPerRealisation) { - this.timePeriodsPerRealisation = timePeriodsPerRealisation; - } /** --- 177,184 ---- */ public int getTimePeriodsPerRealisation() { ! Integer tr = (Integer) this.getParameterValue("TimePeriodsPerRealisation"); ! return tr.intValue(); } /** *************** *** 196,209 **** */ public int getTimePeriodsPerYear() { ! return timePeriodsPerYear; } ! /** ! * set the number of time periods per year ! * @param timePeriodsPerYear time periods per year. ! */ ! public void setTimePeriodsPerYear(int timePeriodsPerYear) { ! this.timePeriodsPerYear = timePeriodsPerYear; ! } /** --- 187,195 ---- */ public int getTimePeriodsPerYear() { ! Integer tr = (Integer) this.getParameterValue("TimePeriodsPerYear"); ! return tr.intValue(); } ! /** *************** *** 220,224 **** * @throws java.io.IOException if something goes wrong * @return null if results are not to be written to file, otherwise the destination ! */ public PrintWriter getResultWriter(int rnum) throws IOException { if (!outputResults) { --- 206,210 ---- * @throws java.io.IOException if something goes wrong * @return null if results are not to be written to file, otherwise the destination ! */ public PrintWriter getResultWriter(int rnum) throws IOException { if (!outputResults) { *************** *** 238,241 **** --- 224,241 ---- } + protected String checkParameterValue(ModelParameter param) { + String prob = null; + String pname = param.getName(); + if (pname.equals("TotalRealisations") || + pname.equals("TimePeriodsPerRealisation") || + pname.equals("TimePeriodsPerYear")) { + Integer v = (Integer) param.getValue(); + if (v.intValue() <= 0) { + prob = pname + " must be greater than zero: " + v; + } + } + return prob; + } + } Index: CashPool.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/CashPool.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** CashPool.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- CashPool.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 12,15 **** --- 12,16 ---- import icamodel.framework.AssetPool; + import icamodel.utils.ModelParameter; /** *************** *** 26,30 **** super(name); } ! /** * Calculate the investment income for the specified time period --- 27,31 ---- super(name); } ! /** * Calculate the investment income for the specified time period *************** *** 42,46 **** return ans; } ! /** * cash never has any capital appreciation --- 43,47 ---- return ans; } ! /** * cash never has any capital appreciation *************** *** 52,56 **** return 0; } ! /** * do things after the children have been reset for the specified realisation --- 53,57 ---- return 0; } ! /** * do things after the children have been reset for the specified realisation *************** *** 60,62 **** --- 61,68 ---- } + protected String checkParameterValue(ModelParameter param) { + // no parameters, so no checking to do. + return null; + } + } Index: Assets.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Assets.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Assets.java 24 Mar 2007 19:33:30 -0000 1.2 --- Assets.java 19 Aug 2007 14:39:07 -0000 1.3 *************** *** 16,19 **** --- 16,20 ---- import icamodel.framework.ResultName; import icamodel.utils.Doer; + import icamodel.utils.ModelParameter; /** *************** *** 124,127 **** --- 125,133 ---- } + + protected String checkParameterValue(ModelParameter param) { + // no parameters, so no checking to do. + return null; + } Index: FixedInterestRate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/FixedInterestRate.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** FixedInterestRate.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- FixedInterestRate.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 14,17 **** --- 14,18 ---- import icamodel.framework.ModelBit; import icamodel.utils.ModelException; + import icamodel.utils.ModelParameter; /** *************** *** 21,25 **** public class FixedInterestRate extends ModelBit implements InterestRate { ! private double rate; /** --- 22,26 ---- public class FixedInterestRate extends ModelBit implements InterestRate { ! private double rate = 0; /** *************** *** 29,65 **** public FixedInterestRate(String name) { super(name); } ! /** ! * Make a new one, specifying the name and fixed annual rate ! * @param name the (unique) name of the ModelBit ! * @param rate the fixed annual interest rate ! */ ! public FixedInterestRate(String name, double rate) { ! super(name); ! setRate(rate); ! } ! ! /** * get the fixed interest rate per time period * @return the interest rate */ public double getRate() { return rate; } /** - * set the fixed annual interest rate - * @param arate the fixed interest rate - */ - public void setRate(double arate) { - this.rate = fromAnnualRate(arate); - } - - /** * do things before the children are reset at the start of a realisation * @param rnum realisation number */ protected void startReset(int rnum) { } --- 30,56 ---- public FixedInterestRate(String name) { super(name); + addValidParameter("Rate", "number"); } ! /** * get the fixed interest rate per time period * @return the interest rate */ public double getRate() { + // cache the conversion from annual rate to per time period rate + // assumes the annual rate is only ever set once + if (rate == 0) { + Double ar = (Double) getParameterValue("Rate"); + rate = fromAnnualRate(ar.doubleValue()); + } return rate; } /** * do things before the children are reset at the start of a realisation * @param rnum realisation number */ protected void startReset(int rnum) { + rate = 0; } *************** *** 93,97 **** */ public double getRate(int term) { ! return rate; } --- 84,88 ---- */ public double getRate(int term) { ! return getRate(); } *************** *** 104,108 **** */ public double getRate(int tnum, int term) { ! return rate; } --- 95,99 ---- */ public double getRate(int tnum, int term) { ! return getRate(); } *************** *** 117,119 **** --- 108,115 ---- } + protected String checkParameterValue(ModelParameter param) { + // no constraints, so no checking + return null; + } + } Index: LossTypeConstant.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/LossTypeConstant.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** LossTypeConstant.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- LossTypeConstant.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 13,16 **** --- 13,17 ---- import icamodel.framework.LossType; import icamodel.utils.InitialisationException; + import icamodel.utils.ModelParameter; /** *************** *** 20,25 **** public class LossTypeConstant extends LossType { ! private double lossAmount = -1; ! /** * Creates a new instance of LossTypeConstant --- 21,25 ---- public class LossTypeConstant extends LossType { ! /** * Creates a new instance of LossTypeConstant *************** *** 28,31 **** --- 28,32 ---- public LossTypeConstant(String name) { super(name); + addValidParameter("ConstantLossAmount","number"); } *************** *** 37,41 **** */ protected double calcIncurredLossRate(int rnum, int tnum) { ! return lossAmount; } --- 38,43 ---- */ protected double calcIncurredLossRate(int rnum, int tnum) { ! Double la = (Double) getParameterValue("ConstantLossAmount"); ! return la.doubleValue(); } *************** *** 45,49 **** protected void checkForInitProblems() { super.checkForInitProblems(); ! if (lossAmount <0) { addInitProblem("Loss amount per unit exposure must be set"); } --- 47,52 ---- protected void checkForInitProblems() { super.checkForInitProblems(); ! Double la = (Double) getParameterValue("ConstantLossAmount"); ! if (la.doubleValue() <0) { addInitProblem("Loss amount per unit exposure must be set"); } *************** *** 72,84 **** } ! /** ! * Set the constant loss amount per unit of exposure. ! * @param val constant loss amount ! */ ! public void setConstantLossAmount(double val) { ! if (val < 0) { ! throw new InitialisationException("Loss amount per unit of exposure must be non negative, not " + val); ! } ! lossAmount = val; } } --- 75,80 ---- } ! protected String checkParameterValue(ModelParameter param) { ! return null; } } Index: RandomInterestRate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/RandomInterestRate.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RandomInterestRate.java 26 Jan 2007 14:40:31 -0000 1.1.1.1 --- RandomInterestRate.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 15,18 **** --- 15,19 ---- import icamodel.framework.ResultName; import icamodel.utils.ModelException; + import icamodel.utils.ModelParameter; /** *************** *** 102,104 **** --- 103,110 ---- } + protected String checkParameterValue(ModelParameter param) { + // no params so no checking + return null; + } + } Index: Liabilities.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Liabilities.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Liabilities.java 24 Mar 2007 19:33:30 -0000 1.2 --- Liabilities.java 19 Aug 2007 14:39:11 -0000 1.3 *************** *** 15,18 **** --- 15,19 ---- import icamodel.framework.ResultName; import icamodel.utils.Doer; + import icamodel.utils.ModelParameter; /** *************** *** 94,97 **** --- 95,103 ---- setResult(ResultName.NET_CASH_FLOW, tnum, total); } + + protected String checkParameterValue(ModelParameter param) { + // no parameters, so no checking + return null; + } Index: Corporate.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/Corporate.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** Corporate.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- Corporate.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 12,15 **** --- 12,16 ---- import icamodel.framework.ModelBit; + import icamodel.utils.ModelParameter; /** *************** *** 69,72 **** } ! } --- 70,76 ---- } ! protected String checkParameterValue(ModelParameter param) { ! // no parameters, so no checking to do. ! return null; ! } } Index: LossTypeRange.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/LossTypeRange.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LossTypeRange.java 24 Jun 2007 16:09:34 -0000 1.2 --- LossTypeRange.java 19 Aug 2007 14:39:11 -0000 1.3 *************** *** 13,16 **** --- 13,17 ---- import icamodel.framework.LossType; import icamodel.utils.InitialisationException; + import icamodel.utils.ModelParameter; /** *************** *** 31,47 **** public LossTypeRange(String name) { super(name); } ! /** ! * Creates a new instance of LossTypeRange, specifying the range ! * @param name the (unique) name of the ModelBit ! * @param lower the lower bound of the range ! * @param upper the upper bound of the range ! */ ! public LossTypeRange(String name, double... range) { ! super(name); ! setLossAmountBounds(range); ! } ! ! /** * calculate the losses incurred in this time period. * @param rnum realisation number --- 32,39 ---- public LossTypeRange(String name) { super(name); + addValidParameter("LossAmountBounds", "range"); } ! ! /** * calculate the losses incurred in this time period. * @param rnum realisation number *************** *** 54,62 **** return incurred; } ! /** * check for initialisation problems */ protected void checkForInitProblems() { super.checkForInitProblems(); if (lowerBound <0) { addInitProblem("Lower bound of loss amount per unit exposure must be set"); --- 46,58 ---- return incurred; } ! /** * check for initialisation problems */ protected void checkForInitProblems() { super.checkForInitProblems(); + double[] bounds = (double[]) getParameterValue("LossAmountBounds"); + + lowerBound = bounds[0]; + upperBound = bounds[1]; if (lowerBound <0) { addInitProblem("Lower bound of loss amount per unit exposure must be set"); *************** *** 66,101 **** } } ! protected void reallyStartLossTypeUpdate(int rnum, int tnum) { } ! protected void startReset(int rnum) { } ! protected void endReset(int rnum) { } ! /** ! * Set the bounds between which the loss amount per unit of exposure will vary. ! * @param lower the lower bound of the range ! * @param upper the upper bound of the range ! */ ! public void setLossAmountBounds(double... range) { ! if (range.length != 2) { ! throw new InitialisationException("Loss amount range must have 2 elements, not " + range.length); ! } ! double lower = range[0]; ! double upper = range[1]; ! if (lower < 0) { ! throw new InitialisationException("Lower bound of loss amount per unit of exposure must be non negative, not " + lower); ! } ! if (upper < 0) { ! throw new InitialisationException("Upper bound of loss amount per unit of exposure must be non negative, not " + lower); ! } ! if (upper <= lower) { ! throw new InitialisationException("Upper bound of loss amount per unit of exposure must be greater than lower bound" ); } ! lowerBound = lower; ! upperBound = upper; ! ! } } --- 62,102 ---- } } ! protected void reallyStartLossTypeUpdate(int rnum, int tnum) { } ! protected void startReset(int rnum) { } ! protected void endReset(int rnum) { } ! ! protected String checkParameterValue(ModelParameter param) { ! String prob = null; ! if ("LossAmountBounds".equals(param.getName())) { ! double[] range = (double[]) param.getValue(); ! if (range.length != 2) { ! prob = "Loss amount range must have 2 elements, not " + range.length; ! } ! if (null != prob) return prob; // no point continuing ! double lower = range[0]; ! double upper = range[1]; ! if (lower < 0) { ! prob = "Lower bound of loss amount per unit of exposure must be non negative, not " + ! lower; ! return prob; // no point continuing ! } ! if (upper < 0) { ! prob = "Upper bound of loss amount per unit of exposure must be non negative, not " + ! lower; ! return prob; // no point continuing ! } ! if (upper <= lower) { ! prob = "Upper bound of loss amount per unit of exposure must be greater than lower bound" ; ! return prob; // no point continuing ! } ! } ! return prob; ! } } Index: External.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/External.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** External.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- External.java 19 Aug 2007 14:39:11 -0000 1.2 *************** *** 15,18 **** --- 15,19 ---- import icamodel.framework.RandomNumberGenerator; import icamodel.utils.ModelException; + import icamodel.utils.ModelParameter; /** *************** *** 163,169 **** this.gen.reset(seeds); } ! ! ! } --- 164,172 ---- this.gen.reset(seeds); } ! ! protected String checkParameterValue(ModelParameter param) { ! // no parameters, so no checking to do. ! return null; ! } } |
|
From: Louise P. <lm...@us...> - 2007-08-19 14:39:16
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/utils In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11829/src/icamodel/utils Modified Files: BasicRandomNumberGenerator.java NonRandomNumberGenerator.java PaymentPattern.java Added Files: ICAModelJFrame.form ICAModelJFrame.java ModelNode.java ModelParameter.java Log Message: Changes for GUI interface. Includes making parameters more abstract. Prepartory steps for being able to show tree. Index: BasicRandomNumberGenerator.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/BasicRandomNumberGenerator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** BasicRandomNumberGenerator.java 26 Jan 2007 16:57:01 -0000 1.2 --- BasicRandomNumberGenerator.java 19 Aug 2007 14:39:12 -0000 1.3 *************** *** 26,30 **** * Creates a new instance of BasicRandomNumberGenerator */ ! public BasicRandomNumberGenerator() { myGenerator = new Random(); } --- 26,31 ---- * Creates a new instance of BasicRandomNumberGenerator */ ! public BasicRandomNumberGenerator(String name) { ! super(name); myGenerator = new Random(); } *************** *** 33,37 **** * @param seed the seed */ ! public BasicRandomNumberGenerator(long seed) { myGenerator = new Random(seed); } --- 34,39 ---- * @param seed the seed */ ! public BasicRandomNumberGenerator(String name, long seed) { ! super(name); myGenerator = new Random(seed); } *************** *** 52,55 **** --- 54,61 ---- return myGenerator.nextDouble(); } + + protected String checkParameterValue(ModelParameter param) { + return null; // nochecking + } --- NEW FILE: ModelNode.java --- /* * ModelNode.java * * Created on 18 August 2007, 21:25 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package icamodel.utils; /** * An interface that supplies the information that's needed to show the model in a tree * @author Louise */ public interface ModelNode { /* * Return children, index, and count values */ public int index(ModelNode child); public ModelNode child(int searchIndex); public int childCount(); } --- NEW FILE: ICAModelJFrame.form --- <?xml version="1.0" encoding="UTF-8" ?> <Form version="1.3" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> <Properties> <Property name="defaultCloseOperation" type="int" value="3"/> </Properties> <SyntheticProperties> <SyntheticProperty name="formSizePolicy" type="int" value="1"/> </SyntheticProperties> <AuxValues> <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> </AuxValues> <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="1" attributes="0"> <Group type="103" groupAlignment="1" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Component id="jScrollPane2" pref="565" max="32767" attributes="0"/> </Group> <Group type="102" alignment="0" attributes="0"> <EmptySpace min="-2" pref="220" max="-2" attributes="0"/> <Component id="titleLabel" min="-2" pref="86" max="-2" attributes="0"/> </Group> <Group type="102" alignment="1" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="1" attributes="0"> <Component id="statusLabel" alignment="0" pref="565" max="32767" attributes="0"/> <Component id="jScrollPane1" alignment="0" pref="565" max="32767" attributes="0"/> <Group type="102" alignment="1" attributes="0"> <Component id="browseButton" linkSize="1" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="loadButton" linkSize="1" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="viewButton" min="-2" pref="80" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="runButton" min="-2" pref="80" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="exitButton" min="-2" pref="80" max="-2" attributes="0"/> </Group> <Group type="102" alignment="0" attributes="0"> <Component id="currentPfileLabel" min="-2" pref="479" max="-2" attributes="0"/> <EmptySpace pref="86" max="32767" attributes="0"/> </Group> <Group type="102" alignment="0" attributes="0"> <Component id="jLabel1" min="-2" pref="226" max="-2" attributes="0"/> <EmptySpace pref="20" max="32767" attributes="0"/> <Component id="pfileStatusLabel" min="-2" pref="319" max="-2" attributes="0"/> </Group> </Group> </Group> </Group> <EmptySpace max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Component id="titleLabel" min="-2" pref="27" max="-2" attributes="0"/> <EmptySpace min="-2" pref="23" max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="pfileStatusLabel" alignment="3" min="-2" pref="27" max="-2" attributes="0"/> </Group> <EmptySpace max="-2" attributes="0"/> <Component id="currentPfileLabel" min="-2" pref="24" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="exitButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="runButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="viewButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="loadButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="browseButton" alignment="3" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace min="-2" pref="10" max="-2" attributes="0"/> <Component id="jScrollPane1" min="-2" pref="73" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="statusLabel" min="-2" pref="36" max="-2" attributes="0"/> <EmptySpace min="-2" pref="20" max="-2" attributes="0"/> <Component id="jScrollPane2" pref="349" max="32767" attributes="0"/> <EmptySpace max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> </Layout> <SubComponents> <Component class="javax.swing.JLabel" name="titleLabel"> <Properties> <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Tahoma" size="14" style="1"/> </Property> <Property name="horizontalAlignment" type="int" value="0"/> <Property name="text" type="java.lang.String" value="ICAModel"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="statusLabel"> <Properties> <Property name="text" type="java.lang.String" value="Current status"/> <Property name="verticalAlignment" type="int" value="1"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel1"> <Properties> <Property name="text" type="java.lang.String" value="Current parameter file:"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="currentPfileLabel"> <Properties> <Property name="text" type="java.lang.String" value="None selected"/> </Properties> </Component> <Component class="javax.swing.JButton" name="browseButton"> <Properties> <Property name="text" type="java.lang.String" value="Browse..."/> <Property name="actionCommand" type="java.lang.String" value="Browse"/> </Properties> </Component> <Component class="javax.swing.JButton" name="loadButton"> <Properties> <Property name="text" type="java.lang.String" value="Load"/> <Property name="actionCommand" type="java.lang.String" value="Load"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="pfileStatusLabel"> <Properties> <Property name="horizontalAlignment" type="int" value="11"/> <Property name="text" type="java.lang.String" value="Not loaded"/> </Properties> </Component> <Component class="javax.swing.JButton" name="runButton"> <Properties> <Property name="text" type="java.lang.String" value="Run"/> </Properties> </Component> <Component class="javax.swing.JButton" name="viewButton"> <Properties> <Property name="text" type="java.lang.String" value="View"/> </Properties> </Component> <Component class="javax.swing.JButton" name="exitButton"> <Properties> <Property name="text" type="java.lang.String" value="Exit"/> </Properties> </Component> <Container class="javax.swing.JScrollPane" name="jScrollPane1"> <Properties> <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor"> <Border info="null"/> </Property> </Properties> <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> <SubComponents> <Component class="javax.swing.JTextArea" name="logTextArea"> <Properties> <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor"> <Color blue="d8" green="e9" id="Label.background" palette="3" red="ec" type="palette"/> </Property> <Property name="columns" type="int" value="20"/> <Property name="editable" type="boolean" value="false"/> <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor"> <Font name="Tahoma" size="11" style="0"/> </Property> <Property name="rows" type="int" value="3"/> </Properties> </Component> </SubComponents> </Container> <Container class="javax.swing.JScrollPane" name="jScrollPane2"> <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/> </Container> </SubComponents> </Form> --- NEW FILE: ICAModelJFrame.java --- /* * ICAModelJFrame.java * * Created on 18 August 2007, 16:35 * $Header: /cvsroot/icamodel/icamodel/src/icamodel/utils/ICAModelJFrame.java,v 1.1 2007/08/19 14:39:12 lmpryor Exp $ * $Revision: 1.1 $ * $Date: 2007/08/19 14:39:12 $ */ package icamodel.utils; import icamodel.bits.ModelRoot; import icamodel.framework.Parameters; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /** * Possible states: * - no parameter file specified * o user can specify parameter file to be loaded * - parameter file specified * o user can load parameter file of specify another one * - paramter file loaded, but invalid * o user can reload parameter file or specify another one * - parameter file loaded, but invalid model * o user can reload parameter file or specify another one * - valid parameter file loaded; not run yet * o user can reload parameter file or specify another one * o user can run the model * - model running * o user has to wait * - model has run but there was a problem * o user can reload parameter file or specify another one * o user can run the model * - model has run successfully * o user can inspect results * o user can reload parameter file or specify another one * * @author Louise */ public class ICAModelJFrame extends javax.swing.JFrame implements ActionListener { private ModelState myState; private File paramFile; private String currentProblem; private List<String> allProblems; private Parameters theParams; private ModelRoot theRoot; /** Creates new form ICAModelJFrame */ public ICAModelJFrame() { initComponents(); theParams = Parameters.getInstance(); theRoot = ModelRoot.getInstance(); setState(ModelState.INITIAL); browseButton.addActionListener(this); loadButton.addActionListener(this); viewButton.addActionListener(this); runButton.addActionListener(this); exitButton.addActionListener(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { titleLabel = new javax.swing.JLabel(); statusLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); currentPfileLabel = new javax.swing.JLabel(); browseButton = new javax.swing.JButton(); loadButton = new javax.swing.JButton(); pfileStatusLabel = new javax.swing.JLabel(); runButton = new javax.swing.JButton(); viewButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); logTextArea = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); titleLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); titleLabel.setText("ICAModel"); statusLabel.setText("Current status"); statusLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); jLabel1.setText("Current parameter file:"); currentPfileLabel.setText("None selected"); browseButton.setText("Browse..."); browseButton.setActionCommand("Browse"); loadButton.setText("Load"); loadButton.setActionCommand("Load"); pfileStatusLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); pfileStatusLabel.setText("Not loaded"); runButton.setText("Run"); viewButton.setText("View"); exitButton.setText("Exit"); jScrollPane1.setBorder(null); logTextArea.setBackground(javax.swing.UIManager.getDefaults().getColor("Label.background")); logTextArea.setColumns(20); logTextArea.setEditable(false); logTextArea.setFont(new java.awt.Font("Tahoma", 0, 11)); logTextArea.setRows(3); jScrollPane1.setViewportView(logTextArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(220, 220, 220) .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(statusLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(browseButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loadButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(viewButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(exitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(currentPfileLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addComponent(pfileStatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {browseButton, loadButton}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(pfileStatusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(currentPfileLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(exitButton) .addComponent(runButton) .addComponent(viewButton) .addComponent(loadButton) .addComponent(browseButton)) .addGap(10, 10, 10) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void setState(ModelState mState) { myState = mState; if (myState == ModelState.INITIAL) { setStatus(""); currentPfileLabel.setText("None selected"); pfileStatusLabel.setText(""); logTextArea.setText(""); logTextArea.setRows(1); loadButton.setText("Load"); loadButton.setEnabled(false); viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.FILE_CHOSEN) { setStatus(""); currentPfileLabel.setText(paramFile.getPath()); pfileStatusLabel.setText("Selected but not loaded"); logTextArea.setText(""); logTextArea.setRows(1); loadButton.setText("Load"); loadButton.setEnabled(true); viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.INVALID_FILE) { // there was something wrong with the file setStatus(""); currentPfileLabel.setText(paramFile.getName()); pfileStatusLabel.setText("Invalid parameter file"); logTextArea.setRows(1); logTextArea.setText(currentProblem); loadButton.setText("Reload"); loadButton.setEnabled(true); viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.INVALID_MODEL) { // there was something wrong with the model setStatus(""); currentPfileLabel.setText(paramFile.getName()); pfileStatusLabel.setText("Invalid model specification"); logTextArea.setRows(1); logTextArea.setText(""); if (allProblems == null) { logTextArea.setText(currentProblem); } else { setProblems(allProblems); } loadButton.setText("Reload"); loadButton.setEnabled(true); viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.PARAMS_LOADED) { // there was something wrong with the model setStatus(""); currentPfileLabel.setText(paramFile.getPath()); pfileStatusLabel.setText("Parameters loaded"); logTextArea.setRows(1); logTextArea.setText(""); loadButton.setText("Reload"); loadButton.setEnabled(true); viewButton.setEnabled(true); runButton.setEnabled(true); } else if (myState == ModelState.RUNNING) { setStatus(""); currentPfileLabel.setText(paramFile.getPath()); pfileStatusLabel.setText("Model running"); logTextArea.setRows(1); logTextArea.setText(""); loadButton.setText("Reload"); loadButton.setEnabled(false); viewButton.setEnabled(false); runButton.setEnabled(false); } else if (myState == ModelState.RUN_PROBLEM) { currentPfileLabel.setText(paramFile.getPath()); pfileStatusLabel.setText("Model problem"); logTextArea.setRows(1); logTextArea.setText(currentProblem); loadButton.setText("Reload"); loadButton.setEnabled(true); viewButton.setEnabled(true); runButton.setEnabled(true); } else if (myState == ModelState.DONE) { currentPfileLabel.setText(paramFile.getPath()); pfileStatusLabel.setText("Model run"); logTextArea.setRows(1); logTextArea.setText(""); loadButton.setText("Reload"); loadButton.setEnabled(true); viewButton.setEnabled(true); runButton.setEnabled(true); } currentProblem = ""; allProblems = null; } public void setStatus(String sText) { statusLabel.setText(sText); } private void setProblems(List<String> probs) { String text = "Initialisation problems:"; int rows = 1; if (! probs.isEmpty()) { // there are problems, so tell the user what they are for (Iterator<String> it = probs.iterator(); it.hasNext();) { String msg = it.next(); text += "\n" + msg; rows++; } } logTextArea.setRows(rows); logTextArea.setText(text); } /** * TODO: this is a really clunky way. Should probably be done through a logger */ public void addProblem(String prob) { int rows = logTextArea.getRows(); logTextArea.setRows(rows +1); String text = logTextArea.getText(); logTextArea.setText(text + "\n" + prob); } public void actionPerformed(ActionEvent e) { if ("Browse".equals(e.getActionCommand())) { doFindParamFile(); } else if ("Load".equals(e.getActionCommand())) { doLoadParamFile(); } else if ("View".equals(e.getActionCommand())) { theParams.viewTree(); } else if ("Run".equals(e.getActionCommand())) { doRunModel(); } else if ("Exit".equals(e.getActionCommand())) { System.exit(0); } } private void doFindParamFile() { // the Browse button has been clicked. find the parameter file JFileChooser chooser = new JFileChooser("data"); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Text and xml files", "txt", "xml"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { paramFile = chooser.getSelectedFile(); setState(ModelState.FILE_CHOSEN); } } private void doLoadParamFile() { // the Load button has been clicked. // read in the parameter file setStatus("Reading parameter file"); String result = theParams.readParamFile(paramFile); setStatus("Parameter file read"); if ("".equals(result)) { // file was OK try { setStatus("Building model tree"); theParams.buildModel(); List<String> probs = theRoot.getAllInitProblems(); if (probs.size() < 1) { setStatus("Model tree built"); setState(ModelState.PARAMS_LOADED); } else { allProblems = probs; setStatus("Model tree built"); setState(ModelState.INVALID_MODEL); } } catch (ModelException mex) { // there were problems with the model currentProblem = mex.getMessage(); setState(ModelState.INVALID_MODEL); } catch (InitialisationException mex) { // there were problems with the model currentProblem = mex.getMessage(); setState(ModelState.INVALID_MODEL); } } else { // there was a problem with the parameter file currentProblem = result; setState(ModelState.INVALID_FILE); } } private void doRunModel() { // the Run button has been clicked. // run the model. setState(ModelState.RUNNING); PrintWriter bw; // do the right number of realisations for (int rnum = 1; rnum <= ModelRoot.getInstance().getTotalRealisations(); rnum++) { theRoot.reset(rnum); // and in each realisation, do the right number of time periods for (int tnum = 1; tnum <= ModelRoot.getInstance().getTimePeriodsPerRealisation(); tnum++) { setStatus("Realisation: " + rnum + "; Time period: " + tnum); theRoot.update(rnum, tnum); } // and at the end of the realisation, write the results try { bw = theRoot.getResultWriter(rnum); if (bw != null) { theRoot.writeResults(bw); } } catch (IOException iox) { currentProblem = iox.getMessage(); setState(ModelState.RUN_PROBLEM); } setState(ModelState.DONE); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseButton; private javax.swing.JLabel currentPfileLabel; private javax.swing.JButton exitButton; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton loadButton; private javax.swing.JTextArea logTextArea; private javax.swing.JLabel pfileStatusLabel; private javax.swing.JButton runButton; private javax.swing.JLabel statusLabel; private javax.swing.JLabel titleLabel; private javax.swing.JButton viewButton; // End of variables declaration//GEN-END:variables private enum ModelState { INITIAL, FILE_CHOSEN, INVALID_FILE, INVALID_MODEL, PARAMS_LOADED, RUNNING, RUN_PROBLEM, DONE, } } --- NEW FILE: ModelParameter.java --- /* * ModelParameter.java * * Created on 18 August 2007, 22:24 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package icamodel.utils; import wrapr.RFunction; /** * Used so that we can see the parameters in the tree * @author Louise */ public class ModelParameter implements ModelNode { private String name; private String type; private Object value; /** Creates a new instance of ModelParameter */ public ModelParameter(String n, String t, Object v) { this.name = n; this.type = t; this.value = v; } public String getName() { return name; } public String getType() { return type; } public Object getValue() { return value; } public boolean isValueValidType() { boolean ans = false; if (type.equals("integer")) { ans = value instanceof Integer; } else if (type.equals("number")) { ans = value instanceof Double; } else if (type.equals("listString")) { ans = value instanceof String[]; } else if (type.equals("listInteger")) { ans = value instanceof int[]; } else if (type.equals("listNumber")) { ans = value instanceof double[]; } else if (type.equals("range")) { ans = value instanceof double[]; } else if (type.equals("paymentPattern")) { ans = value instanceof PaymentPattern; } else { ans = false; } return ans; } /** * Get the value as a single string, to be sent through to R */ public String getGluedValue() { String ans = null; if (type.equals("integer")) { ans = value.toString(); } else if (type.equals("number")) { ans = value.toString(); } else if (type.equals("listString")) { ans = RFunction.glueArgs(( String[]) value); } else if (type.equals("listInteger")) { ans = RFunction.glueArgs(( int[]) value); } else if (type.equals("listNumber")) { ans = RFunction.glueArgs(( double[]) value); } else if (type.equals("range")) { ans = RFunction.glueArgs(( double[]) value); } else if (type.equals("paymentPattern")) { // can't handle this } return ans; } /********************************************************************************************* * things to implement ModelNode ********************************************************************************************/ public int index(ModelNode child) { return -1; // always a leaf } public ModelNode child(int searchIndex) { return null; // no children } public int childCount() { return 0; // no children } } Index: NonRandomNumberGenerator.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/NonRandomNumberGenerator.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** NonRandomNumberGenerator.java 24 Jun 2007 16:09:35 -0000 1.3 --- NonRandomNumberGenerator.java 19 Aug 2007 14:39:12 -0000 1.4 *************** *** 21,29 **** private double fixed; ! public void setFixedNumber(double number) throws ModelException { ! if (number < 0 || number > 1) { ! throw new ModelException("Non random number must be between 0 and 1"); ! } ! fixed = number; } --- 21,27 ---- private double fixed; ! public NonRandomNumberGenerator(String name) { ! super(name); ! addValidParameter("FixedNumber", "number"); } *************** *** 42,45 **** --- 40,55 ---- return fixed; } + + protected String checkParameterValue(ModelParameter param) { + String prob = null; + if (param.getName().equals("FixedNumber")) { + double number = ((Double) param.getValue()).doubleValue(); + if (number < 0 || number > 1) { + prob = "FixedNumber must be between 0 and 1: " + number; + } + } + return prob; + } + } Index: PaymentPattern.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/PaymentPattern.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PaymentPattern.java 24 Mar 2007 19:33:30 -0000 1.3 --- PaymentPattern.java 19 Aug 2007 14:39:12 -0000 1.4 *************** *** 20,24 **** */ public class PaymentPattern { ! private double[] pattern; // elements all in [0,1] and sum to 1.0 private Incidence incidence; --- 20,24 ---- */ public class PaymentPattern { ! private double[] pattern; // elements all in [0,1] and sum to 1.0 private Incidence incidence; *************** *** 31,35 **** * EVEN: amount within a period is evenly spread throughout the period * OTHER: some other arrangement ! */ public enum Incidence { FRONT, --- 31,35 ---- * EVEN: amount within a period is evenly spread throughout the period * OTHER: some other arrangement ! */ public enum Incidence { FRONT, *************** *** 37,41 **** OTHER } ! /** * Creates a new instance of PaymentPattern --- 37,41 ---- OTHER } ! /** * Creates a new instance of PaymentPattern *************** *** 83,87 **** } } ! /** * set the assumed incidence of payments within each period --- 83,87 ---- } } ! /** * set the assumed incidence of payments within each period *************** *** 139,152 **** return 1.0 - getCumulativeProportion(tPeriod); } ! /** * Create a new pattern by convoluting two existing patterns. ! * taking into account the assumed incidence of payments within the patterns' periods. * Eg, convolute writing pattern and earning delay pattern to get overall earning pattern. ! * If either of the incidences is OTHER then the other one must be FRONT or the function will chuck a wobbly. * @param p1 pattern that runs from the overall start period * @param p2 pattern that runs relative to periods in p1 * @return pattern that runs from overall start period and combines effects of p1 & p2. ! * Length of new pattern is sum of lengths of existing patterns ! * (minus 1 if incidence of either p1 or p2 is FRONT). */ public static PaymentPattern compoundPatterns(PaymentPattern p1, PaymentPattern p2) { --- 139,152 ---- return 1.0 - getCumulativeProportion(tPeriod); } ! /** * Create a new pattern by convoluting two existing patterns. ! * taking into account the assumed incidence of payments within the patterns' periods. * Eg, convolute writing pattern and earning delay pattern to get overall earning pattern. ! * If either of the incidences is OTHER then the other one must be FRONT or the function will chuck a wobbly. * @param p1 pattern that runs from the overall start period * @param p2 pattern that runs relative to periods in p1 * @return pattern that runs from overall start period and combines effects of p1 & p2. ! * Length of new pattern is sum of lengths of existing patterns ! * (minus 1 if incidence of either p1 or p2 is FRONT). */ public static PaymentPattern compoundPatterns(PaymentPattern p1, PaymentPattern p2) { *************** *** 184,186 **** --- 184,200 ---- return new PaymentPattern(newIncid, newArr); } + + public String toString() { + String ans = "PaymentPattern{"; + ans += incidence.toString() + ": "; + for (int i=0; i<pattern.length; i++) { + if (i > 0) { + ans += ","; + } + ans += pattern[i]; + } + ans += "}"; + return ans; + } + } |
|
From: Richard P. <ric...@us...> - 2007-07-13 08:49:31
|
Update of /cvsroot/icamodel/icamodel/src/R In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv9387 Added Files: StochTotalReturn.R Removed Files: icamodel-bits-StochTotalReturn.R Log Message: no message --- icamodel-bits-StochTotalReturn.R DELETED --- --- NEW FILE: StochTotalReturn.R --- ################################################################################ # CONTENTS # 1. Notes # 2 R style help file # 3. Main function # 4. Sub functions (called by Main function) # 5. Example ################################################################################ # Notes # the following variables will have been set up already (when the java code sources "createRVariables.r" # strAssetNames - a (string) vector with names of asset classes (one of these must be "cash") # dblAssetReturn_annual - a (double) vector with annual total returns on the asset class # dblPortfolioMix - a (double) vector with the proportions of each asset in the fund # mtxBrownianCorrelations - a (double) matrix with correlations between the underlying brownian motions # intNumPeriodsInYear - an (integer) with the number of time periods that fall within a year (1= annual, 12= monthly etc) # tax presumably done as another module? # note there has to be a "cash" class - remember this when building the user interface... setCorrs.StochTotalReturn<-function(correlationVectorDouble){ lVec <- length(correlationVectorDouble) squareSide <- lVec^0.5 isSquareMatrix<-(abs(floor(squareSide)-squareSide)<0.00000001) if (isSquareMatrix) { mtxBrownianCorrelations<<-matrix(correlationVectorDouble, nrow=squareSide, byrow=TRUE) } else { stop("not square") } } setMeans.StochTotalReturn<-function(annualReturnVectorDouble){ dblAssetReturn_annual<<-annualReturnVectorDouble } setMixes.StochTotalReturn<-function(mixVectorDouble){ dblPortfolioMix<-mixVectorDouble maxError <- 0.000001 if(abs(1-sum(dblPortfolioMix))>maxError) stop("proportions dont sum to 100%") dblPortfolioMix<<-dblPortfolioMix } setNames.StochTotalReturn<-function(namesVectorString){ strAssetNames<<-namesVectorString } setTimePeriodsPerYear.StochTotalReturn<-function(tInteger){ intNumPeriodsInYear<<-tInteger } ################################################################################ # R STYLE HELP FILE # Name: createPortfolioReturn.StochTotalReturn # Description # Creates a single TOTAL period return from a portfolio of assets; each asset assumed # to follow a geometric brownian motion. # Usage: # createPortfolioReturn.StochTotalReturn(portfolioMix=NULL,returnParam=NULL,brownianCorrelations=NULL,numPeriodsInYear=NULL,numSims=1) # Arguments # portfolioMix - this need not be specified here provided the createRVariables code has been run # a vector containing the proportions of each asset class in the portfolio (must sum to 100%) # returnParam - this need not be specified here provided the createRVariables code has been run # a data frame containing ANNUAL total returns for each named asset class created by # the createReturnParam function # brownianCorrelations - this need not be specified provided the createRVariables code has been run # a matrix of correlations between the underlying brownian motions (note this does not equal the # correlations between the individual asset classes # numPeriodsInYear - this need not be specified here provided the createRVariables code has been run # the return produced by the function will be a per period return (e.g. per month) # here we specify how many periods make up one year (so monthly=12) # numSims - default is 1, but can produce many simulations at once # Details: # the createPortfolioReturn.StochTotalReturn function simulates geometric brownian motions for asset classes specified and named by the user # (the createAssetsims function does this bit and produces a list of returns for each specified asset class). The ################################################################################ # Main Function createPortfolioReturn.StochTotalReturn<-function(portfolioMix=NULL,...){ if (is.null(portfolioMix)) portfolioMix = dblPortfolioMix createReturnParam() assetSimsList<<-createAssetSims(...) assetSimsMtx<<-convertListToMtx(assetSimsList) portfolioReturn<-assetSimsMtx %*% portfolioMix # rm(strAssetNames, dblAssetReturn_annual,dblPortfolioMix, mtxBrownianCorrelations, intNumPeriodsInYear, assetSimsList, assetSimsMtx, pos=1) #remove variables that have been created # rm(convertListToMtx,createAssetNames,createAssetReturn_annual,createAssetSims,createBrownianCorrelations,createNumPeriodsInYear, # createPortfolioMix, getCashReturn,getDriftAndVolParameters,getGrossPeriodReturns,joinDriftVolAndZ,produceCorrelatedNormals, # testCompatibility,dfrmReturnParam,createReturnParam ,pos=1)# remove functions that have been sourced (unless we can speed things up by just calling these once? e.g. with a flag that says we've done it return(as.vector(portfolioReturn)) } ################################################################################ # sub functions createAssetSims<-function(returnParam=NULL,brownianCorrelations=NULL,numPeriodsInYear=NULL, numSims=1){ if (is.null(returnParam)) returnParam = dfrmReturnParam if (is.null(brownianCorrelations)) brownianCorrelations = mtxBrownianCorrelations if (is.null(numPeriodsInYear)) numPeriodsInYear = intNumPeriodsInYear r_cash<-getCashReturn(returnParam) driftAndVolParam<-apply(as.array(returnParam$assetReturn_annual), 1, FUN=getDriftAndVolParameters, r_cash,numPeriodsInYear) compatible<-testCompatibility(brownianCorrelations,returnParam) if(!compatible) stop("Error: correlation matrix doesnt match number of assets chosen") Z<-produceCorrelatedNormals(brownianCorrelations,numSims) allParms<-joinDriftVolAndZ(driftAndVolParam, Z) onePeriodReturns<-lapply(allParms,getGrossPeriodReturns) names(onePeriodReturns)<-returnParam[,1] return(onePeriodReturns) } convertListToMtx<-function(lstVals){ # this assumes that lstVals is a list with each element containing a single vector of the same length numElements<-length(lstVals) mtx <-NULL for (i in seq(1, numElements)){ mtx<-cbind(mtx,lstVals[[i]]) } colnames(mtx)<-names(lstVals) return(mtx) } createReturnParam<-function(assetNames=NULL, assetReturn_annual=NULL){ if (is.null(assetNames)) assetNames=strAssetNames if (is.null(assetReturn_annual)) assetReturn_annual = dblAssetReturn_annual returnParam<-data.frame(as.character(assetNames),assetReturn_annual,stringsAsFactors=FALSE) names(returnParam)<-c("assetNames","assetReturn_annual") dfrmReturnParam<<-returnParam } # getReturnParameters --------------------------------------------------------- # r_cash - the total return on cash # r_x - the annualised total return on the required asset class # numPeriodsInYear - the time period (1= annual, 4= quarterly, 12= monthly). getDriftAndVolParameters<-function(r_x, r_cash, numPeriodsInYear){ mu <- 1/numPeriodsInYear * log(1+r_cash) vol <- sqrt(2/numPeriodsInYear * log((1+r_x)/(1+r_cash))) rslt<-list(mu=mu, vol=vol) return(rslt) } #------------------------------------------------------------------------------- # produceCorrelatedNormals # R a square matrix, 1's down diagonal, opposite cells of equal value, positive definate - a correlation matrix # numSims - number of simulations required produceCorrelatedNormals<-function(R, numSims){ Rdim<-dim(R) if (Rdim[1]!=Rdim[2]) strop("Error: correlation matrix R should be square") numVars<-Rdim[1] Z_ind<-matrix(rnorm(numSims*numVars), nrow=numVars) Z<-t(chol(R))%*%Z_ind return(Z) } #------------------------------------------------------------------------------- # getGrossPeriodReturns # mu - the drift of the geometric brownian motion # vol - the volatility of the geometrix brownian motion # Z - a vector of normal random variables getGrossPeriodReturns<-function(parms){ mu<-parms$mu vol<-parms$vol Z<-parms$Z return(exp(mu + vol * Z)) } #------------------------------------------------------------------------------- # testCompatibility testCompatibility<-function(R,returnParam){ compat<-TRUE Rdim<-dim(R) if (Rdim[1]!=Rdim[2]) stop("Error: correlation matrix R should be square") Rsize<-Rdim[1] Psize<-dim(returnParam)[1] if (Rsize!=Psize) compat<-FALSE return(compat) } #------------------------------------------------------------------------------- # joinDriftVolandZ # Concerned this is pretty inefficient..... though we'll only be calling this once joinDriftVolAndZ<-function(driftAndVolParam, Z){ numAssets<-dim(Z)[1] join<-function(assetNum,driftAndVolParam,Z){ rslt<-list(mu=driftAndVolParam[[assetNum]]$mu, vol=driftAndVolParam[[assetNum]]$vol, Z=Z[assetNum,]) return(rslt) } fullRslt<-lapply(as.list(seq(1,numAssets)),join, driftAndVolParam,Z) return(fullRslt) } #------------------------------------------------------------------------------- # getCashReturn getCashReturn<-function(returnParam){ cashPos<-match(returnParam$assetNames, c("cash")) # just in case the user hasnt put cash first in the list if(!any(!is.na(cashPos))) stop("Error: there must be an asset class called 'cash'") cashReturn<-returnParam[cashPos,2] cashReturn<-cashReturn[!is.na(cashReturn)] if(cashReturn>min(returnParam$assetReturn_annual)) stop("Error:Cash should be the asset with the lowest return") return(cashReturn) } ################################################################################ # EXAMPLE wantExample=F if(wantExample){ setNames.StochTotalReturn(c("cash", "equity", "gilt", "property")) setMeans.StochTotalReturn(c(0.04, 0.07,0.05, 0.065)) setMixes.StochTotalReturn(c(0.2, 0.3, 0.4,0.1)) setCorrs.StochTotalReturn(c(1.0, 0.0, 0.0, 0.0,0.0, 1.0, 0.3, 0.1,0.0, 0.3, 1.0, 0.1,0.0, 0.1, 0.1, 1.0)) setTimePeriodsPerYear.StochTotalReturn(12) createPortfolioReturn.StochTotalReturn() } rm(wantExample) |
|
From: Richard P. <ric...@us...> - 2007-07-13 08:46:55
|
Update of /cvsroot/icamodel/WrapR/src/wrapr/examples In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv7824/wrapr/examples Added Files: RunMe2.form RunMe2.java RunMe1.java Examples.java Removed Files: Example1.java Main.java Log Message: no message --- NEW FILE: RunMe2.form --- <?xml version="1.0" encoding="UTF-8" ?> <Form version="1.3" type="org.netbeans.modules.form.forminfo.JFrameFormInfo"> <NonVisualComponents> <Menu class="javax.swing.JMenuBar" name="mainMenu"> <SubComponents> <Menu class="javax.swing.JMenu" name="fileMenu"> <Properties> <Property name="text" type="java.lang.String" value="File"/> </Properties> <SubComponents> <MenuItem class="javax.swing.JMenuItem" name="exitMenuItem"> <Properties> <Property name="text" type="java.lang.String" value="Exit"/> <Property name="toolTipText" type="java.lang.String" value="Guess what this does"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitMenuItemActionPerformed"/> </Events> </MenuItem> </SubComponents> </Menu> </SubComponents> </Menu> </NonVisualComponents> <Properties> <Property name="defaultCloseOperation" type="int" value="3"/> <Property name="title" type="java.lang.String" value="WrapR Example 2"/> </Properties> <SyntheticProperties> <SyntheticProperty name="menuBar" type="java.lang.String" value="mainMenu"/> <SyntheticProperty name="formSizePolicy" type="int" value="1"/> </SyntheticProperties> <AuxValues> <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> </AuxValues> <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace max="32767" attributes="0"/> <Group type="103" groupAlignment="1" attributes="0"> <Group type="102" alignment="1" attributes="0"> <Component id="showPlotButton" min="-2" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="1" attributes="0"> <Component id="exitButton" alignment="1" min="-2" max="-2" attributes="0"/> <Component id="hidePlotButton" alignment="1" min="-2" max="-2" attributes="0"/> </Group> </Group> <Group type="102" alignment="1" attributes="0"> <Group type="103" groupAlignment="1" attributes="0"> <Component id="jLabel1" alignment="1" min="-2" max="-2" attributes="0"/> <Component id="jLabel2" alignment="1" min="-2" max="-2" attributes="0"/> <Component id="jLabel3" alignment="1" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Group type="103" alignment="0" groupAlignment="0" max="-2" attributes="0"> <Component id="startX" max="32767" attributes="1"/> <Component id="endX" alignment="0" min="-2" pref="76" max="-2" attributes="1"/> </Group> <Component id="formulaY" min="-2" pref="76" max="-2" attributes="0"/> </Group> </Group> </Group> <EmptySpace min="-2" pref="30" max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> <DimensionLayout dim="1"> <Group type="103" groupAlignment="0" attributes="0"> <Group type="102" alignment="0" attributes="0"> <EmptySpace max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="startX" alignment="3" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace min="-2" pref="2" max="-2" attributes="0"/> <Group type="103" groupAlignment="0" attributes="0"> <Component id="endX" min="-2" max="-2" attributes="0"/> <Component id="jLabel2" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace min="-2" pref="18" max="-2" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="formulaY" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace max="32767" attributes="0"/> <Group type="103" groupAlignment="3" attributes="0"> <Component id="hidePlotButton" alignment="3" min="-2" max="-2" attributes="0"/> <Component id="showPlotButton" alignment="3" min="-2" max="-2" attributes="0"/> </Group> <EmptySpace min="-2" pref="14" max="-2" attributes="0"/> <Component id="exitButton" min="-2" max="-2" attributes="0"/> <EmptySpace min="-2" pref="84" max="-2" attributes="0"/> </Group> </Group> </DimensionLayout> </Layout> <SubComponents> <Component class="javax.swing.JTextField" name="startX"> <Properties> <Property name="text" type="java.lang.String" value="-2.5"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel1"> <Properties> <Property name="text" type="java.lang.String" value="Start x value"/> </Properties> </Component> <Component class="javax.swing.JTextField" name="endX"> <Properties> <Property name="text" type="java.lang.String" value="10"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel2"> <Properties> <Property name="text" type="java.lang.String" value="End x value"/> </Properties> </Component> <Component class="javax.swing.JTextField" name="formulaY"> <Properties> <Property name="text" type="java.lang.String" value="x^2"/> </Properties> </Component> <Component class="javax.swing.JLabel" name="jLabel3"> <Properties> <Property name="text" type="java.lang.String" value="Formula for y in terms of x"/> </Properties> </Component> <Component class="javax.swing.JButton" name="showPlotButton"> <Properties> <Property name="text" type="java.lang.String" value="Show Plot"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="showPlotButtonActionPerformed"/> </Events> </Component> <Component class="javax.swing.JButton" name="hidePlotButton"> <Properties> <Property name="text" type="java.lang.String" value="Hide Plot"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="hidePlotButtonActionPerformed"/> </Events> </Component> <Component class="javax.swing.JButton" name="exitButton"> <Properties> <Property name="text" type="java.lang.String" value="Exit"/> </Properties> <Events> <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitButtonActionPerformed"/> </Events> </Component> </SubComponents> </Form> --- NEW FILE: RunMe2.java --- /* * RunMe2.java * * $Header: /cvsroot/icamodel/WrapR/src/wrapr/examples/RunMe2.java,v 1.1 2007/07/13 08:45:59 richardpercy Exp $ * $Revision: 1.1 $ * $Date: 2007/07/13 08:45:59 $ */ package wrapr.examples; import java.io.File; import javax.swing.JOptionPane; import wrapr.*; /** * * @author richard */ public class RunMe2 extends javax.swing.JFrame { /** * Creates new form RunMe2 */ public RunMe2() { eg1 = new Examples(); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { startX = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); endX = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); formulaY = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); showPlotButton = new javax.swing.JButton(); hidePlotButton = new javax.swing.JButton(); exitButton = new javax.swing.JButton(); mainMenu = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); exitMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("WrapR Example 2"); startX.setText("-2.5"); jLabel1.setText("Start x value"); endX.setText("10"); jLabel2.setText("End x value"); formulaY.setText("x^2"); jLabel3.setText("Formula for y in terms of x"); showPlotButton.setText("Show Plot"); showPlotButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { showPlotButtonActionPerformed(evt); } }); hidePlotButton.setText("Hide Plot"); hidePlotButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hidePlotButtonActionPerformed(evt); } }); exitButton.setText("Exit"); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); } }); fileMenu.setText("File"); exitMenuItem.setText("Exit"); exitMenuItem.setToolTipText("Guess what this does"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); mainMenu.add(fileMenu); setJMenuBar(mainMenu); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(showPlotButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(exitButton) .addComponent(hidePlotButton))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(startX) .addComponent(endX, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(formulaY, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(30, 30, 30)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(startX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(endX, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(formulaY, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(hidePlotButton) .addComponent(showPlotButton)) .addGap(14, 14, 14) .addComponent(exitButton) .addGap(84, 84, 84)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void hidePlotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hidePlotButtonActionPerformed hideGraphics(); }//GEN-LAST:event_hidePlotButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { // Ensure RFunction knows where to find R source files RFunction.setRootPath("src" + File.separator + "R"); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RunMe2().setVisible(true); } }); } private void showPlotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showPlotButtonActionPerformed try{ eg1.showPlot( Double.valueOf(startX.getText()), Double.valueOf(endX.getText()), formulaY.getText()); } catch (RCodeException rex) { JOptionPane.showMessageDialog(null, rex.getRErrorMessage(), "Error in R code", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_showPlotButtonActionPerformed private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed hideGraphics(); System.exit(0); }//GEN-LAST:event_exitButtonActionPerformed private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed hideGraphics(); System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void hideGraphics() { try{ eg1.hideGraphics(); } catch (RCodeException rex) { JOptionPane.showMessageDialog(null, rex.getRErrorMessage(), "Error in R code", JOptionPane.ERROR_MESSAGE); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField endX; private javax.swing.JButton exitButton; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JMenu fileMenu; private javax.swing.JTextField formulaY; private javax.swing.JButton hidePlotButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenuBar mainMenu; private javax.swing.JButton showPlotButton; private javax.swing.JTextField startX; // End of variables declaration//GEN-END:variables // Some more privates Examples eg1; } --- NEW FILE: RunMe1.java --- /* * RunMe1.java * * $Header: /cvsroot/icamodel/WrapR/src/wrapr/examples/RunMe1.java,v 1.1 2007/07/13 08:45:59 richardpercy Exp $ * $Revision: 1.1 $ * $Date: 2007/07/13 08:45:59 $ */ /** * * @author richard */ package wrapr.examples; import java.io.File; import java.io.IOException; import java.util.Arrays; import wrapr.RCodeException; import wrapr.RCommands; import wrapr.RFunction; public class RunMe1 { /** * Creates a new instance of RunMe1 */ public RunMe1() { } /** * @param args the command line arguments */ public static void main(String[] args) { // Ensure RFunction knows where to find R source files RFunction.setRootPath("src" + File.separator + "R"); try{ Examples e1 = new Examples(); e1.runCommands(); e1.runFunctions(); } catch (RCodeException rex) { rex.printStackTrace(); System.exit(1); } System.exit(0); } } --- Main.java DELETED --- --- Example1.java DELETED --- --- NEW FILE: Examples.java --- /* * Examples.java * * $Header: /cvsroot/icamodel/WrapR/src/wrapr/examples/Examples.java,v 1.1 2007/07/13 08:45:59 richardpercy Exp $ * $Revision: 1.1 $ * $Date: 2007/07/13 08:45:59 $ */ package wrapr.examples; import java.util.Arrays; import wrapr.*; /** * * @author richard */ public class Examples { /** * Creates a new instance of Examples */ public Examples() { // We have one R source file that contains all functions RFunction rf = new RFunction(this); rf.declare(); } public void runCommands(){ //causes exception //double i = RCommands.execDouble("as.integer(2^2)"); //System.out.println(i); double d = RCommands.execDouble("sqrt(2)"); System.out.println(d); double da[] = RCommands.execDoubleArray("sqrt(c(2,3))"); System.out.println(Arrays.toString(da)); RCommands.exec("chav=3"); boolean b = RCommands.execBooleanBuiltin("exists('chav')"); System.out.println(b); b = RCommands.execBooleanBuiltin("exists('chavette')"); System.out.println(b); RCommands.exec("sqrt(2))"); // should produce syntax error - reported to rosuda //RCommands.exec("sqrt(funky)"); //produces error - OK } public void runFunctions(){ RFunction rf1 = new RFunction(this, "testMe1"); double arg1 = 2.51; double arg2 = 77.03; // double res1 = rf1.callDouble("rubbish",Double.toString(arg2)); double res1 = rf1.callDouble(arg1,arg2); System.out.println(res1); double[] arg3 = new double[] {1.0, 2.0}; double[] arg4 = new double[] {5.0, 10.0}; double[] res2 = rf1.callDoubleArray("c" + RFunction.glueArgs(arg3),"c" + RFunction.glueArgs(arg4)); System.out.println(Arrays.toString(res2)); String[] arg5 = new String[] {"aaaa", "bbbbbbb"}; System.out.println(RFunction.glueArgs(arg5)); RFunction rf2 = new RFunction(this, "testMe2"); System.out.println(Arrays.toString(rf2.callDoubleArray("c(3,4)"))); } /** Creates a simple plot in a new window using the R library JavaGD * args startX lower limit of x values * args endX lower limit of y values * args formulaY formula for y in terms of x that R can understand, such as "x^2" */ public void showPlot(double startX, double endX, String formulaY) { RFunction rf1 = new RFunction(this, "showPlot1"); /* In this instance we have to surround the text string with R quotes * because we are mixing argument types in rf1.call() */ rf1.call(startX, endX, '\'' + formulaY + '\''); } /** Closes all graphics devices */ public void hideGraphics(){ RFunction rf3 = new RFunction(this,"hideGraphics"); rf3.call(); } } |
|
From: Richard P. <ric...@us...> - 2007-07-13 08:46:55
|
Update of /cvsroot/icamodel/WrapR/src/wrapr In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv7824/wrapr Modified Files: RFunction.java Log Message: no message Index: RFunction.java =================================================================== RCS file: /cvsroot/icamodel/WrapR/src/wrapr/RFunction.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RFunction.java 9 Jun 2007 14:32:39 -0000 1.1.1.1 --- RFunction.java 13 Jul 2007 08:46:00 -0000 1.2 *************** *** 18,22 **** * An RFunction expects the user to provide a corresponding file of R code. * The source file must have a name in the form rootPath\className[-methodName].R, ! * where className includes the full package name with periods replaced by hyphens. * <p> * Note that -methodName can be omitted if the --- 18,22 ---- * An RFunction expects the user to provide a corresponding file of R code. * The source file must have a name in the form rootPath\className[-methodName].R, ! * where className doesn't include the full package name. * <p> * Note that -methodName can be omitted if the *************** *** 26,30 **** * but it is normally best to wrap the latter with accessor functions so that they can * be called by corresponding methods in the calling Java class. ! * The methods should have a name of the form methodName.className * <p> * <b>Typical usage:</b><br> --- 26,31 ---- * but it is normally best to wrap the latter with accessor functions so that they can * be called by corresponding methods in the calling Java class. ! * The methods should have a name of the form methodName.className, which is the normal ! * convention in R. * <p> * <b>Typical usage:</b><br> *************** *** 60,64 **** */ public RFunction(Object requestor, String methodName) throws RCodeException { ! this.className = requestor.getClass().getName(); this.methodName = methodName; String rootPath = getRootPath(); --- 61,66 ---- */ public RFunction(Object requestor, String methodName) throws RCodeException { ! String s = requestor.getClass().getName(); ! this.className = s.substring(1 + s.lastIndexOf('.')); this.methodName = methodName; String rootPath = getRootPath(); *************** *** 76,80 **** */ public RFunction(Object requestor) throws RCodeException { ! this.className = requestor.getClass().getName(); this.methodName = null; String rootPath = getRootPath(); --- 78,83 ---- */ public RFunction(Object requestor) throws RCodeException { ! String s = requestor.getClass().getName(); ! this.className = s.substring(1 + s.lastIndexOf('.')); this.methodName = null; String rootPath = getRootPath(); |
|
From: Richard P. <ric...@us...> - 2007-07-13 08:46:55
|
Update of /cvsroot/icamodel/WrapR/src/R In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv7824/R Added Files: Examples.R Removed Files: wrapr-examples-Example1.R Log Message: no message --- NEW FILE: Examples.R --- testMe1.Examples = function(arg1, arg2) { return(arg1 * arg2) } testMe2.Examples = function(num) { return(num^2) } # Opens a Java graphics window and plots a chart. # You must have installed the JavaGD package from the CRAN before running this. # startX is the starting x value # endX is the ending x value # formulaY is a text string representing an expression that R will be able to parse showPlot1.Examples = function(startX, endX, formulaY) { if(is.null(dev.list())) { require(JavaGD) JavaGD(name="Java Graphics with Java Swing, JRI and JavaGD") } x = startX:endX e = parse(text = formulaY) plot(x, eval(e), ylab = 'y', title='rubbish') } # Closes all graphics devices hideGraphics.Examples = function() { graphics.off() } --- wrapr-examples-Example1.R DELETED --- |
|
From: Richard P. <ric...@us...> - 2007-07-06 21:06:15
|
Update of /cvsroot/icamodel/WrapR/nbproject In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv23400/nbproject Modified Files: project.properties Log Message: no message Index: project.properties =================================================================== RCS file: /cvsroot/icamodel/WrapR/nbproject/project.properties,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** project.properties 9 Jun 2007 14:32:38 -0000 1.1.1.1 --- project.properties 6 Jul 2007 21:06:14 -0000 1.2 *************** *** 19,23 **** jar.compress=false javac.classpath=\ ! ${libs.JRI.classpath} # Space-separated list of extra javac options javac.compilerargs= --- 19,24 ---- jar.compress=false javac.classpath=\ ! ${libs.JRI.classpath}:\ ! ${libs.JavaGD.classpath} # Space-separated list of extra javac options javac.compilerargs= |
|
From: Richard P. <ric...@us...> - 2007-07-06 21:06:15
|
Update of /cvsroot/icamodel/WrapR/src/wrapr/examples In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv23400/src/wrapr/examples Modified Files: Example1.java Log Message: no message Index: Example1.java =================================================================== RCS file: /cvsroot/icamodel/WrapR/src/wrapr/examples/Example1.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** Example1.java 9 Jun 2007 14:32:39 -0000 1.1.1.1 --- Example1.java 6 Jul 2007 21:06:13 -0000 1.2 *************** *** 88,96 **** System.out.println(Arrays.toString(rf2.callDoubleArray("c(3,4)"))); ! /* this bit doesn't work yet RFunction rf3 = new RFunction(this, "showGraphics1"); rf3.call(); try{ ! TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e){ --- 88,96 ---- System.out.println(Arrays.toString(rf2.callDoubleArray("c(3,4)"))); ! // this bit doesn't work yet RFunction rf3 = new RFunction(this, "showGraphics1"); rf3.call(); try{ ! TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e){ *************** *** 99,103 **** System.out.println("finished sleeping"); rf3 = new RFunction(this,"hideGraphics"); ! */ } --- 99,104 ---- System.out.println("finished sleeping"); rf3 = new RFunction(this,"hideGraphics"); ! rf3.call(); ! // } |
|
From: Louise P. <lm...@us...> - 2007-06-24 16:09:37
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/framework In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv8442/src/icamodel/framework Modified Files: BusinessLine.java ModelBit.java Parameters.java RandomNumberGenerator.java Log Message: XML parameter file. Needed to standardise some things: All ModelBits must have 1-arg constructor All parameter setting must be via single arg setter Index: ModelBit.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/ModelBit.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ModelBit.java 23 Jun 2007 18:20:47 -0000 1.3 --- ModelBit.java 24 Jun 2007 16:09:35 -0000 1.4 *************** *** 28,31 **** --- 28,33 ---- * Basic model element. A node in the tree. This just provides the basic * mechanism. Concrete subclasses must override the abstract methods. + * Subclasses must be in package icamodel.bits (else they won't be found when we parse the parameter file). + * they must also have a constructor that takes a single string argument (the name). * * @author Louise Index: RandomNumberGenerator.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/RandomNumberGenerator.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RandomNumberGenerator.java 16 May 2007 16:42:31 -0000 1.3 --- RandomNumberGenerator.java 24 Jun 2007 16:09:35 -0000 1.4 *************** *** 12,16 **** /** ! * something that'll get random numbers for us * @author Louise */ --- 12,18 ---- /** ! * something that'll get random numbers for us. ! * Subclasses must be in package icamodel.utils (else they won't be found when we parse the parameter file). ! * They must also have a default constructor (ie, one without arguments). * @author Louise */ Index: Parameters.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/Parameters.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Parameters.java 24 Jun 2007 10:45:15 -0000 1.1 --- Parameters.java 24 Jun 2007 16:09:35 -0000 1.2 *************** *** 11,20 **** --- 11,33 ---- package icamodel.framework; + import icamodel.bits.Assets; + import icamodel.bits.External; + import icamodel.bits.Liabilities; + import icamodel.bits.ModelRoot; + import icamodel.utils.InitialisationException; + import icamodel.utils.ModelException; + import icamodel.utils.PaymentPattern; import java.io.File; import java.io.IOException; + import java.lang.reflect.Constructor; + import java.lang.reflect.InvocationTargetException; + import java.lang.reflect.Method; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; + import org.w3c.dom.Element; + import org.w3c.dom.Node; + import org.w3c.dom.NodeList; import org.xml.sax.SAXException; *************** *** 77,83 **** /** * build our model from the Document that's been created */ ! public void buildModel() { } } --- 90,496 ---- /** * build our model from the Document that's been created + * hard code in the (required) top level nodes. All others are + * done as generic ModelBits. */ ! public void buildModel() throws InitialisationException, ModelException { ! ! // we expect the root to be <model> and there to be only one of them ! NodeList kids = paramTree.getChildNodes(); ! Node kid = null; ! for (int i=0; i<kids.getLength(); i++) { ! if (kids.item(i).getNodeType() == Node.ELEMENT_NODE) { ! if (kid != null) { ! // we already have an element. Something has gone wrong ! throw new InitialisationException("Your model must have only one root."); ! } else { ! kid = kids.item(i); ! } ! } else if (kids.item(i).getNodeType() != Node.COMMENT_NODE && ! kids.item(i).getNodeType() != Node.TEXT_NODE) { ! throw new InitialisationException("Unexpected entry: " + kids.item(i)); ! } ! } ! ! Element modelElement = (Element) kid; ! if (modelElement.getTagName() != "model") { ! throw new InitialisationException("The model root must be a <model> element. Your file has <" + ! modelElement.getTagName() +">."); ! } ! ! // OK, we're OK so far. ! kids = modelElement.getChildNodes(); ! ModelRoot root = ModelRoot.getInstance(); ! // It should have some parameters ! setParameters( root, kids); ! ! // now we do the children: External, Liabilities, Assets, Corporate, BusinessLogic ! Element extElement = null; ! Element liabElement = null; ! Element assElement = null; ! Element corpElement = null; ! Element busElement = null; ! for (int i=0; i < kids.getLength(); i++) { ! if (kids.item(i).getNodeType() != Node.ELEMENT_NODE ) { ! continue; // skip this one ! } ! Element elt = (Element) kids.item(i); ! if (elt.getTagName().equals("external")) { ! if (extElement != null) { ! throw new InitialisationException("You have more than one <external> node."); ! } ! extElement = elt; ! } else if (elt.getTagName().equals("liabilities")) { ! if (liabElement != null) { ! throw new InitialisationException("You have more than one <liabilities> node."); ! } ! liabElement = elt; ! } else if (elt.getTagName().equals("assets")) { ! if (assElement != null) { ! throw new InitialisationException("You have more than one <assets> node."); ! } ! assElement = elt; ! } else if (elt.getTagName().equals("corporate")) { ! if (corpElement != null) { ! throw new InitialisationException("You have more than one <corporate> node."); ! } ! corpElement = elt; ! } else if (elt.getTagName().equals("businessLogic")) { ! if (busElement != null) { ! throw new InitialisationException("You have more than one <businessLogic> node."); ! } ! busElement = elt; ! } else if (elt.getTagName().equals("param")){ ! continue; // not interested in this one ! } else { ! throw new InitialisationException("Unexpected tag: <elt.getTagName()>."); ! } ! } // we've now dealt with all the Element children ! ! // do the External one. ! if (extElement != null) { ! buildExternalModelBit(extElement); ! } ! // do the Liabilities one. ! if (liabElement != null) { ! buildLiabilitiesModelBit(liabElement); ! } ! // do the Assets one. ! if (assElement != null) { ! buildAssetsModelBit(assElement); ! } ! } ! ! /** ! * We expect a random number generator, plus ModelBit children. No parameters at present, but ! * there might be later ! */ ! private static void buildExternalModelBit(Element extElement) ! throws InitialisationException, ModelException { ! External ext = External.getInstance(); ! NodeList kids = extElement.getChildNodes(); ! setParameters(ext, kids); ! for (int i = 0; i < kids.getLength(); i++) { ! if (kids.item(i).getNodeType() != Node.ELEMENT_NODE ) { ! continue; // skip this one ! } ! Element kid = (Element) kids.item(i); ! if (kid.getTagName().equals("randomNumberGenerator")) { ! buildRandomNumberGenerator(ext, kid); ! } else if (kid.getTagName().equals("modelBit")) { ! addModelBit(ext, kid); ! } else if (kid.getTagName().equals("param")) { ! continue; ! } else { ! throw new InitialisationException("Unrecognised tag <" + kid.getTagName() + ">"); ! } ! } ! } ! ! /** ! * We only expect params and modelBits ! */ ! private static void buildLiabilitiesModelBit(Element liabElement) ! throws InitialisationException, ModelException { ! ! Liabilities liabs = Liabilities.getInstance(); ! NodeList kids = liabElement.getChildNodes(); ! setParameters(liabs, kids); ! for (int i = 0; i < kids.getLength(); i++) { ! if (kids.item(i).getNodeType() != Node.ELEMENT_NODE ) { ! continue; // skip this one ! } ! Element kid = (Element) kids.item(i); ! if (kid.getTagName().equals("modelBit")) { ! addModelBit(liabs, kid); ! } else if (kid.getTagName().equals("param")) { ! continue; ! } else { ! throw new InitialisationException("Unrecognised tag <" + kid.getTagName() + ">"); ! } ! } ! ! } ! /** ! * We only expect params and modelBits ! */ ! private static void buildAssetsModelBit(Element assElement) ! throws InitialisationException, ModelException { ! ! Assets assets = Assets.getInstance(); ! NodeList kids = assElement.getChildNodes(); ! setParameters(assets, kids); ! for (int i = 0; i < kids.getLength(); i++) { ! if (kids.item(i).getNodeType() != Node.ELEMENT_NODE ) { ! continue; // skip this one ! } ! Element kid = (Element) kids.item(i); ! if (kid.getTagName().equals("modelBit")) { ! addModelBit(assets, kid); ! } else if (kid.getTagName().equals("param")) { ! continue; ! } else { ! throw new InitialisationException("Unrecognised tag <" + kid.getTagName() + ">"); ! } ! } } + + private static void buildRandomNumberGenerator(External ext, Element rngElement) + throws InitialisationException { + + String rngType = rngElement.getAttribute("type"); + if (rngType == "") { + throw new InitialisationException("<randomNumberGenerator> element must have a type"); + } + Class<?> rngClass = null; + try { + rngClass = Class.forName("icamodel.utils." + rngType); + } catch (ClassNotFoundException ex) { + throw new InitialisationException("Invalid type for random number generator: " + rngType, ex); + } + Object rng = null; + try { + rng = rngClass.newInstance(); + } catch (InstantiationException ex) { + throw new InitialisationException("Problem making object of class " + rngType); + } catch (IllegalAccessException ex) { + throw new InitialisationException("Problem making object of class " + rngType); + } + // check that it is a subclass of RandomNumberGenerator + if (! (rng instanceof RandomNumberGenerator)) { + throw new InitialisationException(rngType + " is not a valid random number generator."); + } + setParameters(rng, rngElement.getChildNodes()); + ext.setRandomNumberGenerator((RandomNumberGenerator) rng); + } + + /** + * A modelBit tag can contain other modelBit tags and param tags. + */ + private static void addModelBit(ModelBit parent, Element mbElement) + throws InitialisationException, ModelException { + String mbName = mbElement.getAttribute("name"); + if (mbName == "") { + throw new InitialisationException("<modelBit> element must have a name"); + } + String mbType = mbElement.getAttribute("type"); + if (mbType == "") { + throw new InitialisationException(mbName + ": <modelBit> element must have a type"); + } + Class<?> mbClass = null; + try { + mbClass = Class.forName("icamodel.bits." + mbType); + } catch (ClassNotFoundException ex) { + throw new InitialisationException("Invalid type for modelBit: " + mbType, ex); + } + Constructor<?> mbConstructor = null; + try { + mbConstructor = mbClass.getConstructor(String.class); + } catch (NoSuchMethodException ex) { + throw new InitialisationException("Can't create instance of " + mbType, ex); + } + Object mbObj = null; + try { + mbObj = mbConstructor.newInstance(mbName); + } catch (InstantiationException ex) { + throw new InitialisationException("Can't create instance of " + mbType, ex); + } catch (IllegalAccessException ex) { + throw new InitialisationException("Can't create instance of " + mbType, ex); + } catch (InvocationTargetException ex) { + throw new InitialisationException("Can't create instance of " + mbType, ex); + } + if (! (mbObj instanceof ModelBit)) { + throw new InitialisationException("Invalid type for modelBit: " + mbType); + } + + ModelBit mBit = (ModelBit) mbObj; + // We've created the object and it is a model bit + // Now set its parameters, then add it to the tree. + // finally, do its children. + NodeList kids = mbElement.getChildNodes(); + setParameters(mbObj, kids); + parent.addChild(mBit); + + for (int i = 0; i < kids.getLength(); i++) { + if (kids.item(i).getNodeType() != Node.ELEMENT_NODE ) { + continue; // skip this one + } + Element kid = (Element) kids.item(i); + if (kid.getTagName().equals("modelBit")) { + addModelBit(mBit, kid); + } else if (kid.getTagName().equals("param")) { + continue; + } else { + throw new InitialisationException("Unrecognised tag <" + kid.getTagName() + ">"); + } + } + } + /** + * set some parameters of an object (usually a ModelBit). + * the id attribute of the element says what method to use + * the type attribute says how to interpret the value + * the text inside the element is the value + * TODO: more useful error messages + **/ + private static void setParameters(Object mBit, NodeList paramElements) throws InitialisationException { + // first we get all the methods that the modelBit has + Class<?> mClass = mBit.getClass(); + Method[] meths = mClass.getMethods(); + + // now go through the params + int paramCount = paramElements.getLength(); + for (int i=0; i < paramCount; i++) { + if (paramElements.item(i).getNodeType() != Node.ELEMENT_NODE ) { + continue; // skip this one + } + Element paramElt = (Element) paramElements.item(i); + if (! paramElt.getTagName().equals("param")) { + continue; // not interested in this one + } + setParameter(mBit, paramElt, meths); + } + } + + private static void setParameter(Object mBit, Element paramElt, Method[] meths) throws InitialisationException { + String id = paramElt.getAttribute("id"); + if (id == "") { + throw new InitialisationException("<param> element must have an id"); + } + Method setterMethod = null; + for (int j=0; j< meths.length; j++) { + Method thisMethod = meths[j]; + if (thisMethod.getName().equals("set" + id)) { + setterMethod = thisMethod; + break; + } + } + if (setterMethod == null) { + throw new InitialisationException("Invalid id in <param> element (" + id + ")."); + } + // OK, we've got a method. Now let's try to use it + Object realVal = getTypedParamValue(paramElt); + // apply + try { + setterMethod.invoke(mBit, realVal); + } catch (IllegalAccessException ex) { + throw new InitialisationException("Invalid value (" + + realVal + ") for parameter " + id + ".", + ex); + } catch (InvocationTargetException ex) { + throw new InitialisationException("Invalid value (" + + realVal + ") for parameter " + id + ".", + ex); + + } catch (IllegalArgumentException ex) { + throw new InitialisationException("Invalid value (" + + realVal + ") for parameter " + id + ".", + ex); + } + } + + private static Object getTypedParamValue(Element paramElt) throws InitialisationException { + String paramType = paramElt.getAttribute("type"); + if (paramType == "") { + throw new InitialisationException("<param> element must have a type"); + } + // for most params the actual value is in the text + String textVal = paramElt.getTextContent(); + // convert it + Object ans = null; + try { + if (paramType.equals("integer")) { + ans = Integer.parseInt(textVal.trim()); + } else if (paramType.equals("number")) { + ans = Double.parseDouble(textVal.trim()); + } else if (paramType.equals("listString")) { + String[] slist = textVal.trim().split(","); + for (int i = 0; i < slist.length; i++) { + slist[i] = slist[i].trim(); + } + ans = slist; + } else if (paramType.equals("listInteger")) { + String[] slist = textVal.trim().split(","); + int[] ilist = new int[slist.length]; + for (int i = 0; i < slist.length; i++) { + ilist[i] = Integer.parseInt(slist[i].trim()); + } + ans = ilist; + } else if (paramType.equals("listNumber") || paramType.equals("range")) { + String[] slist = textVal.trim().split(","); + if (paramType.equals("range") && slist.length != 2) { + throw new InitialisationException("A range must have 2 elements."); + } + double[] dlist = new double[slist.length]; + for (int i = 0; i < slist.length; i++) { + dlist[i] = Double.parseDouble(slist[i].trim()); + } + ans = dlist; + } else if (paramType.equals("paymentPattern")) { + PaymentPattern.Incidence inc = PaymentPattern.Incidence.EVEN; + double[] dlist = null; + NodeList kids = paramElt.getChildNodes(); + for (int j =0; j < kids.getLength(); j++) { + if (kids.item(j).getNodeType() != Node.ELEMENT_NODE) { + continue; // skip this one + } + Element kid = (Element) kids.item(j); + if (kid.getTagName().equals("incidence")) { + String iString = kid.getTextContent().trim(); + if (iString.equalsIgnoreCase("EVEN")) { + inc = PaymentPattern.Incidence.EVEN; + } else if (iString.equalsIgnoreCase("FRONT")) { + inc = PaymentPattern.Incidence.FRONT; + } else if (iString.equalsIgnoreCase("OTHER")) { + inc = PaymentPattern.Incidence.OTHER; + } else { + throw new InitialisationException("Unrecognised incidence type: " + iString); + } + } else if (kid.getTagName().equals("values")) { + // the value is a list of doubles + String[] slist = kid.getTextContent().trim().split(","); + dlist = new double[slist.length]; + for (int i = 0; i < slist.length; i++) { + dlist[i] = Double.parseDouble(slist[i].trim()); + } + } + } + if (dlist == null) { + throw new InitialisationException("Missing values in PaymentPattern " + + paramElt.getAttribute("id")); + } + ans = new PaymentPattern(inc, dlist); + + } else { + throw new InitialisationException("Unrecognised parameter type: " + paramType); + } + } catch (NumberFormatException ex) { + throw new InitialisationException("Invalid parameter value: " + textVal, ex); + } + return ans; + } + + private static boolean nodeHasOneChild(Node n) { + NodeList kids = n.getChildNodes(); + return (kids.getLength() == 1); + } } Index: BusinessLine.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/framework/BusinessLine.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** BusinessLine.java 24 Mar 2007 19:33:30 -0000 1.2 --- BusinessLine.java 24 Jun 2007 16:09:35 -0000 1.3 *************** *** 68,73 **** * Each represents proportion of contracts incepting in time period from start of projection. */ ! public void setInceptionPattern(PaymentPattern.Incidence incidence, double... args) { ! inceptionPattern = new PaymentPattern(incidence, args); writingDelayPattern = new PaymentPattern(PaymentPattern.Incidence.FRONT, 1.0); writingPattern = PaymentPattern.compoundPatterns(inceptionPattern, writingDelayPattern); --- 68,73 ---- * Each represents proportion of contracts incepting in time period from start of projection. */ ! public void setInceptionPattern(PaymentPattern pattern) { ! inceptionPattern = pattern; writingDelayPattern = new PaymentPattern(PaymentPattern.Incidence.FRONT, 1.0); writingPattern = PaymentPattern.compoundPatterns(inceptionPattern, writingDelayPattern); *************** *** 81,86 **** * Each element represents proportion of each contract's risk exposure in time period from inception. */ ! public void setExposureDelayPattern(PaymentPattern.Incidence incidence, double... args) { ! exposureDelayPattern = new PaymentPattern(incidence, args); exposurePattern = PaymentPattern.compoundPatterns(inceptionPattern, exposureDelayPattern); earningDelayPattern = new PaymentPattern(exposureDelayPattern); --- 81,86 ---- * Each element represents proportion of each contract's risk exposure in time period from inception. */ ! public void setExposureDelayPattern(PaymentPattern pattern) { ! exposureDelayPattern = pattern; exposurePattern = PaymentPattern.compoundPatterns(inceptionPattern, exposureDelayPattern); earningDelayPattern = new PaymentPattern(exposureDelayPattern); *************** *** 94,99 **** * Each represents proportion of each contract's premiums received in time period from inception. */ ! public void setPremiumReceiptDelayPattern(PaymentPattern.Incidence incidence, double... args) { ! receiptDelayPattern = new PaymentPattern(incidence, args); receiptPattern = PaymentPattern.compoundPatterns(inceptionPattern, receiptDelayPattern); } --- 94,99 ---- * Each represents proportion of each contract's premiums received in time period from inception. */ ! public void setPremiumReceiptDelayPattern(PaymentPattern pattern) { ! receiptDelayPattern = pattern; receiptPattern = PaymentPattern.compoundPatterns(inceptionPattern, receiptDelayPattern); } |
|
From: Louise P. <lm...@us...> - 2007-06-24 16:09:37
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/utils In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv8442/src/icamodel/utils Modified Files: NonRandomNumberGenerator.java Log Message: XML parameter file. Needed to standardise some things: All ModelBits must have 1-arg constructor All parameter setting must be via single arg setter Index: NonRandomNumberGenerator.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/utils/NonRandomNumberGenerator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** NonRandomNumberGenerator.java 26 Jan 2007 16:57:01 -0000 1.2 --- NonRandomNumberGenerator.java 24 Jun 2007 16:09:35 -0000 1.3 *************** *** 21,30 **** private double fixed; ! /** ! * Creates a new instance of NonRandomNumberGenerator ! * @param number the non-random number ! * @throws icamodel.utils.ModelException if there's a problem ! */ ! public NonRandomNumberGenerator(double number) throws ModelException { if (number < 0 || number > 1) { throw new ModelException("Non random number must be between 0 and 1"); --- 21,25 ---- private double fixed; ! public void setFixedNumber(double number) throws ModelException { if (number < 0 || number > 1) { throw new ModelException("Non random number must be between 0 and 1"); |
|
From: Louise P. <lm...@us...> - 2007-06-24 16:09:37
|
Update of /cvsroot/icamodel/icamodel/data In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv8442/data Added Files: example-params.xml Removed Files: params.xml Log Message: XML parameter file. Needed to standardise some things: All ModelBits must have 1-arg constructor All parameter setting must be via single arg setter --- params.xml DELETED --- --- NEW FILE: example-params.xml --- <?xml version='1.0' encoding='utf-8'?> <!-- Copy this file to params.xml and edit to taste. Basic format Required modelBits don't have names. They may have types. In each modelBit, specify its own parameters first. Then specify its required children (which usually have their own tags). Then specify its generic children, using the modelBit tag. --> <model> <param id="TotalRealisations" type="integer"> 10 </param> <param id="TimePeriodsPerRealisation" type="integer"> 5 </param> <param id="TimePeriodsPerYear" type="integer"> 1 </param> <!-- external --> <external> <randomNumberGenerator type="BasicRandomNumberGenerator"> <!-- depending on the type of RNG, might have params in here --> </randomNumberGenerator> <!-- can only have one interest rate <modelBit name="intRate4%" type="FixedInterestRate"> <param id="Rate" type="number"> 0.04 </param> </modelBit> --> <modelBit name="Maynardius Maximus" type="StochTotalReturn"> <param id="Names" type="listString"> cash, equity, gilt, property </param> <param id="Means" type="listNumber"> 0.04, 0.07, 0.05, 0.065 </param> <param id="Mixes" type="listNumber"> 0.2, 0.3, 0.4, 0.1 </param> <param id="Corrs" type="listNumber"> 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.3, 0.1, 0.0, 0.3, 1.0, 0.1, 0.0, 0.1, 0.1, 1.0 </param> </modelBit> </external> <!-- liabilities --> <liabilities> <modelBit name="BLine1" type="BusinessLineConstant"> <param type="paymentPattern" id="InceptionPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="ExposureDelayPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="PremiumReceiptDelayPattern"> <incidence>Front</incidence> <values>1.0</values> </param> <param id="ExposureUnits" type="number"> 1.0 </param> <param id="PremiumRate" type="number"> 1.0 </param> <modelBit name="LType1" type="LossTypeConstant"> <param id="ConstantLossAmount" type="number"> 1.0 </param> <param id="ClaimsPaymentPattern" type="listNumber"> 1.0, 2.0 </param> </modelBit> <!-- end of LType1 --> </modelBit> <!-- end of BLine1 --> <modelBit name="Bline2" type="BusinessLineConstant"> <!-- this one has half exposure & premium in each of first 2 periods --> <param type="paymentPattern" id="InceptionPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="ExposureDelayPattern"> <incidence>Even</incidence> <values>1.0,1.0</values> </param> <param type="paymentPattern" id="PremiumReceiptDelayPattern"> <incidence>Front</incidence> <values>1.0,1.0</values> </param> <param id="ExposureUnits" type="number"> 3.0 </param> <param id="PremiumRate" type="number"> 2.0 </param> <modelBit name="LType2" type="LossTypeRange"> <param id="LossAmountBounds" type="range"> 1.5, 2.1 </param> <param id="ClaimsPaymentPattern" type="listNumber"> 1.0, 1.0, 1.0, 1.0 </param> </modelBit> <!-- end of LType1 --> </modelBit> <!-- end of Bline2 --> </liabilities> <!-- assets --> <assets> <modelBit name="Cash" type="CashPool"> <param id="InitialValue" type="number"> 300 </param> </modelBit> </assets> </model> |
|
From: Louise P. <lm...@us...> - 2007-06-24 16:09:35
|
Update of /cvsroot/icamodel/icamodel/src/icamodel In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv8442/src/icamodel Modified Files: ICAModel.java Log Message: XML parameter file. Needed to standardise some things: All ModelBits must have 1-arg constructor All parameter setting must be via single arg setter Index: ICAModel.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/ICAModel.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ICAModel.java 24 Jun 2007 10:45:12 -0000 1.6 --- ICAModel.java 24 Jun 2007 16:09:35 -0000 1.7 *************** *** 134,195 **** // TODO: different option for running the system, just lets you view // the model set up. // TODO: extend the viewer so you can edit the param file? ! // DOMEcho.makeFrame(theParams.getParamTree()); ! ! ! // global parameters ! ModelRoot root = ModelRoot.getInstance(); ! root.setTotalRealisations(10); ! root.setTimePeriodsPerRealisation(5); ! root.setTimePeriodsPerYear(1); ! ! // set up the external things ! External ext = External.getInstance(); ! // ModelBit thing1 = new FixedInterestRate("intRate4%", 0.04); // Louise original ! StochTotalReturn tr = new StochTotalReturn("Maynardius Maximus"); // Richard new ! tr.setNames(new String[] {"cash", "equity", "gilt", "property"}); ! tr.setMeans(new double [] {0.04, 0.07, 0.05, 0.065}); ! tr.setMixes(new double [] {0.2, 0.3, 0.4, 0.1}); ! tr.setCorrs(new double[] {1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.3, 0.1, 0.0, 0.3, 1.0, 0.1, 0.0, 0.1, 0.1, 1.0}); ! ext.addChild(tr); ! // RandomNumberGenerator rng = new NonRandomNumberGenerator(.04); ! RandomNumberGenerator rng = new BasicRandomNumberGenerator(); ! ext.setRandomNumberGenerator(rng); ! ! // set up the liabilities ! Liabilities liab = Liabilities.getInstance(); ! BusinessLineConstant bLine = new BusinessLineConstant("BLine1"); ! // all exposure and premium payment in first period - v simple! ! bLine.setInceptionPattern(PaymentPattern.Incidence.EVEN, 1.0); ! bLine.setExposureDelayPattern(PaymentPattern.Incidence.EVEN, 1.0); ! bLine.setPremiumReceiptDelayPattern(PaymentPattern.Incidence.FRONT, 1.0); // no delay in receiving cash ! bLine.setExposureUnits(1.0); ! bLine.setPremiumRate(1.0); ! liab.addChild(bLine); ! ! LossTypeConstant lType = new LossTypeConstant("LType1"); ! lType.setConstantLossAmount(1.0); ! lType.setClaimsPaymentPattern(1.0, 2.0); ! bLine.addChild(lType); ! ! bLine = new BusinessLineConstant("BLine2"); ! // this one has half exposure & premium in each of first 2 periods ! bLine.setInceptionPattern(PaymentPattern.Incidence.EVEN, 1.0); ! bLine.setExposureDelayPattern(PaymentPattern.Incidence.EVEN, 1.0,1.0); ! bLine.setPremiumReceiptDelayPattern(PaymentPattern.Incidence.FRONT, 1.0,1.0); // installments ! bLine.setExposureUnits(3.0); ! bLine.setPremiumRate(2.0); ! liab.addChild(bLine); ! ! LossTypeRange lType2 = new LossTypeRange("LType2", 1.5, 2.1); ! lType2.setClaimsPaymentPattern(1.0, 1.0, 1.0, 1.0); ! bLine.addChild(lType2); ! ! // set up the assets ! Assets ass = Assets.getInstance(); ! CashPool cash = new CashPool("Cash"); ! cash.setInitialValue(300); ! ass.addChild(cash); } --- 134,144 ---- // TODO: different option for running the system, just lets you view // the model set up. + // TODO: improve the viewer so you can actually see the model structure // TODO: extend the viewer so you can edit the param file? ! // DOMEcho.makeFrame(theParams.getParamTree()); + theParams.buildModel(); + + // TODO: give user a record of all the parameters } |
|
From: Louise P. <lm...@us...> - 2007-06-24 16:09:35
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/bits In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv8442/src/icamodel/bits Modified Files: LossTypeRange.java Log Message: XML parameter file. Needed to standardise some things: All ModelBits must have 1-arg constructor All parameter setting must be via single arg setter Index: LossTypeRange.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/bits/LossTypeRange.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** LossTypeRange.java 26 Jan 2007 14:40:30 -0000 1.1.1.1 --- LossTypeRange.java 24 Jun 2007 16:09:34 -0000 1.2 *************** *** 38,44 **** * @param upper the upper bound of the range */ ! public LossTypeRange(String name, double lower, double upper) { super(name); ! setLossAmountBounds(lower, upper); } --- 38,44 ---- * @param upper the upper bound of the range */ ! public LossTypeRange(String name, double... range) { super(name); ! setLossAmountBounds(range); } *************** *** 80,84 **** * @param upper the upper bound of the range */ ! public void setLossAmountBounds(double lower, double upper) { if (lower < 0) { throw new InitialisationException("Lower bound of loss amount per unit of exposure must be non negative, not " + lower); --- 80,89 ---- * @param upper the upper bound of the range */ ! public void setLossAmountBounds(double... range) { ! if (range.length != 2) { ! throw new InitialisationException("Loss amount range must have 2 elements, not " + range.length); ! } ! double lower = range[0]; ! double upper = range[1]; if (lower < 0) { throw new InitialisationException("Lower bound of loss amount per unit of exposure must be non negative, not " + lower); |
|
From: Louise P. <lm...@us...> - 2007-06-24 10:45:42
|
Update of /cvsroot/icamodel/icamodel/src/icamodel In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11230/src/icamodel Modified Files: ICAModel.java Log Message: First steps towards an XML parameter file Index: ICAModel.java =================================================================== RCS file: /cvsroot/icamodel/icamodel/src/icamodel/ICAModel.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ICAModel.java 23 Jun 2007 18:20:20 -0000 1.5 --- ICAModel.java 24 Jun 2007 10:45:12 -0000 1.6 *************** *** 116,122 **** --- 116,141 ---- /* * Set up the parameters by hand. Change this to change the parameters. + * TODO: allow user to specify which parameter file to use */ private static void setParameters() throws ModelException { + // Look for the parameter file. Should be data/params.xml + String fileName = "params.xml"; + String dirName = "data"; + File paramFile = new File(dirName + File.separator + fileName); + + System.out.println("Reading parameter file " + fileName); + Parameters theParams = Parameters.getInstance(); + theParams.readParamFile(paramFile); + + // We now have a DOM Document containing all the parameters. + // we could look at it, but the viewer isn't that helpful + // Also, it disappears when the program exits + // TODO: different option for running the system, just lets you view + // the model set up. + // TODO: extend the viewer so you can edit the param file? + // DOMEcho.makeFrame(theParams.getParamTree()); + + // global parameters ModelRoot root = ModelRoot.getInstance(); |
|
From: Louise P. <lm...@us...> - 2007-06-24 10:45:42
|
Update of /cvsroot/icamodel/icamodel/src/icamodel/utils In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11230/src/icamodel/utils Added Files: DOMEcho.java Log Message: First steps towards an XML parameter file --- NEW FILE: DOMEcho.java --- /* * DOMEcho.java * * Created on 24 June 2007, 11:02 * * $Header: /cvsroot/icamodel/icamodel/src/icamodel/utils/DOMEcho.java,v 1.1 2007/06/24 10:45:11 lmpryor Exp $ * $Revision: 1.1 $ * $Date: 2007/06/24 10:45:11 $ */ package icamodel.utils; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.border.BevelBorder; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreePath; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * A GUI for viewing a DOM. We could use it for looking at the parameters, but * quite honestly it's not that helpful as it is now. * Adapted from the java DOM tutorial * @author Louise */ public class DOMEcho extends JPanel { static final int windowHeight = 460; static final int leftWidth = 300; static final int rightWidth = 340; static final int windowWidth = leftWidth + rightWidth; /** Creates a new instance of DOMEcho */ public DOMEcho(Document domDoc) { // Make a nice border EmptyBorder eb = new EmptyBorder(5,5,5,5); BevelBorder bb = new BevelBorder(BevelBorder.LOWERED); CompoundBorder cb = new CompoundBorder(eb,bb); this.setBorder(new CompoundBorder(cb,eb)); // Set up the tree JTree tree = new JTree(new DomToTreeModelAdapter(domDoc)); // Iterate over the tree and make nodes visible // (Otherwise, the tree shows up fully collapsed) //TreePath nodePath = ???; // tree.expandPath(nodePath); // Build left-side view JScrollPane treeView = new JScrollPane(tree); treeView.setPreferredSize(new Dimension( leftWidth, windowHeight )); // Build right-side view JEditorPane htmlPane = new JEditorPane("text/html",""); htmlPane.setEditable(false); JScrollPane htmlView = new JScrollPane(htmlPane); htmlView.setPreferredSize(new Dimension( rightWidth, windowHeight )); // Build split-pane view JSplitPane splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, treeView, htmlView ); splitPane.setContinuousLayout( true ); splitPane.setDividerLocation( leftWidth ); splitPane.setPreferredSize(new Dimension( windowWidth + 10, windowHeight+10 )); // Add GUI components this.setLayout(new BorderLayout()); this.add("Center", splitPane ); } // An array of names for DOM node-types // (Array indexes = nodeType() values.) static final String[] typeName = { "none", "Element", "Attr", "Text", "CDATA", "EntityRef", "Entity", "ProcInstr", "Comment", "Document", "DocType", "DocFragment", "Notation", }; public static JFrame makeFrame(Document domDoc) { // Set up a GUI framework JFrame frame = new JFrame("DOM Echo"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} } ); // Set up the tree, the views, and display it all final DOMEcho echoPanel = new DOMEcho(domDoc); frame.getContentPane().add("Center", echoPanel ); frame.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int w = windowWidth + 10; int h = windowHeight + 10; frame.setLocation(screenSize.width/3 - w/2, screenSize.height/2 - h/2); frame.setSize(w, h); frame.setVisible(true); return frame; } // makeFrame // This class wraps a DOM node and returns the text we want to // display in the tree. It also returns children, index values, // and child counts. public class AdapterNode { org.w3c.dom.Node domNode; // Construct an Adapter node from a DOM node public AdapterNode(org.w3c.dom.Node node) { domNode = node; } // Return a string that identifies this node in the tree // *** Refer to table at top of org.w3c.dom.Node *** public String toString() { String s = typeName[domNode.getNodeType()]; String nodeName = domNode.getNodeName(); if (! nodeName.startsWith("#")) { s += ": " + nodeName; } if (domNode.getNodeValue() != null) { if (s.startsWith("ProcInstr")) s += ", "; else s += ": "; // Trim the value to get rid of NL's at the front String t = domNode.getNodeValue().trim(); int x = t.indexOf("\n"); if (x >= 0) t = t.substring(0, x); s += t; } return s; } /* * Return children, index, and count values */ public int index(AdapterNode child) { //System.err.println("Looking for index of " + child); int count = childCount(); for (int i=0; i<count; i++) { AdapterNode n = this.child(i); if (child.domNode == n.domNode) return i; } return -1; // Should never get here. } public AdapterNode child(int searchIndex) { //Note: JTree index is zero-based. org.w3c.dom.Node node = domNode.getChildNodes().item(searchIndex); return new AdapterNode(node); } public int childCount() { return domNode.getChildNodes().getLength(); } } // This adapter converts the current Document (a DOM) into // a JTree model. public class DomToTreeModelAdapter implements javax.swing.tree.TreeModel { private Document _domDoc; public DomToTreeModelAdapter(Document domDoc) { _domDoc = domDoc; } // Basic TreeModel operations public Object getRoot() { //System.err.println("Returning root: " +document); return new AdapterNode(_domDoc); } public boolean isLeaf(Object aNode) { // Determines whether the icon shows up to the left. // Return true for any node with no children AdapterNode node = (AdapterNode) aNode; if (node.childCount() > 0) return false; return true; } public int getChildCount(Object parent) { AdapterNode node = (AdapterNode) parent; return node.childCount(); } public Object getChild(Object parent, int index) { AdapterNode node = (AdapterNode) parent; return node.child(index); } public int getIndexOfChild(Object parent, Object child) { AdapterNode node = (AdapterNode) parent; return node.index((AdapterNode) child); } public void valueForPathChanged(TreePath path, Object newValue) { // Null. We won't be making changes in the GUI // If we did, we would ensure the new value was really new, // adjust the model, and then fire a TreeNodesChanged event. } /* * Use these methods to add and remove event listeners. * (Needed to satisfy TreeModel interface, but not used.) */ private List listenerList = new LinkedList(); public void addTreeModelListener(TreeModelListener listener) { if ( listener != null && ! listenerList.contains( listener ) ) { listenerList.add( listener ); } } public void removeTreeModelListener(TreeModelListener listener) { listenerList.remove(listener); } /* * Invoke these methods to inform listeners of changes. * (Not needed for this example.) * Methods taken from TreeModelSupport class described at * http://java.sun.com/products/jfc/tsc/articles/jtree/index.html * That architecture (produced by Tom Santos and Steve Wilson) * is more elegant. I just hacked 'em in here so they are * immediately at hand. */ public void fireTreeNodesChanged( TreeModelEvent e ) { Iterator it = listenerList.iterator(); while ( it.hasNext() ) { TreeModelListener listener = (TreeModelListener) it.next(); listener.treeNodesChanged( e ); } } public void fireTreeNodesInserted( TreeModelEvent e ) { Iterator it = listenerList.iterator(); while ( it.hasNext() ) { TreeModelListener listener = (TreeModelListener) it.next(); listener.treeNodesInserted( e ); } } public void fireTreeNodesRemoved( TreeModelEvent e ) { Iterator it = listenerList.iterator(); while ( it.hasNext() ) { TreeModelListener listener = (TreeModelListener) it.next(); listener.treeNodesRemoved( e ); } } public void fireTreeStructureChanged( TreeModelEvent e ) { Iterator it = listenerList.iterator(); while ( it.hasNext() ) { TreeModelListener listener = (TreeModelListener) it.next(); listener.treeStructureChanged( e ); } } } } |
|
From: Louise P. <lm...@us...> - 2007-06-24 10:45:42
|
Update of /cvsroot/icamodel/icamodel/data In directory sc8-pr-cvs2.sourceforge.net:/tmp/cvs-serv11230/data Added Files: params.xml Log Message: First steps towards an XML parameter file --- NEW FILE: params.xml --- <?xml version='1.0' encoding='utf-8'?> <!-- Basic format Required modelBits don't have names. They may have types. In each modelBit, specify its own parameters first. Then specify its required children (which usually have their own tags). Then specify its generic children, using the modelBit tag. --> <model> <param id="TotalRealisations" type="number"> 10 </param> <param id="TimePeriodsPerRealisation" type="number"> 5 </param> <param id="TimePeriodsPerYear" type="number"> 1 </param> <!-- external --> <external> <randomNumberGenerator type="BasicRandomNumberGenerator"> </randomNumberGenerator> <modelBit name="intRate4%" type="FixedInterestRate"> <param id="Rate" type="number"> 0.04 </param> </modelBit> </external> <!-- liabilities --> <liabilities> <modelBit name="BLine1" type="BusinessLineConstant"> <param type="paymentPattern" id="InceptionPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="ExposureDelayPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="PremiumReceiptDelayPattern"> <incidence>Front</incidence> <values>1.0</values> </param> <param id="ExposureUnits" type="number"> 1.0 </param> <param id="PremiumRate" type="number"> 1.0 </param> <modelBit name="LType1" type="LossTypeConstant"> <param id="ConstantLossAmount" type="number"> 1.0 </param> <param id="ClaimsPaymentPattern" type="list"> 1.0, 2.0 </param> </modelBit> <!-- end of LType1 --> </modelBit> <!-- end of BLine1 --> <modelBit name="Bline2" type="BusinessLineConstant"> <!-- this one has half exposure & premium in each of first 2 periods --> <param type="paymentPattern" id="InceptionPattern"> <incidence>Even</incidence> <values>1.0</values> </param> <param type="paymentPattern" id="ExposureDelayPattern"> <incidence>Even</incidence> <values>1.0,1.0</values> </param> <param type="paymentPattern" id="PremiumReceiptDelayPattern"> <incidence>Front</incidence> <values>1.0,1.0</values> </param> <param id="ExposureUnits" type="number"> 3.0 </param> <param id="PremiumRate" type="number"> 2.0 </param> <modelBit name="LType2" type="LossTypeRange"> <param id="LossAmountBounds" type="range"> 1.5, 2.1 </param> <param id="ClaimsPaymentPattern" type="list"> 1.0, 1.0, 1.0, 1.0 </param> </modelBit> <!-- end of LType1 --> </modelBit> <!-- end of Bline2 --> </liabilities> <!-- assets --> <assets> <modelBit name="Cash" type="CashPool"> <param id="InitialValue" type="number"> 300 </param> </modelBit> </assets> </model> |