Search in sources :

Example 61 with Parameters

use of edu.cmu.tetrad.util.Parameters in project tetrad by cmu-phil.

the class SimulationEditor method getFileMenu.

private void getFileMenu(final JMenu fileMenu, final Simulation simulation, final GraphSelectionEditor graphEditor, final DataEditor dataEditor, final JTabbedPane tabbedPane, final String[] simulationItems) {
    JMenuItem loadSimulation = new JMenuItem("Load Simulation");
    JMenuItem saveSimulation = new JMenuItem("Save Simulation");
    loadSimulation.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            String sessionSaveLocation = Preferences.userRoot().get("fileSaveLocation", "");
            chooser.setCurrentDirectory(new File(sessionSaveLocation));
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int ret1 = chooser.showOpenDialog(JOptionUtils.centeringComp());
            if (!(ret1 == JFileChooser.APPROVE_OPTION)) {
                return;
            }
            File file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }
            // Check to make sure the directory has the right structure.
            File[] files = file.listFiles();
            if (files == null) {
                JOptionPane.showMessageDialog((SimulationEditor.this), "That wasn't a directory");
                return;
            }
            boolean correctStructure = isCorrectStructure(files);
            if (!correctStructure) {
                int count = 0;
                File thisOne = null;
                for (File _file : files) {
                    File[] _files = _file.listFiles();
                    if (_files == null) {
                        continue;
                    }
                    if (isCorrectStructure(_files)) {
                        count++;
                        thisOne = _file;
                    }
                }
                if (thisOne == null) {
                    JOptionPane.showMessageDialog((SimulationEditor.this), "That file was not a simulation, and none of its subdirectories was either. " + "\nNeed a directory with a 'data' subdirectory, a 'graph' subdirectory, " + "\nand a 'parameters.txt' file.");
                    return;
                }
                if (count > 1) {
                    JOptionPane.showMessageDialog((SimulationEditor.this), "More than one subdirectory of that directory was a simulation; please select " + "\none of the subdirectories.");
                    return;
                }
                file = thisOne;
            }
            edu.cmu.tetrad.algcomparison.simulation.Simulation _simulation = new LoadContinuousDataAndGraphs(file.getPath());
            _simulation.createData(simulation.getParams());
            if (_simulation.getNumDataModels() > 0) {
                Graph trueGraph = _simulation.getTrueGraph(0);
                edu.cmu.tetrad.graph.GraphUtils.circleLayout(trueGraph, 225, 200, 150);
                List<Graph> graphs = new ArrayList<>();
                for (int i = 0; i < _simulation.getNumDataModels(); i++) {
                    graphs.add(_simulation.getTrueGraph(i));
                }
                graphEditor.replace(graphs);
                DataWrapper wrapper = new DataWrapper(new Parameters());
                DataModelList list = new DataModelList();
                for (int i = 0; i < _simulation.getNumDataModels(); i++) {
                    list.add(_simulation.getDataModel(i));
                }
                wrapper.setDataModelList(list);
                tabbedPane.setComponentAt(2, new DataEditor(wrapper, false, JTabbedPane.LEFT));
            }
            String graphPref = null;
            String simPref = null;
            if (_simulation.getParameters().contains("graphsDropdownPreference")) {
                graphPref = (String) simulation.getParams().get("graphsDropdownPreference");
            }
            if (_simulation.getParameters().contains("simulationsDropdownPreference")) {
                simPref = (String) simulation.getParams().get("simulationsDropdownPreference");
            }
            if (graphPref != null) {
                graphsDropdown.setSelectedItem(graphPref);
                System.out.println("Set pre-loaded Graph: " + graphPref);
            }
            if (simPref != null) {
                simulationsDropdown.setSelectedItem(simPref);
                System.out.println("Set pre-loaded sim: " + simPref);
            }
            simulation.setSimulation(_simulation, simulation.getParams());
            resetPanel(simulation, graphItems, simulationItems, tabbedPane);
        }

        private boolean isCorrectStructure(File[] files) {
            boolean hasDataDir = false;
            boolean hasGraphDir = false;
            boolean hasParametersFile = false;
            for (File _file : files) {
                if (_file.isDirectory() && _file.getName().equals("data")) {
                    hasDataDir = true;
                }
                if (_file.isDirectory() && _file.getName().equals("graph")) {
                    hasGraphDir = true;
                }
                if (_file.isFile() && _file.getName().equals("parameters.txt")) {
                    hasParametersFile = true;
                }
            }
            return hasDataDir && hasGraphDir && hasParametersFile;
        }
    });
    saveSimulation.addActionListener((e) -> {
        JFileChooser chooser = new JFileChooser();
        String sessionSaveLocation = Preferences.userRoot().get("fileSaveLocation", "");
        chooser.setCurrentDirectory(new File(sessionSaveLocation));
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int ret1 = chooser.showSaveDialog(JOptionUtils.centeringComp());
        if (!(ret1 == JFileChooser.APPROVE_OPTION)) {
            return;
        }
        final File selectedFile = chooser.getSelectedFile();
        if (selectedFile == null) {
            return;
        }
        // if (file.listFiles().length != 0) {
        // JOptionPane.showMessageDialog((SimulationEditor.this),
        // "That wasn't a a new or empty directory; try typing a name for the directory\n" +
        // "or creating an empty directory.");
        // return;
        // }
        new Comparison().saveToFiles(selectedFile.getAbsolutePath(), simulation.getSimulation(), simulation.getParams());
        Preferences.userRoot().put("fileSaveLocation", selectedFile.getParent());
    });
    fileMenu.addSeparator();
    fileMenu.add(loadSimulation);
    fileMenu.add(saveSimulation);
}
Also used : Parameters(edu.cmu.tetrad.util.Parameters) ActionEvent(java.awt.event.ActionEvent) LoadContinuousDataAndGraphs(edu.cmu.tetrad.algcomparison.simulation.LoadContinuousDataAndGraphs) DataWrapper(edu.cmu.tetradapp.model.DataWrapper) RandomGraph(edu.cmu.tetrad.algcomparison.graph.RandomGraph) SingleGraph(edu.cmu.tetrad.algcomparison.graph.SingleGraph) EdgeListGraph(edu.cmu.tetrad.graph.EdgeListGraph) Graph(edu.cmu.tetrad.graph.Graph) ActionListener(java.awt.event.ActionListener) JFileChooser(javax.swing.JFileChooser) TimeSeriesSemSimulation(edu.cmu.tetrad.algcomparison.simulation.TimeSeriesSemSimulation) GeneralSemSimulation(edu.cmu.tetrad.algcomparison.simulation.GeneralSemSimulation) SemSimulation(edu.cmu.tetrad.algcomparison.simulation.SemSimulation) ConditionalGaussianSimulation(edu.cmu.tetrad.algcomparison.simulation.ConditionalGaussianSimulation) StandardizedSemSimulation(edu.cmu.tetrad.algcomparison.simulation.StandardizedSemSimulation) BooleanGlassSimulation(edu.cmu.tetrad.algcomparison.simulation.BooleanGlassSimulation) Simulation(edu.cmu.tetradapp.model.Simulation) LeeHastieSimulation(edu.cmu.tetrad.algcomparison.simulation.LeeHastieSimulation) BayesNetSimulation(edu.cmu.tetrad.algcomparison.simulation.BayesNetSimulation) DataModelList(edu.cmu.tetrad.data.DataModelList) Comparison(edu.cmu.tetrad.algcomparison.Comparison) List(java.util.List) ArrayList(java.util.ArrayList) DataModelList(edu.cmu.tetrad.data.DataModelList) JMenuItem(javax.swing.JMenuItem) File(java.io.File)

Example 62 with Parameters

use of edu.cmu.tetrad.util.Parameters in project tetrad by cmu-phil.

the class FgesRunner method execute.

// ============================PUBLIC METHODS==========================//
/**
 * Executes the algorithm, producing (at least) a result workbench. Must be
 * implemented in the extending class.
 */
public void execute() {
    System.out.println("A");
    Object model = getDataModel();
    if (model == null && getSourceGraph() != null) {
        model = getSourceGraph();
    }
    if (model == null) {
        throw new RuntimeException("Data source is unspecified. You may need to double click all your data boxes, \n" + "then click Save, and then right click on them and select Propagate Downstream. \n" + "The issue is that we use a seed to simulate from IM's, so your data is not saved to \n" + "file when you save the session. It can, however, be recreated from the saved seed.");
    }
    Parameters params = getParams();
    if (model instanceof Graph) {
        GraphScore gesScore = new GraphScore((Graph) model);
        fges = new Fges(gesScore);
        fges.setKnowledge((IKnowledge) getParams().get("knowledge", new Knowledge2()));
        fges.setVerbose(true);
    } else {
        double penaltyDiscount = params.getDouble("penaltyDiscount", 4);
        if (model instanceof DataSet) {
            DataSet dataSet = (DataSet) model;
            if (dataSet.isContinuous()) {
                SemBicScore gesScore = new SemBicScore(new CovarianceMatrixOnTheFly((DataSet) model));
                // SemBicScore2 gesScore = new SemBicScore2(new CovarianceMatrixOnTheFly((DataSet) model));
                // SemGpScore gesScore = new SemGpScore(new CovarianceMatrixOnTheFly((DataSet) model));
                // SvrScore gesScore = new SvrScore((DataSet) model);
                gesScore.setPenaltyDiscount(penaltyDiscount);
                System.out.println("Score done");
                fges = new Fges(gesScore);
            } else if (dataSet.isDiscrete()) {
                double samplePrior = getParams().getDouble("samplePrior", 1);
                double structurePrior = getParams().getDouble("structurePrior", 1);
                BDeuScore score = new BDeuScore(dataSet);
                score.setSamplePrior(samplePrior);
                score.setStructurePrior(structurePrior);
                fges = new Fges(score);
            } else {
                ConditionalGaussianScore gesScore = new ConditionalGaussianScore(dataSet, 1, false);
                gesScore.setPenaltyDiscount(penaltyDiscount);
                fges = new Fges(gesScore);
            }
        } else if (model instanceof ICovarianceMatrix) {
            SemBicScore gesScore = new SemBicScore((ICovarianceMatrix) model);
            gesScore.setPenaltyDiscount(penaltyDiscount);
            gesScore.setPenaltyDiscount(penaltyDiscount);
            fges = new Fges(gesScore);
        } else if (model instanceof DataModelList) {
            DataModelList list = (DataModelList) model;
            for (DataModel dataModel : list) {
                if (!(dataModel instanceof DataSet || dataModel instanceof ICovarianceMatrix)) {
                    throw new IllegalArgumentException("Need a combination of all continuous data sets or " + "covariance matrices, or else all discrete data sets, or else a single initialGraph.");
                }
            }
            if (list.size() != 1) {
                throw new IllegalArgumentException("FGES takes exactly one data set, covariance matrix, or initialGraph " + "as input. For multiple data sets as input, use IMaGES.");
            }
            if (allContinuous(list)) {
                double penalty = getParams().getDouble("penaltyDiscount", 4);
                if (params.getBoolean("firstNontriangular", false)) {
                    SemBicScoreImages fgesScore = new SemBicScoreImages(list);
                    fgesScore.setPenaltyDiscount(penalty);
                    fges = new Fges(fgesScore);
                } else {
                    SemBicScoreImages fgesScore = new SemBicScoreImages(list);
                    fgesScore.setPenaltyDiscount(penalty);
                    fges = new Fges(fgesScore);
                }
            } else if (allDiscrete(list)) {
                double structurePrior = getParams().getDouble("structurePrior", 1);
                double samplePrior = getParams().getDouble("samplePrior", 1);
                BdeuScoreImages fgesScore = new BdeuScoreImages(list);
                fgesScore.setSamplePrior(samplePrior);
                fgesScore.setStructurePrior(structurePrior);
                if (params.getBoolean("firstNontriangular", false)) {
                    fges = new Fges(fgesScore);
                } else {
                    fges = new Fges(fgesScore);
                }
            } else {
                throw new IllegalArgumentException("Data must be either all discrete or all continuous.");
            }
        } else {
            System.out.println("No viable input.");
        }
    }
    fges.setInitialGraph(initialGraph);
    fges.setKnowledge((IKnowledge) getParams().get("knowledge", new Knowledge2()));
    fges.setNumPatternsToStore(params.getInt("numPatternsToSave", 1));
    fges.setVerbose(true);
    fges.setFaithfulnessAssumed(params.getBoolean("faithfulnessAssumed", true));
    Graph graph = fges.search();
    if (getSourceGraph() != null) {
        GraphUtils.arrangeBySourceGraph(graph, getSourceGraph());
    } else if (((IKnowledge) getParams().get("knowledge", new Knowledge2())).isDefaultToKnowledgeLayout()) {
        SearchGraphUtils.arrangeByKnowledgeTiers(graph, (IKnowledge) getParams().get("knowledge", new Knowledge2()));
    } else {
        GraphUtils.circleLayout(graph, 200, 200, 150);
    }
    setResultGraph(graph);
    this.topGraphs = new ArrayList<>(fges.getTopGraphs());
    if (topGraphs.isEmpty()) {
        topGraphs.add(new ScoredGraph(getResultGraph(), Double.NaN));
    }
    setIndex(topGraphs.size() - 1);
}
Also used : Parameters(edu.cmu.tetrad.util.Parameters) Graph(edu.cmu.tetrad.graph.Graph)

Example 63 with Parameters

use of edu.cmu.tetrad.util.Parameters in project tetrad by cmu-phil.

the class CfciRunner method getIndependenceTest.

public IndependenceTest getIndependenceTest() {
    Object dataModel = getDataModel();
    if (dataModel == null) {
        dataModel = getSourceGraph();
    }
    Parameters params = getParams();
    IndTestType testType;
    if (getParams() instanceof Parameters) {
        Parameters _params = params;
        testType = (IndTestType) _params.get("indTestType", IndTestType.FISHER_Z);
    } else {
        Parameters _params = params;
        testType = (IndTestType) _params.get("indTestType", IndTestType.FISHER_Z);
    }
    return new IndTestChooser().getTest(dataModel, params, testType);
}
Also used : Parameters(edu.cmu.tetrad.util.Parameters) IndTestType(edu.cmu.tetrad.search.IndTestType)

Example 64 with Parameters

use of edu.cmu.tetrad.util.Parameters in project tetrad by cmu-phil.

the class FciRunner method getIndependenceTest.

public IndependenceTest getIndependenceTest() {
    Object dataModel = getDataModel();
    if (dataModel == null) {
        dataModel = getSourceGraph();
    }
    Parameters params = getParams();
    IndTestType testType;
    if (getParams() instanceof Parameters) {
        Parameters _params = params;
        testType = (IndTestType) _params.get("indTestType", IndTestType.FISHER_Z);
    } else {
        Parameters _params = params;
        testType = (IndTestType) _params.get("indTestType", IndTestType.FISHER_Z);
    }
    return new IndTestChooser().getTest(dataModel, params, testType);
}
Also used : Parameters(edu.cmu.tetrad.util.Parameters)

Example 65 with Parameters

use of edu.cmu.tetrad.util.Parameters in project tetrad by cmu-phil.

the class LofsSearchEditor method getToolbar.

/**
 * Construct the toolbar panel.
 */
protected JPanel getToolbar() {
    JPanel toolbar = new JPanel();
    getExecuteButton().setText("Execute*");
    getExecuteButton().addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            execute();
        }
    });
    JCheckBox doRuleR1CheckBox = new JCheckBox("R1");
    JCheckBox doRuleR2CheckBox = new JCheckBox("R2");
    final Parameters searchParams = getAlgorithmRunner().getParams();
    JRadioButton B = new JRadioButton("B");
    JRadioButton A = new JRadioButton("A");
    ButtonGroup group = new ButtonGroup();
    group.add(B);
    group.add(A);
    if (!searchParams.getBoolean("orientStrongerDirection", true)) {
        A.setSelected(true);
    } else {
        B.setSelected(true);
    }
    A.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            JRadioButton button = (JRadioButton) actionEvent.getSource();
            if (button.isSelected()) {
                searchParams.set("orientStrongerDirection", false);
            }
        }
    });
    B.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            JRadioButton button = (JRadioButton) actionEvent.getSource();
            if (button.isSelected()) {
                searchParams.set("orientStrongerDirection", true);
            }
        }
    });
    JCheckBox orient2cycles = new JCheckBox("Orient 2 cycles in R2");
    orient2cycles.setSelected(searchParams.getBoolean("r2Orient2Cycles", false));
    orient2cycles.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            JCheckBox checkBox = (JCheckBox) actionEvent.getSource();
            searchParams.set("r2Orient2Cycles", checkBox.isSelected());
        }
    });
    JCheckBox meanCenterResiduals = new JCheckBox("Mean center residuals");
    meanCenterResiduals.setSelected(searchParams.getBoolean("meanCenterResiduals", false));
    meanCenterResiduals.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            JCheckBox checkBox = (JCheckBox) actionEvent.getSource();
            searchParams.set("meanCenterResiduals", checkBox.isSelected());
        }
    });
    JComboBox scoreBox = new JComboBox();
    scoreBox.addItem("Anderson Darling");
    // scoreBox.addItem("Skew");
    scoreBox.addItem("Kurtosis");
    // scoreBox.addItem("Fifth Moment");
    scoreBox.addItem("Mean Absolute");
    Lofs.Score _score = (Lofs.Score) searchParams.get("score", Lofs.Score.andersonDarling);
    if (_score == Lofs.Score.andersonDarling) {
        scoreBox.setSelectedItem("Anderson Darling");
    } else if (_score == Lofs.Score.skew) {
        scoreBox.setSelectedItem("Skew");
    } else if (_score == Lofs.Score.kurtosis) {
        scoreBox.setSelectedItem("Kurtosis");
    } else if (_score == Lofs.Score.fifthMoment) {
        scoreBox.setSelectedItem("Fifth Moment");
    } else if (_score == Lofs.Score.absoluteValue) {
        scoreBox.setSelectedItem("Mean Absolute");
    }
    scoreBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent actionEvent) {
            JComboBox box = (JComboBox) actionEvent.getSource();
            String item = (String) box.getSelectedItem();
            System.out.println(item);
            if ("Anderson Darling".equals(item)) {
                searchParams.set("score", Lofs.Score.andersonDarling);
            } else if ("Skew".equals(item)) {
                searchParams.set("score", Lofs.Score.skew);
            } else if ("Kurtosis".equals(item)) {
                searchParams.set("score", Lofs.Score.kurtosis);
            } else if ("Fifth Moment".equals(item)) {
                searchParams.set("score", Lofs.Score.fifthMoment);
            } else if ("Mean Absolute".equals(item)) {
                searchParams.set("score", Lofs.Score.absoluteValue);
            } else {
                throw new IllegalStateException();
            }
        }
    });
    Box b1 = Box.createVerticalBox();
    b1.add(getParamsPanel());
    b1.add(Box.createVerticalStrut(10));
    Box b2 = Box.createHorizontalBox();
    b2.add(Box.createGlue());
    b2.add(getExecuteButton());
    b1.add(b2);
    b1.add(Box.createVerticalStrut(10));
    // Box b3a = Box.createHorizontalBox();
    // b3a.add(Box.createGlue());
    // b1.add(b3a);;
    Box b3b = Box.createHorizontalBox();
    b3b.add(new JLabel("Do rules:"));
    b3b.add(doRuleR1CheckBox);
    b3b.add(doRuleR2CheckBox);
    // b3b.add(doMeekCheckBox);
    b3b.add(Box.createHorizontalGlue());
    b1.add(b3b);
    Box b3c = Box.createHorizontalBox();
    // b3c.add(new JLabel("R2:"));
    b3c.add(B);
    b3c.add(A);
    b3c.add(Box.createHorizontalGlue());
    b1.add(b3c);
    Box b3d = Box.createHorizontalBox();
    // b3d.add(new JLabel("R2:"));
    b3d.add(orient2cycles);
    b3d.add(Box.createHorizontalGlue());
    b1.add(b3d);
    Box b3e = Box.createHorizontalBox();
    b3e.add(meanCenterResiduals);
    b3e.add(Box.createHorizontalGlue());
    b1.add(b3e);
    Box b3f = Box.createHorizontalBox();
    b3f.add(new JLabel("Score:"));
    b3f.add(scoreBox);
    b3f.add(Box.createHorizontalGlue());
    b1.add(b3f);
    Box b4 = Box.createHorizontalBox();
    JLabel label = new JLabel("<html>" + "*Please note that some" + "<br>searches may take a" + "<br>long time to complete." + "</html>");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setVerticalAlignment(SwingConstants.CENTER);
    label.setBorder(new TitledBorder(""));
    b4.add(label);
    b1.add(Box.createVerticalStrut(10));
    b1.add(b4);
    toolbar.add(b1);
    return toolbar;
}
Also used : Parameters(edu.cmu.tetrad.util.Parameters) ActionEvent(java.awt.event.ActionEvent) TitledBorder(javax.swing.border.TitledBorder) ActionListener(java.awt.event.ActionListener)

Aggregations

Parameters (edu.cmu.tetrad.util.Parameters)134 Comparison (edu.cmu.tetrad.algcomparison.Comparison)30 Graph (edu.cmu.tetrad.graph.Graph)26 Algorithms (edu.cmu.tetrad.algcomparison.algorithm.Algorithms)25 DataSet (edu.cmu.tetrad.data.DataSet)22 Knowledge2 (edu.cmu.tetrad.data.Knowledge2)20 IKnowledge (edu.cmu.tetrad.data.IKnowledge)18 Simulations (edu.cmu.tetrad.algcomparison.simulation.Simulations)17 RandomForward (edu.cmu.tetrad.algcomparison.graph.RandomForward)14 ArrayList (java.util.ArrayList)14 SemBicScore (edu.cmu.tetrad.algcomparison.score.SemBicScore)13 Test (org.junit.Test)13 Node (edu.cmu.tetrad.graph.Node)11 ActionEvent (java.awt.event.ActionEvent)10 ActionListener (java.awt.event.ActionListener)10 Algorithm (edu.cmu.tetrad.algcomparison.algorithm.Algorithm)8 Fges (edu.cmu.tetrad.algcomparison.algorithm.oracle.pattern.Fges)8 DataModel (edu.cmu.tetrad.data.DataModel)8 TitledBorder (javax.swing.border.TitledBorder)8 FisherZ (edu.cmu.tetrad.algcomparison.independence.FisherZ)7