Exemplo n.º 1
0
        public void Add(FitElement e)
        {
            InnerList.Add(e);
            e.Changed += new EventHandler(EhChildChanged);

            OnChanged();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets a new or recycled fit document for a given plot item <see cref="XYColumnPlotItem"/>.
        /// </summary>
        /// <param name="xyPlotItem">The xy plot item.</param>
        /// <param name="ctrl">The control.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">xyPlotItem</exception>
        private static Tuple <string, NonlinearFitDocument, string, XYPlotLayer> GetNewFitDocumentFor(XYColumnPlotItem xyPlotItem, Altaxo.Gui.Graph.Gdi.Viewing.IGraphController ctrl)
        {
            if (null == xyPlotItem)
            {
                throw new ArgumentNullException(nameof(xyPlotItem));
            }

            var activeLayer = Altaxo.Main.AbsoluteDocumentPath.GetRootNodeImplementing <XYPlotLayer>(xyPlotItem);
            var xColumn     = xyPlotItem.XYColumnPlotData.XColumn;
            var yColumn     = xyPlotItem.XYColumnPlotData.YColumn;

            if (xColumn == null || xColumn.ItemType != typeof(double))
            {
                return(new Tuple <string, NonlinearFitDocument, string, XYPlotLayer>("The x-column is not numeric", null, null, activeLayer));
            }

            if (yColumn == null || yColumn.ItemType != typeof(double))
            {
                return(new Tuple <string, NonlinearFitDocument, string, XYPlotLayer>("The y-column is not numeric", null, null, activeLayer));
            }

            var localdoc = (ctrl.Doc.GetGraphProperty(FitDocumentPropertyName) as Calc.Regression.Nonlinear.NonlinearFitDocument) ??
                           (Altaxo.Calc.Regression.Nonlinear.NonlinearFitDocument)_lastFitDocument?.Clone() ??
                           new Altaxo.Calc.Regression.Nonlinear.NonlinearFitDocument();

            if (localdoc.FitEnsemble.Count == 0) // if there was no fit before
            {
                var fitele = new Altaxo.Calc.Regression.Nonlinear.FitElement(
                    xyPlotItem.Data.DataTable,
                    xyPlotItem.Data.GroupNumber,
                    xyPlotItem.Data.DataRowSelection,
                    xColumn,
                    yColumn);

                localdoc.FitEnsemble.Add(fitele);
            }
            else // there was a fit before, thus localdoc.FitEnsemble.Count>0
            {
                bool hasColumnsChanged = false;

                hasColumnsChanged |= !(object.ReferenceEquals(localdoc.FitEnsemble[0].DataTable, xyPlotItem.Data.DataTable));
                hasColumnsChanged |= !(object.ReferenceEquals(localdoc.FitEnsemble[0].GroupNumber, xyPlotItem.Data.GroupNumber));
                hasColumnsChanged |= !(object.ReferenceEquals(localdoc.FitEnsemble[0].IndependentVariables(0), xColumn));
                hasColumnsChanged |= !(object.ReferenceEquals(localdoc.FitEnsemble[0].DependentVariables(0), yColumn));

                localdoc.FitEnsemble[0].SetIndependentVariable(0, xColumn);
                localdoc.FitEnsemble[0].SetDependentVariable(0, yColumn);

                if (hasColumnsChanged) // if some of the columns has changed, take the data row selection of the plot item
                {
                    localdoc.FitEnsemble[0].DataRowSelection = xyPlotItem.Data.DataRowSelection;
                }
            }

            return(new Tuple <string, NonlinearFitDocument, string, XYPlotLayer>(string.Empty, localdoc, null, activeLayer));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Calculates the jacobian values, i.e. the derivatives of the fitting values with respect to the parameters.
        /// </summary>
        /// <param name="parameter">The parameter used to calculate the values.</param>
        /// <param name="outputValues">You must provide an array to hold the calculated values. Size of the array must be
        /// at least <see cref="NumberOfData" />*<see cref="FitElement.NumberOfParameters" />.</param>
        /// <param name="adata">Currently ignored.</param>
        /// <remarks>The values of the fit elements are stored in the order from element_0 to element_n*m. If there is more
        /// than one used dependent variable per fit element, the output values are stored in interleaved order. The derivatives
        /// on one fitting value  are stored in successive order.
        /// </remarks>
        public void EvaluateFitJacobian(double[] parameter, double[] outputValues, object adata)
        {
            outputValues.Initialize(); // make sure every element contains zero

            int outputValuesPointer = 0;

            for (int ele = 0; ele < _cachedFitElementInfo.Length; ele++)
            {
                CachedFitElementInfo info   = _cachedFitElementInfo[ele];
                FitElement           fitEle = _fitEnsemble[ele];


                // make sure, that the dimension of the DYs is ok
                if (info.DYs == null || info.DYs.Length != fitEle.NumberOfDependentVariables || info.DYs[0].Length != fitEle.NumberOfParameters)
                {
                    info.DYs = LinearAlgebra.JaggedArrayMath.GetMatrixArray(fitEle.NumberOfDependentVariables, fitEle.NumberOfParameters);
                }

                // copy of the parameter to the temporary array
                for (int i = 0; i < info.Parameters.Length; i++)
                {
                    int idx = info.ParameterMapping[i];
                    info.Parameters[i] = idx >= 0 ? parameter[idx] : _constantParameters[-1 - idx];
                }


                IAscendingIntegerCollection validRows = info.ValidRows;
                int numValidRows = validRows.Count;
                // Evaluate the function for all points
                for (int i = 0; i < numValidRows; ++i)
                {
                    for (int k = info.Xs.Length - 1; k >= 0; k--)
                    {
                        info.Xs[k] = fitEle.IndependentVariables(k)[validRows[i]];
                    }

                    ((IFitFunctionWithGradient)fitEle.FitFunction).EvaluateGradient(info.Xs, info.Parameters, info.DYs);

                    // copy the evaluation result to the output array (interleaved)
                    for (int k = 0; k < info.DependentVariablesInUse.Length; ++k)
                    {
                        for (int l = 0; l < info.Parameters.Length; ++l)
                        {
                            int idx = info.ParameterMapping[l];
                            if (idx >= 0)
                            {
                                outputValues[outputValuesPointer + idx] += info.DYs[info.DependentVariablesInUse[k]][l];
                            }
                        }
                        outputValuesPointer += parameter.Length; // increase output pointer only by the varying (!) number of parameters
                    }
                }
            }
        }
Exemplo n.º 4
0
            public virtual void Serialize(object obj, Altaxo.Serialization.Xml.IXmlSerializationInfo info)
            {
                FitElement s = (FitElement)obj;

                info.AddValue("FitFunction", s._fitFunction);
                info.AddValue("NumberOfRows", s._rangeOfRows.Count);
                info.AddValue("FirstRow", s._rangeOfRows.First);

                info.AddArray("IndependentVariables", s._independentVariables, s._independentVariables.Length);
                info.AddArray("DependentVariables", s._dependentVariables, s._dependentVariables.Length);
                info.AddArray("VarianceEvaluation", s._errorEvaluation, s._errorEvaluation.Length);
                info.AddArray("ParameterNames", s._parameterNames, s._parameterNames.Length);
                info.AddValue("ParameterNameStart", s._parameterNameStart);
            }
Exemplo n.º 5
0
            public virtual object Deserialize(object o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object parent)
            {
                FitElement s = o != null ? (FitElement)o : new FitElement();

                s.FitFunction = (IFitFunction)info.GetValue("FitFunction", s);

                int numRows  = info.GetInt32("NumberOfRows");
                int firstRow = info.GetInt32("FirstRow");

                s._rangeOfRows = PositiveIntegerRange.NewFromFirstAndCount(firstRow, numRows);

                int arraycount = info.OpenArray();

                s._independentVariables = new NumericColumnProxy[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._independentVariables[i] = (NumericColumnProxy)info.GetValue(s);
                }
                info.CloseArray(arraycount);

                arraycount            = info.OpenArray();
                s._dependentVariables = new NumericColumnProxy[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._dependentVariables[i] = (NumericColumnProxy)info.GetValue(s);
                }
                info.CloseArray(arraycount);


                arraycount         = info.OpenArray();
                s._errorEvaluation = new IVarianceScaling[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._errorEvaluation[i] = (IVarianceScaling)info.GetValue(s);
                }
                info.CloseArray(arraycount);

                info.GetArray("ParameterNames", out s._parameterNames);
                for (int i = 0; i < s._parameterNames.Length; ++i)
                {
                    if (s._parameterNames[i] == string.Empty)
                    {
                        s._parameterNames[i] = null; // serialization can not distinguish between an empty string and a null string
                    }
                }
                s._parameterNameStart = info.GetString("ParameterNameStart");
                return(s);
            }
Exemplo n.º 6
0
        public FitElement(FitElement from)
        {
            if (from._fitFunction is ICloneable fromFitFunc1)
            {
                _fitFunction = (IFitFunction)fromFitFunc1.Clone();
                if (_fitFunction is Main.IDocumentLeafNode thisFitFunc1)
                {
                    thisFitFunc1.ParentObject = this;
                }
            }
            else
            {
                _fitFunction = from._fitFunction;
            }

            if (null != _fitFunction)
            {
                _fitFunction.Changed += EhFitFunctionChanged;
            }

            ChildCopyToMember(ref _dataTable, from._dataTable);
            _groupNumber = from._groupNumber;
            ChildCloneToMember(ref _rangeOfRows, from._rangeOfRows);

            _independentVariables = new IReadableColumnProxy[from._independentVariables.Length];
            for (int i = 0; i < _independentVariables.Length; ++i)
            {
                ChildCloneToMember(ref _independentVariables[i], from._independentVariables[i]);
            }

            _dependentVariables = new IReadableColumnProxy[from._dependentVariables.Length];
            for (int i = 0; i < _dependentVariables.Length; ++i)
            {
                ChildCloneToMember(ref _dependentVariables[i], from._dependentVariables[i]);
            }

            _errorEvaluation = new IVarianceScaling[from._errorEvaluation.Length];
            for (int i = 0; i < _errorEvaluation.Length; ++i)
            {
                if (from._errorEvaluation[i] != null)
                {
                    _errorEvaluation[i] = (IVarianceScaling)from._errorEvaluation[i].Clone();
                }
            }

            _parameterNames     = (string[])from._parameterNames.Clone();
            _parameterNameStart = from._parameterNameStart;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Calculates the fitting values.
        /// </summary>
        /// <param name="parameter">The parameter used to calculate the values.</param>
        /// <param name="outputValues">You must provide an array to hold the calculated values. Size of the array must be
        /// at least <see cref="NumberOfData" />.</param>
        /// <param name="calculateUnusedDependentVariablesAlso">If <c>true</c>, the unused dependent variables are also calculated (and plotted).</param>
        /// <remarks>The values of the fit elements are stored in the order from element_0 to element_n. If there is more
        /// than one used dependent variable per fit element, the output values are stored in interleaved order.
        /// </remarks>
        public void EvaluateFitValues(double[] parameter, double[] outputValues, bool calculateUnusedDependentVariablesAlso)
        {
            int outputValuesPointer = 0;

            for (int ele = 0; ele < _cachedFitElementInfo.Length; ele++)
            {
                CachedFitElementInfo info   = _cachedFitElementInfo[ele];
                FitElement           fitEle = _fitEnsemble[ele];

                // copy of the parameter to the temporary array
                for (int i = 0; i < info.Parameters.Length; i++)
                {
                    int idx = info.ParameterMapping[i];
                    info.Parameters[i] = idx >= 0 ? parameter[idx] : _constantParameters[-1 - idx];
                }

                IAscendingIntegerCollection validRows = info.ValidRows;
                int numValidRows = validRows.Count;
                // Evaluate the function for all points
                for (int i = 0; i < numValidRows; ++i)
                {
                    for (int k = info.Xs.Length - 1; k >= 0; k--)
                    {
                        info.Xs[k] = fitEle.IndependentVariables(k)[validRows[i]];
                    }

                    fitEle.FitFunction.Evaluate(info.Xs, info.Parameters, info.Ys);

                    if (calculateUnusedDependentVariablesAlso)
                    {
                        // copy the evaluation result to the output array (interleaved)
                        for (int k = 0; k < fitEle.NumberOfDependentVariables; ++k)
                        {
                            outputValues[outputValuesPointer++] = info.Ys[k];
                        }
                    }
                    else
                    {
                        // copy the evaluation result to the output array (interleaved)
                        for (int k = 0; k < info.DependentVariablesInUse.Length; ++k)
                        {
                            outputValues[outputValuesPointer++] = info.Ys[info.DependentVariablesInUse[k]];
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        public FitElement this[int i]
        {
            get
            {
                return((FitElement)InnerList[i]);
            }
            set
            {
                FitElement oldValue = this[i];
                oldValue.Changed -= new EventHandler(EhChildChanged);

                InnerList[i]   = value;
                value.Changed += new EventHandler(EhChildChanged);

                OnChanged();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates an instance of this class. This constructor needs either
        /// <paramref name="dataTable"/>, <paramref name="xCol"/> and <paramref name="yCol"/> to be valid, or all to be null.
        /// If all null, consider to use the other provided constructor.
        /// </summary>
        /// <param name="fitFunc">Fitting function.</param>
        /// <param name="parameter">Array of default parameters (length must match the expected number of parameter of fitFunc).</param>
        /// <param name="dataTable">The data table from which the provided <paramref name="xCol"/> and <paramref name="yCol"/> originate.</param>
        /// <param name="groupNumber">The group number of the columns <paramref name="xCol"/> and <paramref name="yCol"/>.</param>
        /// <param name="xCol">Data column of independent values.</param>
        /// <param name="yCol">Data column of dependent values.</param>
        /// <param name="start">First point to be used for fitting.</param>
        /// <param name="count">Number of points to be used for fitting.</param>
        public SimpleNonlinearFit(FitEvaluationFunction fitFunc, double[] parameter, Altaxo.Data.DataTable dataTable, int groupNumber, Altaxo.Data.INumericColumn xCol, Altaxo.Data.INumericColumn yCol, int start, int count)
        {
            _fitDoc = new NonlinearFitDocument();

            if (null == dataTable && null == xCol && null == yCol)
            {
                _fitEle = new FitElement(Altaxo.Data.Selections.RangeOfRowIndices.FromStartAndCount(start, count));
            }
            else
            {
                _fitEle = new FitElement(dataTable, groupNumber, Altaxo.Data.Selections.RangeOfRowIndices.FromStartAndCount(start, count), xCol, yCol);
            }

            _fitEle.FitFunction = new DummyFitFunc(fitFunc, parameter);
            _fitDoc.FitEnsemble.Add(_fitEle);
            _fitDoc.SetDefaultParametersForFitElement(0);
        }
Exemplo n.º 10
0
        public double[] GetParametersForFitElement(int idx)
        {
            FitElement fitele = _fitEnsemble[idx];

            System.Collections.Hashtable byName = new System.Collections.Hashtable();
            for (int i = 0; i < _currentParameters.Count; i++)
            {
                byName.Add(_currentParameters[i].Name, _currentParameters[i].Parameter);
            }

            double[] result = new double[fitele.NumberOfParameters];
            for (int i = 0; i < result.Length; ++i)
            {
                result[i] = (double)byName[fitele.ParameterName(i)];
            }

            return(result);
        }
Exemplo n.º 11
0
        public double[] GetParametersForFitElement(int idx)
        {
            FitElement fitele = _fitEnsemble[idx];

            var byName = new Dictionary <string, double>();

            for (int i = 0; i < _currentParameters.Count; i++)
            {
                byName.Add(_currentParameters[i].Name, _currentParameters[i].Parameter);
            }

            double[] result = new double[fitele.NumberOfParameters];
            for (int i = 0; i < result.Length; ++i)
            {
                result[i] = byName[fitele.ParameterName(i)];
            }

            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Stores the dependent values of all elements in an array. The data
        /// are stored from FitElement_0 to FitElement_n. For FitElements with more than one dependent
        /// variable in use, the data are stored interleaved.
        /// </summary>
        /// <param name="values">The array used to store the values.</param>
        public void GetDependentValues(double[] values)
        {
            int outputValuesPointer = 0;

            for (int ele = 0; ele < _cachedFitElementInfo.Length; ele++)
            {
                CachedFitElementInfo info   = _cachedFitElementInfo[ele];
                FitElement           fitEle = _fitEnsemble[ele];

                IAscendingIntegerCollection validRows = info.ValidRows;
                int numValidRows = validRows.Count;
                // Evaluate the function for all points
                for (int i = 0; i < numValidRows; ++i)
                {
                    for (int j = 0; j < info.DependentVariablesInUse.Length; ++j)
                    {
                        values[outputValuesPointer++] = fitEle.DependentVariables(info.DependentVariablesInUse[j])[validRows[i]];
                    }
                }
            }
        }
Exemplo n.º 13
0
        public FitElement(FitElement from)
        {
            this._fitFunction = from._fitFunction;
            if (_fitFunction is ICloneable)
            {
                this._fitFunction = (IFitFunction)((ICloneable)from.FitFunction).Clone();
            }

            _rangeOfRows          = PositiveIntegerRange.NewFromFirstAndCount(from._rangeOfRows.First, from._rangeOfRows.Count);
            _independentVariables = new NumericColumnProxy[from._independentVariables.Length];
            for (int i = 0; i < _independentVariables.Length; ++i)
            {
                if (from._independentVariables[i] != null)
                {
                    _independentVariables[i] = (NumericColumnProxy)from._independentVariables[i].Clone();
                }
            }

            _dependentVariables = new NumericColumnProxy[from._dependentVariables.Length];
            for (int i = 0; i < _dependentVariables.Length; ++i)
            {
                if (from._dependentVariables[i] != null)
                {
                    _dependentVariables[i] = (NumericColumnProxy)from._dependentVariables[i].Clone();
                }
            }
            _errorEvaluation = new IVarianceScaling[from._errorEvaluation.Length];
            for (int i = 0; i < _errorEvaluation.Length; ++i)
            {
                if (from._errorEvaluation[i] != null)
                {
                    _errorEvaluation[i] = (IVarianceScaling)from._errorEvaluation[i].Clone();
                }
            }

            _parameterNames     = (string[])from._parameterNames.Clone();
            _parameterNameStart = from._parameterNameStart;
        }
Exemplo n.º 14
0
        protected void CollectParameterNames()
        {
            _ParametersSortedByName = new System.Collections.SortedList();

            int nameposition = 0;

            for (int i = 0; i < InnerList.Count; i++)
            {
                if (null == this[i].FitFunction)
                {
                    continue;
                }
                IFitFunction func = this[i].FitFunction;
                FitElement   ele  = this[i];

                for (int k = 0; k < func.NumberOfParameters; k++)
                {
                    if (!(_ParametersSortedByName.ContainsKey(ele.ParameterName(k))))
                    {
                        _ParametersSortedByName.Add(ele.ParameterName(k), nameposition++);
                    }
                }
            }

            // now sort the items in the order of the namepositions
            System.Collections.SortedList sortedbypos = new System.Collections.SortedList();
            foreach (DictionaryEntry en in _ParametersSortedByName)
            {
                sortedbypos.Add(en.Value, en.Key);
            }


            _parameterNames = new string[sortedbypos.Count];
            for (int i = 0; i < _parameterNames.Length; i++)
            {
                _parameterNames[i] = (string)sortedbypos[i];
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// This will set all parameters in the ensembly with the same name than that of the parameter names
        /// of fit function at index <c>idx</c> to their default values (those are provided by the fit function).
        /// </summary>
        /// <param name="idx">Index of the fit element.</param>
        public void SetDefaultParametersForFitElement(int idx)
        {
            FitElement fitele = _fitEnsemble[idx];

            if (fitele.FitFunction == null)
            {
                return;
            }

            var byName = new System.Collections.Hashtable();

            for (int i = 0; i < _currentParameters.Count; i++)
            {
                byName.Add(_currentParameters[i].Name, i);
            }

            for (int i = 0; i < fitele.NumberOfParameters; ++i)
            {
                int k = (int)byName[fitele.ParameterName(i)];
                _currentParameters[k].Parameter = fitele.FitFunction.DefaultParameterValue(i);
            }

            _currentParameters.OnInitializationFinished();
        }
Exemplo n.º 16
0
    public void Initialize(FitElement fitElement)
    {
      _fitElement = fitElement;

      _numberOfX = _fitElement.NumberOfIndependentVariables;
      _numberOfY = _fitElement.NumberOfDependentVariables;
      _numberOfParameter = _fitElement.NumberOfParameters;

      _totalSlots = Math.Max(_numberOfParameter, _numberOfX + _numberOfY + 1);
      _slotHeight = System.Windows.Forms.SystemInformation.MenuButtonSize.Height;
      _pen = System.Drawing.Pens.Blue;

      this.ClientSize = new Size(this.ClientSize.Width, _totalSlots * _slotHeight);
    }
Exemplo n.º 17
0
		public void Initialize(Calc.Regression.Nonlinear.FitElement fitElement)
		{
			_fitElement = fitElement;

			_numberOfX = _fitElement.NumberOfIndependentVariables;
			_numberOfY = _fitElement.NumberOfDependentVariables;
			_numberOfParameter = _fitElement.NumberOfParameters;

			_totalSlots = Math.Max(_numberOfParameter, _numberOfX + _numberOfY + 4);
			SetupElements();
		}
    void Select(IFitFunction func)
    {
      bool changed = false;
      if (_doc.FitEnsemble.Count == 0) // Fitting is fresh, we can add the function silently
      {
        FitElement newele = new FitElement();
        newele.FitFunction = func;
        _doc.FitEnsemble.Add(newele);
        _doc.SetDefaultParametersForFitElement(0);
        changed = true;
      }
      else if (_doc.FitEnsemble.Count > 0 && _doc.FitEnsemble[_doc.FitEnsemble.Count - 1].FitFunction == null)
      {
        _doc.FitEnsemble[_doc.FitEnsemble.Count - 1].FitFunction = func;
        _doc.SetDefaultParametersForFitElement(_doc.FitEnsemble.Count - 1);
        changed = true;
      }
      else // Count>0, and there is already a fit function, we
      { // have to ask the user whether he wants to discard the old functions or keep them

        System.Enum selchoice = _lastSelectionChoice;
        if (Current.Gui.ShowDialog(ref selchoice, "As only or as additional?"))
        {
          _lastSelectionChoice = (SelectionChoice)selchoice;
          if (_lastSelectionChoice == SelectionChoice.SelectAsAdditional)
          {
            FitElement newele = new FitElement();
            newele.FitFunction = func;
            _doc.FitEnsemble.Add(newele);
            _doc.SetDefaultParametersForFitElement(_doc.FitEnsemble.Count - 1);
            changed = true;
          }
          else // select as only
          {
            _doc.FitEnsemble[0].FitFunction = func;
            _doc.SetDefaultParametersForFitElement(0);

            for (int i = _doc.FitEnsemble.Count - 1; i >= 1; --i)
              _doc.FitEnsemble.RemoveAt(i);

            changed = true;
          }
        }
      }

      if (changed)
      {
        // _doc.FitEnsemble.InitializeParameterSetFromEnsembleParameters(_doc.CurrentParameters);

        this._fitEnsembleController.Refresh();
      
      }
    }
Exemplo n.º 19
0
 public FitElementController(FitElement doc)
 {
   _doc = doc;
 }
Exemplo n.º 20
0
    public FitElement(FitElement from)
    {
      this._fitFunction = from._fitFunction;
      if (_fitFunction is ICloneable)
        this._fitFunction = (IFitFunction)((ICloneable)from.FitFunction).Clone();

      _rangeOfRows = PositiveIntegerRange.NewFromFirstAndCount(from._rangeOfRows.First, from._rangeOfRows.Count);
      _independentVariables = new NumericColumnProxy[from._independentVariables.Length];
      for (int i = 0; i < _independentVariables.Length; ++i)
      {
        if(from._independentVariables[i]!=null)
          _independentVariables[i] = (NumericColumnProxy)from._independentVariables[i].Clone();
      }

      _dependentVariables = new NumericColumnProxy[from._dependentVariables.Length];
      for (int i = 0; i < _dependentVariables.Length; ++i)
      {
        if (from._dependentVariables[i] != null)
          _dependentVariables[i] = (NumericColumnProxy)from._dependentVariables[i].Clone();
      }
      _errorEvaluation = new IVarianceScaling[from._errorEvaluation.Length];
      for (int i = 0; i < _errorEvaluation.Length; ++i)
      {
        if (from._errorEvaluation[i] != null)
          _errorEvaluation[i] = (IVarianceScaling)from._errorEvaluation[i].Clone();
      }

      _parameterNames = (string[])from._parameterNames.Clone();
      _parameterNameStart = from._parameterNameStart;

    }
Exemplo n.º 21
0
		public FitElement(FitElement from)
		{
			this._fitFunction = from._fitFunction;
			if (_fitFunction is ICloneable)
				this._fitFunction = (IFitFunction)((ICloneable)from.FitFunction).Clone();
			if (null != _fitFunction)
				_fitFunction.Changed += EhFitFunctionChanged;

			ChildCopyToMember(ref _dataTable, from._dataTable);
			this._groupNumber = from._groupNumber;
			ChildCloneToMember(ref _rangeOfRows, from._rangeOfRows);

			_independentVariables = new IReadableColumnProxy[from._independentVariables.Length];
			for (int i = 0; i < _independentVariables.Length; ++i)
			{
				if (from._independentVariables[i] != null)
					_independentVariables[i] = (IReadableColumnProxy)from._independentVariables[i].Clone();
			}

			_dependentVariables = new IReadableColumnProxy[from._dependentVariables.Length];
			for (int i = 0; i < _dependentVariables.Length; ++i)
			{
				if (from._dependentVariables[i] != null)
					_dependentVariables[i] = (IReadableColumnProxy)from._dependentVariables[i].Clone();
			}
			_errorEvaluation = new IVarianceScaling[from._errorEvaluation.Length];
			for (int i = 0; i < _errorEvaluation.Length; ++i)
			{
				if (from._errorEvaluation[i] != null)
					_errorEvaluation[i] = (IVarianceScaling)from._errorEvaluation[i].Clone();
			}

			_parameterNames = (string[])from._parameterNames.Clone();
			_parameterNameStart = from._parameterNameStart;
		}
Exemplo n.º 22
0
        /// <summary>
        /// Internal function to set up the cached data for the fitting procedure.
        /// </summary>
        /// <param name="paraSet">The set of parameters (the information which parameters are fixed is mainly used here).</param>
        private void CalculateCachedData(ParameterSet paraSet)
        {
            // Preparation: Store the parameter names by name and index, and store
            // all parameter values in _constantParameters
            var paraNames        = new System.Collections.Hashtable();
            var varyingParaNames = new System.Collections.Hashtable();

            _constantParameters = new double[paraSet.Count];
            int numberOfVaryingParameters = 0;

            for (int i = 0; i < paraSet.Count; ++i)
            {
                paraNames.Add(paraSet[i].Name, i);
                _constantParameters[i] = paraSet[i].Parameter;
                if (paraSet[i].Vary)
                {
                    ++numberOfVaryingParameters;
                }
            }
            _cachedVaryingParameters = new double[numberOfVaryingParameters];
            for (int i = 0, k = 0; i < paraSet.Count; ++i)
            {
                if (paraSet[i].Vary)
                {
                    varyingParaNames.Add(paraSet[i].Name, k);
                    _cachedVaryingParameters[k++] = paraSet[i].Parameter;
                }
            }

            _cachedNumberOfData   = 0;
            _cachedFitElementInfo = new CachedFitElementInfo[_fitEnsemble.Count];
            for (int i = 0; i < _fitEnsemble.Count; i++)
            {
                var info = new CachedFitElementInfo();
                _cachedFitElementInfo[i] = info;
                FitElement fitEle = _fitEnsemble[i];

                info.ValidRows = fitEle.CalculateValidNumericRows();

                info.Xs         = new double[fitEle.NumberOfIndependentVariables];
                info.Parameters = new double[fitEle.NumberOfParameters];
                info.Ys         = new double[fitEle.NumberOfDependentVariables];

                // Calculate the number of used variables
                int numVariablesUsed = 0;
                for (int j = 0; j < fitEle.NumberOfDependentVariables; ++j)
                {
                    if (fitEle.DependentVariables(j) != null)
                    {
                        ++numVariablesUsed;
                    }
                }
                info.DependentVariablesInUse = new int[numVariablesUsed];
                for (int j = 0, used = 0; j < fitEle.NumberOfDependentVariables; ++j)
                {
                    if (fitEle.DependentVariables(j) != null)
                    {
                        info.DependentVariablesInUse[used++] = j;
                    }
                }

                // calculate the total number of data points
                _cachedNumberOfData += numVariablesUsed * info.ValidRows.Count;

                // now create the parameter mapping
                info.ParameterMapping = new int[fitEle.NumberOfParameters];

                for (int j = 0; j < info.ParameterMapping.Length; ++j)
                {
                    if (!paraNames.Contains(fitEle.ParameterName(j)))
                    {
                        throw new ArgumentException(string.Format("ParameterSet does not contain parameter {0}, which is used by function[{1}]", fitEle.ParameterName(j), i));
                    }

                    int idx = (int)paraNames[fitEle.ParameterName(j)];
                    if (paraSet[idx].Vary)
                    {
                        info.ParameterMapping[j] = (int)varyingParaNames[fitEle.ParameterName(j)];
                    }
                    else
                    {
                        info.ParameterMapping[j] = -idx - 1;
                    }
                }
            }

            _cachedDependentValues = new double[_cachedNumberOfData];
            GetDependentValues(_cachedDependentValues);

            if (HasToUseWeights())
            {
                _cachedWeights = new double[_cachedNumberOfData];
                GetWeights(_cachedWeights);
            }
            else
            {
                _cachedWeights = null;
            }
        }
Exemplo n.º 23
0
            public virtual object Deserialize(object o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object parent)
            {
                FitElement s = o != null ? (FitElement)o : new FitElement();

                s.ChildSetMemberAlt(ref s._fitFunction, (IFitFunction)info.GetValue("FitFunction", s));

                int numRows  = info.GetInt32("NumberOfRows");
                int firstRow = info.GetInt32("FirstRow");

                s._rangeOfRows = RangeOfRowIndices.FromStartAndCount(firstRow, numRows);
                if (null != s._rangeOfRows)
                {
                    s._rangeOfRows.ParentObject = s;
                }

                int arraycount = info.OpenArray();

                s._independentVariables = new IReadableColumnProxy[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._independentVariables[i] = (IReadableColumnProxy)info.GetValue("e", s);
                    if (null != s._independentVariables[i])
                    {
                        s._independentVariables[i].ParentObject = s;
                    }
                }
                info.CloseArray(arraycount);

                arraycount            = info.OpenArray();
                s._dependentVariables = new IReadableColumnProxy[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._dependentVariables[i] = (IReadableColumnProxy)info.GetValue("e", s);
                    if (null != s._dependentVariables[i])
                    {
                        s._dependentVariables[i].ParentObject = s;
                    }
                }
                info.CloseArray(arraycount);

                arraycount         = info.OpenArray();
                s._errorEvaluation = new IVarianceScaling[arraycount];
                for (int i = 0; i < arraycount; ++i)
                {
                    s._errorEvaluation[i] = (IVarianceScaling)info.GetValue("e", s);
                }
                info.CloseArray(arraycount);

                info.GetArray("ParameterNames", out s._parameterNames);
                for (int i = 0; i < s._parameterNames.Length; ++i)
                {
                    if (s._parameterNames[i] == string.Empty)
                    {
                        s._parameterNames[i] = null; // serialization can not distinguish between an empty string and a null string
                    }
                }
                s._parameterNameStart = info.GetString("ParameterNameStart");

                // now some afterwork
                if (s.InternalCheckAndCorrectArraySize(false, false))
                {
                    Current.Console.WriteLine("Error: Fitelement array size mismatch");
                }

                return(s);
            }
Exemplo n.º 24
0
    public void Add(FitElement e)
    {
      InnerList.Add(e);
      e.Changed += new EventHandler(EhChildChanged);

      OnChanged();
    }
Exemplo n.º 25
0
		/// <summary>
		/// Creates an instance of this class.
		/// </summary>
		/// <param name="fitFunc">Fitting function.</param>
		/// <param name="parameter">Array of default parameters (length must match the expected number of parameter of fitFunc).</param>
		/// <param name="xCol">Data column of independent values.</param>
		/// <param name="yCol">Data column of dependent values.</param>
		/// <param name="start">First point to be used for fitting.</param>
		/// <param name="count">Number of points to be used for fitting.</param>
		public SimpleNonlinearFit(FitEvaluationFunction fitFunc, double[] parameter, Altaxo.Data.INumericColumn xCol, Altaxo.Data.INumericColumn yCol, int start, int count)
		{
			_fitDoc = new NonlinearFitDocument();
			_fitEle = new FitElement(null, 0, Altaxo.Data.Selections.RangeOfRowIndices.FromStartAndCount(start, count), xCol, yCol);
			_fitEle.FitFunction = new DummyFitFunc(fitFunc, parameter);
			_fitDoc.FitEnsemble.Add(_fitEle);
			_fitDoc.SetDefaultParametersForFitElement(0);
		}