diff options
Diffstat (limited to 'nlpsolver/src/com')
21 files changed, 2572 insertions, 0 deletions
diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseEvolutionarySolver.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseEvolutionarySolver.java new file mode 100644 index 000000000..c5724ca54 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseEvolutionarySolver.java @@ -0,0 +1,389 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.comp.Calc.NLPSolver.dialogs.DummyEvolutionarySolverStatusDialog; +import com.sun.star.comp.Calc.NLPSolver.dialogs.EvolutionarySolverStatusUno; +import com.sun.star.comp.Calc.NLPSolver.dialogs.IEvolutionarySolverStatusDialog; +import com.sun.star.sheet.SolverConstraintOperator; +import com.sun.star.uno.XComponentContext; +import java.util.ArrayList; +import net.adaptivebox.global.BasicBound; +import net.adaptivebox.goodness.ACRComparator; +import net.adaptivebox.goodness.BCHComparator; +import net.adaptivebox.goodness.IGoodnessCompareEngine; +import net.adaptivebox.knowledge.Library; +import net.adaptivebox.knowledge.SearchPoint; +import net.adaptivebox.problem.ProblemEncoder; + +public abstract class BaseEvolutionarySolver extends BaseNLPSolver { + + public BaseEvolutionarySolver(XComponentContext xContext, String name) { + super(xContext, name); + + registerProperty(m_swarmSize); + registerProperty(m_learningCycles); + registerProperty(m_guessVariableRange); + registerProperty(m_variableRangeThreshold); + registerProperty(m_useACRComperator); + + registerProperty(m_useRandomStartingPoint); + + registerProperty(m_required); + registerProperty(m_tolerance); + + registerProperty(m_enhancedSolverStatus); + } + + private static class Variable { + private final CellMap CellMap; + private final int OriginalVariable; + private double MinValue; + private double MaxValue; + private double Granularity; + + private Variable(CellMap cellMap, int originalVariable) { + this.CellMap = cellMap; + this.OriginalVariable = originalVariable; + this.MinValue = BasicBound.MINDOUBLE; + this.MaxValue = BasicBound.MAXDOUBLE; + this.Granularity = 0.0; + } + } + + private class CalcProblemEncoder extends ProblemEncoder { + + private final ArrayList<Variable> m_variables; + private final ArrayList<ExtSolverConstraint> m_constraints; + + private CalcProblemEncoder(ArrayList<Variable> variables, + ArrayList<ExtSolverConstraint> constraints) throws Exception { + //m_variableCount variables to solve, target function + constraints to match + super(variables.size(), 1 + constraints.size()); + + m_variables = variables; + m_constraints = constraints; + + double objective = m_maximize ? BasicBound.MAXDOUBLE : BasicBound.MINDOUBLE; + setDefaultYAt(0, objective, objective); + + for (int i = 0; i < constraints.size(); i++) { + ExtSolverConstraint constraint = constraints.get(i); + + switch (constraint.Operator.getValue()) { + case SolverConstraintOperator.EQUAL_value: + setDefaultYAt(i + 1, constraint.Data, constraint.Data); + break; + case SolverConstraintOperator.GREATER_EQUAL_value: + setDefaultYAt(i + 1, constraint.Data, BasicBound.MAXDOUBLE); + break; + case SolverConstraintOperator.LESS_EQUAL_value: + setDefaultYAt(i + 1, BasicBound.MINDOUBLE, constraint.Data); + break; + case SolverConstraintOperator.INTEGER_value: + setDefaultYAt(i + 1, BasicBound.MINDOUBLE, BasicBound.MAXDOUBLE); + break; + case SolverConstraintOperator.BINARY_value: + setDefaultYAt(i + 1, 0, 1); + break; + } + } + + for (int i = 0; i < m_variables.size(); i++) { + Variable variable = m_variables.get(i); + setDefaultXAt(i, variable.MinValue, variable.MaxValue, variable.Granularity); + } + } + + @Override + protected double calcTargetAt(int index, double[] VX) { + if (index == 0) { + //calcTargetAt is called in a loop over all functions, so it's + //enough to set the variables in the first step only + for (int i = 0; i < m_variables.size(); i++) { + CellMap variableMap = m_variables.get(i).CellMap; + m_variableData[variableMap.Range][variableMap.Row][variableMap.Col] = VX[i]; + } + for (int i = 0; i < m_cellRangeCount; i++) + m_cellRangeData[i].setData(m_variableData[i]); + + //errors are punished + if (m_objectiveCell.getError() != 0) + return m_maximize ? BasicBound.MINDOUBLE : BasicBound.MAXDOUBLE; + + double result = m_objectiveCell.getValue(); + + if (result >= m_toleratedMin && result <= m_toleratedMax && checkConstraints()) + m_toleratedCount++; + + return result; + } else + return m_constraints.get(index - 1).getLeftValue(); + } + + } + + protected CalcProblemEncoder m_problemEncoder; + protected Library m_library; + protected IGoodnessCompareEngine m_envCompareEngine; + protected IGoodnessCompareEngine m_specCompareEngine; + protected SearchPoint m_totalBestPoint; + + protected int m_toleratedCount; + protected double m_toleratedMin; + protected double m_toleratedMax; + + private final ArrayList<Variable> m_variables = new ArrayList<Variable>(); + + //properties + protected PropertyInfo<Integer> m_swarmSize = new PropertyInfo<Integer>("SwarmSize", 70, "Size of Swam"); + protected PropertyInfo<Integer> m_librarySize = new PropertyInfo<Integer>("LibrarySize", 210, "Size of Library"); + protected PropertyInfo<Integer> m_learningCycles = new PropertyInfo<Integer>("LearningCycles", 2000, "Learning Cycles"); + private final PropertyInfo<Boolean> m_guessVariableRange = new PropertyInfo<Boolean>("GuessVariableRange", true, "Variable Bounds Guessing"); + private final PropertyInfo<Double> m_variableRangeThreshold = new PropertyInfo<Double>("VariableRangeThreshold", 3.0, "Variable Bounds Threshold (when guessing)"); //to approximate the variable bounds + private final PropertyInfo<Boolean> m_useACRComperator = new PropertyInfo<Boolean>("UseACRComparator", false, "Use ACR Comparator (instead of BCH)"); + private final PropertyInfo<Boolean> m_useRandomStartingPoint = new PropertyInfo<Boolean>("UseRandomStartingPoint", false, "Use Random starting point"); + protected PropertyInfo<Integer> m_required = new PropertyInfo<Integer>("StagnationLimit", 70, "Stagnation Limit"); + protected PropertyInfo<Double> m_tolerance = new PropertyInfo<Double>("Tolerance", 1e-6, "Stagnation Tolerance"); + private final PropertyInfo<Boolean> m_enhancedSolverStatus = new PropertyInfo<Boolean>("EnhancedSolverStatus", true, "Show enhanced solver status"); + + protected IEvolutionarySolverStatusDialog m_solverStatusDialog; + + private void prepareVariables(double[][] variableBounds) { + m_variables.clear(); + for (int i = 0; i < m_variableCount; i++) { + Variable var = new Variable(m_variableMap[i], i); + var.MinValue = variableBounds[i][0]; + var.MaxValue = variableBounds[i][1]; + var.Granularity = variableBounds[i][2]; + m_variables.add(var); + } + } + + @Override + protected void initializeSolve() { + super.initializeSolve(); + + if (m_variableCount == 0) + { + return; + } + if (m_enhancedSolverStatus.getValue()) + m_solverStatusDialog = new EvolutionarySolverStatusUno(m_xContext); + else + m_solverStatusDialog = new DummyEvolutionarySolverStatusDialog(); + + //Init: + double[][] variableBounds = new double[m_variableCount][3]; + //approximate variable bounds + for (int i = 0; i < m_variableCount; i++) { + if (m_guessVariableRange.getValue()) { + double value = m_variableCells[i].getValue(); + + //0 is a bad starting point, so just pick some other. + //That is certainly not optimal but the user should specify + //bounds or at least a good starting point anyway. + if (value == 0.0) + value = 1000; + + double b1; + double b2; + + if (m_assumeNonNegative.getValue()) { + b1 = 0; + b2 = value + value * 2 * m_variableRangeThreshold.getValue(); + } else { + b1 = value + value * m_variableRangeThreshold.getValue(); + b2 = value - value * m_variableRangeThreshold.getValue(); + } + + variableBounds[i][0] = Math.min(b1, b2); + variableBounds[i][1] = Math.max(b1, b2); + } else { + //that almost always leads to bad or no solutions at all + if (m_assumeNonNegative.getValue()) + variableBounds[i][0] = 0.0; + else + variableBounds[i][0] = BasicBound.MINDOUBLE; + variableBounds[i][1] = BasicBound.MAXDOUBLE; + } + variableBounds[i][2] = 0.0; + } + + //prepare constraints and parse them for variable bounds + ArrayList<ExtSolverConstraint> constraints = new ArrayList<ExtSolverConstraint>(); + for (int i = 0; i < m_constraintCount; i++) { + Double doubleValue; + + if (m_extConstraints[i].Right != null) + doubleValue = null; + else + doubleValue = m_extConstraints[i].Data; + + boolean isVariableBound = false; + //If it refers to a cell, it has to be treated as constraint, not as + //bound. + if (m_extConstraints[i].Right == null) { + for (int j = 0; j < m_variableCount && !isVariableBound; j++) { + if (m_constraints[i].Left.Sheet == super.m_variables[j].Sheet && + m_constraints[i].Left.Column == super.m_variables[j].Column && + m_constraints[i].Left.Row == super.m_variables[j].Row) { + isVariableBound = true; + + //Therefore we try to use it as bounds for this variable. + + switch (m_extConstraints[i].Operator.getValue()) { + case SolverConstraintOperator.EQUAL_value: + if (doubleValue == null) + continue; + variableBounds[j][0] = doubleValue; + variableBounds[j][1] = doubleValue; + break; + case SolverConstraintOperator.GREATER_EQUAL_value: + if (doubleValue == null) + continue; + variableBounds[j][0] = doubleValue; + break; + case SolverConstraintOperator.LESS_EQUAL_value: + if (doubleValue == null) + continue; + variableBounds[j][1] = doubleValue; + break; + case SolverConstraintOperator.INTEGER_value: + variableBounds[j][2] = 1.0; + break; + case SolverConstraintOperator.BINARY_value: + variableBounds[j][0] = 0.0; + variableBounds[j][1] = 1.0; + variableBounds[j][2] = 1.0; + break; + default: + //If it is neither <=, nor =, nor >=, we treat + //it as normal constraint. + isVariableBound = false; + } + } + } + } + + if (!isVariableBound) { + constraints.add(m_extConstraints[i]); + } + } + + prepareVariables(variableBounds); + + try { + m_problemEncoder = new CalcProblemEncoder(m_variables, constraints); + } catch (Exception e) { + m_problemEncoder = null; + return; + } + + m_library = new Library(m_librarySize.getValue(), m_problemEncoder); + + if (m_useRandomStartingPoint.getValue()) { + m_totalBestPoint = m_problemEncoder.getEncodedSearchPoint(); + } else { + m_totalBestPoint = m_problemEncoder.getFreshSearchPoint(); + double[] currentValues = new double[m_variables.size()]; + for (int i = 0; i < m_variables.size(); i++) + currentValues[i] = m_currentParameters[m_variables.get(i).OriginalVariable]; + m_totalBestPoint.importLocation(currentValues); + m_problemEncoder.evaluate(m_totalBestPoint); + } + //input the chosen point into the library as reference for the individuals + m_library.getSelectedPoint(0).importPoint(m_totalBestPoint); + + m_solverStatusDialog.setBestSolution(m_totalBestPoint.getObjectiveValue(), checkConstraints()); + + m_envCompareEngine = new BCHComparator(); + m_specCompareEngine = m_useACRComperator.getValue() ? new ACRComparator(m_library, m_learningCycles.getValue()) : new BCHComparator(); + } + + protected void applySolution() { + double[] location = m_totalBestPoint.getLocation(); + + //make sure, the "Integer" variable type is met + m_problemEncoder.getDesignSpace().getMappingPoint(location); + + //get the function value for our optimal point + for (int i = 0; i < m_variableCount; i++) { + m_variableCells[i].setValue(location[i]); + m_currentParameters[i] = location[i]; + } + m_functionValue = m_objectiveCell.getValue(); + } + + @Override + protected void finalizeSolve() { + applySolution(); + + m_success = (m_objectiveCell.getError() == 0 && checkConstraints()); + + m_solverStatusDialog.setVisible(false); + m_solverStatusDialog.dispose(); + + super.finalizeSolve(); + } + + private boolean checkConstraints() { + boolean result = true; + for (int i = 0; i < m_constraintCount && result; i++) { + if (m_extConstraints[i].Left.getError() == 0) { + Double value, targetValue; + + value = m_extConstraints[i].getLeftValue(); + targetValue = m_extConstraints[i].Data; + + switch (m_extConstraints[i].Operator.getValue()) { + case SolverConstraintOperator.EQUAL_value: + result = (targetValue != null && value.equals(targetValue)); + break; + case SolverConstraintOperator.GREATER_EQUAL_value: + result = (targetValue != null && value >= targetValue); + break; + case SolverConstraintOperator.LESS_EQUAL_value: + result = (targetValue != null && value <= targetValue); + break; + case SolverConstraintOperator.INTEGER_value: + result = (Math.rint(value) == value); + break; + case SolverConstraintOperator.BINARY_value: + result = (value == 0.0 || value == 1.0); + break; + } + } else { + result = false; + } + } + + return result; + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseNLPSolver.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseNLPSolver.java new file mode 100644 index 000000000..d425e2a4c --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/BaseNLPSolver.java @@ -0,0 +1,551 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.awt.XReschedule; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertyChangeListener; +import com.sun.star.beans.XPropertySetInfo; +import com.sun.star.beans.XVetoableChangeListener; +import com.sun.star.chart.XChartDataArray; +import com.sun.star.container.XIndexAccess; +import com.sun.star.document.XEmbeddedObjectSupplier; +import com.sun.star.frame.XModel; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.IndexOutOfBoundsException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.sheet.SolverConstraint; +import com.sun.star.sheet.SolverConstraintOperator; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.table.CellAddress; +import com.sun.star.table.CellContentType; +import com.sun.star.table.CellRangeAddress; +import com.sun.star.table.XCell; +import com.sun.star.table.XTableChartsSupplier; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class BaseNLPSolver extends WeakBase + implements com.sun.star.lang.XLocalizable, + com.sun.star.sheet.XSolver, + com.sun.star.sheet.XSolverDescription, + com.sun.star.beans.XPropertySet, + com.sun.star.beans.XPropertySetInfo +{ + + protected final XComponentContext m_xContext; + private final String m_name; + + private final ArrayList<PropertyInfo> m_properties = new ArrayList<PropertyInfo>(); + private final HashMap<String, PropertyInfo> m_propertyMap = new HashMap<String, PropertyInfo>(); + + private com.sun.star.lang.Locale m_locale = new com.sun.star.lang.Locale(); + private final ResourceManager resourceManager; + + private CellAddress m_objective; + protected CellAddress[] m_variables; + protected SolverConstraint[] m_constraints; + + public BaseNLPSolver(XComponentContext xContext, String name) { + m_xContext = xContext; + m_name = name; + // init members exposed as XSolver properties through uno bridge + m_objective = new CellAddress(); + m_variables = new CellAddress[0]; + m_constraints = new SolverConstraint[0]; + + XMultiComponentFactory componentFactory = xContext.getServiceManager(); + try { + Object toolkit = componentFactory.createInstanceWithContext("com.sun.star.awt.Toolkit", xContext); + m_xReschedule = UnoRuntime.queryInterface(XReschedule.class, toolkit); + } catch (Exception ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } + + resourceManager = new ResourceManager(xContext, "com.sun.star.comp.Calc.NLPSolver", "/locale", "NLPSolverCommon"); + + registerProperty(m_assumeNonNegative); + } + + protected void registerProperty(PropertyInfo property) { + m_properties.add(property); + m_propertyMap.put(property.getProperty().Name, property); + property.localize(resourceManager); + } + + // com.sun.star.lang.XLocalizable: + public void setLocale(com.sun.star.lang.Locale eLocale) + { + m_locale = eLocale; + } + + public com.sun.star.lang.Locale getLocale() + { + return m_locale; + } + + // com.sun.star.sheet.XSolver: + + private XSpreadsheetDocument m_document; + private XModel m_xModel; + protected XReschedule m_xReschedule; + protected ExtSolverConstraint[] m_extConstraints; + protected boolean m_maximize; + + protected int m_variableCount; + protected int m_constraintCount; + protected int m_cellRangeCount; + protected XCell m_objectiveCell; + protected XCell[] m_variableCells; + protected XChartDataArray[] m_cellRangeData; + protected CellMap[] m_variableMap; + protected double[][][] m_variableData; + + protected double m_functionValue; + protected double[] m_currentParameters; + protected boolean m_success = false; + + public XSpreadsheetDocument getDocument() { + return m_document; + } + + public void setDocument(XSpreadsheetDocument document) { + m_document = document; + m_xModel = UnoRuntime.queryInterface(XModel.class, m_document); + } + + public CellAddress getObjective() { + return m_objective; + } + + public void setObjective(CellAddress objective) { + m_objective = objective; + m_objectiveCell = getCell(objective); + } + + public CellAddress[] getVariables() { + return m_variables; + } + + private static class RowInfo { + private short Sheet; + private int Row; + private int StartCol; + private int EndCol; + + private RowInfo(short sheet, int row) { + Sheet = sheet; + Row = row; + } + + private CellRangeAddress getCellRangeAddress(int lastRow) { + CellRangeAddress result = new CellRangeAddress(); + result.Sheet = Sheet; + result.StartColumn = StartCol; + result.StartRow = Row; + result.EndColumn = EndCol; + result.EndRow = lastRow; + return result; + } + } + + protected static class CellMap { + protected int Range; + protected int Col; + protected int Row; + } + + protected class ExtSolverConstraint { + + public XCell Left; + public SolverConstraintOperator Operator; + public XCell Right; + public double Data; + + private ExtSolverConstraint(XCell left, SolverConstraintOperator operator, Object right) { + this.Left = left; + this.Operator = operator; + this.Right = null; + if (right instanceof Number) { + this.Data = ((Number)right).doubleValue(); + } else if (right instanceof CellAddress) { + XCell cell = getCell((CellAddress)right); + if (cell.getType() == CellContentType.VALUE) { + this.Data = cell.getValue(); + } else { + this.Right = cell; + this.Data = 0.0; + } + } + } + + public double getLeftValue() { + if (this.Right == null) { + return this.Left.getValue(); + } else { + return this.Left.getValue() - this.Right.getValue(); + } + } + + } + + public void setVariables(CellAddress[] variables) { + m_variables = variables; + m_variableCount = variables.length; + + //update cell references + m_variableCells = new XCell[m_variableCount]; + m_currentParameters = new double[m_variableCount]; + for (int i = 0; i < m_variableCount; i++) { + m_variableCells[i] = getCell(variables[i]); + m_currentParameters[i] = m_variableCells[i].getValue(); + } + + //parse for cell ranges (under the assumption, that the cells are ordered + //left to right, top to bottom for each cell range + m_variableMap = new CellMap[m_variableCount]; + m_variableData = new double[m_variableCount][][]; + + ArrayList<RowInfo> rows = new ArrayList<RowInfo>(); + RowInfo currentRow = null; + int lastSheet = -1, lastRow = -1; + for (int i = 0; i < m_variableCount; i++) { + boolean match = lastSheet == m_variables[i].Sheet && + lastRow == m_variables[i].Row; + assert !match || currentRow != null; + if (match && currentRow.EndCol == m_variables[i].Column - 1) + currentRow.EndCol++; + else { + currentRow = new RowInfo(m_variables[i].Sheet, m_variables[i].Row); + currentRow.StartCol = m_variables[i].Column; + currentRow.EndCol = m_variables[i].Column; + rows.add(currentRow); + lastSheet = currentRow.Sheet; + lastRow = currentRow.Row; + } + } + + ArrayList<CellRangeAddress> cellRangeAddresses = new ArrayList<CellRangeAddress>(); + if (rows.size() > 0) { + RowInfo firstRow = rows.get(0); + int offset = 0; + for (int i = 1; i < rows.size(); i++) { + currentRow = rows.get(i); + if (currentRow.Sheet != firstRow.Sheet || + currentRow.Row != firstRow.Row + offset + 1 || + currentRow.StartCol != firstRow.StartCol || + currentRow.EndCol != firstRow.EndCol) { + cellRangeAddresses.add(firstRow.getCellRangeAddress(firstRow.Row + offset)); + firstRow = currentRow; + offset = 0; + } else { + offset++; + } + } + cellRangeAddresses.add(firstRow.getCellRangeAddress(firstRow.Row + offset)); + } + + m_cellRangeCount = cellRangeAddresses.size(); + m_cellRangeData = new XChartDataArray[m_cellRangeCount]; + int varID = 0; + //get cell range data and map the variables to their new location + for (int i = 0; i < m_cellRangeCount; i++) { + for (int y = 0; y <= cellRangeAddresses.get(i).EndRow - cellRangeAddresses.get(i).StartRow; y++) + for (int x = 0; x <= cellRangeAddresses.get(i).EndColumn - cellRangeAddresses.get(i).StartColumn; x++) { + CellMap map = new CellMap(); + m_variableMap[varID++] = map; + map.Range = i; + map.Col = x; + map.Row = y; + } + m_cellRangeData[i] = getChartDataArray(cellRangeAddresses.get(i)); + m_variableData[i] = m_cellRangeData[i].getData(); + } + } + + public SolverConstraint[] getConstraints() { + return m_constraints; + } + + public void setConstraints(SolverConstraint[] constraints) { + m_constraints = constraints; + m_constraintCount = constraints.length; + + //update cell references + m_extConstraints = new ExtSolverConstraint[m_constraintCount]; + for (int i = 0; i < m_constraintCount; i++) { + m_extConstraints[i] = new ExtSolverConstraint( + getCell(constraints[i].Left), + constraints[i].Operator, + constraints[i].Right); + } + } + + public boolean getMaximize() { + return m_maximize; + } + + public void setMaximize(boolean maximize) { + m_maximize = maximize; + } + + public boolean getSuccess() { + return m_success; + } + + public double getResultValue() { + return m_functionValue; + } + + public double[] getSolution() { + return m_currentParameters; + } + + private XCell getCell(CellAddress cellAddress) { + return getCell(cellAddress.Column, cellAddress.Row, cellAddress.Sheet); + } + + private XCell getCell(int col, int row, int sheet) { + try { + XSpreadsheets xSpreadsheets = m_document.getSheets(); + XIndexAccess xSheetIndex = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets); + XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface(XSpreadsheet.class, xSheetIndex.getByIndex(sheet)); + return xSpreadsheet.getCellByPosition(col, row); + } catch (IndexOutOfBoundsException ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } catch (WrappedTargetException ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } + + return null; + } + + + + private XChartDataArray getChartDataArray(CellRangeAddress cellRangeAddress) { + return getChartDataArray(cellRangeAddress.Sheet, cellRangeAddress.StartColumn, + cellRangeAddress.StartRow, cellRangeAddress.EndColumn, cellRangeAddress.EndRow); + } + + private XChartDataArray getChartDataArray(int sheet, int startCol, int startRow, int endCol, int endRow) { + try { + XSpreadsheets xSpreadsheets = m_document.getSheets(); + XIndexAccess xSheetIndex = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets); + XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface(XSpreadsheet.class, xSheetIndex.getByIndex(sheet)); + return UnoRuntime.queryInterface(XChartDataArray.class, xSpreadsheet.getCellRangeByPosition(startCol, startRow, endCol, endRow)); + } catch (IndexOutOfBoundsException ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } catch (WrappedTargetException ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } + + return null; + } + + protected PropertyInfo<Boolean> m_assumeNonNegative = new PropertyInfo<Boolean>("AssumeNonNegative", false, "Assume Non-Negative Variables"); + + protected void initializeSolve() { + lockDocument(); + } + + protected void finalizeSolve() { + unlockDocument(); + } + + public String getComponentDescription() { + return m_name; + } + + public String getStatusDescription() { + return ""; + } + + public String getPropertyDescription(String property) { + PropertyInfo propertyInfo = m_propertyMap.get(property); + if (propertyInfo != null) + return propertyInfo.getDescription(); + else + return ""; + } + + // com.sun.star.beans.XPropertySet: + + public XPropertySetInfo getPropertySetInfo() { + return this; + } + + public void setPropertyValue(String property, Object value) throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException { + PropertyInfo propertyInfo = m_propertyMap.get(property); + if (propertyInfo != null) + propertyInfo.setValue(value); + else + throw new UnknownPropertyException(); + } + + public Object getPropertyValue(String property) throws UnknownPropertyException, WrappedTargetException { + PropertyInfo propertyInfo = m_propertyMap.get(property); + if (propertyInfo != null) + return propertyInfo.getValue(); + else + throw new UnknownPropertyException(); + } + + public void addPropertyChangeListener(String property, XPropertyChangeListener listener) throws UnknownPropertyException, WrappedTargetException { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void removePropertyChangeListener(String property, XPropertyChangeListener listener) throws UnknownPropertyException, WrappedTargetException { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void addVetoableChangeListener(String property, XVetoableChangeListener listener) throws UnknownPropertyException, WrappedTargetException { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void removeVetoableChangeListener(String property, XVetoableChangeListener listener) throws UnknownPropertyException, WrappedTargetException { + throw new UnsupportedOperationException("Not supported yet."); + } + + // com.sun.star.beans.XPropertySetInfo: + + public Property[] getProperties() { + int propertyCount = m_properties.size(); + Property[] properties = new Property[propertyCount]; + for (int i = 0; i < propertyCount; i++) + properties[i] = m_properties.get(i).getProperty(); + return properties; + } + + public Property getPropertyByName(String property) throws UnknownPropertyException { + PropertyInfo propertyInfo = m_propertyMap.get(property); + if (propertyInfo != null) + return propertyInfo.getProperty(); + else + throw new UnknownPropertyException(); + } + + public boolean hasPropertyByName(String property) { + return m_propertyMap.containsKey(property); + } + + // Helper functions + private void lockDocument(boolean lock) { + if (lock) + m_xModel.lockControllers(); + else + m_xModel.unlockControllers(); + + try { + XIndexAccess xSpreadsheets = UnoRuntime.queryInterface(XIndexAccess.class, m_document.getSheets()); + int sheets = xSpreadsheets.getCount(); + for (int i = 0; i < sheets; i++) { + Object sheet = xSpreadsheets.getByIndex(i); + XTableChartsSupplier xTableChartsSupplier = UnoRuntime.queryInterface(XTableChartsSupplier.class, sheet); + XIndexAccess xCharts = UnoRuntime.queryInterface(XIndexAccess.class, xTableChartsSupplier.getCharts()); + int charts = xCharts.getCount(); + for (int j = 0; j < charts; j++) { + Object chart = xCharts.getByIndex(j); + XEmbeddedObjectSupplier xChartObjects = UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, chart); + XModel xChartModel = UnoRuntime.queryInterface(XModel.class, xChartObjects.getEmbeddedObject()); + if (lock) + xChartModel.lockControllers(); + else + xChartModel.unlockControllers(); + } + } + } catch (Exception ex) { + Logger.getLogger(BaseNLPSolver.class.getName()).log(Level.SEVERE, null, ex); + } + } + + protected void lockDocument() { + lockDocument(true); + } + + protected void unlockDocument() { + lockDocument(false); + } + + public static String nanoTimeToString(ResourceManager resourceManager, long nanoseconds) { + if (nanoseconds < 0) return null; // shouldn't happen... but if it does, throw an error! + + if (nanoseconds == 0) return "0"; + + if (nanoseconds < 1000) + return nanoseconds + " " + resourceManager.getLocalizedString("Time.Nanoseconds", "Nanoseconds"); + + double microseconds = (double) nanoseconds / 1000; + if (microseconds < 1000) + return String.format("%.2f %s", microseconds, resourceManager.getLocalizedString("Time.Microseconds", "Microseconds")); + + double milliseconds = microseconds / 1000; + if (milliseconds < 1000) + return String.format("%.2f %s", milliseconds, resourceManager.getLocalizedString("Time.Milliseconds", "Milliseconds")); + + double seconds = milliseconds / 1000; + if (seconds < 90) + return String.format("%.2f %s", seconds, resourceManager.getLocalizedString("Time.Seconds", "Seconds")); + + long minutes = (long) seconds / 60; + seconds -= minutes * 60; + long hours = minutes / 60; + minutes -= hours * 60; + long days = hours / 24; + hours -= days * 24; + + if (days > 0) + return String.format("%d %s, %d %s", + days, resourceManager.getLocalizedString(String.format("Time.Day%s", days == 1 ? "" : "s"), "Days"), + hours, resourceManager.getLocalizedString(String.format("Time.Hour%s", hours == 1 ? "" : "s"), "Hours")); + + if (hours > 0) + return String.format("%d %s, %d %s", + hours, resourceManager.getLocalizedString(String.format("Time.Hour%s", hours == 1 ? "" : "s"), "Hours"), + minutes, resourceManager.getLocalizedString(String.format("Time.Minute%s", minutes == 1 ? "" : "s"), "Minutes")); + + if (minutes > 0) + return String.format("%d %s, %.0f %s", + minutes, resourceManager.getLocalizedString(String.format("Time.Minute%s", minutes == 1 ? "" : "s"), "Minutes"), + Math.floor(seconds), resourceManager.getLocalizedString(String.format("Time.Second%s", Math.floor(seconds) == 1 ? "" : "s"), "Seconds")); + + return String.format("%.2f %s", seconds, resourceManager.getLocalizedString("Time.Seconds", "Seconds")); + } + // </editor-fold> + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/DEPSSolverImpl.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/DEPSSolverImpl.java new file mode 100644 index 000000000..aff425ba4 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/DEPSSolverImpl.java @@ -0,0 +1,216 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import net.adaptivebox.deps.DEPSAgent; +import net.adaptivebox.deps.behavior.DEGTBehavior; +import net.adaptivebox.deps.behavior.PSGTBehavior; +import net.adaptivebox.global.IUpdateCycleEngine; +import net.adaptivebox.knowledge.Library; +import net.adaptivebox.knowledge.SearchPoint; + +import com.sun.star.comp.Calc.NLPSolver.dialogs.IEvolutionarySolverStatusDialog; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.uno.XComponentContext; + + +public final class DEPSSolverImpl extends BaseEvolutionarySolver + implements com.sun.star.lang.XServiceInfo +{ + private static final String m_implementationName = DEPSSolverImpl.class.getName(); + private static final String[] m_serviceNames = { + "com.sun.star.sheet.Solver", + "com.sun.star.beans.PropertySet" + }; + + public DEPSSolverImpl( XComponentContext context ) + { + super(context, "DEPS Evolutionary Algorithm"); + + registerProperty(m_agentSwitchRate); + registerProperty(m_minFactor); + registerProperty(m_maxFactor); + registerProperty(m_CR); + registerProperty(m_c1); + registerProperty(m_c2); + registerProperty(m_weight); + registerProperty(m_CL); + } + + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( m_implementationName ) ) + xFactory = Factory.createComponentFactory(DEPSSolverImpl.class, m_serviceNames); + return xFactory; + } + + public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) { + return Factory.writeRegistryServiceInfo(m_implementationName, + m_serviceNames, + xRegistryKey); + } + + // com.sun.star.lang.XServiceInfo: + public String getImplementationName() { + return m_implementationName; + } + + public boolean supportsService( String sService ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if (sService.equals(m_serviceNames[i])) + return true; + } + return false; + } + + public String[] getSupportedServiceNames() { + return m_serviceNames; + } + + private final PropertyInfo<Double> m_agentSwitchRate = new PropertyInfo<Double>("AgentSwitchRate", 0.5, "Agent Switch Rate (DE Probability)"); + // --DE + private final PropertyInfo<Double> m_minFactor = new PropertyInfo<Double>("DEFactorMin", 0.5, "DE: Min Scaling Factor (0-1.2)"); + private final PropertyInfo<Double> m_maxFactor = new PropertyInfo<Double>("DEFactorMax", 0.5, "DE: Max Scaling Factor (0-1.2)"); + private final PropertyInfo<Double> m_CR = new PropertyInfo<Double>("DECR", 0.9, "DE: Crossover Probability (0-1)"); + // --PS + private final PropertyInfo<Double> m_c1 = new PropertyInfo<Double>("PSC1", 1.494, "PS: Cognitive Constant"); + private final PropertyInfo<Double> m_c2 = new PropertyInfo<Double>("PSC2", 1.494, "PS: Social Constant"); + private final PropertyInfo<Double> m_weight = new PropertyInfo<Double>("PSWeight", 0.729, "PS: Constriction Coefficient"); + private final PropertyInfo<Double> m_CL = new PropertyInfo<Double>("PSCL", 0.0, "PS: Mutation Probability (0-0.005)"); + + public void solve() { + try { + m_librarySize.setValue(m_swarmSize.getValue()); //DEPS' library is as large as the swarm + } catch (IllegalArgumentException ex) { + Logger.getLogger(DEPSSolverImpl.class.getName()).log(Level.SEVERE, null, ex); + } + initializeSolve(); + if (m_problemEncoder == null) + { + return; + } + + //Init: + DEPSAgent[] agents = new DEPSAgent[m_swarmSize.getValue()]; + for (int i = 0; i < m_swarmSize.getValue(); i++) { + agents[i] = new DEPSAgent(); + agents[i].setProblemEncoder(m_problemEncoder); + agents[i].setPbest(m_library.getSelectedPoint(i)); + + DEGTBehavior deGTBehavior = new DEGTBehavior(); + deGTBehavior.MIN_FACTOR = Math.min(m_minFactor.getValue(), m_maxFactor.getValue()); + deGTBehavior.MAX_FACTOR = Math.max(m_minFactor.getValue(), m_maxFactor.getValue()); + deGTBehavior.CR = m_CR.getValue(); + + PSGTBehavior psGTBehavior = new PSGTBehavior(); + psGTBehavior.c1 = m_c1.getValue(); + psGTBehavior.c2 = m_c2.getValue(); + psGTBehavior.CL = m_CL.getValue(); + psGTBehavior.weight = m_weight.getValue(); + + agents[i].switchP = m_agentSwitchRate.getValue(); + agents[i].setGTBehavior(deGTBehavior); + agents[i].setGTBehavior(psGTBehavior); + + agents[i].setSpecComparator(m_specCompareEngine); + agents[i].setLibrary(m_library); + } + + //Learn: + m_solverStatusDialog.setVisible(true); + m_solverStatusDialog.setMaxIterations(m_learningCycles.getValue()); + m_solverStatusDialog.setMaxStagnation(m_required.getValue()); + int learningCycle = 1; + long runtime = 0; + do { + long startTime = System.nanoTime(); + + if (learningCycle >= m_learningCycles.getValue()) + learningCycle = 1; + + if (m_solverStatusDialog.getUserState() == IEvolutionarySolverStatusDialog.CONTINUE) + lockDocument(); + + m_toleratedCount = 0; + m_toleratedMin = -1.0 * m_tolerance.getValue(); + m_toleratedMax = m_tolerance.getValue(); + for (; learningCycle <= m_learningCycles.getValue() && + m_toleratedCount < m_required.getValue() && + m_solverStatusDialog.getUserState() != IEvolutionarySolverStatusDialog.CANCEL; learningCycle++) { + m_library.refreshGbest(m_specCompareEngine); + + for (int i = 0; i < m_swarmSize.getValue(); i++) + agents[i].generatePoint(); + + for (int i = 0; i < m_swarmSize.getValue(); i++) + agents[i].learn(); + + for (int i = 0; i < m_swarmSize.getValue(); i++) { + SearchPoint agentPoint = agents[i].getMGState(); + boolean inRange = (agentPoint.getObjectiveValue() >= m_toleratedMin && agentPoint.getObjectiveValue() <= m_toleratedMax); + if (Library.replace(m_envCompareEngine, agentPoint, m_totalBestPoint)) { + m_solverStatusDialog.setBestSolution(m_totalBestPoint.getObjectiveValue(), m_totalBestPoint.isFeasible()); + if (!inRange) { + m_toleratedMin = agentPoint.getObjectiveValue() - m_tolerance.getValue(); + m_toleratedMax = agentPoint.getObjectiveValue() + m_tolerance.getValue(); + m_toleratedCount = 0; + } + } + } + + if (m_specCompareEngine instanceof IUpdateCycleEngine) + ((IUpdateCycleEngine)m_specCompareEngine).updateCycle(learningCycle); + + m_solverStatusDialog.setIteration(learningCycle); + m_solverStatusDialog.setStagnation(m_toleratedCount); + m_solverStatusDialog.setRuntime(runtime + (System.nanoTime() - startTime)); + m_xReschedule.reschedule(); + } + + applySolution(); //show the current solution + unlockDocument(); //allow the solution to be displayed + + runtime += (System.nanoTime() - startTime); + m_solverStatusDialog.setRuntime(runtime); + } while (m_solverStatusDialog.waitForUser() == IEvolutionarySolverStatusDialog.CONTINUE); + + lockDocument(); + + finalizeSolve(); + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/META-INF/manifest.xml b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/META-INF/manifest.xml new file mode 100644 index 000000000..0867cdd96 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/META-INF/manifest.xml @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?> +<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest"> + <manifest:file-entry manifest:media-type="application/vnd.sun.star.uno-components" + manifest:full-path="components.rdb"/> + <manifest:file-entry manifest:media-type="application/vnd.sun.star.help" + manifest:full-path="help"/> + <manifest:file-entry manifest:media-type="application/vnd.sun.star.package-bundle-description" + manifest:full-path="description/extensiondescription.txt"/> +</manifest:manifest>
\ No newline at end of file diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Manifest.mf b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Manifest.mf new file mode 100644 index 000000000..d194e6a3b --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Manifest.mf @@ -0,0 +1 @@ +RegistrationClassName: com.sun.star.comp.Calc.NLPSolver.Registration diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/PropertyInfo.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/PropertyInfo.java new file mode 100644 index 000000000..f1a7a4714 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/PropertyInfo.java @@ -0,0 +1,100 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.beans.Property; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.uno.Type; + +public class PropertyInfo<PropType> { + + private Property m_property; + private PropType m_value; + private String m_description; + + public Property getProperty() { + return m_property; + } + + public PropType getValue() { + return m_value; + } + + public String getDescription() { + return m_description; + } + + public void setValue(Object value) throws IllegalArgumentException { + if (m_property.Type == Type.LONG) { + if (!(value instanceof Integer)) + throw new IllegalArgumentException(); + m_value = (PropType)value; + } else if (m_property.Type == Type.DOUBLE) { + if (!(value instanceof Double)) + throw new IllegalArgumentException(); + m_value = (PropType)value; + } else if (m_property.Type == Type.BOOLEAN) { + if (!(value instanceof Boolean)) + throw new IllegalArgumentException(); + m_value = (PropType)value; + } + } + + public PropertyInfo(String name, PropType value, String description) { + this(name, value, (short)0, description); + } + + private PropertyInfo(String name, PropType value, short attributes, + String description) { + m_property = new Property(); + m_property.Name = name; + m_property.Attributes = attributes; + m_property.Handle = -1; + + if (value instanceof Integer) + m_property.Type = Type.LONG; + else if (value instanceof Double) + m_property.Type = Type.DOUBLE; + else if (value instanceof Boolean) + m_property.Type = Type.BOOLEAN; + + m_value = value; + m_description = description; + } + + public void localize(ResourceManager resourceManager) { + try { + m_description = resourceManager.getLocalizedString("Properties." + + m_property.Name); + } catch (com.sun.star.resource.MissingResourceException ex) { + System.out.println("Can't localize. Resource missing for property: " + + m_property.Name); + } + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Registration.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Registration.java new file mode 100644 index 000000000..157f4963f --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/Registration.java @@ -0,0 +1,38 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; + +public final class Registration { + + private static final String[] m_serviceNames = { + "com.sun.star.beans.PropertySet", + "com.sun.star.sheet.Solver" + }; + + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) + { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( "com.sun.star.comp.Calc.NLPSolver.DEPSSolverImpl" ) ) + xFactory = Factory.createComponentFactory( com.sun.star.comp.Calc.NLPSolver.DEPSSolverImpl.class, + m_serviceNames ); + if ( sImplementationName.equals( "com.sun.star.comp.Calc.NLPSolver.SCOSolverImpl" ) ) + xFactory = Factory.createComponentFactory( com.sun.star.comp.Calc.NLPSolver.SCOSolverImpl.class, + m_serviceNames ); + + return xFactory; + } + private Registration() {} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/ResourceManager.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/ResourceManager.java new file mode 100644 index 000000000..33eebc831 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/ResourceManager.java @@ -0,0 +1,93 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.beans.PropertyState; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.configuration.theDefaultProvider; +import com.sun.star.deployment.PackageInformationProvider; +import com.sun.star.deployment.XPackageInformationProvider; +import com.sun.star.lang.Locale; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.resource.StringResourceWithLocation; +import com.sun.star.resource.XStringResourceWithLocation; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +public class ResourceManager { + + private final String m_resourceBasename; + private XStringResourceWithLocation m_xStrResource; + + public ResourceManager(XComponentContext xContext, String oxtId, String relativeResourceBaseUrl, String resourceBasename) { + m_resourceBasename = resourceBasename; + + XPackageInformationProvider xPkgInfo = PackageInformationProvider.get(xContext); + final String oxtRoot = xPkgInfo.getPackageLocation(oxtId); + final String resourceBaseUrl = oxtRoot + relativeResourceBaseUrl; + + try { + XMultiServiceFactory xConfig = theDefaultProvider.get(xContext); + + Object[] args = new Object[1]; + args[0] = new PropertyValue("nodepath", 0, "/org.openoffice.Setup/L10N", PropertyState.DIRECT_VALUE); + XPropertySet xConfigProps = UnoRuntime.queryInterface(XPropertySet.class, + xConfig.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", args)); + String[] localeProp = AnyConverter.toString(xConfigProps.getPropertyValue("ooLocale")).split("-"); + String lang = localeProp[0]; + String country = (localeProp.length >= 2 ? localeProp[1] : ""); + String variant = (localeProp.length >= 3 ? localeProp[2] : ""); + Locale locale = new Locale(lang, country, variant); + + m_xStrResource = StringResourceWithLocation.create(xContext, resourceBaseUrl, true, locale, m_resourceBasename, "", null); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + /* This implementation is used if the presence of the key will be handled + * "outside" (i.e. by catching the appropriate MissingResourceException). */ + public String getLocalizedString(String key) throws com.sun.star.resource.MissingResourceException { + return m_xStrResource.resolveString(m_resourceBasename + "." + key); + } + + /* This implementation on the other hand handles the exception by itself + * and returns a (predefined) default value if necessary. */ + public String getLocalizedString(String key, String defaultValue) { + try { + return m_xStrResource.resolveString(m_resourceBasename + "." + key); + } catch (com.sun.star.resource.MissingResourceException ex) { + return defaultValue; + } + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/SCOSolverImpl.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/SCOSolverImpl.java new file mode 100644 index 000000000..c1798606d --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/SCOSolverImpl.java @@ -0,0 +1,167 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver; + +import com.sun.star.comp.Calc.NLPSolver.dialogs.IEvolutionarySolverStatusDialog; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.registry.XRegistryKey; +import net.adaptivebox.sco.SCAgent; +import net.adaptivebox.global.IUpdateCycleEngine; +import net.adaptivebox.knowledge.Library; +import net.adaptivebox.knowledge.SearchPoint; + + +public final class SCOSolverImpl extends BaseEvolutionarySolver + implements com.sun.star.lang.XServiceInfo +{ + private static final String m_implementationName = SCOSolverImpl.class.getName(); + private static final String[] m_serviceNames = { + "com.sun.star.sheet.Solver", + "com.sun.star.beans.PropertySet" + }; + + public SCOSolverImpl( XComponentContext context ) + { + super(context, "SCO Evolutionary Algorithm"); + + registerProperty(m_librarySize); //SCO allows the user to specify the size of the library + } + + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( m_implementationName ) ) + xFactory = Factory.createComponentFactory(SCOSolverImpl.class, m_serviceNames); + return xFactory; + } + + public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) { + return Factory.writeRegistryServiceInfo(m_implementationName, + m_serviceNames, + xRegistryKey); + } + + // com.sun.star.lang.XServiceInfo: + public String getImplementationName() { + return m_implementationName; + } + + public boolean supportsService( String sService ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if (sService.equals(m_serviceNames[i])) + return true; + } + return false; + } + + public String[] getSupportedServiceNames() { + return m_serviceNames; + } + + public void solve() { + initializeSolve(); + + if (m_problemEncoder == null) + { + return; + } + + //Init: + int swarmSize = m_swarmSize.getValue(); + SCAgent[] agents = new SCAgent[swarmSize]; + for (int i = 0; i < swarmSize; i++) { + agents[i] = new SCAgent(); + agents[i].setProblemEncoder(m_problemEncoder); + agents[i].setSpecComparator(m_specCompareEngine); + agents[i].setExternalLib(m_library); + } + + //Learn: + m_solverStatusDialog.setVisible(true); + int learningCycles = m_learningCycles.getValue(); + m_solverStatusDialog.setMaxIterations(learningCycles); + m_solverStatusDialog.setMaxStagnation(m_required.getValue()); + int learningCycle = 1; + long runtime = 0; + do { + long startTime = System.nanoTime(); + + if (learningCycle >= m_learningCycles.getValue()) + learningCycle = 1; + + if (m_solverStatusDialog.getUserState() == IEvolutionarySolverStatusDialog.CONTINUE) + lockDocument(); + + m_toleratedCount = 0; + m_toleratedMin = -1.0 * m_tolerance.getValue(); + m_toleratedMax = m_tolerance.getValue(); + for (; learningCycle <= learningCycles && + m_toleratedCount < m_required.getValue() && + m_solverStatusDialog.getUserState() != IEvolutionarySolverStatusDialog.CANCEL; learningCycle++) { + for (int i = 0; i < swarmSize; i++) { + SearchPoint point = agents[i].generatePoint(); + boolean inRange = (point.getObjectiveValue() >= m_toleratedMin && point.getObjectiveValue() <= m_toleratedMax); + if (Library.replace(m_envCompareEngine, point, m_totalBestPoint)) { + m_solverStatusDialog.setBestSolution(m_totalBestPoint.getObjectiveValue(), m_totalBestPoint.isFeasible()); + if (!inRange) { + m_toleratedMin = point.getObjectiveValue() - m_tolerance.getValue(); + m_toleratedMax = point.getObjectiveValue() + m_tolerance.getValue(); + m_toleratedCount = 0; + } + } + } + + for (int i = 0; i < swarmSize; i++) + agents[i].updateInfo(); + + if (m_specCompareEngine instanceof IUpdateCycleEngine) + ((IUpdateCycleEngine)m_specCompareEngine).updateCycle(learningCycle); + + m_solverStatusDialog.setIteration(learningCycle); + m_solverStatusDialog.setStagnation(m_toleratedCount); + m_solverStatusDialog.setRuntime(runtime + (System.nanoTime() - startTime)); + m_xReschedule.reschedule(); + } + + applySolution(); //show the current solution + unlockDocument(); //allow the solution to be displayed + + runtime += (System.nanoTime() - startTime); + m_solverStatusDialog.setRuntime(runtime); + } while (m_solverStatusDialog.waitForUser() == IEvolutionarySolverStatusDialog.CONTINUE); + + lockDocument(); + + finalizeSolve(); + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/components.rdb b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/components.rdb new file mode 100644 index 000000000..151ec5eed --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/components.rdb @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<components xmlns="http://openoffice.org/2010/uno-components"> + <component loader="com.sun.star.loader.Java2" uri="./nlpsolver.jar"> + <implementation name="com.sun.star.comp.Calc.NLPSolver.DEPSSolverImpl"> + <service name="com.sun.star.beans.PropertySet"/> + <service name="com.sun.star.sheet.Solver"/> + </implementation> + <implementation name="com.sun.star.comp.Calc.NLPSolver.SCOSolverImpl"> + <service name="com.sun.star.beans.PropertySet"/> + <service name="com.sun.star.sheet.Solver"/> + </implementation> + </component> +</components> diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description-en-US.txt b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description-en-US.txt new file mode 100644 index 000000000..9288dcf75 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description-en-US.txt @@ -0,0 +1 @@ +This extension integrates into Calc and offers new Solver engines to use for optimizing nonlinear programming models. diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description.xml b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description.xml new file mode 100644 index 000000000..928975682 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/description.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!--Created with OpenOffice.org API plug-in for NetBeans Version 2.0.3--> +<description xmlns="http://openoffice.org/extensions/description/2006" xmlns:xlink="http://www.w3.org/1999/xlink"> + <version value="0.9"/> + <identifier value="com.sun.star.comp.Calc.NLPSolver"/> + <display-name> + <name lang="en-US">Solver for Nonlinear Programming</name> + </display-name> + <publisher> + <name lang="en-US" xlink:href="http://www.documentfoundation.org">The Document Foundation</name> + </publisher> + <extension-description> + <src lang="en-US" xlink:href="description-en-US.txt"/> + </extension-description> + <dependencies> + <OpenOffice.org-minimal-version xmlns:d="http://openoffice.org/extensions/description/2006" d:name="OpenOffice.org 3.0" value="3.0"/> + </dependencies> +</description> diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/BaseDialog.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/BaseDialog.java new file mode 100644 index 000000000..d10ad3493 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/BaseDialog.java @@ -0,0 +1,151 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs; + +import com.sun.star.awt.InvalidateStyle; +import com.sun.star.awt.PosSize; +import com.sun.star.awt.Rectangle; +import com.sun.star.comp.Calc.NLPSolver.dialogs.controls.BaseControl; +import com.sun.star.awt.XControl; +import com.sun.star.awt.XControlModel; +import com.sun.star.awt.XDialog; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The BaseDialog represents the base for all dialogs used within the addon. + * It automatically loads the necessary interfaces to access OpenOffice.org dialogs. + */ +public abstract class BaseDialog extends BaseControl { + + private XMultiComponentFactory xMCF; + private XMultiServiceFactory xMSF; + protected XWindow xWindow; + protected XDialog xDialog; + private XWindowPeer xWindowPeer; + + @Override + public String getName() { + return null; + } + + public XMultiServiceFactory getMultiServiceFactory() { + return xMSF; + } + + private XFrame getCurrentFrame() throws Exception { + Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", context); + XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, oDesktop); + XComponent xComponent = xDesktop.getCurrentComponent(); + XModel xModel = UnoRuntime.queryInterface(XModel.class, xComponent); + XController xController = xModel.getCurrentController(); + return xController.getFrame(); + } + + private Rectangle getWorkspaceDimensions() throws Exception { + return getCurrentFrame().getComponentWindow().getPosSize(); + } + + public BaseDialog(XComponentContext context, String title, int x, int y, int width, int height) { + super(context); + try { + xMCF = context.getServiceManager(); + setUnoModel(xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialogModel", context)); + xMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, getUnoModel()); + + setProperty("Title", title); + setPosition(x, y); + setSize(width, height); + + unoControl = xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", context); + XControl xControl = UnoRuntime.queryInterface(XControl.class, unoControl); + XControlModel xControlModel = UnoRuntime.queryInterface(XControlModel.class, getUnoModel()); + xControl.setModel(xControlModel); + + Object toolkit = xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", context); + XToolkit xToolkit = UnoRuntime.queryInterface(XToolkit.class, toolkit); + xWindow = UnoRuntime.queryInterface(XWindow.class, unoControl); + xWindow.setVisible(false); + XWindowPeer xParentWindowPeer = UnoRuntime.queryInterface(XWindowPeer.class, getCurrentFrame().getComponentWindow()); + xControl.createPeer(xToolkit, xParentWindowPeer); + xWindowPeer = xControl.getPeer(); + + xDialog = UnoRuntime.queryInterface(XDialog.class, unoControl); + + //center if necessary + if (x < 0 || y < 0) { + Rectangle workspacePosSize = getWorkspaceDimensions(); + Rectangle dialogPosSize = xWindow.getPosSize(); + if (x < 0) + dialogPosSize.X = workspacePosSize.X + (workspacePosSize.Width / 2) - (dialogPosSize.Width / 2); + if (y < 0) + dialogPosSize.Y = workspacePosSize.Y + (workspacePosSize.Height / 2) - (dialogPosSize.Height / 2); + + xWindow.setPosSize(dialogPosSize.X, dialogPosSize.Y, + dialogPosSize.Width, dialogPosSize.Height, PosSize.POS); + } + + } catch (Exception ex) { + Logger.getLogger(BaseDialog.class.getName()).log(Level.SEVERE, null, ex); + } + } + + @Override + protected void finalize() throws Throwable { + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, unoControl); + xComponent.dispose(); + super.finalize(); + } + + + + + + public void setCloseable(boolean closeable) { + setProperty("Closeable", Boolean.valueOf(closeable)); + } + + public void repaint() { + xWindowPeer.invalidate((short)(InvalidateStyle.CHILDREN /*| InvalidateStyle.NOERASE*/ | + InvalidateStyle.UPDATE | InvalidateStyle.TRANSPARENT)); + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/DummyEvolutionarySolverStatusDialog.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/DummyEvolutionarySolverStatusDialog.java new file mode 100644 index 000000000..92f45b9a8 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/DummyEvolutionarySolverStatusDialog.java @@ -0,0 +1,73 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs; + +public class DummyEvolutionarySolverStatusDialog + implements IEvolutionarySolverStatusDialog { + + public int getUserState() { + return OK; + } + + public void setBestSolution(double solution, boolean feasible) { + + } + + public void setMaxIterations(int maxIterations) { + + } + + public void setMaxStagnation(int maxStagnation) { + + } + + public void setIteration(int iteration) { + + } + + public void setStagnation(int stagnation) { + + } + + public void setRuntime(long runtime) { + + } + + public int waitForUser() { + return OK; + } + + public void setVisible(boolean visible) { + + } + + public void dispose() { + + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/EvolutionarySolverStatusUno.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/EvolutionarySolverStatusUno.java new file mode 100644 index 000000000..e3695a0c7 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/EvolutionarySolverStatusUno.java @@ -0,0 +1,292 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs; + +import com.sun.star.comp.Calc.NLPSolver.BaseNLPSolver; +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.XActionListener; +import com.sun.star.comp.Calc.NLPSolver.ResourceManager; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XComponent; +import com.sun.star.style.VerticalAlignment; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.comp.Calc.NLPSolver.dialogs.controls.Button; +import com.sun.star.comp.Calc.NLPSolver.dialogs.controls.Label; +import com.sun.star.comp.Calc.NLPSolver.dialogs.controls.ProgressBar; + +public class EvolutionarySolverStatusUno extends BaseDialog + implements IEvolutionarySolverStatusDialog, + XActionListener { + + private int userState; + private final Label lblSolutionValue; + private final Label lblIteration; + private final ProgressBar pbIteration; + private final Label lblIterationValue; + private final Label lblStagnation; + private final ProgressBar pbStagnation; + private final Label lblStagnationValue; + private final Label lblRuntimeValue; + private final Button btnStop; + private final Button btnOK; + private final Button btnContinue; + private final int defaultTextColor; + private int maxIterations; + private int maxStagnation; + + private final ResourceManager resourceManager; + + private static final int COLOR_RED = 0xFF0000; + + public EvolutionarySolverStatusUno(XComponentContext xContext) { + super(xContext, "Solver Status", -1, -1, 170, 95); //center the dialog on the parent + + setCloseable(false); + userState = IEvolutionarySolverStatusDialog.OK; + + resourceManager = new ResourceManager(xContext, "com.sun.star.comp.Calc.NLPSolver", "/locale", "NLPSolverStatusDialog"); + + try { + setProperty("Title", resourceManager.getLocalizedString("Dialog.Caption")); + } catch (com.sun.star.resource.MissingResourceException ex) {} //leave the title as it is + + int y = 5; + Label lblSolution = new Label(this, "lblSolution"); + lblSolution.setPosition(5, y); + lblSolution.setSize(60, 10); + lblSolution.setLabel(resourceManager.getLocalizedString("Controls.lblSolution", "Current Solution:")); + lblSolution.setParentControl(this); + + lblSolutionValue = new Label(this, "lblSolutionValue"); + lblSolutionValue.setPosition(65, y); + lblSolutionValue.setSize(100, 10); + lblSolutionValue.setParentControl(this); + defaultTextColor = lblSolutionValue.getTextColor(); + y += 15; + + lblIteration = new Label(this, "lblIteration"); + lblIteration.setPosition(5, y); + lblIteration.setSize(60, 15); + lblIteration.setLabel(resourceManager.getLocalizedString("Controls.lblIteration", "Iteration:")); + lblIteration.setVerticalAlign(VerticalAlignment.MIDDLE); + lblIteration.setParentControl(this); + + pbIteration = new ProgressBar(this, "pbIteration"); + pbIteration.setPosition(65, y); + pbIteration.setSize(100, 15); + pbIteration.setParentControl(this); + + lblIterationValue = new Label(this, "lblIterationValue"); + lblIterationValue.setPosition(65, y); + lblIterationValue.setSize(100, 20); + lblIterationValue.setVerticalAlign(VerticalAlignment.MIDDLE); + lblIterationValue.setMultiLine(true); + lblIterationValue.setParentControl(this); + lblIterationValue.setVisible(false); + y += 20; + + lblStagnation = new Label(this, "lblStagnation"); + lblStagnation.setPosition(5, y); + lblStagnation.setSize(60, 15); + lblStagnation.setLabel(resourceManager.getLocalizedString("Controls.lblStagnation", "Stagnation:")); + lblStagnation.setVerticalAlign(VerticalAlignment.MIDDLE); + lblStagnation.setParentControl(this); + + pbStagnation = new ProgressBar(this, "pbStagnation"); + pbStagnation.setPosition(65, y); + pbStagnation.setSize(100, 15); + pbStagnation.setParentControl(this); + + lblStagnationValue = new Label(this, "lblStagnationValue"); + lblStagnationValue.setPosition(65, y); + lblStagnationValue.setSize(100, 20); + lblStagnationValue.setVerticalAlign(VerticalAlignment.MIDDLE); + lblStagnationValue.setMultiLine(true); + lblStagnationValue.setParentControl(this); + lblStagnationValue.setVisible(false); + y+= 20; + + Label lblRuntime = new Label(this, "lblRuntime"); + lblRuntime.setPosition(5, y); + lblRuntime.setSize(60, 10); + lblRuntime.setLabel(resourceManager.getLocalizedString("Controls.lblRuntime", "Runtime:")); + lblRuntime.setParentControl(this); + + lblRuntimeValue = new Label(this, "lblRuntimeValue"); + lblRuntimeValue.setPosition(65, y); + lblRuntimeValue.setSize(100, 10); + lblRuntimeValue.setParentControl(this); + y += 15; + + btnStop = new Button(this, "btnStop"); + btnStop.setPosition(5, y); + btnStop.setSize(45, 15); + btnStop.setLabel(resourceManager.getLocalizedString("Controls.btnStop", "Stop")); + btnStop.setParentControl(this); + btnStop.addActionListener(this); + btnStop.setActionCommand("btnStopClick"); + + btnOK = new Button(this, "btnOK"); + btnOK.setPosition(65, y); + btnOK.setSize(40, 15); + btnOK.setLabel(resourceManager.getLocalizedString("Controls.btnOK", "OK")); + btnOK.setParentControl(this); + btnOK.addActionListener(this); + btnOK.setActionCommand("btnOKClick"); + btnOK.setEnabled(false); + + btnContinue = new Button(this, "btnContinue"); + btnContinue.setPosition(110, y); + btnContinue.setSize(55, 15); + btnContinue.setLabel(resourceManager.getLocalizedString("Controls.btnContinue", "Continue")); + btnContinue.setParentControl(this); + btnContinue.addActionListener(this); + btnContinue.setActionCommand("btnContinueClick"); + btnContinue.setEnabled(false); + y += 15; + } + + public int getUserState() { + return userState; + } + + public void setBestSolution(double solution, boolean feasible) { + lblSolutionValue.setLabel(String.format("%g", solution)); + if (feasible) + lblSolutionValue.setTextColor(defaultTextColor); + else + lblSolutionValue.setTextColor(COLOR_RED); //red + } + + public void setMaxIterations(int maxIterations) { + pbIteration.setRange(0, maxIterations); + this.maxIterations = maxIterations; + } + + public void setMaxStagnation(int maxStagnation) { + pbStagnation.setRange(0, maxStagnation); + this.maxStagnation = maxStagnation; + } + + public void setIteration(int iteration) { + pbIteration.setValue(iteration); + } + + public void setStagnation(int stagnation) { + pbStagnation.setValue(stagnation); + } + + public void setRuntime(long runtime) { + lblRuntimeValue.setLabel(BaseNLPSolver.nanoTimeToString(resourceManager, runtime)); + } + + public int waitForUser() { + btnStop.setEnabled(false); + btnOK.setEnabled(true); + btnContinue.setEnabled(true); + + if (pbIteration.getValue() >= maxIterations) { + lblIteration.setTextColor(COLOR_RED); + if (userState != IEvolutionarySolverStatusDialog.CANCEL) + lblStagnationValue.setLabel( + resourceManager.getLocalizedString("Message.StopIteration", + "Maximum iterations reached.")); + } + + if (pbStagnation.getValue() >= maxStagnation) { + lblStagnation.setTextColor(COLOR_RED); + if (userState != IEvolutionarySolverStatusDialog.CANCEL) + lblStagnationValue.setLabel( + resourceManager.getLocalizedString("Message.StopStagnation", + "Process stopped due to stagnation.")); + } + + lblIterationValue.setLabel(String.format( + resourceManager.getLocalizedString("Message.CurrentIteration", + "Process stopped at iteration %d of %d."), + pbIteration.getValue(), maxIterations)); + if (userState == IEvolutionarySolverStatusDialog.CANCEL) + lblStagnationValue.setLabel( + resourceManager.getLocalizedString("Message.StopUser", + "Process stopped due to user interruption.")); + + pbIteration.setVisible(false); + pbStagnation.setVisible(false); + lblIterationValue.setVisible(true); + lblStagnationValue.setVisible(true); + + repaint(); + + userState = IEvolutionarySolverStatusDialog.WAITING; + xDialog.execute(); + + lblIteration.setTextColor(defaultTextColor); + lblStagnation.setTextColor(defaultTextColor); + + lblIterationValue.setVisible(false); + lblStagnationValue.setVisible(false); + pbIteration.setVisible(true); + pbStagnation.setVisible(true); + + btnStop.setEnabled(true); + btnOK.setEnabled(false); + btnContinue.setEnabled(false); + + return userState; + } + + @Override + public void setVisible(boolean visible) { + xWindow.setVisible(visible); + } + + public void dispose() { + XComponent component = UnoRuntime.queryInterface(XComponent.class, xDialog); + component.dispose(); + } + + public void actionPerformed(ActionEvent actionEvent) { + if (userState == IEvolutionarySolverStatusDialog.WAITING) { + xDialog.endExecute(); + setVisible(true); + } + + if (actionEvent.ActionCommand.equals("btnStopClick")) + userState = IEvolutionarySolverStatusDialog.CANCEL; + else if (actionEvent.ActionCommand.equals("btnOKClick")) + userState = IEvolutionarySolverStatusDialog.OK; + else if (actionEvent.ActionCommand.equals("btnContinueClick")) + userState = IEvolutionarySolverStatusDialog.CONTINUE; + } + + public void disposing(EventObject eventObject) { + + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/IEvolutionarySolverStatusDialog.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/IEvolutionarySolverStatusDialog.java new file mode 100644 index 000000000..9ef12e09e --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/IEvolutionarySolverStatusDialog.java @@ -0,0 +1,48 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs; + +public interface IEvolutionarySolverStatusDialog { + int WAITING = 0; + int OK = 1; + int CONTINUE = 2; + int CANCEL = 3; + + int getUserState(); + + void setBestSolution(double solution, boolean feasible); + void setMaxIterations(int maxIterations); + void setMaxStagnation(int maxStagnation); + void setIteration(int iteration); + void setStagnation(int stagnation); + void setRuntime(long runtime); + int waitForUser(); + + void setVisible(boolean visible); + void dispose(); +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/BaseControl.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/BaseControl.java new file mode 100644 index 000000000..7de59c4b0 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/BaseControl.java @@ -0,0 +1,141 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs.controls; + +import com.sun.star.awt.XControlContainer; +import com.sun.star.awt.XWindow; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.ElementExistException; +import com.sun.star.container.XNameContainer; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import java.util.logging.Level; +import java.util.logging.Logger; + +public abstract class BaseControl { + + protected XComponentContext context; + private Object unoModel; + protected Object unoControl; + private XPropertySet properties; + + + public abstract String getName(); + + public Object getUnoModel() { + return unoModel; + } + + /** + * This is used <b>internally</b> to update the UnoModel and refresh the + * associated PropertySet. + * @param unoModel The new UnoModel for this control. + */ + protected void setUnoModel(Object unoModel) { + this.unoModel = unoModel; + properties = UnoRuntime.queryInterface(XPropertySet.class, unoModel); + } + + public void setParentControl(BaseControl parentControl) { + //TODO : remove from existing parentControl + try { + String name = getName(); + XNameContainer nameContainer = UnoRuntime.queryInterface(XNameContainer.class, parentControl.unoModel); + nameContainer.insertByName(name, unoModel); + + XControlContainer controlContainer = UnoRuntime.queryInterface(XControlContainer.class, parentControl.unoControl); + unoControl = controlContainer.getControl(name); + + } catch (IllegalArgumentException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (ElementExistException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (WrappedTargetException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public BaseControl(XComponentContext context) { + this.context = context; + unoModel = null; + unoControl = null; + } + + protected void setProperty(String name, Object value) { + try { + properties.setPropertyValue(name, value); + } catch (UnknownPropertyException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (PropertyVetoException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (IllegalArgumentException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (WrappedTargetException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } + } + + protected Object getProperty(String name) { + try { + return properties.getPropertyValue(name); + } catch (UnknownPropertyException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } catch (WrappedTargetException ex) { + Logger.getLogger(BaseControl.class.getName()).log(Level.SEVERE, null, ex); + } + return null; + } + + // <editor-fold defaultstate="collapsed" desc="Uno Properties"> + + public void setPosition(int x, int y) { + setProperty("PositionX", Integer.valueOf(x)); + setProperty("PositionY", Integer.valueOf(y)); + } + + public void setSize(int width, int height) { + setProperty("Width", Integer.valueOf(width)); + setProperty("Height", Integer.valueOf(height)); + } + + public void setEnabled(boolean enabled) { + setProperty("Enabled", Boolean.valueOf(enabled)); + } + + public void setVisible(boolean visible) { + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, unoControl); + xWindow.setVisible(visible); + } + + // </editor-fold> + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Button.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Button.java new file mode 100644 index 000000000..61ae47c19 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Button.java @@ -0,0 +1,73 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs.controls; + +import com.sun.star.awt.XActionListener; +import com.sun.star.awt.XButton; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import java.util.logging.Level; +import java.util.logging.Logger; +import com.sun.star.comp.Calc.NLPSolver.dialogs.BaseDialog; + +public class Button extends LabeledControl { + + private String name; + private XButton xButton; + + public Button(BaseDialog owner, String name) { + super(owner.context); + try { + setUnoModel(owner.getMultiServiceFactory().createInstance("com.sun.star.awt.UnoControlButtonModel")); + this.name = name; + setProperty("Name", name); + } catch (Exception ex) { + Logger.getLogger(Button.class.getName()).log(Level.SEVERE, null, ex); + } + } + + @Override + public String getName() { + return name; + } + + @Override + public void setParentControl(BaseControl parentControl) { + super.setParentControl(parentControl); + xButton = UnoRuntime.queryInterface(XButton.class, unoControl); + } + + public void addActionListener(XActionListener actionListener) { + xButton.addActionListener(actionListener); + } + + public void setActionCommand(String actionCommand) { + xButton.setActionCommand(actionCommand); + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Label.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Label.java new file mode 100644 index 000000000..689350ce2 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/Label.java @@ -0,0 +1,78 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs.controls; + +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.style.VerticalAlignment; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import com.sun.star.comp.Calc.NLPSolver.dialogs.BaseDialog; + +public class Label extends LabeledControl { + + private String name; + + public Label(BaseDialog owner, String name) { + super(owner.context); + try { + setUnoModel(owner.getMultiServiceFactory().createInstance("com.sun.star.awt.UnoControlFixedTextModel")); + this.name = name; + setProperty("Name", name); + } catch (Exception ex) { + Logger.getLogger(Button.class.getName()).log(Level.SEVERE, null, ex); + } + } + + @Override + public String getName() { + return name; + } + + public void setVerticalAlign(VerticalAlignment align) { + setProperty("VerticalAlign", align); + } + + + public void setTextColor(int RGB) { + setProperty("TextColor", Integer.valueOf(RGB)); + } + + public int getTextColor() { + try { + Object prop = getProperty("TextColor"); + if (AnyConverter.getType(prop) == Type.LONG) + return AnyConverter.toInt(prop); + } catch (IllegalArgumentException ex) { + Logger.getLogger(LabeledControl.class.getName()).log(Level.SEVERE, null, ex); + } + return 0; + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/LabeledControl.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/LabeledControl.java new file mode 100644 index 000000000..a1c8c7674 --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/LabeledControl.java @@ -0,0 +1,46 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs.controls; + +import com.sun.star.uno.XComponentContext; + +public abstract class LabeledControl extends BaseControl { + + public LabeledControl(XComponentContext context) { + super(context); + } + + public void setLabel(String label) { + setProperty("Label", label); + } + + public void setMultiLine(boolean multiLine) { + setProperty("MultiLine", Boolean.valueOf(multiLine)); + } + +} diff --git a/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/ProgressBar.java b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/ProgressBar.java new file mode 100644 index 000000000..a62ea7d9f --- /dev/null +++ b/nlpsolver/src/com/sun/star/comp/Calc/NLPSolver/dialogs/controls/ProgressBar.java @@ -0,0 +1,74 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package com.sun.star.comp.Calc.NLPSolver.dialogs.controls; + +import com.sun.star.awt.XProgressBar; +import com.sun.star.uno.UnoRuntime; +import java.util.logging.Level; +import java.util.logging.Logger; +import com.sun.star.comp.Calc.NLPSolver.dialogs.BaseDialog; + +public class ProgressBar extends BaseControl { + + private String m_name; + private XProgressBar m_progressBar; + + public ProgressBar(BaseDialog owner, String name) { + super(owner.context); + try { + setUnoModel(owner.getMultiServiceFactory().createInstance("com.sun.star.awt.UnoControlProgressBarModel")); + m_name = name; + setProperty("Name", name); + } catch (Exception ex) { + Logger.getLogger(Button.class.getName()).log(Level.SEVERE, null, ex); + } + } + + @Override + public String getName() { + return m_name; + } + + @Override + public void setParentControl(BaseControl parentControl) { + super.setParentControl(parentControl); + m_progressBar = UnoRuntime.queryInterface(XProgressBar.class, unoControl); + } + + public void setRange(int min, int max) { + m_progressBar.setRange(min, max); + } + + public void setValue(int value) { + m_progressBar.setValue(value); + } + + public int getValue() { + return m_progressBar.getValue(); + } +} |