﻿Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Windows.Forms
Imports GrapeCity.Spreadsheet
Imports FarPoint.Win.Spread
Imports GrapeCity.CalcEngine
Imports Spread.Common.Features.Spread.Common.Features.Sample

Namespace Features
    Partial Public Class ZetaCalculator
        Inherits BaseSampleControl
        Public Sub New()
            InitializeComponent()
            fpSpread2.AddCustomFunction(New ZetaFunction())
            formulaTextBox1.Attach(fpSpread2)
            fpSpread2.StatusBarVisible = True
        End Sub
        Private Function GetInputValues(ByRef initval As Double, ByRef incr As Double, ByRef rc As Integer, ByRef iter As Long) As Boolean
            If Not Double.TryParse(textBoxStart.Text, initval) Then
                MessageBox.Show("Please enter a double value for Start Value.")
                textBoxStart.Focus()
                Return False
            End If
            If Not Double.TryParse(textBoxIncrement.Text, incr) Then
                MessageBox.Show("Please enter a double value for Increment.")
                textBoxIncrement.Focus()
                Return False
            End If
            If Not Integer.TryParse(textBoxCount.Text, rc) Then
                MessageBox.Show("Please enter an integer value for Count.")
                textBoxCount.Focus()
                Return False
            End If
            Long.TryParse(textBoxIter.Text, iter)
            Return True
        End Function
        ''' <summary>
        ''' Returns the number format speifying the number of decimal places used for increment.
        ''' </summary>
        ''' <returns>
        ''' The number format specifying the number of decimal places used for increment.
        ''' </returns>
        ''' <remarks>
        ''' The calculator formats the first column using the number of decimal places for increment.
        ''' </remarks>
        Private Function GetIncrementNumberFormat() As String
            Dim incr As Double = 0.1
            If Not Double.TryParse(textBoxIncrement.Text, incr) Then
                Return "0.0"
            End If
            Dim sb As New StringBuilder()
            sb.Append("0.")
            While incr < 1
                sb.Append("0")
                incr *= 10
            End While
            Return sb.ToString()
        End Function
        ''' <summary>
        ''' Handle the "Calculate" button click.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks>
        ''' This event handler reinitialized the worksheet with the newly-generated Zeta calculation table.
        ''' This code sets the formula to calculate ZETA as an array formula, and the spreadsheet calculates the result
        ''' once, and sets the result to the range all at once using an array.
        ''' The actual calculation is handled inside the custom function that is active (ZetaFunction or ZetaFunctionInfo).
        ''' The title bar text is updated at the end with timing and call count information about the custom function execution.
        ''' </remarks>
        Private Sub buttonCalculate_Click(sender As Object, e As EventArgs)
            Dim initval As Double = 0.0
            Dim incr As Double = 0.01
            Dim rc As Integer = 12000
            Dim iter As Long = 10000
            If Not GetInputValues(initval, incr, rc, iter) Then
                Return
            End If
            fpSpread2.SuspendLayout()
            Cursor = Cursors.WaitCursor
            Text = "Calculating, please wait..."
            ' inialize sheet with Zeta calculation table headers
            Dim sheet As SheetView = fpSpread2.ActiveSheet
            sheet.Reset()
            sheet.RowCount = rc + 1
            sheet.ColumnCount = 5
            sheet.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1
            sheet.Cells(0, 0).Text = "bi"
            sheet.Cells(0, 1).Text = "Re( ζ(0.5+bi) )"
            sheet.Cells(0, 2).Text = "Im( ζ(0.5+bi) )"
            sheet.Cells(0, 3).Text = "ζ(0.5+bi)"
            sheet.Cells(0, 4).Text = "IMABS( ζ(0.5+bi) )"
            sheet.Cells(0, 0, 0, 4).HorizontalAlignment = CellHorizontalAlignment.Center
            ' apply built-in styles for table header cells
            Dim workbook As IWorkbook = fpSpread2.AsWorkbook()
            workbook.ActiveSheet.Cells(0, 0, 0, 4).ApplyStyle(BuiltInStyle.Percent20Accent3)
            workbook.ActiveSheet.Cells(0, 0, 0, 4).ApplyStyle(BuiltInStyle.Heading3)
            ' initialize the values to be calculated
            For r As Integer = 1 To rc
                sheet.Cells(r, 0).Value = initval + incr * r
            Next
            ' format the cells to show the number decimal places appropriate for increment
            fpSpread2.AsWorkbook().Worksheets(0).Cells(1, 0, rc, 0).NumberFormat = GetIncrementNumberFormat()
            ' create the formula to calculate the ZETA function along the critical line Re = 0.5 for the 
            ' set of points starting with the initial value and using the specified increment and iterations
            Dim formula As String = "ZETA(0.5,RC1," + rc.ToString().Trim() + "," + incr.ToString().Trim() + "," + iter.ToString().Trim() + ")"
            sheet.Cells(1, 1, rc, 2).FormulaArray = formula
            ' apply the COMPLEX function to the two values returned for the real (in column 1) and imaginary (in column 2) parts to get the resulting complex number calculated
            sheet.Cells(1, 3, rc, 3).Formula = "COMPLEX(RC2,RC3)"
            ' apply IMABS function to resulting complex number -- this is equivalent to SQRT(RC2*RC2+RC3*RC3) and computes the length of the complex vector
            ' IMABS values less than increment are considered "close" to a root and highlighted if the value is a local minimum
            sheet.Cells(1, 4, rc, 4).Formula = "IMABS(RC4)"
            ' set column widths
            sheet.SetColumnWidth(0, CInt(sheet.GetPreferredColumnWidth(0)))
            sheet.SetColumnWidth(1, 150)
            sheet.SetColumnWidth(2, 150)
            sheet.SetColumnWidth(3, CInt(sheet.GetPreferredColumnWidth(3)))
            sheet.SetColumnWidth(4, CInt(sheet.GetPreferredColumnWidth(4)))
            ' enable auto filter on the range
            workbook.ActiveSheet.Cells(0, 0, rc, 4).AutoFilter()
            ' freeze first row from scrolling to keep table headers visible
            sheet.FrozenRowCount = 1
            ' renumber row headings 
            sheet.StartingRowNumber = 0
            ' clear the text in the first row header
            sheet.RowHeader.Cells(0, 0).Text = " "
            ' map the clipboard shortcut keys to special actions that copy only visible values as text
            ' (so the sheet can be filtered and copy/paste works as expected)
            fpSpread2.GetInputMap(InputMapMode.WhenFocused).Put(New Keystroke(Keys.C, Keys.Control), SpreadActions.ClipboardCopyAsStringSkipHidden)
            fpSpread2.GetInputMap(InputMapMode.WhenFocused).Put(New Keystroke(Keys.Insert, Keys.Control), SpreadActions.ClipboardCopyAsStringSkipHidden)
            ' create a conditional format to highlight the root (local minima IMABS < increment) values with yellow
            Dim conditionformula As String = "AND(RC5<" + incr.ToString() + ",RC5<R[1]C5,RC5<R[-1]C5)"
            Dim formulaRule As New FormulaConditionalFormattingRule(conditionformula)
            formulaRule.BackColor = System.Drawing.Color.Yellow
            sheet.SetConditionalFormatting(1, 0, rc, 5, New IConditionalFormattingRule() {formulaRule})
            ' cleanup, update window text with function call count and timing stats, enable filter roots button'
            fpSpread2.ResumeLayout()
            Cursor = Cursors.[Default]
            If checkBoxFunctionInfo.Checked Then
                Text = "Zeta Calculation Complete! [ZetaFunctionInfo Call #" + ZetaFunctionInfo.cnt.ToString() + " in " + (ZetaFunctionInfo.t2 - ZetaFunctionInfo.t1).ToString() + "]"
            Else
                Text = "Zeta Calculation Complete! [ZetaFunction Call #" + ZetaFunction.cnt.ToString() + " in " + (ZetaFunction.t2 - ZetaFunction.t1).ToString() + "]"
            End If
            buttonFilterRootsOnly.Enabled = True
        End Sub
        ''' <summary>
        ''' Apply a filter on the range to show only the root values.
        ''' Creates a color filter for the first column in the worksheet.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub buttonFilterRootsOnly_Click(sender As Object, e As EventArgs)
            Dim workbook As IWorkbook = fpSpread2.AsWorkbook()
            Dim worksheet As IWorksheet = workbook.ActiveSheet
            Dim fill As New Fill(GrapeCity.Spreadsheet.Color.FromKnownColor(GrapeCity.Core.KnownColor.Yellow))
            worksheet.Cells(0, 0, worksheet.RowCount - 1, 4).AutoFilter(0, fill)
        End Sub
        ''' <summary>
        ''' Toggles between using the new-style calculation function ZetaFunction and the old-style calculation function ZetaFunctionInfo.
        ''' The new-style calculation function is recommended as it is slightly faster and easier to use than the old-style calculation function,
        ''' which must be wrapped internally using GrapeCity.CalcEngine APIs to work in the new GrapeCity.CalcEngine.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub checkBoxFunctionInfo_CheckedChanged(sender As Object, e As EventArgs)
            If checkBoxFunctionInfo.Checked Then
                ' this method is marked obsolete and deprecated -- you should port your old FunctionInfo class to a Function class
                fpSpread2.ActiveSheet.AddCustomFunction(New ZetaFunctionInfo())
            Else
                fpSpread2.AddCustomFunction(New ZetaFunction())
            End If
        End Sub
        ''' <summary>
        ''' Event handler for the LeaveCell event.
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks>
        ''' This event handler enables and disables the GoalSeek button based on whether the active row is a highlighted root value.
        ''' </remarks>
        Private Sub fpSpread2_LeaveCell(sender As Object, e As LeaveCellEventArgs)
            Dim workbook As IWorkbook = fpSpread2.AsWorkbook()
            ' get the interior color of the cell becoming active, enable goal seek button if it's a highlighted root value
            Dim c As GrapeCity.Spreadsheet.Color = workbook.ActiveSheet.Cells(e.NewRow, e.NewColumn).DisplayFormat.Interior.Color
            If c.Equals(GrapeCity.Spreadsheet.Color.FromKnownColor(GrapeCity.Core.KnownColor.Yellow)) Then
                buttonGoalSeek.Enabled = True
            Else
                buttonGoalSeek.Enabled = False
            End If
        End Sub
        ''' <summary>
        ''' Do a high-precision goal seek to 4 decimal places
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks>
        ''' The spreadsheet has built-in GoalSeek logic, but that logic is limited to 2 decimal places.
        ''' This function uses the CalculationEngine to perform a goal seek to 4 decimal places.
        ''' </remarks>
        Private Sub buttonGoalSeek_Click(sender As Object, e As EventArgs)
            Dim t2 As DateTime, t1 As DateTime = DateTime.Now
            ' for timing the goal-seek
            Dim wb As IWorkbook = fpSpread2.AsWorkbook()
            Dim calcengine As CalculationEngine = wb.WorkbookSet.CalculationEngine
            Dim ws As IWorksheet = wb.ActiveSheet
            Dim sheet As SheetView = fpSpread2.ActiveSheet
            Dim initval As Double = 0.0
            Dim incr As Double = 0.01
            Dim rc As Integer = 12000
            Dim iter As Long = 10000
            Dim row As Integer = sheet.ActiveRowIndex
            Dim cnt As Integer, cnt2 As Integer
            ' for counting the number of ZETA function calls performed during goal-seek
            Dim maxchange As Double
            ' current decimal place of search
            Dim formula As String, formulaNext As String
            ' formula for value and formula for next value to be tested
            Dim result As IValue, resultNext As IValue
            ' calculated result of formula for value and formula for next value
            ' temp variables for calculating IMABS of result and resultNext
            Dim temp As Double, temp1 As Double, temp2 As Double, tempNext As Double, tempNext1 As Double, tempNext2 As Double
            Dim nextDecimalPlace As Boolean
            ' flag for moving to next decimal place
            Dim value As Double
            ' current value being tested
            ' save initial ZETA call count
            If checkBoxFunctionInfo.Checked Then
                cnt = ZetaFunctionInfo.cnt
            Else
                cnt = ZetaFunction.cnt
            End If
            If Not GetInputValues(initval, incr, rc, iter) Then
                Return
            End If
            ' force 100K iterations for improved accuracy
            iter = 100000
            ' do goal seek on the cell [row, 0]:
            value = Math.Round(CDbl(ws.Cells(row, 0).Value), 1) + 0.04
            ' start with value XXX.X4
            ws.Cells(row, 0).NumberFormat = "0.0000"
            ' format cell for 4 decimal places
            ' my implementation for goal seek:
            Cursor = Cursors.WaitCursor
            maxchange = 0.01
            While maxchange > 0.00001
                ' start changing the hundredths place, then move on to each sucessive decimal place until maxchange = 1e-10
                nextDecimalPlace = False
                ' reset flag 
                ' calculate value
                formula = "ZETA(0.5," + value.ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")"
                result = calcengine.Evaluate(formula, ws, New GrapeCity.Spreadsheet.CellReference(row, 1))
                temp1 = result.GetValuesArray()(0, 0).GetNumber()
                temp2 = result.GetValuesArray()(0, 1).GetNumber()
                ' calculate absolute values of results
                temp = Math.Sqrt(temp1 * temp1 + temp2 * temp2)
                Do
                    ' next value (value + maxchange) using CalculationEngine.Evaluate
                    formulaNext = "ZETA(0.5," + (value + maxchange).ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")"
                    resultNext = calcengine.Evaluate(formulaNext, ws, New GrapeCity.Spreadsheet.CellReference(row, 1))
                    tempNext1 = resultNext.GetValuesArray()(0, 0).GetNumber()
                    tempNext2 = resultNext.GetValuesArray()(0, 1).GetNumber()
                    ' calculate absolute values of results
                    tempNext = Math.Sqrt(tempNext1 * tempNext1 + tempNext2 * tempNext2)
                    If tempNext < temp Then
                        value += maxchange
                        ' next value is closer, increment value and continue checking next higher value
                        temp = tempNext
                    Else
                        ' next value is not closer, check previous value(s)
                        Do
                            ' calculate previous value
                            formulaNext = "ZETA(0.5," + (value - maxchange).ToString().Trim() + ",1,0," + iter.ToString().Trim() + ")"
                            resultNext = calcengine.Evaluate(formulaNext, ws, New GrapeCity.Spreadsheet.CellReference(row, 1))
                            tempNext1 = resultNext.GetValuesArray()(0, 0).GetNumber()
                            tempNext2 = resultNext.GetValuesArray()(0, 1).GetNumber()
                            ' calculate absolute value
                            tempNext = Math.Sqrt(tempNext1 * tempNext1 + tempNext2 * tempNext2)
                            If tempNext < temp Then
                                ' previous value is closer, decrement value and continue checking next previous value
                                value -= maxchange
                                temp = tempNext
                            Else
                                ' previous value is not closer, current value is closest -- continue to next decimal place
                                nextDecimalPlace = True
                                ' decrement current decimal place value by 1 to avoid rounding errors, then make the new last decimal place a 4
                                value = value + 4 * (maxchange / 10)
                            End If
                        Loop While Not nextDecimalPlace
                    End If
                Loop While Not nextDecimalPlace
                maxchange *= 0.1
            End While
            ' discard last digit
            value = Math.Truncate(value * 10000) / 10000
            ' cleanup
            t2 = DateTime.Now
            Cursor = Cursors.[Default]
            If checkBoxFunctionInfo.Checked Then
                cnt2 = ZetaFunctionInfo.cnt
            Else
                cnt2 = ZetaFunction.cnt
            End If
            sheet.Cells(row, 0).Value = value
            sheet.Columns(0).Width = sheet.GetPreferredColumnWidth(0)
            MessageBox.Show("Zero Value: " + value.ToString() + vbCr & vbLf & "Calculation completed in " + (t2 - t1).ToString() + " with " + (cnt2 - cnt).ToString() + " calls to ZETA function.")
        End Sub
    End Class
End Namespace

'
'
'

Namespace Features
	Partial Class ZetaCalculator
		''' <summary> 
		''' Required designer variable.
		''' </summary>
		Private components As System.ComponentModel.IContainer = Nothing

        ''' <summary> 
        ''' Clean up any resources being used.
        ''' </summary>
        ''' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        Protected Sub Dispose(disposing As Boolean)
            If disposing AndAlso (components IsNot Nothing) Then
                components.Dispose()
            End If
            MyBase.Dispose(disposing)
        End Sub

#Region "Windows Form Designer generated code"

        ''' <summary>
        ''' Required method for Designer support - do not modify
        ''' the contents of this method with the code editor.
        ''' </summary>
        Private Sub InitializeComponent()
               Me.components = New System.ComponentModel.Container()
               Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(ZetaCalculator))
               Me.panel1 = New System.Windows.Forms.Panel()
               Me.checkBoxFunctionInfo = New System.Windows.Forms.CheckBox()
               Me.buttonFilterRootsOnly = New System.Windows.Forms.Button()
               Me.formulaTextBox1 = New FarPoint.Win.Spread.FormulaTextBox()
               Me.buttonGoalSeek = New System.Windows.Forms.Button()
               Me.buttonCalculate = New System.Windows.Forms.Button()
               Me.textBoxIter = New System.Windows.Forms.TextBox()
               Me.label4 = New System.Windows.Forms.Label()
               Me.textBoxCount = New System.Windows.Forms.TextBox()
               Me.label3 = New System.Windows.Forms.Label()
               Me.textBoxIncrement = New System.Windows.Forms.TextBox()
               Me.label2 = New System.Windows.Forms.Label()
               Me.textBoxStart = New System.Windows.Forms.TextBox()
               Me.label1 = New System.Windows.Forms.Label()
               Me.toolTip1 = New System.Windows.Forms.ToolTip(Me.components)
               Me.fpSpread2 = New FarPoint.Win.Spread.FpSpread(FarPoint.Win.Spread.LegacyBehaviors.None, CType(resources.GetObject("resource1"), System.IO.MemoryStream))
               Me.fpSpread2_Sheet1 = Me.fpSpread2.GetSheet(0)
               Me.panel1.SuspendLayout()
               CType(Me.fpSpread2, System.ComponentModel.ISupportInitialize).BeginInit()
               Me.SuspendLayout()
               '
               'pnlMain
               '
               Me.pnlMain.Size = New System.Drawing.Size(588, 450)
               '
               'pnlControls
               '
               Me.pnlControls.Size = New System.Drawing.Size(195, 450)
               '
               'panel1
               '
               Me.panel1.Controls.Add(Me.checkBoxFunctionInfo)
               Me.panel1.Controls.Add(Me.buttonFilterRootsOnly)
               Me.panel1.Controls.Add(Me.formulaTextBox1)
               Me.panel1.Controls.Add(Me.buttonGoalSeek)
               Me.panel1.Controls.Add(Me.buttonCalculate)
               Me.panel1.Controls.Add(Me.textBoxIter)
               Me.panel1.Controls.Add(Me.label4)
               Me.panel1.Controls.Add(Me.textBoxCount)
               Me.panel1.Controls.Add(Me.label3)
               Me.panel1.Controls.Add(Me.textBoxIncrement)
               Me.panel1.Controls.Add(Me.label2)
               Me.panel1.Controls.Add(Me.textBoxStart)
               Me.panel1.Controls.Add(Me.label1)
               Me.panel1.Dock = System.Windows.Forms.DockStyle.Top
               Me.panel1.Location = New System.Drawing.Point(0, 0)
               Me.panel1.Name = "panel1"
               Me.panel1.Size = New System.Drawing.Size(784, 63)
               Me.panel1.TabIndex = 0
               '
               'checkBoxFunctionInfo
               '
               Me.checkBoxFunctionInfo.AutoSize = True
               Me.checkBoxFunctionInfo.Location = New System.Drawing.Point(12, 12)
               Me.checkBoxFunctionInfo.Name = "checkBoxFunctionInfo"
               Me.checkBoxFunctionInfo.Size = New System.Drawing.Size(129, 17)
               Me.checkBoxFunctionInfo.TabIndex = 12
               Me.checkBoxFunctionInfo.Text = "Use ZetaFunctionInfo"
               Me.toolTip1.SetToolTip(Me.checkBoxFunctionInfo, "Check this box to use the old FarPoint.CalcEngine.CalcFunction type to implement " &
        "the custom ZETA function instead of the new GrapeCity.CalcEngine.Function type.")
               Me.checkBoxFunctionInfo.UseVisualStyleBackColor = True
               '
               'buttonFilterRootsOnly
               '
               Me.buttonFilterRootsOnly.Enabled = False
               Me.buttonFilterRootsOnly.Location = New System.Drawing.Point(585, 37)
               Me.buttonFilterRootsOnly.Name = "buttonFilterRootsOnly"
               Me.buttonFilterRootsOnly.Size = New System.Drawing.Size(92, 22)
               Me.buttonFilterRootsOnly.TabIndex = 11
               Me.buttonFilterRootsOnly.Text = "Filter Roots Only"
               Me.toolTip1.SetToolTip(Me.buttonFilterRootsOnly, "Click this button to filter the rows in the spreadsheet to show only the root val" &
        "ues found, which are highlighted yellow.")
               Me.buttonFilterRootsOnly.UseVisualStyleBackColor = True
               '
               'formulaTextBox1
               '
               Me.formulaTextBox1.Location = New System.Drawing.Point(12, 37)
               Me.formulaTextBox1.Name = "formulaTextBox1"
               Me.formulaTextBox1.Size = New System.Drawing.Size(567, 19)
               Me.formulaTextBox1.TabIndex = 10
               Me.toolTip1.SetToolTip(Me.formulaTextBox1, "The formula in the active cell shows in this control and can be edited.")
               '
               'buttonGoalSeek
               '
               Me.buttonGoalSeek.Enabled = False
               Me.buttonGoalSeek.Location = New System.Drawing.Point(683, 37)
               Me.buttonGoalSeek.Name = "buttonGoalSeek"
               Me.buttonGoalSeek.Size = New System.Drawing.Size(92, 22)
               Me.buttonGoalSeek.TabIndex = 9
               Me.buttonGoalSeek.Text = "GoalSeek Root"
               Me.toolTip1.SetToolTip(Me.buttonGoalSeek, "Click this button to perform a custom goal seek on the selected root value to 9 d" &
        "ecimal places. You must select a root value in the spreadsheet to use this butto" &
        "n.")
               Me.buttonGoalSeek.UseVisualStyleBackColor = True
               '
               'buttonCalculate
               '
               Me.buttonCalculate.Location = New System.Drawing.Point(683, 12)
               Me.buttonCalculate.Name = "buttonCalculate"
               Me.buttonCalculate.Size = New System.Drawing.Size(92, 20)
               Me.buttonCalculate.TabIndex = 8
               Me.buttonCalculate.Text = "Calculate"
               Me.buttonCalculate.UseVisualStyleBackColor = True
               '
               'textBoxIter
               '
               Me.textBoxIter.Location = New System.Drawing.Point(607, 12)
               Me.textBoxIter.Name = "textBoxIter"
               Me.textBoxIter.Size = New System.Drawing.Size(70, 20)
               Me.textBoxIter.TabIndex = 7
               Me.textBoxIter.Text = "10000"
               Me.toolTip1.SetToolTip(Me.textBoxIter, "Number of iterations to calculate convergent series.  Higher values result in gre" &
        "ater precision, but take longer to calcuate.")
               '
               'label4
               '
               Me.label4.AutoSize = True
               Me.label4.Location = New System.Drawing.Point(548, 13)
               Me.label4.Name = "label4"
               Me.label4.Size = New System.Drawing.Size(53, 13)
               Me.label4.TabIndex = 6
               Me.label4.Text = "Iterations:"
               '
               'textBoxCount
               '
               Me.textBoxCount.Location = New System.Drawing.Point(471, 11)
               Me.textBoxCount.Name = "textBoxCount"
               Me.textBoxCount.Size = New System.Drawing.Size(70, 20)
               Me.textBoxCount.TabIndex = 5
               Me.textBoxCount.Text = "1000"
               Me.toolTip1.SetToolTip(Me.textBoxCount, "Number of points to calculate along the critical line Re = 1/2.")
               '
               'label3
               '
               Me.label3.AutoSize = True
               Me.label3.Location = New System.Drawing.Point(427, 13)
               Me.label3.Name = "label3"
               Me.label3.Size = New System.Drawing.Size(38, 13)
               Me.label3.TabIndex = 4
               Me.label3.Text = "Count:"
               '
               'textBoxIncrement
               '
               Me.textBoxIncrement.Location = New System.Drawing.Point(352, 10)
               Me.textBoxIncrement.Name = "textBoxIncrement"
               Me.textBoxIncrement.Size = New System.Drawing.Size(69, 20)
               Me.textBoxIncrement.TabIndex = 3
               Me.textBoxIncrement.Text = "0.1"
               Me.toolTip1.SetToolTip(Me.textBoxIncrement, "Increment between successive values of ZETA calulated along the critical line Re " &
        "= 1/2.")
               '
               'label2
               '
               Me.label2.AutoSize = True
               Me.label2.Location = New System.Drawing.Point(289, 14)
               Me.label2.Name = "label2"
               Me.label2.Size = New System.Drawing.Size(57, 13)
               Me.label2.TabIndex = 2
               Me.label2.Text = "Increment:"
               '
               'textBoxStart
               '
               Me.textBoxStart.Location = New System.Drawing.Point(213, 10)
               Me.textBoxStart.Name = "textBoxStart"
               Me.textBoxStart.Size = New System.Drawing.Size(70, 20)
               Me.textBoxStart.TabIndex = 1
               Me.textBoxStart.Text = "14.0"
               Me.toolTip1.SetToolTip(Me.textBoxStart, "The initial value for the imaginary component of the first point to calculate alo" &
        "ng the critical line.")
               '
               'label1
               '
               Me.label1.AutoSize = True
               Me.label1.Location = New System.Drawing.Point(145, 14)
               Me.label1.Name = "label1"
               Me.label1.Size = New System.Drawing.Size(62, 13)
               Me.label1.TabIndex = 0
               Me.label1.Text = "Start Value:"
               '
               'fpSpread2
               '
               Me.fpSpread2.AccessibleDescription = ""
               Me.fpSpread2.BackColor = System.Drawing.Color.White
               Me.fpSpread2.Dock = System.Windows.Forms.DockStyle.Fill
               Me.fpSpread2.Font = New System.Drawing.Font("Calibri", 11.0!)
               Me.fpSpread2.Location = New System.Drawing.Point(0, 63)
               Me.fpSpread2.Name = "fpSpread2"
               Me.fpSpread2.Size = New System.Drawing.Size(784, 387)
               Me.fpSpread2.TabIndex = 1
               '
               'ZetaCalculator
               '
               Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
               Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
               Me.Controls.Add(Me.fpSpread2)
               Me.Controls.Add(Me.panel1)
               Me.Name = "Zeta Calculator"
               Me.Size = New System.Drawing.Size(784, 450)
               Me.Controls.SetChildIndex(Me.panel1, 0)
               Me.Controls.SetChildIndex(Me.fpSpread2, 0)
               Me.panel1.ResumeLayout(False)
               Me.panel1.PerformLayout()
               CType(Me.fpSpread2, System.ComponentModel.ISupportInitialize).EndInit()
               Me.ResumeLayout(False)

          End Sub

#End Region

          Private panel1 As System.Windows.Forms.Panel
		Private buttonCalculate As System.Windows.Forms.Button
		Private textBoxIter As System.Windows.Forms.TextBox
		Private label4 As System.Windows.Forms.Label
		Private textBoxCount As System.Windows.Forms.TextBox
		Private label3 As System.Windows.Forms.Label
		Private textBoxIncrement As System.Windows.Forms.TextBox
		Private label2 As System.Windows.Forms.Label
		Private textBoxStart As System.Windows.Forms.TextBox
		Private label1 As System.Windows.Forms.Label
		Private fpSpread2 As FarPoint.Win.Spread.FpSpread
		Private fpSpread2_Sheet1 As FarPoint.Win.Spread.SheetView
		Private buttonGoalSeek As System.Windows.Forms.Button
		Private formulaTextBox1 As FarPoint.Win.Spread.FormulaTextBox
		Private buttonFilterRootsOnly As System.Windows.Forms.Button
		Private checkBoxFunctionInfo As System.Windows.Forms.CheckBox
		Private toolTip1 As System.Windows.Forms.ToolTip

	End Class
End Namespace

'
'ZetaFunction.vb
'

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Threading
Imports GrapeCity.CalcEngine

Namespace Features
	Friend NotInheritable Class ZetaFunction
		Inherits [Function]
		' keep count of function calls
		Friend Shared cnt As Integer = 0
		' time calculation
		Friend Shared t1 As DateTime
		Friend Shared t2 As DateTime
		''' <summary>
		''' Create the ZetaFunction.
		''' </summary>
		Public Sub New()
				' minimum args 4, maximum args 5, returns array value
			MyBase.New("ZETA", 4, 5, FunctionAttributes.Array)
		End Sub
		''' <summary>
		''' Evaluate the ZETA function.
		''' </summary>
		''' <param name="args">IArguments specifying arguments passed to ZETA</param>
		''' <param name="result">IValue for returning calculation result</param>
		Protected Overrides Sub Evaluate(args As IArguments, result As IValue)
			cnt += 1
			' increment function call counter
			t1 = DateTime.Now
			' start timing evaluation
			Dim l As Long = 10000L
			' default to 10K iterations if not specified
			' get function arguments
			Dim d As Double = args(0).GetPrimitiveValue(args.EvaluationContext).GetNumber()
			' real part
			Dim d1 As Double = args(1).GetPrimitiveValue(args.EvaluationContext).GetNumber()
			' imaginary part
			Dim count As Long = CLng(args(2).GetPrimitiveValue(args.EvaluationContext).GetNumber())
			' number of points to calculate
			Dim incr As Double = args(3).GetPrimitiveValue(args.EvaluationContext).GetNumber()
			' increment between points
			If args.Count > 4 Then
				' iterations is optional
				l = CLng(args(4).GetPrimitiveValue(args.EvaluationContext).GetNumber())
			End If
			Dim array As IValuesArray = result.CreateValuesArray(CInt(count), 2)
			' create array to return values
			Dim arr As Double(,) = New Double(count - 1, 1) {}
			' create local array to calculate values (can't set values to IValuesArray from another thread)
			' do the ZETA calculation in a Task using Parallel.For for better performance
			Dim t As New Task(Sub() Parallel.[For](0, count, Function(i) 
			Dim d2 = 0.0
			Dim d3 = 0.0
			Dim d4 = 0.0
			Dim d5 = 0.0
			Dim dd1 = d1 + i * incr
                                                                 For l1 As Integer = 1 To l
                                                                     ' calculate Dirichlet Eta series partial sum of l iterations
                                                                     Dim d6 = 2 * l1 - 1
                                                                     Dim d7 = 2 * l1
                                                                     Dim d14 = 0.0
                                                                     Dim d15 = 0.0
                                                                     Dim d16 = 0.0
                                                                     Dim d8 = (dd1 * Math.Log(d6)) Mod 6.28318530717959
                                                                     Dim d9 = (dd1 * Math.Log(d7)) Mod 6.28318530717959
                                                                     Dim d10 = -d
                                                                     Dim d11 = Math.Pow(d6, d10)
                                                                     Dim d12 = Math.Pow(d7, d10)
                                                                     d2 += d11 * Math.Cos(d8) - d12 * Math.Cos(d9)
                                                                     d3 += d12 * Math.Sin(d9) - d11 * Math.Sin(d8)
                                                                     d4 += Math.Pow(d6, -0.5) * Math.Cos(d8) - Math.Pow(d7, -0.5) * Math.Cos(d9)
                                                                     d14 = Math.Pow(d7, -0.5) * Math.Sin(d9)
                                                                     d15 = Math.Pow(d6, -0.5)
                                                                     d16 = Math.Sin(d8)
                                                                     d5 += d14 - d15 * d16
                                                                 Next
                                                                 ' calculate Zeta from Eta value
                                                                 Dim d17 = 1.0 - Math.Pow(2, 1.0 - d) * Math.Cos(d1 * Math.Log(2))
			Dim d18 = Math.Pow(2, 1.0 - d) * Math.Sin(d1 * Math.Log(2))
			Dim d19 = (d17 * d2 + d18 * d3) / (Math.Pow(d17, 2) + Math.Pow(d18, 2))
			Dim d20 = (d17 * d3 - d18 * d2) / (Math.Pow(d17, 2) + Math.Pow(d18, 2))
			Interlocked.Exchange(arr(i, 0), d19)
			Interlocked.Exchange(arr(i, 1), d20)

End Function))
			t.RunSynchronously()
			' need to run this task synchronously on the UI thread
			' copy values from arr to the IValuesArray
			For i As Integer = 0 To count - 1
				array(i, 0).SetValue(arr(i, 0))
				array(i, 1).SetValue(arr(i, 1))
			Next
			result.SetValue(array)
			' set result -- this is important! If you don't return a result, then the cells remain marked dirty and Evaluate will be called again...
			t2 = DateTime.Now
			' time calculation
		End Sub
	End Class
End Namespace

'
'ZetaFunctionInfo.vb
'

Imports System
Imports System.Threading
Imports System.Threading.Tasks
Imports FarPoint.CalcEngine

Namespace Features
    Friend NotInheritable Class ZetaFunctionInfo
        Inherits FunctionInfo

        Friend Shared cnt As Integer = 0
        Friend Shared t1 As DateTime
        Friend Shared t2 As DateTime

        Public Overrides ReadOnly Property Name As String
            Get
                Return "ZETA"
            End Get
        End Property

        Public Overrides ReadOnly Property MinArgs As Integer
            Get
                Return 4
            End Get
        End Property

        Public Overrides ReadOnly Property MaxArgs As Integer
            Get
                Return 5
            End Get
        End Property

        Public Overrides Function Evaluate(ByVal args As Object()) As Object
            cnt += 1
            t1 = DateTime.Now
            Dim l As Integer = 10000
            Dim d As Double = CalcConvert.ToDouble(args(0))
            Dim d1 As Double = CalcConvert.ToDouble(args(1))
            Dim count As Integer = CalcConvert.ToInt(args(2))
            Dim incr As Double = CalcConvert.ToDouble(args(3))
            If args.Length > 4 Then l = CalcConvert.ToInt(args(4))
            Dim arr As Double(,) = New Double(count - 1, 1) {}
            Dim t As Task = New Task(Sub()
                                         Parallel.[For](0, count, Sub(i)
                                                                      Dim d2 = 0.0
                                                                      Dim d3 = 0.0
                                                                      Dim d4 = 0.0
                                                                      Dim d5 = 0.0
                                                                      Dim dd1 = d1 + i * incr

                                                                      For l1 As Integer = 1 To l
                                                                          Dim d6 = 2 * l1 - 1
                                                                          Dim d7 = 2 * l1
                                                                          Dim d14 = 0.0
                                                                          Dim d15 = 0.0
                                                                          Dim d16 = 0.0
                                                                          Dim d8 = (dd1 * Math.Log(d6)) Mod 6.2831853071795862
                                                                          Dim d9 = (dd1 * Math.Log(d7)) Mod 6.2831853071795862
                                                                          Dim d10 = -1 * d
                                                                          Dim d11 = -1 * 0.5
                                                                          Dim d12 = Math.Pow(d6, d10)
                                                                          Dim d13 = Math.Pow(d7, d10)
                                                                          d2 += d12 * Math.Cos(d8) - d13 * Math.Cos(d9)
                                                                          d3 += d13 * Math.Sin(d9) - d12 * Math.Sin(d8)
                                                                          d4 += Math.Pow(d6, d11) * Math.Cos(d8) - Math.Pow(d7, d11) * Math.Cos(d9)
                                                                          d14 = Math.Pow(d7, d11) * Math.Sin(d9)
                                                                          d15 = Math.Pow(d6, d11)
                                                                          d16 = Math.Sin(d8)
                                                                          d5 += d14 - d15 * d16
                                                                      Next

                                                                      Dim d17 = 1.0 - Math.Pow(2, 1.0 - d) * Math.Cos(d1 * Math.Log(2))
                                                                      Dim d18 = Math.Pow(2, 1.0 - d) * Math.Sin(d1 * Math.Log(2))
                                                                      Dim d19 = (d17 * d2 + d18 * d3) / (Math.Pow(d17, 2) + Math.Pow(d18, 2))
                                                                      Dim d20 = (d17 * d3 - d18 * d2) / (Math.Pow(d17, 2) + Math.Pow(d18, 2))
                                                                      Interlocked.Exchange(arr(i, 0), d19)
                                                                      Interlocked.Exchange(arr(i, 1), d20)
                                                                  End Sub)
                                     End Sub)
            t.RunSynchronously()
            t2 = DateTime.Now
            Return New ArrayResult(arr)
        End Function
    End Class

    Public Class ArrayResult
        Inherits CalcArray

        Private values As Double(,)

        Public Sub New(ByVal values As Double(,))
            If values Is Nothing Then values = New Double(-1, -1) {}
            Me.values = values
        End Sub

        Public Overrides ReadOnly Property RowCount As Integer
            Get
                Return values.GetUpperBound(0) - values.GetLowerBound(0) + 1
            End Get
        End Property

        Public Overrides ReadOnly Property ColumnCount As Integer
            Get
                Return values.GetUpperBound(1) - values.GetLowerBound(1) + 1
            End Get
        End Property

        Public Overrides Function GetValue(ByVal row As Integer, ByVal column As Integer) As Object
            Return values(row, column)
        End Function
    End Class
End Namespace

