Imports DataFitXD2

Public Class Form1
    Inherits System.Windows.Forms.Form


#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(104, 88)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Solve"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 174)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim dfxData As DataCollection
        Dim dfxModel As NonlinearRegression
        Dim dfxParameter As RegressionParameter
        Dim dfxDefinition As ModelDefinition
        Dim Roots() As Double
        Dim Result As Double
        Dim i As Long
        Dim dfxInfo As GlobalConstants

        ' Enable Error handling
        On Error GoTo RegressionError

        ' Create the DataCollection object and import the tabbed delimited data
        ' file thurber.dat. The file contains 2 columns of named data labeled
        ' Density and Electron Mobility (the first non-blank line in the file
        ' contains the series names). The first column is the independent
        ' variable X (Density), the second column is the dependent
        ' variable Y (Electron Mobility). This will add 2 DataSeries objects to
        ' the DataCollection, one named "Density" the other named "Electron Mobility".
        dfxData = New DataCollection
        dfxData.ImportNamedSeriesFromFile("thurber.dat", DelimiterTypeEnum.dfxDelimiterTab)

        ' Set the RegressionKey properties for the DataCollection according to the
        ' above description. The following is equivalent to
        ' dfxData.Item("Density").RegressionKey = "X" since "Item" is the default property.
        dfxData("Density").RegressionKey = "X"
        dfxData("Electron Mobility").RegressionKey = "Y"

        ' The model being solved is:
        ' Y = (B1+B2*x+B3*x^2+B4*x^3) / (1+B5*x+B6*x^2+B7*x^3)
        ' where B1 through B7 are the fitting parameters, and X
        ' is the independent variable "Density".
        ' Create the model definition object so that we may define
        ' a multi-line user-defined model.
        dfxDefinition = New ModelDefinition
        With dfxDefinition
            .Description = "Semiconductor electron mobility modeling"
            .F1 = "(B1 + B2 * x + B3 * x ^ 2 + B4 * x ^ 3)"
            .F2 = "(1 + B5 * x + B6 * x ^ 2 + B7 * x ^ 3)"
            .Y = "F1/F2"
        End With

        ' Create an instance of the NonlinearRegression object
        dfxModel = New NonlinearRegression

        With dfxModel

            ' Define the multi-line user-defined model
            ' according to the above definition in dfxDefinition.
            ' Since we are using a ModelDefinition object to define
            ' the model, use the DefineUserModelSub method.
            .DefineUserModelSub(dfxDefinition)

            ' Define the intial estimates for the model since this is a
            ' user-defined model. There are seven parameters, B1 through B7.
            ' Item is the default property of the RegressionParameters object,
            ' so it is not necessary.
            ' .RegressionParameters.Item("B1").InitialEstimate = 1000
            .RegressionParameters("B1").InitialEstimate = 1000
            .RegressionParameters("B2").InitialEstimate = 1000
            .RegressionParameters("B3").InitialEstimate = 400
            .RegressionParameters("B4").InitialEstimate = 40
            .RegressionParameters("B5").InitialEstimate = 0.7
            .RegressionParameters("B6").InitialEstimate = 0.3
            .RegressionParameters("B7").InitialEstimate = 0.03

            ' Set the regression solution options
            .MaxIterations = 100
            .MaxUnchangedIterations = 10
            .RegressionTolerance = 0.0000000001

            ' Fit the model to the DataCollection dfxData
            .FitCollection(dfxData)

            ' If the model solved successfully, display some sample results. Otherwise,
            ' display the solution log information to diagnose why it may have failed.
            If .IsSolved Then
                FileOpen(1, "results.dat", OpenMode.Output)

                dfxInfo = New GlobalConstants
                PrintLine(1, "DataFitX version " & dfxInfo.dfxMajorVersion & "." & _
                              dfxInfo.dfxMinorVersion & "." & dfxInfo.dfxRevision)
                PrintLine(1, dfxInfo.dfxCopyright)
                PrintLine(1, "Results for model: ")
                PrintLine(1, "F1 = " & .ModelDefinition.F1)
                PrintLine(1, "F2 = " & .ModelDefinition.F2)
                PrintLine(1, "Y = " & .ModelDefinition.Y)
                PrintLine(1, "Description: " & .ModelDefinition.Description)

                ' Print information about the data
                PrintLine(1, "Data set: Thurber.dat")
                PrintLine(1, "Independent Variable (X): " & .ResultTables.Item(1).Name)
                PrintLine(1, "Dependent Variable (Y): " & .ResultTables.Item(2).Name)
                PrintLine(1, "Number of Observations = " & .NumObservations)
                PrintLine(1, "XMin = " & dfxModel.ResultTables.Item(1).Minimum)
                PrintLine(1, "XMax = " & dfxModel.ResultTables.Item(1).Maximum)
                PrintLine(1, "YMin = " & dfxModel.ResultTables.Item(2).Minimum)
                PrintLine(1, "YMax = " & dfxModel.ResultTables.Item(2).Maximum)
                PrintLine(1)

                ' Print the parameter names, values and standard errors
                PrintLine(1, "Parameter Results:")
                For Each dfxParameter In .RegressionParameters
                    PrintLine(1, dfxParameter.Name & " = " & dfxParameter.Value & _
                                ", Standard Error = " & dfxParameter.StandardError)
                Next dfxParameter
                PrintLine(1)

                ' Print goodness of fit information
                PrintLine(1, "Number of Nonlinear Iterations = " & .NumIterations)
                PrintLine(1, "Residual Standard Error = " & .StandardError)
                PrintLine(1, "R2 Value = " & .R2)
                PrintLine(1, "Regression Sum of Squares = " & .SSR)
                PrintLine(1, "Residual Sum of Squares = " & .SSE)
                PrintLine(1)

                ' Other sample output

                ' Single Predicted value
                PrintLine(1, "Value of Y at X = 0.79: " & .PredictValue(0.79))

                ' Value of X at specified Y (Root)
                PrintLine(1, "Value(s) of X at Y = 1408.1046: ")
                Roots = .CalculateRoots(1408.1046, -5.0#, 2.0#)
                For i = 0 To UBound(Roots)
                    PrintLine(1, "Root at X = " & Roots(i))
                Next i

                ' Derivative of Y at X = 2.1
                PrintLine(1, "Derivative at X = 2.1: " & .CalculateDerivative(2.1))

                ' Integration from X = -2.1 to 2.1
                PrintLine(1, "Integral from -2.1 to 2.1: " & .CalculateIntegral(-2.1, 2.1))

                FileClose(1)

                MsgBox("Solution successful - see results.dat")

            Else

                .SaveLog("log.txt")
                MsgBox("Solution failed - see log.txt")

            End If

        End With


        Exit Sub

RegressionError:

        Select Case Err.Number

            Case 429
                MsgBox("Error 429: ActiveX component can't create object. The DataFitX " & _
                       "component must be installed and registered to run this sample.", vbOKOnly, "Error")

            Case Else
                MsgBox("Error " & Err.Number & ": " & Err.Description, vbOKOnly, "Error")

        End Select


    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class
