├── .build.ps1 ├── .gitignore ├── COPYING ├── COPYING.LESSER ├── LICENSE.txt ├── README.md ├── scripts ├── PSMath.Format.ps1xml ├── PSMath.psd1 └── PSMath.psm1 ├── source ├── Horker.Math.sln ├── Horker.Math │ ├── ArrayMethods │ │ ├── ArrayMethodsHelper.cs │ │ ├── Typed │ │ │ ├── Additional.cs │ │ │ ├── Elementwise.cs │ │ │ ├── Linq.cs │ │ │ └── Matrix.cs │ │ └── Untyped │ │ │ ├── Additional.cs │ │ │ ├── Matrix.cs │ │ │ ├── Measures.cs │ │ │ ├── Tools.cs │ │ │ └── Vector.cs │ ├── Collections │ │ ├── DataFrame │ │ │ ├── DataFrame.cs │ │ │ ├── DataFrameColumn.cs │ │ │ ├── DataFrameColumnBase.cs │ │ │ ├── DataFrameColumnFactory.cs │ │ │ ├── DataFrameColumnInfo.cs │ │ │ ├── DataFrameGroup.cs │ │ │ ├── DataFrameType.cs │ │ │ ├── KeyComparers.cs │ │ │ └── NewMathDataFrame.cs │ │ ├── DataTable │ │ │ ├── DataTableExtensionMethods.cs │ │ │ └── DataTablePSMethods.cs │ │ ├── Matrix │ │ │ ├── Matrix.cs │ │ │ ├── MatrixCmdlets.cs │ │ │ └── New-Math.Matrix.cs │ │ └── Slice │ │ │ ├── Get-Math.Slice.cs │ │ │ └── Slice.cs │ ├── Conversions │ │ ├── ConversionCmdlets.cs │ │ └── Converter.cs │ ├── Horker.Math.csproj │ ├── Math │ │ ├── DataSummary.cs │ │ └── MathCmdlets.cs │ ├── PSObject │ │ ├── AdditionalPSObjectMethods.cs │ │ ├── ConvertFrom-PSObject.BinaryFormat.cs │ │ ├── ConvertTo-PSObject.BinaryFormat.cs │ │ ├── Export-PSObject.BinaryFormat.cs │ │ ├── Get-PSObject.Summary.cs │ │ ├── Get-PSObject.TypeInformation.cs │ │ ├── Import-PSObject.BinaryFormat.cs │ │ ├── New-PSObject.OneHot.cs │ │ ├── New-PSObject.TruthTable.cs │ │ └── ObjectListCmdletBase.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Sequence │ │ └── SequenceCmdlets.cs │ ├── Statistics │ │ ├── Analyses │ │ │ └── InvokeDescriptiveAnalysis.cs │ │ ├── Distributions │ │ │ └── Distributions.cs │ │ ├── KalmanFilter2D.cs │ │ ├── Regressions │ │ │ ├── InvokeGeneralizedLinearRegression.cs │ │ │ ├── InvokeLinearRegression.cs │ │ │ ├── InvokeLogisticRegression.cs │ │ │ └── InvokeStepwiseLogisticRegression.cs │ │ └── Tests │ │ │ ├── InvokeBinomialTest.cs │ │ │ ├── InvokeChiSquareTest.cs │ │ │ ├── InvokeFTest.cs │ │ │ ├── InvokeFisherExactTest.cs │ │ │ ├── InvokeKolmogorovSmirnovTest.cs │ │ │ ├── InvokeLeveneTest.cs │ │ │ ├── InvokeMannWhitneyWilcoxonTest.cs │ │ │ ├── InvokeOneWayAnova.cs │ │ │ ├── InvokePairedTTest.cs │ │ │ ├── InvokeShapiroWilkTest.cs │ │ │ ├── InvokeSignTest.cs │ │ │ ├── InvokeTTest.cs │ │ │ ├── InvokeTwoSampleKolmogorovSmirnovTest.cs │ │ │ ├── InvokeTwoSampleSignTest.cs │ │ │ ├── InvokeTwoSampleTTest.cs │ │ │ ├── InvokeTwoSampleWilcoxonSignedRankTest.cs │ │ │ ├── InvokeTwoWayAnova.cs │ │ │ ├── InvokeWilcoxonSignedRankTest.cs │ │ │ └── TestHelper.cs │ └── packages.config └── Tests │ ├── Properties │ └── AssemblyInfo.cs │ ├── TestArrayMethods.cs │ ├── TestDataFrame.cs │ ├── TestDataFrameColumn.cs │ ├── TestDataTableMethods.cs │ ├── TestNewMathMatrix.cs │ ├── TestNewMathSequence.cs │ ├── Tests.csproj │ └── packages.config └── tools └── Publish.ps1 /.build.ps1: -------------------------------------------------------------------------------- 1 | task . Compile, Build, ImportDebug 2 | 3 | Set-StrictMode -Version 4 4 | 5 | ############################################################ 6 | 7 | $SOURCE_PATH = "$PSScriptRoot\source\Horker.Math" 8 | $SCRIPT_PATH = "$PSScriptRoot\scripts" 9 | 10 | $MODULE_PATH = "$PSScriptRoot\psmath" 11 | $MODULE_PATH_DEBUG = "$PSScriptRoot\debug\psmath" 12 | 13 | $SOLUTION_FILE = "$PSScriptRoot\source\Horker.Math.sln" 14 | 15 | $OBJECT_FILES = @( 16 | "Accord.dll" 17 | "Accord.Math.Core.dll" 18 | "Accord.Math.dll" 19 | "Accord.Statistics.dll" 20 | "Horker.Math.dll" 21 | "Horker.Math.pdb" 22 | ) 23 | 24 | #$HELP_INPUT = "$SOURCE_PATH\bin\Release\Horker.Math.dll" 25 | #$HELP_INTERM = "$SOURCE_PATH\bin\Release\Horker.Data.dll-Help.xml" 26 | #$HELP_OUTPUT = "$MODULE_PATH\Horker.Data.dll-Help.xml" 27 | #$HELPGEN = "$PSScriptRoot\vendor\XmlDoc2CmdletDoc.0.2.10\tools\XmlDoc2CmdletDoc.exe" 28 | 29 | ############################################################ 30 | 31 | function New-Folder2 { 32 | param( 33 | [string]$Path 34 | ) 35 | 36 | try { 37 | $null = New-Item -Type Directory $Path -EA Stop 38 | Write-Host -ForegroundColor DarkCyan "$Path created" 39 | } 40 | catch { 41 | Write-Host -ForegroundColor DarkYellow $_ 42 | } 43 | } 44 | 45 | function Copy-Item2 { 46 | param( 47 | [string]$Source, 48 | [string]$Dest 49 | ) 50 | 51 | try { 52 | Copy-Item $Source $Dest -EA Stop 53 | Write-Host -ForegroundColor DarkCyan "Copy from $Source to $Dest done" 54 | } 55 | catch { 56 | Write-Host -ForegroundColor DarkYellow $_ 57 | } 58 | } 59 | 60 | function Remove-Item2 { 61 | param( 62 | [string]$Path 63 | ) 64 | 65 | try { 66 | Remove-Item $Path -EA Stop 67 | Write-Host -ForegroundColor DarkCyan "$Path removed" 68 | } 69 | catch { 70 | Write-Host -ForegroundColor DarkYellow $_ 71 | } 72 | } 73 | 74 | ############################################################ 75 | 76 | task Compile { 77 | msbuild $SOLUTION_FILE /p:Configuration=Debug /nologo /v:minimal 78 | msbuild $SOLUTION_FILE /p:Configuration=Release /nologo /v:minimal 79 | } 80 | 81 | task Build { 82 | . { 83 | $ErrorActionPreference = "Continue" 84 | 85 | function Copy-ObjectFiles { 86 | param( 87 | [string]$targetPath, 88 | [string]$objectPath 89 | ) 90 | New-Folder2 $targetPath 91 | 92 | Copy-Item2 "$SCRIPT_PATH\*" $targetPath 93 | $OBJECT_FILES | foreach { 94 | $path = Join-Path $objectPath $_ 95 | Copy-Item2 $path $targetPath 96 | } 97 | } 98 | 99 | Copy-ObjectFiles $MODULE_PATH "$SOURCE_PATH\bin\Release" 100 | Copy-ObjectFiles $MODULE_PATH_DEBUG "$SOURCE_PATH\bin\Debug" 101 | } 102 | } 103 | 104 | #task BuildHelp ` 105 | # -Inputs $HELP_INPUT ` 106 | # -Outputs $HELP_OUTPUT ` 107 | #{ 108 | # . $HELPGEN $HELP_INPUT 109 | # 110 | # Copy-Item $HELP_INTERM $MODULE_PATH 111 | #} 112 | 113 | task Test Build, ImportDebug, { 114 | Invoke-Pester "$PSScriptRoot\tests" 115 | } 116 | 117 | task ImportDebug { 118 | Import-Module $MODULE_PATH_DEBUG -Force 119 | } 120 | 121 | task Clean { 122 | Remove-Item2 "$MODULE_PATH\*" -Force -Recurse -EA Continue 123 | Remove-Item2 "$MODULE_PATH_DEBUG\*" -Force -Recurse -EA Continue 124 | } 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | psmath/ 2 | debug/ 3 | 4 | .vs/ 5 | bin/ 6 | obj/ 7 | packages/ 8 | *.user 9 | 10 | private/ 11 | vendor/ 12 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | PowerShell Math and Statistics Library 2 | 3 | Copyright 2018 horker 4 | 5 | This program is free software: you can redistribute it and/or modify it under 6 | the terms of the GNU Lesser General Public License as published by the Free 7 | Software Foundation, either version 2.1 of the License, or (at your option) any 8 | later version. 9 | 10 | This program is distributed in the hope that it will be useful, but WITHOUT ANY 11 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 12 | PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 13 | details. 14 | 15 | You should have received a copy of the GNU General Public License along with 16 | this program. If not, see . 17 | -------------------------------------------------------------------------------- /scripts/PSMath.Format.ps1xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Accord.Statistics.Analysis.LogisticRegressionAnalysis 7 | 8 | Accord.Statistics.Analysis.LogisticRegressionAnalysis 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | (($_.Coefficients | Format-Table Name, Value, OddsRatio, StandardError, Wald, LikelihoodRatio | Out-String) -Replace "(\r?\n)+", "`n" ) + 17 | (($_ | Format-List NumberOfSamples, LogLikelihood, Deviance, @{ l = "AIC"; e = { $_.Deviance + 2 * ($_.Inputs.Count + 1) } } | Out-String) -Replace "(\r?\n)+", "`n" -Replace "(\r?\n)$", "") 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | Horker.Math.Matrix 28 | 29 | Horker.Math.Matrix 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | $_.AsString() 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /scripts/PSMath.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'PSMath' 3 | # 4 | # Generated by: horker 5 | # 6 | # Generated on: 2017/12/03 7 | # 8 | 9 | @{ 10 | 11 | # Script module or binary module file associated with this manifest. 12 | RootModule = 'PSMath.psm1' 13 | 14 | # Version number of this module. 15 | ModuleVersion = '0.1.1' 16 | 17 | # Supported PSEditions 18 | # CompatiblePSEditions = '' 19 | 20 | # ID used to uniquely identify this module 21 | GUID = 'e356c4e7-b682-4008-938b-0b81db760c4b' 22 | 23 | # Author of this module 24 | Author = 'horker' 25 | 26 | # Company or vendor of this module 27 | CompanyName = '' 28 | 29 | # Copyright statement for this module 30 | Copyright = '(c) 2018 horker. All rights reserved.' 31 | 32 | # Description of the functionality provided by this module 33 | Description = @" 34 | PowerShell Math and Statistics Library is a collection of math and statistics classes and cmdlets for PowerShell. It is built on top of Accord.NET (http://accord-framework.net/). 35 | 36 | This is a work in progress, but already usable for many use cases. 37 | 38 | For more details, see https://github.com/horker/psmath 39 | "@ 40 | 41 | # Minimum version of the Windows PowerShell engine required by this module 42 | # PowerShellVersion = '' 43 | 44 | # Name of the Windows PowerShell host required by this module 45 | # PowerShellHostName = '' 46 | 47 | # Minimum version of the Windows PowerShell host required by this module 48 | # PowerShellHostVersion = '' 49 | 50 | # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 51 | DotNetFrameworkVersion = '4.5.2' 52 | 53 | # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 54 | # CLRVersion = '' 55 | 56 | # Processor architecture (None, X86, Amd64) required by this module 57 | # ProcessorArchitecture = '' 58 | 59 | # Modules that must be imported into the global environment prior to importing this module 60 | # RequiredModules = @() 61 | 62 | # Assemblies that must be loaded prior to importing this module 63 | RequiredAssemblies = @( 64 | "Accord.dll" 65 | "Accord.Math.Core.dll" 66 | "Accord.Math.dll" 67 | "Accord.Statistics.dll" 68 | ) 69 | 70 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 71 | # ScriptsToProcess = @() 72 | 73 | # Type files (.ps1xml) to be loaded when importing this module 74 | # TypesToProcess = @() 75 | 76 | # Format files (.ps1xml) to be loaded when importing this module 77 | FormatsToProcess = @( 78 | "PSMath.Format.ps1xml" 79 | ) 80 | 81 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 82 | NestedModules = @( 83 | "Horker.Math.dll" 84 | ) 85 | 86 | # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. 87 | FunctionsToExport = @() 88 | 89 | # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. 90 | CmdletsToExport = "*" 91 | 92 | # Variables to export from this module 93 | VariablesToExport = @() 94 | 95 | # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. 96 | AliasesToExport = "*" 97 | 98 | # DSC resources to export from this module 99 | # DscResourcesToExport = @() 100 | 101 | # List of all modules packaged with this module 102 | # ModuleList = @() 103 | 104 | # List of all files packaged with this module 105 | # FileList = @() 106 | 107 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. 108 | PrivateData = @{ 109 | 110 | PSData = @{ 111 | 112 | # Tags applied to this module. These help with module discovery in online galleries. 113 | Tags = @( 114 | 'Accord', 'Accord.NET', 115 | 'math', 'statistics', 'statistical', 116 | 'sin', 'cos', 'exp', 'pow', 'sqrt', 'pi', 'matrix', 117 | 'mean', 'variance', 'standard', 'deviation', 118 | 'normal', 'chi', 'squire', 'f', 't', 'distribution', 119 | 'binomial', 'fisher', 'anova', 120 | 'hypothesis', 'testing', 121 | 'linear', 'logistic', 'regression' 122 | ) 123 | 124 | # A URL to the license for this module. 125 | LicenseUri = 'https://opensource.org/licenses/LGPL-2.1' 126 | 127 | # A URL to the main website for this project. 128 | ProjectUri = 'https://github.com/horker/psmath' 129 | 130 | # A URL to an icon representing this module. 131 | # IconUri = '' 132 | 133 | # ReleaseNotes of this module 134 | ReleaseNotes = @" 135 | v0.1.1 136 | Fix several issues 137 | 138 | v0.1.0 139 | First release 140 | "@ 141 | 142 | } # End of PSData hashtable 143 | 144 | } # End of PrivateData hashtable 145 | 146 | # HelpInfo URI of this module 147 | # HelpInfoURI = '' 148 | 149 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 150 | # DefaultCommandPrefix = '' 151 | 152 | } 153 | -------------------------------------------------------------------------------- /scripts/PSMath.psm1: -------------------------------------------------------------------------------- 1 | Set-StrictMode -Version Latest 2 | 3 | $METHOD_LIST_1D = @( 4 | [PSCustomObject]@{ 5 | ClassInfo = "Horker.Math.ArrayMethods.Typed.Linq[{0}]" 6 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 7 | MethodNames = @( 8 | "Aggregate" 9 | "All" 10 | "Any" 11 | "AsEnumerable" 12 | "Concat" 13 | "Contains" 14 | "DefaultIfEmpty" 15 | "Distinct" 16 | "ElementAt" 17 | "ElementAtOrDefault" 18 | "Except" 19 | "First" 20 | "FirstOrDefault" 21 | #"GroupBy" 22 | "GroupJoin" 23 | "Intersect" 24 | "Join" 25 | "Last" 26 | "LastOrDefault" 27 | "LongCount" 28 | "Max" 29 | "Min" 30 | "OrderBy" 31 | "OrderByDescending" 32 | "Reverse" 33 | "Select" 34 | "SelectMany" 35 | "SequenceEqual" 36 | "Single" 37 | "SingleOrDefault" 38 | "Skip" 39 | "SkipWhile" 40 | "Sum" 41 | "Take" 42 | "TakeWhile" 43 | "ToDictionary" 44 | "ToList" 45 | "ToLookup" 46 | "Union" 47 | "Where" 48 | "Zip" 49 | ) 50 | } 51 | 52 | [PSCustomObject]@{ 53 | ClassInfo = "Horker.Math.ArrayMethods.Untyped.Additional" 54 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 55 | MethodNames = @( 56 | "Clip" 57 | "DropNa" 58 | "DropNaN" 59 | "Histogram" 60 | "Summary" 61 | ) 62 | } 63 | 64 | [PSCustomObject]@{ 65 | ClassInfo = "Horker.Math.ArrayMethods.Typed.Additional[{0}]" 66 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 67 | MethodNames = @( 68 | "Split" 69 | "Shuffle" 70 | "Slice" 71 | "Concatenate" 72 | ) 73 | } 74 | 75 | [PSCustomObject]@{ 76 | ClassInfo = "Horker.Math.ArrayMethods.Measures" 77 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 78 | MethodNames = @( 79 | "ContraHarmonicMean" 80 | "Entropy" 81 | "ExponentialWeightedMean" 82 | "ExponentialWeightedVariance" 83 | "GeometricMean" 84 | "Kurtosis" 85 | "LogGeometricMean" 86 | "LowerQuartile" 87 | "Mean" 88 | "Median" 89 | "Mode" 90 | "Quantile" 91 | "Quantiles" 92 | "Quartiles" 93 | "Skewness" 94 | "StandardDeviation" 95 | "StdDev" 96 | "StandardError" 97 | "TruncatedMean" 98 | "UpperQuartile" 99 | "Variance" 100 | "Var" 101 | ) 102 | } 103 | 104 | [PSCustomObject]@{ 105 | ClassInfo = "Horker.Math.ArrayMethods.Tools" 106 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 107 | MethodNames = @( 108 | "Center" 109 | "Rank" 110 | "Standardize" 111 | "Ties" 112 | ) 113 | } 114 | 115 | [PSCustomObject]@{ 116 | ClassInfo = "Horker.Math.ArrayMethods.Vector" 117 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 118 | MethodNames = @( 119 | "Sample" 120 | "Scale" 121 | "Sort" 122 | ) 123 | } 124 | 125 | [PSCustomObject]@{ 126 | ClassInfo = "Horker.Math.ArrayMethods.Typed.Matrix[{0}]" 127 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 128 | MethodNames = @( 129 | "Clear" 130 | "Copy" 131 | "DistinctCount" 132 | "Expand" 133 | "Find" 134 | "First" 135 | "Get" 136 | "IsEqual" 137 | "IsSorted" 138 | "OneHot" 139 | "Swap" 140 | ) 141 | } 142 | 143 | [PSCustomObject]@{ 144 | ClassInfo = "Horker.Math.ArrayMethods.Untyped.Matrix" 145 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 146 | MethodNames = @( 147 | "ArgMax" 148 | "ArgMin" 149 | "ArgSort" 150 | "Bottom" 151 | "Cartesian" 152 | "Cross" 153 | "CumulativeSum" 154 | "HasInfinity" 155 | "HasNaN" 156 | "Kronecker" 157 | "Normalize" 158 | "Null" 159 | "Outer" 160 | "Product" 161 | "Stack" 162 | "Top" 163 | "Trim" 164 | ) 165 | } 166 | 167 | [PSCustomObject]@{ 168 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseObject" 169 | TargetClass = "Object" 170 | MethodNames = @( 171 | "ElementAdd" 172 | "ElementSubtract" 173 | "ElementMultiply" 174 | "ElementDivide" 175 | "ElementReminder" 176 | "ElementNegate" 177 | ) 178 | } 179 | 180 | [PSCustomObject]@{ 181 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseDouble" 182 | TargetClass = "Double" 183 | MethodNames = @( 184 | "ElementAdd" 185 | "ElementSubtract" 186 | "ElementMultiply" 187 | "ElementDivide" 188 | "ElementReminder" 189 | "ElementNegate" 190 | ) 191 | } 192 | 193 | [PSCustomObject]@{ 194 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseSingle" 195 | TargetClass = "Single" 196 | MethodNames = @( 197 | "ElementAdd" 198 | "ElementSubtract" 199 | "ElementMultiply" 200 | "ElementDivide" 201 | "ElementReminder" 202 | "ElementNegate" 203 | ) 204 | } 205 | 206 | [PSCustomObject]@{ 207 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseInt64" 208 | TargetClass = "Int64" 209 | MethodNames = @( 210 | "ElementAdd" 211 | "ElementSubtract" 212 | "ElementMultiply" 213 | "ElementDivide" 214 | "ElementReminder" 215 | "ElementNegate" 216 | ) 217 | } 218 | 219 | [PSCustomObject]@{ 220 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseInt32" 221 | TargetClass = "Int32" 222 | MethodNames = @( 223 | "ElementAdd" 224 | "ElementSubtract" 225 | "ElementMultiply" 226 | "ElementDivide" 227 | "ElementReminder" 228 | "ElementNegate" 229 | ) 230 | } 231 | 232 | [PSCustomObject]@{ 233 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseInt16" 234 | TargetClass = "Int16" 235 | MethodNames = @( 236 | "ElementAdd" 237 | "ElementSubtract" 238 | "ElementMultiply" 239 | "ElementDivide" 240 | "ElementReminder" 241 | "ElementNegate" 242 | ) 243 | } 244 | 245 | [PSCustomObject]@{ 246 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseByte" 247 | TargetClass = "Byte" 248 | MethodNames = @( 249 | "ElementAdd" 250 | "ElementSubtract" 251 | "ElementMultiply" 252 | "ElementDivide" 253 | "ElementReminder" 254 | "ElementNegate" 255 | ) 256 | } 257 | 258 | [PSCustomObject]@{ 259 | ClassInfo = "Horker.Math.ArrayMethods.Typed.ElementwiseSByte" 260 | TargetClass = "SByte" 261 | MethodNames = @( 262 | "ElementAdd" 263 | "ElementSubtract" 264 | "ElementMultiply" 265 | "ElementDivide" 266 | "ElementReminder" 267 | "ElementNegate" 268 | ) 269 | } 270 | ) 271 | 272 | # Methods for two-dimentional arrays 273 | $METHOD_LIST_2D = @( 274 | [PSCustomObject]@{ 275 | ClassInfo = "Horker.Math.ArrayMethods.Typed.Additional[{0}]" 276 | TargetClass = "Object", "Double", "Single", "Int64", "Int32", "Int16", "Byte", "SByte" 277 | MethodNames = @( 278 | "Concatenate2" 279 | ) 280 | } 281 | ) 282 | 283 | # Methods for System.Data.DataTable 284 | $METHOD_LIST = @( 285 | [PSCustomObject]@{ 286 | ClassInfo = "Horker.Math.DataTablePSMethods" 287 | TargetClass = "System.Data.DataTable" 288 | MethodNames = @( 289 | "ExpandToOneHot" 290 | "GetColumn" 291 | ) 292 | } 293 | ) 294 | 295 | foreach ($l in $METHOD_LIST_1D) { 296 | $targets = $l.TargetClass 297 | foreach ($t in $targets) { 298 | $ci = Invoke-Expression "[$($l.ClassInfo -f $t)]" 299 | foreach ($m in $l.MethodNames) { 300 | $mi = $ci.GetMethod($m) 301 | Update-TypeData -TypeName "$t[]" -MemberName $m -MemberType CodeMethod -Value $mi -Force 302 | } 303 | } 304 | } 305 | 306 | foreach ($l in $METHOD_LIST_2D) { 307 | $targets = $l.TargetClass 308 | foreach ($t in $targets) { 309 | $ci = Invoke-Expression "[$($l.ClassInfo -f $t)]" 310 | foreach ($m in $l.MethodNames) { 311 | $mi = $ci.GetMethod($m) 312 | $name = $m -replace "\d+$", "" # Remove trailing digits 313 | Update-TypeData -TypeName "$t[][]" -MemberName $name -MemberType CodeMethod -Value $mi -Force 314 | } 315 | } 316 | } 317 | 318 | foreach ($l in $METHOD_LIST) { 319 | $targets = $l.TargetClass 320 | foreach ($t in $targets) { 321 | $ci = Invoke-Expression "[$($l.ClassInfo -f $t)]" 322 | foreach ($m in $l.MethodNames) { 323 | $mi = $ci.GetMethod($m) 324 | Update-TypeData -TypeName "$t" -MemberName $m -MemberType CodeMethod -Value $mi -Force 325 | } 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /source/Horker.Math.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2010 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{9E4D2A29-5617-4807-BC37-5AE6938E0195}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Horker.Math", "Horker.Math\Horker.Math.csproj", "{F4C2900E-ADFE-4612-A40C-19393FC2CEFF}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {9E4D2A29-5617-4807-BC37-5AE6938E0195}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {9E4D2A29-5617-4807-BC37-5AE6938E0195}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {9E4D2A29-5617-4807-BC37-5AE6938E0195}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {9E4D2A29-5617-4807-BC37-5AE6938E0195}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {F4C2900E-ADFE-4612-A40C-19393FC2CEFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {F4C2900E-ADFE-4612-A40C-19393FC2CEFF}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {F4C2900E-ADFE-4612-A40C-19393FC2CEFF}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {F4C2900E-ADFE-4612-A40C-19393FC2CEFF}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {B9E873E5-7212-4F40-AB65-221CF93A53C5} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/ArrayMethodsHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Management.Automation; 4 | 5 | namespace Horker.Math.ArrayMethods 6 | { 7 | internal class Helper 8 | { 9 | internal static object[] GetObjectArray(PSObject values) 10 | { 11 | var array = values.BaseObject; 12 | if (array is object[]) 13 | return array as object[]; 14 | else if (array is double[]) 15 | return (array as double[]).Select(x => (object)x).ToArray(); 16 | else if (array is float[]) 17 | return (array as float[]).Select(x => (object)x).ToArray(); 18 | else if (array is Int64[]) 19 | return (array as Int64[]).Select(x => (object)x).ToArray(); 20 | else if (array is Int32[]) 21 | return (array as Int32[]).Select(x => (object)x).ToArray(); 22 | else if (array is Int16[]) 23 | return (array as Int16[]).Select(x => (object)x).ToArray(); 24 | else if (array is Byte[]) 25 | return (array as Byte[]).Select(x => (object)x).ToArray(); 26 | else if (array is SByte[]) 27 | return (array as SByte[]).Select(x => (object)x).ToArray(); 28 | 29 | throw new ArgumentException("Failed to convert to object[]"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Typed/Elementwise.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Math; 6 | using Accord.Math.Random; 7 | 8 | namespace Horker.Math.ArrayMethods.Typed 9 | { 10 | public class ElementwiseObject 11 | { 12 | public static Double[] ElementAdd(PSObject values, Double other) 13 | { return Converter.ToDoubleArray(values).Select(x => x + other).ToArray(); } 14 | 15 | public static Double[] ElementSubtract(PSObject values, Double other) 16 | { return Converter.ToDoubleArray(values).Select(x => x - other).ToArray(); } 17 | 18 | public static Double[] ElementMultiply(PSObject values, Double other) 19 | { return Converter.ToDoubleArray(values).Select(x => x * other).ToArray(); } 20 | 21 | public static Double[] ElementDivide(PSObject values, Double other) 22 | { return Converter.ToDoubleArray(values).Select(x => x / other).ToArray(); } 23 | 24 | public static Double[] ElementReminder(PSObject values, Double other) 25 | { return Converter.ToDoubleArray(values).Select(x => x % other).ToArray(); } 26 | 27 | public static Double[] ElementNegate(PSObject values) 28 | { return Converter.ToDoubleArray(values).Select(x => -x).ToArray(); } 29 | } 30 | 31 | public class ElementwiseDouble 32 | { 33 | public static Double[] ElementAdd(PSObject values, Double other) 34 | { return (values.BaseObject as Double[]).Select(x => x + other).ToArray(); } 35 | 36 | public static Double[] ElementSubtract(PSObject values, Double other) 37 | { return (values.BaseObject as Double[]).Select(x => x - other).ToArray(); } 38 | 39 | public static Double[] ElementMultiply(PSObject values, Double other) 40 | { return (values.BaseObject as Double[]).Select(x => x * other).ToArray(); } 41 | 42 | public static Double[] ElementDivide(PSObject values, Double other) 43 | { return (values.BaseObject as Double[]).Select(x => x / other).ToArray(); } 44 | 45 | public static Double[] ElementReminder(PSObject values, Double other) 46 | { return (values.BaseObject as Double[]).Select(x => x % other).ToArray(); } 47 | 48 | public static Double[] ElementNegate(PSObject values) 49 | { return (values.BaseObject as Double[]).Select(x => -x).ToArray(); } 50 | } 51 | 52 | public class ElementwiseSingle 53 | { 54 | public static Single[] ElementAdd(PSObject values, Single other) 55 | { return (values.BaseObject as Single[]).Select(x => x + other).ToArray(); } 56 | 57 | public static Single[] ElementSubtract(PSObject values, Single other) 58 | { return (values.BaseObject as Single[]).Select(x => x - other).ToArray(); } 59 | 60 | public static Single[] ElementMultiply(PSObject values, Single other) 61 | { return (values.BaseObject as Single[]).Select(x => x * other).ToArray(); } 62 | 63 | public static Single[] ElementDivide(PSObject values, Single other) 64 | { return (values.BaseObject as Single[]).Select(x => x / other).ToArray(); } 65 | 66 | public static Single[] ElementReminder(PSObject values, Single other) 67 | { return (values.BaseObject as Single[]).Select(x => x % other).ToArray(); } 68 | 69 | public static Single[] ElementNegate(PSObject values) 70 | { return (values.BaseObject as Single[]).Select(x => -x).ToArray(); } 71 | } 72 | 73 | public class ElementwiseInt64 74 | { 75 | public static Int64[] ElementAdd(PSObject values, Int64 other) 76 | { return (values.BaseObject as Int64[]).Select(x => x + other).ToArray(); } 77 | 78 | public static Int64[] ElementSubtract(PSObject values, Int64 other) 79 | { return (values.BaseObject as Int64[]).Select(x => x - other).ToArray(); } 80 | 81 | public static Int64[] ElementMultiply(PSObject values, Int64 other) 82 | { return (values.BaseObject as Int64[]).Select(x => x * other).ToArray(); } 83 | 84 | public static Int64[] ElementDivide(PSObject values, Int64 other) 85 | { return (values.BaseObject as Int64[]).Select(x => x / other).ToArray(); } 86 | 87 | public static Int64[] ElementReminder(PSObject values, Int64 other) 88 | { return (values.BaseObject as Int64[]).Select(x => x % other).ToArray(); } 89 | 90 | public static Int64[] ElementNegate(PSObject values) 91 | { return (values.BaseObject as Int64[]).Select(x => -x).ToArray(); } 92 | } 93 | 94 | public class ElementwiseInt32 95 | { 96 | public static Int32[] ElementAdd(PSObject values, Int32 other) 97 | { return (values.BaseObject as Int32[]).Select(x => x + other).ToArray(); } 98 | 99 | public static Int32[] ElementSubtract(PSObject values, Int32 other) 100 | { return (values.BaseObject as Int32[]).Select(x => x - other).ToArray(); } 101 | 102 | public static Int32[] ElementMultiply(PSObject values, Int32 other) 103 | { return (values.BaseObject as Int32[]).Select(x => x * other).ToArray(); } 104 | 105 | public static Int32[] ElementDivide(PSObject values, Int32 other) 106 | { return (values.BaseObject as Int32[]).Select(x => x / other).ToArray(); } 107 | 108 | public static Int32[] ElementReminder(PSObject values, Int32 other) 109 | { return (values.BaseObject as Int32[]).Select(x => x % other).ToArray(); } 110 | 111 | public static Int32[] ElementNegate(PSObject values) 112 | { return (values.BaseObject as Int32[]).Select(x => -x).ToArray(); } 113 | } 114 | 115 | public class ElementwiseInt16 116 | { 117 | public static Int16[] ElementAdd(PSObject values, Int16 other) 118 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(x + other)).ToArray(); } 119 | 120 | public static Int16[] ElementSubtract(PSObject values, Int16 other) 121 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(x - other)).ToArray(); } 122 | 123 | public static Int16[] ElementMultiply(PSObject values, Int16 other) 124 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(x * other)).ToArray(); } 125 | 126 | public static Int16[] ElementDivide(PSObject values, Int16 other) 127 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(x / other)).ToArray(); } 128 | 129 | public static Int16[] ElementReminder(PSObject values, Int16 other) 130 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(x % other)).ToArray(); } 131 | 132 | public static Int16[] ElementNegate(PSObject values) 133 | { return (values.BaseObject as Int16[]).Select(x => (Int16)(-x)).ToArray(); } 134 | } 135 | 136 | public class ElementwiseByte 137 | { 138 | public static Byte[] ElementAdd(PSObject values, Byte other) 139 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(x + other)).ToArray(); } 140 | 141 | public static Byte[] ElementSubtract(PSObject values, Byte other) 142 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(x - other)).ToArray(); } 143 | 144 | public static Byte[] ElementMultiply(PSObject values, Byte other) 145 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(x * other)).ToArray(); } 146 | 147 | public static Byte[] ElementDivide(PSObject values, Byte other) 148 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(x / other)).ToArray(); } 149 | 150 | public static Byte[] ElementReminder(PSObject values, Byte other) 151 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(x % other)).ToArray(); } 152 | 153 | public static Byte[] ElementNegate(PSObject values) 154 | { return (values.BaseObject as Byte[]).Select(x => (Byte)(-x)).ToArray(); } 155 | } 156 | 157 | public class ElementwiseSByte 158 | { 159 | public static SByte[] ElementAdd(PSObject values, SByte other) 160 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(x + other)).ToArray(); } 161 | 162 | public static SByte[] ElementSubtract(PSObject values, SByte other) 163 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(x - other)).ToArray(); } 164 | 165 | public static SByte[] ElementMultiply(PSObject values, SByte other) 166 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(x * other)).ToArray(); } 167 | 168 | public static SByte[] ElementDivide(PSObject values, SByte other) 169 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(x / other)).ToArray(); } 170 | 171 | public static SByte[] ElementReminder(PSObject values, SByte other) 172 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(x % other)).ToArray(); } 173 | 174 | public static SByte[] ElementNegate(PSObject values) 175 | { return (values.BaseObject as SByte[]).Select(x => (SByte)(-x)).ToArray(); } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Typed/Matrix.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Math; 6 | using Accord.Math.Random; 7 | 8 | namespace Horker.Math.ArrayMethods.Typed 9 | { 10 | public class Matrix 11 | { 12 | public static void Clear( 13 | PSObject values 14 | ) 15 | { 16 | var array = (T[])values.BaseObject; 17 | Accord.Math.Matrix.Clear(array); 18 | } 19 | 20 | /* 21 | public static T[] Concatenate( 22 | PSObject a, 23 | T[] b 24 | ) 25 | { 26 | var array = (T[])a.BaseObject; 27 | return Accord.Math.Matrix.Concatenate(b); 28 | } 29 | */ 30 | 31 | public static T[] Copy( 32 | PSObject vector 33 | ) 34 | { 35 | var array = (T[])vector.BaseObject; 36 | var result = new T[array.Length]; 37 | Array.Copy(array, result, array.Length); 38 | return result; 39 | } 40 | 41 | public static int DistinctCount( 42 | PSObject values 43 | ) 44 | { 45 | var array = (T[])values.BaseObject; 46 | return Accord.Math.Matrix.DistinctCount(array); 47 | } 48 | 49 | public static T[] Expand( 50 | PSObject vector, 51 | int[] count 52 | ) 53 | { 54 | var array = (T[])vector.BaseObject; 55 | return Accord.Math.Matrix.Expand(array, count); 56 | } 57 | 58 | public static int[] Find( 59 | PSObject data, 60 | Func func, 61 | bool firstOnly = false 62 | ) 63 | { 64 | var array = (T[])data.BaseObject; 65 | return Accord.Math.Matrix.Find(array, func, firstOnly); 66 | } 67 | 68 | public static T[] First( 69 | PSObject values, 70 | int count 71 | ) 72 | { 73 | var array = (T[])values.BaseObject; 74 | return Accord.Math.Matrix.First(array, count); 75 | } 76 | 77 | public static T[] Get( 78 | PSObject source, 79 | int startRow, 80 | int endRow 81 | ) 82 | { 83 | var array = (T[])source.BaseObject; 84 | return Accord.Math.Matrix.Get(array, startRow, endRow); 85 | } 86 | 87 | public static bool IsEqual( 88 | PSObject a, 89 | PSObject b 90 | ) 91 | { 92 | return Accord.Math.Matrix.IsEqual(a, b);; 93 | } 94 | 95 | public static bool IsSorted( 96 | PSObject values, 97 | Accord.Math.Comparers.ComparerDirection direction = Accord.Math.Comparers.ComparerDirection.Ascending 98 | ) 99 | { 100 | var array = Converter.ToDoubleArray(values); 101 | return Accord.Math.Matrix.IsSorted(array, direction); 102 | } 103 | 104 | public static Matrix OneHot(PSObject values, int? columns = null) 105 | { 106 | var array = (T[])values.BaseObject; 107 | 108 | if (columns.HasValue) 109 | return Accord.Math.Matrix.OneHot(array.Apply(x => Convert.ToInt32(x)), columns.Value); 110 | else 111 | return Accord.Math.Matrix.OneHot(array.Apply(x => Convert.ToInt32(x))); 112 | } 113 | 114 | public static void Swap( 115 | PSObject values, 116 | int a, 117 | int b 118 | ) 119 | { 120 | var array = (T[])values.BaseObject; 121 | Accord.Math.Matrix.Swap(array, a, b); 122 | } 123 | } 124 | } -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Untyped/Additional.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Math; 6 | using Accord.Math.Random; 7 | 8 | namespace Horker.Math.ArrayMethods.Untyped 9 | { 10 | public class HistogramBin 11 | { 12 | public double Lower; 13 | public double Upper; 14 | public int Count; 15 | } 16 | 17 | public class Additional 18 | { 19 | public static double[] Clip(PSObject values, double min, double? max = null) 20 | { 21 | var array = Converter.ToDoubleArray(values); 22 | 23 | if (max.HasValue) 24 | return array.Select(x => x < min ? min : (x > max.Value ? max.Value : x)).ToArray(); 25 | else 26 | return array.Select(x => x > min ? min : x).ToArray(); 27 | } 28 | 29 | public static object[] DropNa(PSObject values) 30 | { 31 | var array = Helper.GetObjectArray(values); 32 | 33 | var result = new List(); 34 | foreach (var value in array) 35 | { 36 | if (value == null) 37 | continue; 38 | if (value is double && double.IsNaN((double)value)) 39 | continue; 40 | if (value is float && float.IsNaN((float)value)) 41 | continue; 42 | 43 | result.Add(value); 44 | } 45 | return result.ToArray(); 46 | } 47 | 48 | public static double[] DropNaN(PSObject values) 49 | { 50 | var array = Converter.ToDoubleArray(values); 51 | return array.RemoveAll(double.NaN); 52 | } 53 | 54 | public static HistogramBin[] HistogramInternal(double[] values, double binWidth = double.NaN, double offset = 0.0) 55 | { 56 | var min = values.Min(); 57 | var max = values.Max(); 58 | 59 | if (double.IsNaN(binWidth)) { 60 | var binCount = System.Math.Min(100, System.Math.Ceiling(System.Math.Sqrt(values.Length))); 61 | binWidth = (max - min) / binCount; 62 | } 63 | 64 | int minBar = (int)System.Math.Floor((min - offset) / binWidth); 65 | int maxBar = (int)System.Math.Floor((max - offset) / binWidth); 66 | 67 | var hist = new int[maxBar - minBar + 1]; 68 | 69 | foreach (var value in values) { 70 | var bin = (int)System.Math.Floor((value - offset) / binWidth) - minBar; 71 | ++hist[bin]; 72 | } 73 | 74 | var result = new HistogramBin[maxBar - minBar + 1]; 75 | for (var i = minBar; i <= maxBar; ++i) { 76 | var bin = new HistogramBin(); 77 | bin.Lower = i * binWidth + offset; 78 | bin.Upper = (i + 1) * binWidth + offset; 79 | bin.Count = hist[i - minBar]; 80 | result[i - minBar] = bin; 81 | } 82 | 83 | return result; 84 | } 85 | 86 | public static HistogramBin[] Histogram(PSObject values, double binWidth = double.NaN, double offset = 0.0) 87 | { 88 | var array = Converter.ToDoubleArray(values); 89 | return HistogramInternal(array, binWidth, offset); 90 | } 91 | 92 | public static DataSummary Summary(PSObject values) 93 | { 94 | var array = Converter.ToDoubleArray(values); 95 | return new DataSummary(array); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Untyped/Matrix.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Math; 6 | using Accord.Math.Random; 7 | 8 | namespace Horker.Math.ArrayMethods.Untyped 9 | { 10 | public class Matrix 11 | { 12 | public static int ArgMax( 13 | PSObject values 14 | ) 15 | { 16 | var array = Converter.ToDoubleArray(values); 17 | return Accord.Math.Matrix.ArgMax(array); 18 | } 19 | 20 | public static int ArgMin( 21 | PSObject values 22 | ) 23 | { 24 | var array = Converter.ToDoubleArray(values); 25 | return Accord.Math.Matrix.ArgMin(array); 26 | } 27 | 28 | public static int[] ArgSort( 29 | PSObject values 30 | ) 31 | { 32 | var array = Converter.ToDoubleArray(values); 33 | return Accord.Math.Matrix.ArgSort(array); 34 | } 35 | 36 | public static int[] Bottom( 37 | PSObject values, 38 | int count 39 | ) 40 | { 41 | var array = Converter.ToDoubleArray(values); 42 | return Accord.Math.Matrix.Bottom(array, count); 43 | } 44 | 45 | public static Horker.Math.Matrix Cartesian( 46 | PSObject sequence1, 47 | PSObject sequence2 48 | ) 49 | { 50 | var s1 = Converter.ToDoubleArray(sequence1); 51 | var s2 = Converter.ToDoubleArray(sequence2); 52 | return Horker.Math.Matrix.Create(Accord.Math.Matrix.Cartesian(s1, s2)); 53 | } 54 | 55 | public static double[] Cross( 56 | PSObject a, 57 | PSObject b 58 | ) 59 | { 60 | var a1 = Converter.ToDoubleArray(a); 61 | var a2 = Converter.ToDoubleArray(b); 62 | return Accord.Math.Matrix.Cross(a1, a2); 63 | } 64 | 65 | public static double[] CumulativeSum( 66 | PSObject vector 67 | ) 68 | { 69 | var array = Converter.ToDoubleArray(vector); 70 | return Accord.Math.Matrix.CumulativeSum(array); 71 | } 72 | 73 | /* 74 | public static double[] Distinct( 75 | PSObject values, 76 | bool allowNulls = true 77 | ) 78 | { 79 | var array = Converter.ToDoubleArray(values); 80 | return Accord.Math.Matrix.Distinct(array, allowNulls); 81 | } 82 | */ 83 | 84 | public static bool HasInfinity( 85 | PSObject matrix 86 | ) 87 | { 88 | var array = Converter.ToDoubleArray(matrix); 89 | return Accord.Math.Matrix.HasInfinity(array); 90 | } 91 | 92 | 93 | public static bool HasNaN( 94 | PSObject matrix 95 | ) 96 | { 97 | var array = Converter.ToDoubleArray(matrix); 98 | return Accord.Math.Matrix.HasNaN(array); 99 | } 100 | 101 | public static double[] Kronecker( 102 | PSObject a, 103 | PSObject b 104 | ) 105 | { 106 | var a1 = Converter.ToDoubleArray(a); 107 | var a2 = Converter.ToDoubleArray(b); 108 | return Accord.Math.Matrix.Kronecker(a1, a2); 109 | } 110 | 111 | /* 112 | public static double[] Merge( 113 | params PSObject[] vectors 114 | ) 115 | { 116 | var jagged = vectors.Select(x => Converter.ToDoubleArray(x)); 117 | return Accord.Math.Matrix.Merge(jagged.ToArray()); 118 | } 119 | */ 120 | 121 | public static double[] Normalize( 122 | PSObject vector 123 | ) 124 | { 125 | var array = Converter.ToDoubleArray(vector); 126 | return Accord.Math.Matrix.Normalize(array); 127 | } 128 | 129 | public static double[][] Null( 130 | PSObject vector 131 | ) 132 | { 133 | var array = Converter.ToDoubleArray(vector); 134 | return Accord.Math.Matrix.Null(array); 135 | } 136 | 137 | public static Horker.Math.Matrix Outer( 138 | PSObject a, 139 | PSObject b 140 | ) 141 | { 142 | var a1 = Converter.ToDoubleArray(a); 143 | var a2 = Converter.ToDoubleArray(b); 144 | return new Horker.Math.Matrix(Accord.Math.Matrix.Outer(a1, a2), true); 145 | } 146 | 147 | public static double Product( 148 | PSObject vector 149 | ) 150 | { 151 | var array = Converter.ToDoubleArray(vector); 152 | return Accord.Math.Matrix.Product(array); 153 | } 154 | 155 | /* 156 | public static double[][] Split( 157 | PSObject vector, 158 | int size 159 | ) 160 | { 161 | var array = Converter.ToDoubleArray(vector); 162 | return Accord.Math.Matrix.Split(array, size); 163 | } 164 | */ 165 | 166 | public static Horker.Math.Matrix Stack( 167 | PSObject a, 168 | PSObject b 169 | ) 170 | { 171 | var a1 = Converter.ToDoubleArray(a); 172 | var a2 = Converter.ToDoubleArray(b); 173 | return new Horker.Math.Matrix(Accord.Math.Matrix.Stack(a1, a2), true); 174 | } 175 | 176 | /* 177 | public static double[][] Separate( 178 | PSObject values, 179 | int[] labels, 180 | int groups 181 | ) 182 | { 183 | var array = Converter.ToDoubleArray(values); 184 | return Accord.Math.Matrix.Separate(array, labels, groups); 185 | } 186 | */ 187 | 188 | public static int[] Top( 189 | PSObject values, 190 | int count 191 | ) 192 | { 193 | var array = Converter.ToDoubleArray(values); 194 | return Accord.Math.Matrix.Top(array, count); 195 | } 196 | 197 | public static double[] Trim( 198 | PSObject values 199 | ) 200 | { 201 | var array = Converter.ToDoubleArray(values); 202 | return (double[])Accord.Math.Matrix.Trim(array); 203 | } 204 | 205 | } 206 | } -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Untyped/Measures.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using Accord.Statistics; 3 | 4 | namespace Horker.Math.ArrayMethods 5 | { 6 | public class Measures 7 | { 8 | public static double ContraHarmonicMean(PSObject values, int order = 1) 9 | { 10 | var array = Converter.ToDoubleArray(values); 11 | return Accord.Statistics.Measures.ContraHarmonicMean(array, order); 12 | } 13 | 14 | public static double Entropy(PSObject values) 15 | { 16 | var array = Converter.ToDoubleArray(values); 17 | return Accord.Statistics.Measures.Entropy(array); 18 | } 19 | 20 | public static double ExponentialWeightedMean( 21 | PSObject values, 22 | int window, 23 | double alpha = 0 24 | ) 25 | { 26 | var array = Converter.ToDoubleArray(values); 27 | return Accord.Statistics.Measures.ExponentialWeightedMean(array, window, alpha); 28 | } 29 | 30 | public static double ExponentialWeightedVariance( 31 | PSObject values, 32 | int window, 33 | double alpha = 0, 34 | bool unbiased = false 35 | ) 36 | { 37 | var array = Converter.ToDoubleArray(values); 38 | return Accord.Statistics.Measures.ExponentialWeightedVariance(array, window, alpha, unbiased); 39 | } 40 | 41 | 42 | public static double GeometricMean( 43 | PSObject values 44 | ) 45 | { 46 | var array = Converter.ToDoubleArray(values); 47 | return Accord.Statistics.Measures.GeometricMean(array); 48 | } 49 | 50 | public static double Kurtosis( 51 | PSObject values, 52 | bool unbiased = false 53 | ) 54 | { 55 | var array = Converter.ToDoubleArray(values); 56 | return Accord.Statistics.Measures.Kurtosis(array, unbiased); 57 | } 58 | 59 | public static double LogGeometricMean( 60 | PSObject values 61 | ) 62 | { 63 | var array = Converter.ToDoubleArray(values); 64 | return Accord.Statistics.Measures.LogGeometricMean(array); 65 | } 66 | 67 | public static double LowerQuartile( 68 | PSObject values, 69 | bool alreadySorted = false, 70 | QuantileMethod type = QuantileMethod.Default, 71 | bool inPlace = false 72 | ) 73 | { 74 | var array = Converter.ToDoubleArray(values); 75 | return Accord.Statistics.Measures.LowerQuartile(array, alreadySorted, type, inPlace); 76 | } 77 | 78 | public static double Mean( 79 | PSObject values 80 | ) 81 | { 82 | var array = Converter.ToDoubleArray(values); 83 | return Accord.Statistics.Measures.Mean(array); 84 | } 85 | 86 | public static double Median( 87 | PSObject values, 88 | bool alreadySorted = false, 89 | QuantileMethod type = QuantileMethod.Default, 90 | bool inPlace = false 91 | ) 92 | { 93 | var array = Converter.ToDoubleArray(values); 94 | return Accord.Statistics.Measures.Median(array, alreadySorted, type, inPlace); 95 | } 96 | 97 | public static double Mode( 98 | PSObject values, 99 | bool inPlace = false, 100 | bool alreadySorted = false 101 | ) 102 | { 103 | var array = Converter.ToDoubleArray(values); 104 | return Accord.Statistics.Measures.Mode(array, inPlace, alreadySorted); 105 | } 106 | 107 | public static double Quantile( 108 | PSObject values, 109 | double probabilities, 110 | bool alreadySorted = false, 111 | QuantileMethod type = QuantileMethod.Default, 112 | bool inPlace = false 113 | ) 114 | { 115 | var array = Converter.ToDoubleArray(values); 116 | return Accord.Statistics.Measures.Quantile(array, probabilities, alreadySorted, type, inPlace); 117 | } 118 | 119 | public static double[] Quantiles( 120 | PSObject values, 121 | double[] probabilities, 122 | bool alreadySorted = false, 123 | QuantileMethod type = QuantileMethod.Default, 124 | bool inPlace = false 125 | ) 126 | { 127 | var array = Converter.ToDoubleArray(values); 128 | return Accord.Statistics.Measures.Quantiles(array, probabilities, alreadySorted, type, inPlace); 129 | } 130 | 131 | public static double Quartiles( 132 | PSObject values, 133 | out double q1, 134 | out double q3, 135 | bool alreadySorted = false, 136 | QuantileMethod type = QuantileMethod.Default 137 | ) 138 | { 139 | var array = Converter.ToDoubleArray(values); 140 | return Accord.Statistics.Measures.Quartiles(array, out q1, out q3, alreadySorted, type, false); 141 | } 142 | 143 | public static double Skewness( 144 | PSObject values, 145 | bool unbiased = false 146 | ) 147 | { 148 | var array = Converter.ToDoubleArray(values); 149 | return Accord.Statistics.Measures.Skewness(array, unbiased); 150 | } 151 | 152 | public static double StandardDeviation( 153 | PSObject values, 154 | bool unbiased = false 155 | ) 156 | { 157 | var array = Converter.ToDoubleArray(values); 158 | return Accord.Statistics.Measures.StandardDeviation(array, unbiased); 159 | } 160 | 161 | public static double StdDev( 162 | PSObject values, 163 | bool unbiased = false 164 | ) 165 | { 166 | return StandardDeviation(values, unbiased); 167 | } 168 | 169 | public static double StandardError( 170 | PSObject values 171 | ) 172 | { 173 | var array = Converter.ToDoubleArray(values); 174 | return Accord.Statistics.Measures.StandardError(array); 175 | } 176 | 177 | public static double TruncatedMean( 178 | PSObject values, 179 | double percent, 180 | bool inPlace = false, 181 | bool alreadySorted = false 182 | ) 183 | { 184 | var array = Converter.ToDoubleArray(values); 185 | return Accord.Statistics.Measures.TruncatedMean(array, percent, inPlace, alreadySorted); 186 | } 187 | 188 | public static double UpperQuartile( 189 | PSObject values, 190 | bool alreadySorted = false, 191 | QuantileMethod type = QuantileMethod.Default, 192 | bool inPlace = false 193 | ) 194 | { 195 | var array = Converter.ToDoubleArray(values); 196 | return Accord.Statistics.Measures.UpperQuartile(array, alreadySorted, type, false); 197 | } 198 | 199 | public static double Variance( 200 | PSObject values, 201 | bool unbiased = false 202 | ) 203 | { 204 | var array = Converter.ToDoubleArray(values); 205 | return Accord.Statistics.Measures.Variance(array, unbiased); 206 | } 207 | 208 | public static double Var( 209 | PSObject values, 210 | bool unbiased = false 211 | ) 212 | { 213 | return Variance(values, unbiased); 214 | } 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Untyped/Tools.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Statistics; 6 | 7 | namespace Horker.Math.ArrayMethods 8 | { 9 | public class Tools 10 | { 11 | public static double[] Center( 12 | PSObject values 13 | ) 14 | { 15 | var array = Converter.ToDoubleArray(values); 16 | return Accord.Statistics.Tools.Center(array, null); 17 | } 18 | 19 | public static double[] Rank( 20 | PSObject samples, 21 | bool alreadySorted = false, 22 | bool adjustForTies = true 23 | ) 24 | { 25 | var array = Converter.ToDoubleArray(samples); 26 | bool hasTies; 27 | return Accord.Statistics.Tools.Rank(array, out hasTies, alreadySorted, adjustForTies); 28 | } 29 | 30 | public static double[] Standardize( 31 | PSObject values, 32 | bool inPlace = false 33 | ) 34 | { 35 | var array = Converter.ToDoubleArray(values); 36 | return Accord.Statistics.Tools.Standardize(array, inPlace); 37 | } 38 | 39 | public static int[] Ties( 40 | PSObject ranks 41 | ) 42 | { 43 | var array = Converter.ToDoubleArray(ranks); 44 | return Accord.Statistics.Tools.Ties(array); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /source/Horker.Math/ArrayMethods/Untyped/Vector.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using Accord.Math; 6 | using Accord.Math.Random; 7 | 8 | namespace Horker.Math.ArrayMethods 9 | { 10 | public class Vector 11 | { 12 | public static object[] Sample(PSObject values, int sampleSize) 13 | { 14 | var array = (values.BaseObject) as object[]; 15 | var populationSize = array.Length; 16 | 17 | var samples = Accord.Math.Vector.Sample(sampleSize, populationSize); 18 | 19 | var result = new object[sampleSize]; 20 | for (var i = 0; i < sampleSize; ++i) 21 | { 22 | result[i] = array[samples[i]]; 23 | } 24 | 25 | return result; 26 | } 27 | 28 | public static double[] Scale( 29 | PSObject values, 30 | double fromMin, 31 | double fromMax, 32 | double? toMin = null, 33 | double? toMax = null 34 | ) 35 | { 36 | var array = Converter.ToDoubleArray(values); 37 | var result = new double[array.Length]; 38 | 39 | if (toMin.HasValue && toMax.HasValue) 40 | return Accord.Math.Vector.Scale(array, fromMin, fromMax, toMin.Value, toMax.Value, result); 41 | else 42 | return Accord.Math.Vector.Scale(array, fromMin, fromMax, result); 43 | } 44 | 45 | /* 46 | public static double[] Shuffle(PSObject values) 47 | { 48 | var array = Converter.ToDoubleArray(values); 49 | return Accord.Math.Vector.Shuffled(array); 50 | } 51 | */ 52 | 53 | public static double[] Sort(PSObject values, bool stable = false, bool asc = true) 54 | { 55 | var array = Converter.ToDoubleArray(values); 56 | return Accord.Math.Vector.Sorted(array, stable, asc); 57 | } 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameColumn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using Accord.Math; 6 | 7 | namespace Horker.Math 8 | { 9 | public enum CodificationType 10 | { 11 | OneHotDropFirst, 12 | OneHot, 13 | Multilevel, 14 | Boolean 15 | } 16 | 17 | public class DataFrameColumn : DataFrameColumnBase, IEnumerable 18 | { 19 | private DataFrame _owner; 20 | private List _data; 21 | 22 | #region Properties 23 | 24 | public override Type DataType => typeof(T); 25 | 26 | public override int Count => _data.Count; 27 | 28 | public override DataFrame Owner 29 | { 30 | get { return _owner; } 31 | internal set { _owner = value; } 32 | } 33 | 34 | public T this[int index] 35 | { 36 | get => _data[index]; 37 | set => _data[index] = value; 38 | } 39 | 40 | #endregion 41 | 42 | #region Override methods 43 | 44 | internal override object[] ToObjectArray() 45 | { 46 | return this.Select(x => (object)x).ToArray(); 47 | } 48 | 49 | internal override object GetObject(int index) => _data[index]; 50 | 51 | internal override DataFrameColumnBase Subset(int index, int count) 52 | { 53 | return new DataFrameColumn(_owner, _data, index, count); 54 | } 55 | 56 | internal override void AddObject(object value) => _data.Add((T)value); 57 | 58 | internal override void SetObject(int index, object value) { _data[index] = (T)value; } 59 | 60 | internal override void AddColumn(DataFrameColumnBase column) 61 | { 62 | if (column.DataType == DataType) 63 | _data.AddRange(((DataFrameColumn)column)._data); 64 | else 65 | { 66 | var count = column.Count; 67 | for (var i = 0; i < count; ++i) 68 | _data.Add((T)column.GetObject(i)); 69 | } 70 | } 71 | 72 | internal override void AddDefaultValues(int count) 73 | { 74 | for (var i = 0; i < count; ++i) 75 | _data.Add(default(T)); 76 | } 77 | 78 | #endregion 79 | 80 | #region IEnumerable 81 | 82 | IEnumerator IEnumerable.GetEnumerator() 83 | { 84 | return _data.GetEnumerator(); 85 | } 86 | 87 | public override IEnumerator GetEnumerator() 88 | { 89 | return _data.GetEnumerator(); 90 | } 91 | 92 | #endregion 93 | 94 | #region Constructors 95 | 96 | public DataFrameColumn(DataFrame owner) 97 | { 98 | _owner = owner; 99 | _data = new List(); 100 | } 101 | 102 | public DataFrameColumn(DataFrame owner, int capacity, int fillSize) 103 | { 104 | _owner = owner; 105 | _data = new List(capacity); 106 | 107 | for (var i = 0; i < fillSize; ++i) 108 | _data.Add(default(T)); 109 | } 110 | 111 | public DataFrameColumn(DataFrame owner, IEnumerable data) 112 | { 113 | _owner = owner; 114 | _data = new List(); 115 | 116 | foreach (var d in data) 117 | _data.Add(d); 118 | } 119 | 120 | public DataFrameColumn(DataFrameColumn source) 121 | { 122 | _owner = source._owner; 123 | _data = new List(source._data); 124 | } 125 | 126 | public DataFrameColumn(DataFrame owner, IList source, int index, int count) 127 | { 128 | _owner = owner; 129 | _data = new List(count); 130 | for (var i = 0; i < count; ++i) 131 | _data.Add(source[index + i]); 132 | } 133 | 134 | #endregion 135 | 136 | #region Manipulators 137 | 138 | internal void Add(T element) 139 | { 140 | _data.Add(element); 141 | } 142 | 143 | #endregion 144 | 145 | #region Conversions 146 | 147 | internal override double[] ToDoubleArray() 148 | { 149 | var result = new double[Count]; 150 | 151 | for (var i = 0; i < Count; ++i) 152 | result[i] = Converter.ToDouble(this[i]); 153 | 154 | return result; 155 | } 156 | 157 | internal override string[] ToStringArray() 158 | { 159 | var result = new string[Count]; 160 | 161 | for (var i = 0; i < Count; ++i) 162 | result[i] = Convert.ToString(this[i]); 163 | 164 | return result; 165 | } 166 | 167 | internal void ToDoubleArray(double[] dest, int offset = 0) 168 | { 169 | if (dest.Length + offset < Count) 170 | throw new ArgumentException("Destination array doesn't have enough size"); 171 | 172 | for (var i = 0; i < Count; ++i) 173 | dest[i + offset] = Converter.ToDouble(this[i]); 174 | } 175 | 176 | public int[] ToIntArray() 177 | { 178 | var result = new int[Count]; 179 | 180 | for (var i = 0; i < Count; ++i) 181 | result[i] = Convert.ToInt32(this[i]); 182 | 183 | return result; 184 | } 185 | 186 | internal override IList ToOneHot(int total, bool dropFirst = false) 187 | { 188 | var result = new List(); 189 | 190 | for (var i = dropFirst ? 1 : 0; i < total; ++i) 191 | { 192 | var column = new DataFrameColumn(null, Count, 0); 193 | for (var j = 0; j < Count; ++j) 194 | column.Add(Converter.ToInt(this[j]) == i ? 1 : 0); 195 | 196 | result.Add(column); 197 | } 198 | 199 | return result; 200 | } 201 | 202 | public override DataFrame ToDummyValues(string baseName, CodificationType codificationType = CodificationType.OneHot) 203 | { 204 | var df = new DataFrame(); 205 | 206 | HashSet set = new HashSet(new ObjectKeyComparer()); 207 | foreach (var e in _data) 208 | { 209 | set.Add(e); 210 | } 211 | 212 | var factors = new List(); 213 | foreach (var e in set) 214 | { 215 | factors.Add(e); 216 | } 217 | factors.Sort(); 218 | 219 | var comparer = new ObjectKeyComparer(); 220 | if (codificationType == CodificationType.Multilevel) 221 | { 222 | var values = new List(Count); 223 | foreach (var e in _data) 224 | { 225 | var index = factors.FindIndex((x) => comparer.Equals(x, e)); 226 | values.Add(index); 227 | } 228 | df.AddColumn(baseName, values); 229 | } 230 | else 231 | { 232 | bool excludeFirst = codificationType == CodificationType.OneHotDropFirst; 233 | bool asBoolean = codificationType == CodificationType.Boolean; 234 | 235 | var values = new List[factors.Count - (excludeFirst ? 1 : 0)]; 236 | for (var i = 0; i < values.Length; ++i) 237 | { 238 | values[i] = new List(Count); 239 | } 240 | 241 | foreach (var e in _data) 242 | { 243 | var index = factors.FindIndex((x) => comparer.Equals(x, e)); 244 | if (excludeFirst) 245 | { 246 | --index; 247 | } 248 | for (var i = 0; i < values.Length; ++i) 249 | { 250 | if (asBoolean) 251 | { 252 | values[i].Add(i == index); 253 | } 254 | else 255 | { 256 | values[i].Add(i == index ? 1 : 0); 257 | } 258 | } 259 | } 260 | 261 | for (var i = 0; i < values.Length; ++i) 262 | { 263 | var name = baseName + factors[i + (excludeFirst ? 1 : 0)].ToString(); 264 | df.AddColumn(name, values[i]); 265 | } 266 | } 267 | 268 | return df; 269 | } 270 | 271 | #endregion 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameColumnBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace Horker.Math 6 | { 7 | public abstract class DataFrameColumnBase : IEnumerable 8 | { 9 | // Common properties 10 | 11 | public abstract Type DataType { get; } 12 | 13 | public abstract int Count { get; } 14 | 15 | public abstract DataFrame Owner { get; internal set; } 16 | 17 | // Internal object methods 18 | 19 | internal abstract object[] ToObjectArray(); 20 | internal abstract double[] ToDoubleArray(); 21 | internal abstract string[] ToStringArray(); 22 | 23 | internal abstract IList ToOneHot(int total, bool dropFirst = false); 24 | 25 | internal abstract object GetObject(int index); 26 | internal abstract DataFrameColumnBase Subset(int index, int count); 27 | 28 | internal abstract void AddObject(object value); 29 | internal abstract void SetObject(int index, object value); 30 | 31 | internal abstract void AddColumn(DataFrameColumnBase column); 32 | internal abstract void AddDefaultValues(int count); 33 | 34 | // Public methods 35 | 36 | public abstract IEnumerator GetEnumerator(); 37 | 38 | public abstract DataFrame ToDummyValues(string baseName, CodificationType codificationType = CodificationType.OneHot); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameColumnFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Horker.Math 8 | { 9 | public class DataFrameColumnFactory 10 | { 11 | public static DataFrameColumnBase Create(DataFrameType type, DataFrame owner) 12 | { 13 | switch (type) 14 | { 15 | case DataFrameType.Object: return new DataFrameColumn(owner); 16 | case DataFrameType.Decimal: return new DataFrameColumn(owner); 17 | case DataFrameType.Double: return new DataFrameColumn(owner); 18 | case DataFrameType.Single: return new DataFrameColumn(owner); 19 | case DataFrameType.Int64: return new DataFrameColumn(owner); 20 | case DataFrameType.Int32: return new DataFrameColumn(owner); 21 | case DataFrameType.Int16: return new DataFrameColumn(owner); 22 | case DataFrameType.Byte: return new DataFrameColumn(owner); 23 | case DataFrameType.SByte: return new DataFrameColumn(owner); 24 | case DataFrameType.String: return new DataFrameColumn(owner); 25 | case DataFrameType.Boolean: return new DataFrameColumn(owner); 26 | } 27 | 28 | throw new ArgumentException("Unknown DataFrameType"); 29 | } 30 | 31 | public static DataFrameColumnBase Create(DataFrameType type, DataFrame owner, int capacity, int fillSize) 32 | { 33 | switch (type) 34 | { 35 | case DataFrameType.Object: return new DataFrameColumn(owner, capacity, fillSize); 36 | case DataFrameType.Decimal: return new DataFrameColumn(owner, capacity, fillSize); 37 | case DataFrameType.Double: return new DataFrameColumn(owner, capacity, fillSize); 38 | case DataFrameType.Single: return new DataFrameColumn(owner, capacity, fillSize); 39 | case DataFrameType.Int64: return new DataFrameColumn(owner, capacity, fillSize); 40 | case DataFrameType.Int32: return new DataFrameColumn(owner, capacity, fillSize); 41 | case DataFrameType.Int16: return new DataFrameColumn(owner, capacity, fillSize); 42 | case DataFrameType.Byte: return new DataFrameColumn(owner, capacity, fillSize); 43 | case DataFrameType.SByte: return new DataFrameColumn(owner, capacity, fillSize); 44 | case DataFrameType.String: return new DataFrameColumn(owner, capacity, fillSize); 45 | case DataFrameType.Boolean: return new DataFrameColumn(owner, capacity, fillSize); 46 | } 47 | 48 | throw new ArgumentException("Unknown DataFrameType"); 49 | } 50 | 51 | public static DataFrameColumnBase Create(Type type, DataFrame owner) 52 | { 53 | return Create(DataFrameTypeHelper.GetDataFrameType(type), owner); 54 | } 55 | 56 | public static DataFrameColumnBase Create(Type type, DataFrame owner, int capacity, int fillSize) 57 | { 58 | return Create(DataFrameTypeHelper.GetDataFrameType(type), owner, capacity, fillSize); 59 | } 60 | 61 | public static DataFrameColumnBase CreateFromTypeName(string typeName, DataFrame owner) 62 | { 63 | if (typeName == "System.Object") 64 | return new DataFrameColumn(owner); 65 | if (typeName == "System.Decimal") 66 | return new DataFrameColumn(owner); 67 | if (typeName == "System.Double") 68 | return new DataFrameColumn(owner); 69 | if (typeName == "System.Single") 70 | return new DataFrameColumn(owner); 71 | if (typeName == "System.Int64") 72 | return new DataFrameColumn(owner); 73 | if (typeName == "System.Int32") 74 | return new DataFrameColumn(owner); 75 | if (typeName == "System.Int16") 76 | return new DataFrameColumn(owner); 77 | if (typeName == "System.Byte") 78 | return new DataFrameColumn(owner); 79 | if (typeName == "System.SByte") 80 | return new DataFrameColumn(owner); 81 | if (typeName == "System.String") 82 | return new DataFrameColumn(owner); 83 | if (typeName == "System.Boolean") 84 | return new DataFrameColumn(owner); 85 | 86 | return new DataFrameColumn(owner); 87 | } 88 | 89 | public static DataFrameColumnBase CreateFromTypeName(string typeName, DataFrame owner, int capacity, int fillSize) 90 | { 91 | if (typeName == "System.Object") 92 | return new DataFrameColumn(owner, capacity, fillSize); 93 | if (typeName == "System.Decimal") 94 | return new DataFrameColumn(owner, capacity, fillSize); 95 | if (typeName == "System.Double") 96 | return new DataFrameColumn(owner, capacity, fillSize); 97 | if (typeName == "System.Single") 98 | return new DataFrameColumn(owner, capacity, fillSize); 99 | if (typeName == "System.Int64") 100 | return new DataFrameColumn(owner, capacity, fillSize); 101 | if (typeName == "System.Int32") 102 | return new DataFrameColumn(owner, capacity, fillSize); 103 | if (typeName == "System.Int16") 104 | return new DataFrameColumn(owner, capacity, fillSize); 105 | if (typeName == "System.Byte") 106 | return new DataFrameColumn(owner, capacity, fillSize); 107 | if (typeName == "System.SByte") 108 | return new DataFrameColumn(owner, capacity, fillSize); 109 | if (typeName == "System.String") 110 | return new DataFrameColumn(owner, capacity, fillSize); 111 | if (typeName == "System.Boolean") 112 | return new DataFrameColumn(owner, capacity, fillSize); 113 | 114 | return new DataFrameColumn(owner, capacity, fillSize); 115 | } 116 | 117 | public static DataFrameColumnBase Clone(DataFrameColumnBase source) 118 | { 119 | switch (DataFrameTypeHelper.GetDataFrameType(source.DataType)) 120 | { 121 | case DataFrameType.Object: return new DataFrameColumn((DataFrameColumn)(source)); 122 | case DataFrameType.Decimal: return new DataFrameColumn((DataFrameColumn)(source)); 123 | case DataFrameType.Double: return new DataFrameColumn((DataFrameColumn)(source)); 124 | case DataFrameType.Single: return new DataFrameColumn((DataFrameColumn)(source)); 125 | case DataFrameType.Int64: return new DataFrameColumn((DataFrameColumn)(source)); 126 | case DataFrameType.Int32: return new DataFrameColumn((DataFrameColumn)(source)); 127 | case DataFrameType.Int16: return new DataFrameColumn((DataFrameColumn)(source)); 128 | case DataFrameType.Byte: return new DataFrameColumn((DataFrameColumn)(source)); 129 | case DataFrameType.SByte: return new DataFrameColumn((DataFrameColumn)(source)); 130 | case DataFrameType.String: return new DataFrameColumn((DataFrameColumn)(source)); 131 | case DataFrameType.Boolean: return new DataFrameColumn((DataFrameColumn)(source)); 132 | } 133 | 134 | throw new ArgumentException("Unknown DataFrameType"); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameColumnInfo.cs: -------------------------------------------------------------------------------- 1 | namespace Horker.Math 2 | { 3 | public class DataFrameColumnInfo 4 | { 5 | public string Name { get; internal set; } 6 | public DataFrameType DataType { get; internal set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameGroup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Horker.Math 9 | { 10 | public class DataFrameGroup : OrderedDictionary 11 | { 12 | public new DataFrame this[object name] { 13 | get => (DataFrame)base[name]; 14 | set => base[name] = (DataFrame)value; 15 | } 16 | 17 | public new DataFrame this[int index] { 18 | get => (DataFrame)base[index]; 19 | set => base[index] = (DataFrame)value; 20 | } 21 | 22 | public double[][] ToDoubleJaggedArrayOf(string columnName) 23 | { 24 | var result = new double[this.Count][]; 25 | 26 | for (var i = 0; i < result.Length; ++i) { 27 | result[i] = ((DataFrame)this[i])[columnName].ToDoubleArray(); 28 | } 29 | 30 | return result; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/DataFrameType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Horker.Math 4 | { 5 | public enum DataFrameType 6 | { 7 | Object, 8 | Decimal, 9 | Double, 10 | Single, 11 | Float = Single, 12 | Int64, 13 | Int32, 14 | Int = Int32, 15 | Int16, 16 | Byte, 17 | SByte, 18 | String, 19 | Boolean 20 | } 21 | 22 | public class DataFrameTypeHelper 23 | { 24 | public static DataFrameType GetDataFrameType(Type type) 25 | { 26 | if (type == typeof(Object)) return DataFrameType.Object; 27 | if (type == typeof(Decimal)) return DataFrameType.Decimal; 28 | if (type == typeof(Double)) return DataFrameType.Double; 29 | if (type == typeof(Single)) return DataFrameType.Single; 30 | if (type == typeof(Int64)) return DataFrameType.Int64; 31 | if (type == typeof(Int32)) return DataFrameType.Int32; 32 | if (type == typeof(Int16)) return DataFrameType.Int16; 33 | if (type == typeof(Byte)) return DataFrameType.Byte; 34 | if (type == typeof(SByte)) return DataFrameType.SByte; 35 | if (type == typeof(String)) return DataFrameType.String; 36 | if (type == typeof(Boolean)) return DataFrameType.Boolean; 37 | 38 | throw new ArgumentException("Unsupported type for DataFrame: " + type.FullName); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/KeyComparers.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Horker.Math 4 | { 5 | public class ObjectKeyComparer : IEqualityComparer 6 | { 7 | public static bool Compare(object o1, object o2) 8 | { 9 | if (o1 == null && o2 == null) { 10 | return true; 11 | } 12 | else if (o1 == null || o2 == null) { 13 | return false; 14 | } 15 | 16 | if (o1 is string && o2 is string) { 17 | return (o1 as string).ToLower() == (o2 as string).ToLower(); 18 | } 19 | 20 | return o1 == o2; 21 | } 22 | 23 | public new bool Equals(object o1, object o2) 24 | { 25 | return Compare(o1, o2); 26 | } 27 | 28 | public int GetHashCode(object o) 29 | { 30 | if (o is string) { 31 | return (o as string).ToLower().GetHashCode(); 32 | } 33 | return o.GetHashCode(); 34 | } 35 | } 36 | 37 | public class StringKeyComparer : IEqualityComparer 38 | { 39 | public static bool Compare(string s1, string s2) 40 | { 41 | if (s1 == null && s2 == null) { 42 | return true; 43 | } 44 | else if (s1 == null || s2 == null) { 45 | return false; 46 | } 47 | 48 | if (s1.ToLower() == s2.ToLower()) { 49 | return true; 50 | } 51 | 52 | return false; 53 | } 54 | 55 | public bool Equals(string s1, string s2) 56 | { 57 | return Compare(s1, s2); 58 | } 59 | 60 | public int GetHashCode(string s) 61 | { 62 | return s.ToLower().GetHashCode(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataFrame/NewMathDataFrame.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Diagnostics; 6 | using System.Data; 7 | 8 | namespace Horker.Math 9 | { 10 | [Cmdlet("New", "Math.DataFrame")] 11 | [Alias("math.df")] 12 | [CmdletBinding(DefaultParameterSetName = "psobjects")] 13 | [OutputType(typeof(DataFrame))] 14 | public class NewMathDataFrame : PSCmdlet 15 | { 16 | [Parameter(Position = 0, Mandatory = false, ValueFromPipeline = true, ParameterSetName = "psobjects")] 17 | public PSObject InputObject; 18 | 19 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "datatable")] 20 | public DataTable DataTable; 21 | 22 | private DataFrame _df; 23 | 24 | protected override void BeginProcessing() 25 | { 26 | if (ParameterSetName == "psobjects") 27 | _df = new DataFrame(); 28 | } 29 | 30 | protected override void ProcessRecord() 31 | { 32 | if (InputObject != null) 33 | _df.AddRow(InputObject); 34 | } 35 | 36 | protected override void EndProcessing() 37 | { 38 | if (ParameterSetName == "datatable") 39 | _df = DataFrame.FromDataTable(DataTable); 40 | 41 | var link = _df.LinkedPSObject; 42 | WriteObject(link); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataTable/DataTableExtensionMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Horker.Math 9 | { 10 | public static class DataTableExtensionMethods 11 | { 12 | public static IEnumerable GetColumn(this DataTable table, string columnName) 13 | { 14 | var column = table.Columns[columnName]; 15 | foreach (DataRow row in table.Rows) 16 | yield return row[column]; 17 | } 18 | 19 | public static void ExpandToOneHot(this DataTable table, string columnName, int total = -1, bool preserve = false, string columnNameTemplate = "{0}_{1}") 20 | { 21 | var index = table.Columns.IndexOf(columnName); 22 | var dataType = table.Columns[columnName].DataType; 23 | 24 | if (total == -1) 25 | { 26 | foreach (DataRow row in table.Rows) 27 | { 28 | var value = Convert.ToInt32(row[index]); 29 | if (total < value) 30 | total = value; 31 | } 32 | ++total; 33 | } 34 | 35 | for (var i = 0; i < total; ++i) 36 | { 37 | var column = new DataColumn(string.Format(columnNameTemplate, columnName, i)); 38 | column.DataType = dataType; 39 | column.DefaultValue = 0; 40 | table.Columns.Add(column); 41 | column.SetOrdinal(index + 1 + i); 42 | } 43 | 44 | foreach (DataRow row in table.Rows) 45 | row[index + 1 + Convert.ToInt32(row[index])] = 1; 46 | 47 | if (!preserve) 48 | table.Columns.RemoveAt(index); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/DataTable/DataTablePSMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Management.Automation; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace Horker.Math 10 | { 11 | public class DataTablePSMethods 12 | { 13 | public static IEnumerable GetColumn(PSObject value, string columnName) 14 | { 15 | var table = value.BaseObject as DataTable; 16 | return table.GetColumn(columnName); 17 | } 18 | 19 | public static object ExpandToOneHot(PSObject value, string columnName, int total = -1, bool preserve = false, string columnNameTemplate = "{0}_{1}") 20 | { 21 | var table = value.BaseObject as DataTable; 22 | table.ExpandToOneHot(columnName, total, preserve, columnNameTemplate); 23 | 24 | return null; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/Matrix/New-Math.Matrix.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Diagnostics; 6 | 7 | namespace Horker.Math 8 | { 9 | [Cmdlet("New", "Math.Matrix")] 10 | [Alias("mat")] 11 | public class NewMathMatrix : PSCmdlet 12 | { 13 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 14 | public object InputObject; 15 | 16 | [Parameter(Position = 0, Mandatory = false)] 17 | public object Values; 18 | 19 | [Parameter(Position = 1, Mandatory = false)] 20 | public int Rows = int.MaxValue; 21 | 22 | [Parameter(Position = 2, Mandatory = false)] 23 | public int Columns = int.MaxValue; 24 | 25 | [Parameter(Position = 3, Mandatory = false)] 26 | public SwitchParameter Transpose = false; 27 | 28 | [Parameter(Position = 4, Mandatory = false)] 29 | public SwitchParameter FromJagged; 30 | 31 | private List _inputObjects; 32 | 33 | protected override void BeginProcessing() 34 | { 35 | _inputObjects = new List(); 36 | } 37 | 38 | protected override void ProcessRecord() 39 | { 40 | _inputObjects.Add(InputObject); 41 | } 42 | 43 | protected override void EndProcessing() 44 | { 45 | object values; 46 | 47 | if (Values != null) 48 | { 49 | if (_inputObjects.Count > 1 || (_inputObjects.Count == 1 && _inputObjects[0] != null)) 50 | { 51 | WriteError(new ErrorRecord(new ArgumentException("Both pipeline and -Value argumetns are given"), "", ErrorCategory.InvalidArgument, null)); 52 | return; 53 | } 54 | values = Values; 55 | } 56 | else 57 | { 58 | if (_inputObjects.Count == 0 || (_inputObjects.Count == 1 && _inputObjects[0] == null)) 59 | { 60 | WriteError(new ErrorRecord(new ArgumentException("Values are required"), "", ErrorCategory.InvalidArgument, null)); 61 | return; 62 | } 63 | values = _inputObjects; 64 | } 65 | 66 | Matrix matrix = null; 67 | if (FromJagged) 68 | matrix = Matrix.Create(Converter.ToDoubleJaggedArray(values)); 69 | else 70 | matrix = Matrix.Create(Converter.ToDoubleArray(values), Rows, Columns); 71 | 72 | if (Transpose) 73 | matrix = matrix.T; 74 | 75 | WriteObject(matrix); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/Slice/Get-Math.Slice.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Management.Automation; 5 | 6 | namespace Horker.Math 7 | { 8 | [Cmdlet("Get", "Math.Slice")] 9 | [Alias("slice")] 10 | public class GetMathSlice : PSCmdlet 11 | { 12 | [Parameter(Position = 0, Mandatory = true)] 13 | public object[] Array; 14 | 15 | [Parameter(Position = 1, Mandatory = true)] 16 | public int Offset; 17 | 18 | [Parameter(Position = 2, Mandatory = true)] 19 | public int Count; 20 | 21 | protected override void EndProcessing() 22 | { 23 | WriteObject(new Slice(Array, Offset, Count)); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /source/Horker.Math/Collections/Slice/Slice.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Management.Automation; 5 | 6 | namespace Horker.Math 7 | { 8 | public class Slice : IEnumerable, IReadOnlyCollection, IReadOnlyList 9 | { 10 | private ArraySegment _segment; 11 | 12 | public Slice(T[] array, int offset, int count) 13 | { 14 | _segment = new ArraySegment(array, offset, count); 15 | } 16 | 17 | public T[] Array { get { return _segment.Array; } } 18 | public int Offset { get { return _segment.Offset; } } 19 | public int Count { get { return _segment.Count; } } 20 | 21 | public T this[int index] 22 | { 23 | get { 24 | if (index < 0 || index >= _segment.Count) { 25 | throw new ArgumentOutOfRangeException("index out of range"); 26 | } 27 | return _segment.Array[index + _segment.Offset]; 28 | } 29 | 30 | set { 31 | if (index < 0 || index >= _segment.Count) { 32 | throw new ArgumentOutOfRangeException("index out of range"); 33 | } 34 | _segment.Array[index + _segment.Offset] = value; 35 | } 36 | } 37 | 38 | public IEnumerator GetEnumerator() 39 | { 40 | return ((IEnumerable)_segment).GetEnumerator(); 41 | } 42 | 43 | IEnumerator IEnumerable.GetEnumerator() 44 | { 45 | return ((IEnumerable)_segment).GetEnumerator(); 46 | } 47 | 48 | public T[] ToArray() 49 | { 50 | var result = new T[_segment.Count]; 51 | System.Array.Copy(_segment.Array, _segment.Offset, result, 0, _segment.Count); 52 | return result; 53 | } 54 | 55 | public static implicit operator T[](Slice s) 56 | { 57 | return s.ToArray(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /source/Horker.Math/Conversions/ConversionCmdlets.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Management.Automation; 3 | 4 | namespace Horker.Math 5 | { 6 | public abstract class ConversionCmdletBase : PSCmdlet 7 | { 8 | protected static DateTime EpochInDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 9 | protected static DateTimeOffset EpochInDateTimeOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); 10 | 11 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 12 | public object InputObject; 13 | 14 | [Parameter(Position = 0, Mandatory = false)] 15 | public object[] Values; 16 | 17 | protected abstract T Convert(object value); 18 | 19 | protected override void ProcessRecord() 20 | { 21 | if (InputObject != null) 22 | WriteObject(Convert(InputObject)); 23 | } 24 | 25 | protected override void EndProcessing() 26 | { 27 | foreach (var value in Values) 28 | { 29 | WriteObject(Convert(value)); 30 | } 31 | } 32 | } 33 | 34 | [Cmdlet("ConvertTo", "Math.Double")] 35 | [Alias("math.todouble")] 36 | public class ConvertToMathDouble : ConversionCmdletBase 37 | { 38 | protected override double Convert(object value) 39 | { 40 | return Converter.ToDouble(value); 41 | } 42 | } 43 | 44 | [Cmdlet("ConvertTo", "Math.DateTime")] 45 | [Alias("math.todatetime")] 46 | public class ConvertToMathDateTime : ConversionCmdletBase 47 | { 48 | [Parameter(Position = 1, Mandatory = false)] 49 | public string Format; 50 | 51 | protected override DateTime? Convert(object value) 52 | { 53 | if (String.IsNullOrEmpty(Format)) 54 | { 55 | return Converter.ToDateTime(value); 56 | } 57 | else 58 | { 59 | return Converter.ToDateTime(value, Format); 60 | } 61 | } 62 | } 63 | 64 | [Cmdlet("ConvertTo", "Math.DateTimeOffset")] 65 | [Alias("math.todatetimeoffset")] 66 | public class ConvertToMathDateTimeOffset : ConversionCmdletBase 67 | { 68 | [Parameter(Position = 1, Mandatory = false)] 69 | public string Format; 70 | 71 | [Parameter(Position = 2, Mandatory = false)] 72 | public SwitchParameter AssumeUniversal; 73 | 74 | protected override DateTimeOffset? Convert(object value) 75 | { 76 | if (String.IsNullOrEmpty(Format)) 77 | { 78 | return Converter.ToDateTimeOffset(value, !AssumeUniversal); 79 | } 80 | else 81 | { 82 | return Converter.ToDateTimeOffset(value, Format); 83 | } 84 | } 85 | } 86 | 87 | [Cmdlet("ConvertTo", "Math.UnixTime")] 88 | [Alias("math.tounixtime")] 89 | public class ConvertToMathUnixTime : ConversionCmdletBase 90 | { 91 | [Parameter(Position = 1, Mandatory = false)] 92 | public string Format; 93 | 94 | [Parameter(Position = 2, Mandatory = false)] 95 | public SwitchParameter AssumeUniversal; 96 | 97 | private DateTimeOffset? ConvertDateTimeOffset(object value) 98 | { 99 | if (String.IsNullOrEmpty(Format)) 100 | { 101 | return Converter.ToDateTimeOffset(value, !AssumeUniversal); 102 | } 103 | else 104 | { 105 | return Converter.ToDateTimeOffset(value, Format); 106 | } 107 | } 108 | 109 | protected override double Convert(object value) 110 | { 111 | if (value is PSObject) 112 | { 113 | value = (value as PSObject).BaseObject; 114 | } 115 | 116 | if (value is DateTime) 117 | { 118 | return ((DateTime)value - EpochInDateTime).TotalSeconds; 119 | } 120 | else if (value is DateTimeOffset) 121 | { 122 | return ((DateTimeOffset)value - EpochInDateTime).TotalSeconds; 123 | } 124 | else 125 | { 126 | var date = ConvertDateTimeOffset(value); 127 | if (!date.HasValue) 128 | { 129 | return double.NaN; 130 | } 131 | return (date.Value - EpochInDateTimeOffset).TotalSeconds; 132 | } 133 | } 134 | } 135 | 136 | [Cmdlet("ConvertFrom", "Math.UnixTime")] 137 | [Alias("math.fromunixtime")] 138 | public class ConvertFromMathUnixTime : ConversionCmdletBase 139 | { 140 | [Parameter(Position = 1, Mandatory = false)] 141 | public SwitchParameter DateTime; 142 | 143 | protected override object Convert(object value) 144 | { 145 | var offset = Converter.ToDouble(value); 146 | var date = EpochInDateTimeOffset.AddSeconds(offset); 147 | 148 | if (DateTime) 149 | return date.LocalDateTime; 150 | 151 | return date; 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /source/Horker.Math/Math/DataSummary.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Accord.Math; 3 | using Accord.Statistics; 4 | 5 | namespace Horker.Math 6 | { 7 | public class DataSummary 8 | { 9 | public string Name; 10 | public int Count; 11 | // public int Unique; 12 | public double Minimum; 13 | public double LowerQuantile; 14 | public double Median; 15 | public double Mean; 16 | public double UpperQuantile; 17 | public double Maximum; 18 | 19 | public DataSummary(IList values, string name = null) 20 | { 21 | var sorted = values.Sorted(); 22 | 23 | Name = name; 24 | Count = sorted.Length; 25 | // Unique = sorted.DistinctCount(); // too time-consuming 26 | Minimum = sorted[0]; 27 | LowerQuantile = sorted.Quantile(.25, true); 28 | Median = sorted.Median(true); 29 | Mean = sorted.Mean(); 30 | UpperQuantile = sorted.Quantile(.75, true); 31 | Maximum = sorted[sorted.Length - 1]; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/AdditionalPSObjectMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Accord.Math; 8 | using Accord.Math.Random; 9 | 10 | namespace Horker.Math.PSObjects 11 | { 12 | [Cmdlet("Get", "PSObject.Sample")] 13 | [Alias("pso.sample")] 14 | public class GetPSObjectSample : ObjectListCmdletBase 15 | { 16 | [Parameter(Position = 1, Mandatory = true)] 17 | public int Size; 18 | 19 | [Parameter(Position = 2, Mandatory = false)] 20 | public SwitchParameter Replacement; 21 | 22 | protected override void Process(IReadOnlyList values) 23 | { 24 | if (Replacement) 25 | { 26 | for (var i = 0; i < Size; ++i) 27 | { 28 | var j = Generator.Random.Next(values.Count); 29 | WriteObject(values[j]); 30 | } 31 | } 32 | else 33 | { 34 | var samples = Vector.Sample(Size, values.Count); 35 | for (var i = 0; i < Size; ++i) 36 | WriteObject(values[samples[i]]); 37 | } 38 | } 39 | } 40 | 41 | [Cmdlet("Get", "PSObject.Shuffle")] 42 | [Alias("pso.shuffle")] 43 | public class GetPSObjectShuffle : ObjectListCmdletBase 44 | { 45 | protected override void Process(IReadOnlyList values) 46 | { 47 | var results = ArrayMethods.Typed.Additional.ShuffleInternal(values); 48 | 49 | foreach (var r in results) 50 | WriteObject(r); 51 | } 52 | } 53 | 54 | [Cmdlet("Get", "PSObject.Split")] 55 | [Alias("pso.split")] 56 | public class NewPSObjectSplit : ObjectListCmdletBase 57 | { 58 | [Parameter(Position = 1, Mandatory = true)] 59 | public object[] Rates; 60 | 61 | protected override void Process(IReadOnlyList values) 62 | { 63 | var results = ArrayMethods.Typed.Additional.SplitInternal(values, Rates); 64 | 65 | foreach (var r in results) 66 | WriteObject(r); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/ConvertFrom-PSObject.BinaryFormat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Runtime.Serialization.Formatters.Binary; 6 | 7 | namespace Horker.Math.PSObjects 8 | { 9 | [Cmdlet("ConvertFrom", "PSObject.BinaryFormat")] 10 | [Alias("pso.frombinary")] 11 | public class ConvertFromPSObjectBinaryFormat : PSCmdlet 12 | { 13 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 14 | public byte InputObject; 15 | 16 | [Parameter(Position = 0, Mandatory = true)] 17 | public string Path; 18 | 19 | [Parameter(Position = 1, Mandatory = false)] 20 | public byte[] Data; 21 | 22 | private List _inputObjects; 23 | 24 | protected override void BeginProcessing() 25 | { 26 | _inputObjects = new List(); 27 | } 28 | 29 | protected override void ProcessRecord() 30 | { 31 | _inputObjects.Add(InputObject); 32 | } 33 | 34 | protected override void EndProcessing() 35 | { 36 | byte[] data; 37 | 38 | if (_inputObjects.Count == 0) 39 | { 40 | if (Data == null) 41 | { 42 | WriteError(new ErrorRecord(new ArgumentException("No input specified"), "", ErrorCategory.InvalidArgument, null)); 43 | return; 44 | } 45 | data = Data; 46 | } 47 | else 48 | { 49 | if (Data != null) 50 | { 51 | WriteError(new ErrorRecord(new ArgumentException("Both pipeline and -Data arguments specified"), "", ErrorCategory.InvalidArgument, null)); 52 | return; 53 | } 54 | data = _inputObjects.ToArray(); 55 | } 56 | 57 | if (!System.IO.Path.IsPathRooted(Path)) 58 | { 59 | var current = SessionState.Path.CurrentFileSystemLocation; 60 | Path = SessionState.Path.Combine(current.ToString(), Path); 61 | } 62 | 63 | using (var stream = new MemoryStream(data)) 64 | { 65 | WriteObject((new BinaryFormatter()).Deserialize(stream)); 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/ConvertTo-PSObject.BinaryFormat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Runtime.Serialization.Formatters.Binary; 6 | 7 | namespace Horker.Math.PSObjects 8 | { 9 | [Cmdlet("ConvertTo", "PSObject.BinaryFormat")] 10 | [Alias("pso.tobinary")] 11 | public class ConvertToPSObjectBinaryFormat : PSCmdlet 12 | { 13 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 14 | public object InputObject; 15 | 16 | [Parameter(Position = 0, Mandatory = true)] 17 | public string Path; 18 | 19 | [Parameter(Position = 1, Mandatory = false)] 20 | public object Data; 21 | 22 | private List _inputObjects; 23 | 24 | protected override void BeginProcessing() 25 | { 26 | _inputObjects = new List(); 27 | } 28 | 29 | protected override void ProcessRecord() 30 | { 31 | _inputObjects.Add(InputObject); 32 | } 33 | 34 | protected override void EndProcessing() 35 | { 36 | object data; 37 | 38 | if (_inputObjects.Count == 0 || (_inputObjects.Count == 1 && _inputObjects[0] == null)) 39 | { 40 | if (Data == null) 41 | { 42 | WriteError(new ErrorRecord(new ArgumentException("No input specified"), "", ErrorCategory.InvalidArgument, null)); 43 | return; 44 | } 45 | data = Data; 46 | } 47 | else 48 | { 49 | if (Data != null) 50 | { 51 | WriteError(new ErrorRecord(new ArgumentException("Both pipeline and -Data arguments specified"), "", ErrorCategory.InvalidArgument, null)); 52 | return; 53 | } 54 | data = _inputObjects.ToArray(); 55 | } 56 | 57 | if (!System.IO.Path.IsPathRooted(Path)) 58 | { 59 | var current = SessionState.Path.CurrentFileSystemLocation; 60 | Path = SessionState.Path.Combine(current.ToString(), Path); 61 | } 62 | 63 | using (var stream = new MemoryStream()) 64 | { 65 | (new BinaryFormatter()).Serialize(stream, data); 66 | 67 | WriteObject(stream.ToArray()); 68 | } 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/Export-PSObject.BinaryFormat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Runtime.Serialization.Formatters.Binary; 6 | 7 | namespace Horker.Math.PSObjects 8 | { 9 | [Cmdlet("Export", "PSObject.BinaryFormat")] 10 | [Alias("pso.exportbinary")] 11 | public class ExportPSObjectBinaryFormat : PSCmdlet 12 | { 13 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 14 | public object InputObject; 15 | 16 | [Parameter(Position = 0, Mandatory = true)] 17 | public string Path; 18 | 19 | [Parameter(Position = 1, Mandatory = false)] 20 | public object Data; 21 | 22 | private List _inputObjects; 23 | 24 | protected override void BeginProcessing() 25 | { 26 | _inputObjects = new List(); 27 | } 28 | 29 | protected override void ProcessRecord() 30 | { 31 | _inputObjects.Add(InputObject); 32 | } 33 | 34 | protected override void EndProcessing() 35 | { 36 | object data; 37 | 38 | if (_inputObjects.Count == 0 || (_inputObjects.Count == 1 && _inputObjects[0] == null)) 39 | { 40 | if (Data == null) 41 | { 42 | WriteError(new ErrorRecord(new ArgumentException("No input specified"), "", ErrorCategory.InvalidArgument, null)); 43 | return; 44 | } 45 | data = Data; 46 | } 47 | else 48 | { 49 | if (Data != null) 50 | { 51 | WriteError(new ErrorRecord(new ArgumentException("Both pipeline and -Data arguments specified"), "", ErrorCategory.InvalidArgument, null)); 52 | return; 53 | } 54 | data = _inputObjects.ToArray(); 55 | } 56 | 57 | if (!System.IO.Path.IsPathRooted(Path)) 58 | { 59 | var current = SessionState.Path.CurrentFileSystemLocation; 60 | Path = SessionState.Path.Combine(current.ToString(), Path); 61 | } 62 | 63 | using (var stream = new FileStream(Path, FileMode.Create, FileAccess.Write, FileShare.None)) 64 | { 65 | (new BinaryFormatter()).Serialize(stream, data); 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/Get-PSObject.Summary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | 6 | namespace Horker.Math.PSObjects 7 | { 8 | [Cmdlet("Get", "PSObject.Summary")] 9 | [Alias("pso.summary")] 10 | public class GetPSObjectSummary : ObjectListCmdletBase 11 | { 12 | protected override void Process(IReadOnlyList data) 13 | { 14 | var propNames = new List(); 15 | var elements = new Dictionary>(); 16 | 17 | foreach (var row in data) 18 | { 19 | foreach (var prop in row.Properties) 20 | { 21 | if (!elements.ContainsKey(prop.Name)) 22 | { 23 | propNames.Add(prop.Name); 24 | elements.Add(prop.Name, new List()); 25 | } 26 | 27 | elements[prop.Name].Add(prop.Value); 28 | } 29 | } 30 | 31 | foreach (var name in propNames) 32 | { 33 | var result = new DataSummary(elements[name].Select(x => Converter.ToDouble(x)).ToArray(), name); 34 | WriteObject(result); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/Get-PSObject.TypeInformation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | 6 | namespace Horker.Math.PSObjects 7 | { 8 | public class Information 9 | { 10 | public string Name; 11 | public int Total; 12 | public int Unique; 13 | public int String; 14 | public int Numeric; 15 | public int DateTime; 16 | public int Boolean; 17 | public int Other; 18 | public int Null; 19 | } 20 | 21 | [Cmdlet("Get", "PSObject.TypeInformation")] 22 | [Alias("pso.typeinfo")] 23 | public class GetPSObjectTypeInformation : ObjectListCmdletBase 24 | { 25 | [Parameter(Position = 1, Mandatory = false)] 26 | public SwitchParameter NoTypeInference; 27 | 28 | protected override void Process(IReadOnlyList data) 29 | { 30 | var propNames = new List(); 31 | var summaries = new Dictionary(); 32 | var elements = new Dictionary>(); 33 | 34 | foreach (var row in data) 35 | { 36 | foreach (var prop in row.Properties) 37 | { 38 | if (!summaries.ContainsKey(prop.Name)) 39 | { 40 | propNames.Add(prop.Name); 41 | var s = new Information(); 42 | s.Name = prop.Name; 43 | summaries.Add(prop.Name, s); 44 | elements.Add(prop.Name, new List()); 45 | } 46 | 47 | var value = prop.Value; 48 | elements[prop.Name].Add(value); 49 | 50 | var summary = summaries[prop.Name]; 51 | 52 | ++summary.Total; 53 | 54 | if (value is null) 55 | { 56 | ++summary.Null; 57 | } 58 | else if (value is Boolean) 59 | { 60 | ++summary.Boolean; 61 | } 62 | else if (value is Double || value is Single) 63 | { 64 | ++summary.Numeric; 65 | if (double.IsNaN((Double)value)) 66 | ++summary.Null; 67 | } 68 | else if (value is Int64 || value is Int32 || value is Byte || value is SByte) 69 | { 70 | ++summary.Numeric; 71 | } 72 | else if (value is DateTime || value is DateTimeOffset) 73 | { 74 | ++summary.DateTime; 75 | } 76 | else if (value is String) 77 | { 78 | var s = value as string; 79 | if (string.IsNullOrWhiteSpace(s)) 80 | { 81 | ++summary.String; 82 | ++summary.Null; 83 | } 84 | else 85 | { 86 | if (NoTypeInference) 87 | ++summary.String; 88 | else 89 | { 90 | bool numeric = false; 91 | bool boolean = false; 92 | bool dateTime = false; 93 | 94 | s = s.Trim().ToLower(); 95 | 96 | if (s == "true" || s == "t" || s == "false" || s == "f") 97 | boolean = true; 98 | else 99 | { 100 | if (s != "nan") 101 | { 102 | var converted = Converter.ToDouble(value); 103 | if (!double.IsNaN(converted)) 104 | numeric = true; 105 | } 106 | 107 | if (!numeric) 108 | { 109 | var converted = Converter.ToDateTimeOffset(value); 110 | if (converted.HasValue) 111 | dateTime = true; 112 | } 113 | } 114 | 115 | if (numeric) 116 | ++summary.Numeric; 117 | else if (boolean) 118 | ++summary.Boolean; 119 | else if (dateTime) 120 | ++summary.DateTime; 121 | else 122 | ++summary.String; 123 | } 124 | } 125 | } 126 | } 127 | } 128 | 129 | foreach (var name in propNames) 130 | { 131 | var summary = summaries[name]; 132 | 133 | summary.Unique = elements[name].Distinct().Count(); 134 | summary.Other = summary.Total - (summary.String + summary.Numeric + summary.DateTime + summary.Boolean); 135 | 136 | WriteObject(summary); 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/Import-PSObject.BinaryFormat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Management.Automation; 5 | using System.Runtime.Serialization.Formatters.Binary; 6 | 7 | namespace Horker.Math.PSObjects 8 | { 9 | [Cmdlet("Import", "PSObject.BinaryFormat")] 10 | [Alias("pso.importbinary")] 11 | public class ImportPSObjectBinaryFormat : PSCmdlet 12 | { 13 | [Parameter(Position = 0, Mandatory = true)] 14 | public string Path; 15 | 16 | protected override void EndProcessing() 17 | { 18 | if (!System.IO.Path.IsPathRooted(Path)) 19 | { 20 | var current = SessionState.Path.CurrentFileSystemLocation; 21 | Path = SessionState.Path.Combine(current.ToString(), Path); 22 | } 23 | 24 | using (var stream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read)) 25 | { 26 | WriteObject((new BinaryFormatter()).Deserialize(stream)); 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/New-PSObject.OneHot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | 8 | namespace Horker.Math.PSObjects 9 | { 10 | [Cmdlet("New", "PSObject.OneHot")] 11 | [Alias("pso.onehot")] 12 | public class NewPSObjectOneHot : ObjectListCmdletBase 13 | { 14 | [Parameter(Position = 1, Mandatory = false)] 15 | public string[] Categories; 16 | 17 | protected override void Process(IReadOnlyList data) 18 | { 19 | string[] categories = Categories; 20 | 21 | if (Categories == null || Categories.Length == 0) 22 | { 23 | categories = data.Distinct().Select(x => x.ToString()).ToArray(); 24 | Array.Sort(categories); 25 | } 26 | 27 | foreach (var d in data) 28 | { 29 | var obj = new PSObject(); 30 | 31 | foreach (var c in categories) 32 | { 33 | if (c == d.ToString()) 34 | obj.Properties.Add(new PSNoteProperty(c, 1)); 35 | else 36 | obj.Properties.Add(new PSNoteProperty(c, 0)); 37 | } 38 | 39 | WriteObject(obj); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/New-PSObject.TruthTable.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using Accord.Math; 3 | 4 | namespace Horker.Math.PSObjects 5 | { 6 | [Cmdlet("Get", "PSObject.TruthTable")] 7 | [Alias("pso.truthtable")] 8 | public class GetPSObjectTruthTable : PSCmdlet 9 | { 10 | [Parameter(Position = 0, Mandatory = true)] 11 | public int[] Symbols; 12 | 13 | [Parameter(Mandatory = false)] 14 | public SwitchParameter Transpose = false; 15 | 16 | protected override void EndProcessing() 17 | { 18 | var df = new DataFrame(); 19 | 20 | if (Transpose) { 21 | bool first = true; 22 | foreach (int[] seq in Combinatorics.Sequences(Symbols, true)) { 23 | if (first) { 24 | for (var column = 0; column < seq.Length; ++column) { 25 | df.AddColumn("c" + column); 26 | } 27 | first = false; 28 | } 29 | 30 | for (var column = 0; column < seq.Length; ++column) { 31 | df.GetColumn(column).SetObject(column, seq[column]); 32 | } 33 | } 34 | } 35 | else { 36 | int column = 0; 37 | foreach (int[] seq in Combinatorics.Sequences(Symbols, true)) { 38 | df.DefineNewColumn("c" + column, new DataFrameColumn(df, seq)); 39 | ++column; 40 | } 41 | } 42 | 43 | WriteObject(df); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /source/Horker.Math/PSObject/ObjectListCmdletBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Management.Automation; 4 | 5 | namespace Horker.Math 6 | { 7 | public abstract class ObjectListCmdletBase : PSCmdlet 8 | { 9 | [Parameter(ValueFromPipeline = true, Mandatory = false)] 10 | public T InputObject; 11 | 12 | [Parameter(Position = 0, Mandatory = false)] 13 | public T[] Data; 14 | 15 | private List _inputObjects; 16 | 17 | protected abstract void Process(IReadOnlyList data); 18 | 19 | protected override void BeginProcessing() 20 | { 21 | _inputObjects = new List(); 22 | } 23 | 24 | protected override void ProcessRecord() 25 | { 26 | _inputObjects.Add(InputObject); 27 | } 28 | 29 | protected override void EndProcessing() 30 | { 31 | IReadOnlyList data; 32 | 33 | if (_inputObjects.Count == 0 || (_inputObjects.Count == 1 && _inputObjects[0] == null)) 34 | { 35 | if (Data == null || Data.Length == 0) 36 | { 37 | WriteError(new ErrorRecord(new ArgumentException("No input specified"), "", ErrorCategory.InvalidArgument, null)); 38 | return; 39 | } 40 | data = Data; 41 | } 42 | else 43 | { 44 | if (Data != null && Data.Length > 0) 45 | { 46 | WriteError(new ErrorRecord(new ArgumentException("Both pipeline and -Data arguments specified"), "", ErrorCategory.InvalidArgument, null)); 47 | return; 48 | } 49 | data = _inputObjects; 50 | } 51 | 52 | Process(data); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /source/Horker.Math/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("Horker.Math")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("Horker.Math")] 10 | [assembly: AssemblyCopyright("Copyright (c) horker")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("f4c2900e-adfe-4612-a40c-19393fc2ceff")] 17 | 18 | [assembly: AssemblyVersion("1.0.0.0")] 19 | [assembly: AssemblyFileVersion("1.0.0.0")] 20 | 21 | [assembly: InternalsVisibleTo("Tests")] 22 | -------------------------------------------------------------------------------- /source/Horker.Math/Sequence/SequenceCmdlets.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Horker.Math 9 | { 10 | class SequenceHelper 11 | { 12 | public static IEnumerable GetRange(double a, double b, double step, bool inclusive) 13 | { 14 | if (System.Math.Sign(b - a) != System.Math.Sign(step)) 15 | throw new ArgumentException("Invalid range definition"); 16 | 17 | if (b >= a) 18 | { 19 | if (inclusive) 20 | for (var i = 0; a + step * i <= b; ++i) 21 | yield return a + step * i; 22 | else 23 | for (var i = 0; a + step * i < b; ++i) 24 | yield return a + step * i; 25 | } 26 | else 27 | { 28 | if (inclusive) 29 | for (var i = 0; a + step * i >= b; ++i) 30 | yield return a + step * i; 31 | else 32 | for (var i = 0; a + step * i > b; ++i) 33 | yield return a + step * i; 34 | } 35 | } 36 | 37 | public static IEnumerable GetInterval(double a, double b, int count, bool inclusive) 38 | { 39 | if (a >= b || count <= 0) 40 | throw new ArgumentException("Invalid range definition"); 41 | 42 | var result = new double[count]; 43 | 44 | double step; 45 | 46 | if (inclusive) 47 | step = (b - a) / (count - 1); 48 | else 49 | step = (b - a) / count; 50 | 51 | for (var i = 0; i < count; ++i) 52 | yield return a + step * i; 53 | } 54 | } 55 | 56 | public abstract class SequenceCmdletBase : PSCmdlet 57 | { 58 | [Parameter(Position = 10, Mandatory = false)] 59 | public ScriptBlock[] Func = null; 60 | 61 | [Parameter(Position = 11, Mandatory = false)] 62 | public SwitchParameter NoSeq; 63 | 64 | [Parameter(Position = 12, Mandatory = false)] 65 | public SwitchParameter AsMatrix; 66 | 67 | protected abstract IEnumerable GetSequence(); 68 | 69 | protected override void EndProcessing() 70 | { 71 | IEnumerable seq = GetSequence(); 72 | 73 | if (!AsMatrix) 74 | { 75 | if (Func == null) 76 | { 77 | foreach (var x in seq) 78 | { 79 | WriteObject(x); 80 | } 81 | } 82 | else if (Func.Length == 1 && NoSeq) 83 | { 84 | var va = new List() { new PSVariable("x") }; 85 | 86 | foreach (var x in seq) 87 | { 88 | va[0].Value = x; 89 | var y = Func[0].InvokeWithContext(null, va, new object[] { x }).Last(); 90 | WriteObject(y); 91 | } 92 | } 93 | else 94 | { 95 | var va = new List() { new PSVariable("x") }; 96 | 97 | foreach (var x in seq) 98 | { 99 | var obj = new PSObject(); 100 | 101 | if (!NoSeq) 102 | obj.Properties.Add(new PSNoteProperty("x", x)); 103 | 104 | for (int i = 0; i < Func.Length; ++i) 105 | { 106 | va[0].Value = x; 107 | var y = Func[i].InvokeWithContext(null, va, new object[] { x }).Last(); 108 | 109 | obj.Properties.Add(new PSNoteProperty("y" + i, y)); 110 | } 111 | 112 | WriteObject(obj); 113 | } 114 | } 115 | } 116 | else 117 | { 118 | if (Func == null) 119 | { 120 | WriteObject(Matrix.Create(seq.ToArray(), int.MaxValue)); 121 | } 122 | else 123 | { 124 | var s = NoSeq ? 0 : 1; 125 | 126 | var seqarray = seq.ToArray(); 127 | var result = new double[seqarray.Length, Func.Length + s]; 128 | 129 | var va = new List() { new PSVariable("x") }; 130 | 131 | for (var i = 0; i < seqarray.Length; ++i) 132 | { 133 | var x = seqarray[i]; 134 | 135 | if (!NoSeq) 136 | result[i, 0] = x; 137 | 138 | for (int j = 0; j < Func.Length; ++j) 139 | { 140 | va[0].Value = x; 141 | var y = Func[j].InvokeWithContext(null, va, new object[] { x }).Last(); 142 | result[i, j + s] = (double)y.BaseObject; 143 | } 144 | } 145 | 146 | WriteObject(new Matrix(result, true)); 147 | } 148 | } 149 | } 150 | } 151 | 152 | [Cmdlet("New", "Math.Sequence")] 153 | [Alias("seq")] 154 | public class NewMathSequence : SequenceCmdletBase 155 | { 156 | [Parameter(Position = 0, Mandatory = true)] 157 | public double Start = 0; 158 | 159 | [Parameter(Position = 1, Mandatory = false)] 160 | public double? Stop = null; 161 | 162 | [Parameter(Position = 2, Mandatory = false)] 163 | public double Step = 1.0; 164 | 165 | [Parameter(Position = 4, Mandatory = false)] 166 | public SwitchParameter Inclusive = false; 167 | 168 | protected override IEnumerable GetSequence() 169 | { 170 | double start, stop; 171 | 172 | if (!Stop.HasValue) 173 | { 174 | start = 0; 175 | stop = Start; 176 | } 177 | else 178 | { 179 | start = Start; 180 | stop = Stop.Value; 181 | } 182 | 183 | return SequenceHelper.GetRange(start, stop, Step, Inclusive); 184 | } 185 | } 186 | 187 | [Cmdlet("New", "Math.SequenceInLinearSpace")] 188 | [Alias("seq.linspace")] 189 | public class NewMathSequenceInLinearSpace : SequenceCmdletBase 190 | { 191 | [Parameter(Position = 0, Mandatory = true)] 192 | public double Start = 0; 193 | 194 | [Parameter(Position = 1, Mandatory = false)] 195 | public double? Stop = null; 196 | 197 | [Parameter(Position = 2, Mandatory = false)] 198 | public int Count = 100; 199 | 200 | [Parameter(Position = 3, Mandatory = false)] 201 | public SwitchParameter Inclusive = false; 202 | 203 | protected override IEnumerable GetSequence() 204 | { 205 | double start, stop; 206 | 207 | if (!Stop.HasValue) 208 | { 209 | start = 0; 210 | stop = Start; 211 | } 212 | else 213 | { 214 | start = Start; 215 | stop = Stop.Value; 216 | } 217 | 218 | return SequenceHelper.GetInterval(start, stop, Count, Inclusive); 219 | } 220 | } 221 | 222 | [Cmdlet("New", "Math.SequenceWithValues")] 223 | [Alias("seq.values")] 224 | public class NewMathSequenceWithValues : SequenceCmdletBase 225 | { 226 | [Parameter(Position = 0, Mandatory = true)] 227 | public object Values = 0; 228 | 229 | [Parameter(Position = 1, Mandatory = false)] 230 | public int Count = int.MaxValue; 231 | 232 | protected override IEnumerable GetSequence() 233 | { 234 | var values = Converter.ToDoubleArray(Values); 235 | 236 | if (Count == int.MaxValue) 237 | { 238 | Count = values.Length; 239 | } 240 | 241 | for (var i = 0; i < Count; ++i) 242 | { 243 | yield return values[i % values.Length]; 244 | } 245 | } 246 | } 247 | 248 | [Cmdlet("New", "Math.ZeroSequence")] 249 | [Alias("seq.zeros")] 250 | public class NewMathZeroSequence : SequenceCmdletBase 251 | { 252 | [Parameter(Position = 0, Mandatory = true)] 253 | public int Count; 254 | 255 | protected override IEnumerable GetSequence() 256 | { 257 | for (var i = 0; i < Count; ++i) 258 | { 259 | yield return 0; 260 | } 261 | } 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Analyses/InvokeDescriptiveAnalysis.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Data; 4 | using System.Collections.Generic; 5 | using System.Management.Automation; 6 | using Accord.Statistics.Analysis; 7 | using Accord.Statistics.Filters; 8 | using Accord.Math; 9 | 10 | namespace Horker.Math 11 | { 12 | [Cmdlet("Invoke", "DescriptiveAnalysis")] 13 | public class InvokeDescriptiveAnalysis : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 16 | public PSObject InputObject; 17 | 18 | private DataFrame _data; 19 | 20 | protected override void BeginProcessing() 21 | { 22 | _data = new DataFrame(); 23 | } 24 | 25 | protected override void ProcessRecord() 26 | { 27 | _data.AddRow(InputObject); 28 | } 29 | 30 | protected override void EndProcessing() 31 | { 32 | var d = new DescriptiveAnalysis(_data.ColumnNames.ToArray()); 33 | 34 | d.Learn(_data.ToDoubleJaggedArray()); 35 | 36 | // TODO: Convert output to prettyprint or define format data 37 | 38 | WriteObject(d); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/KalmanFilter2D.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Management.Automation; 4 | 5 | namespace Horker.Math 6 | { 7 | public class KalmanFilter2DResult 8 | { 9 | public double X; 10 | public double Y; 11 | public double XAxisVelocity; 12 | public double YAxisVelocity; 13 | public double NoiseX; 14 | public double NoiseY; 15 | } 16 | 17 | [Cmdlet("Get", "Math.KalmanFilter2D")] 18 | [Alias("math.kalman")] 19 | public class KalmanFilter2D : PSCmdlet 20 | { 21 | [Parameter(Position = 0, Mandatory = true)] 22 | public object[] X; 23 | 24 | [Parameter(Position = 1, Mandatory = true)] 25 | public object[] Y; 26 | 27 | [Parameter(Position = 2, Mandatory = false)] 28 | public double SamplingRate = 1.0; 29 | 30 | [Parameter(Position = 3, Mandatory = false)] 31 | public double Acceleration = 0.0005; 32 | 33 | [Parameter(Position = 4, Mandatory = false)] 34 | public double AccelerationStdDev = 0.1; 35 | 36 | protected override void EndProcessing() 37 | { 38 | var xSeries = X.Select(x => Converter.ToDouble(x)).ToArray(); 39 | var ySeries = Y.Select(x => Converter.ToDouble(x)).ToArray(); 40 | 41 | if (xSeries.Length != ySeries.Length) 42 | { 43 | WriteError(new ErrorRecord(new ArgumentException("X and Y should have the same length"), "", ErrorCategory.InvalidArgument, null)); 44 | return; 45 | } 46 | 47 | var filter = new Accord.Statistics.Running.KalmanFilter2D(SamplingRate, Acceleration, AccelerationStdDev); 48 | 49 | for (var i = 0; i < xSeries.Length; ++i) 50 | { 51 | filter.Push(xSeries[i], ySeries[i]); 52 | 53 | var result = new KalmanFilter2DResult(); 54 | result.X = filter.X; 55 | result.Y = filter.Y; 56 | result.XAxisVelocity = filter.XAxisVelocity; 57 | result.YAxisVelocity = filter.YAxisVelocity; 58 | result.NoiseX = filter.NoiseX; 59 | result.NoiseY = filter.NoiseY; 60 | 61 | WriteObject(result); 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Regressions/InvokeGeneralizedLinearRegression.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Data; 4 | using System.Collections.Generic; 5 | using System.Management.Automation; 6 | using Accord.Statistics.Analysis; 7 | using Accord.Statistics.Filters; 8 | using Accord.Statistics.Models.Regression; 9 | using Accord.Statistics.Models.Regression.Fitting; 10 | using Accord.Statistics.Links; 11 | using Accord.Math; 12 | 13 | namespace Horker.Math 14 | { 15 | public enum LinkFunctionType 16 | { 17 | Absolute, 18 | Cauchit, 19 | Identity, 20 | Inverse, 21 | InverseSquared, 22 | Logit, 23 | Log, 24 | LogLog, 25 | Probit, 26 | Sin, 27 | Threshold 28 | } 29 | 30 | public class LinkFunctionConvert 31 | { 32 | public static ILinkFunction Get(LinkFunctionType link) 33 | { 34 | ILinkFunction result = null; 35 | switch (link) { 36 | case LinkFunctionType.Absolute: result = new AbsoluteLinkFunction(); break; 37 | case LinkFunctionType.Cauchit: result = new CauchitLinkFunction(); break; 38 | case LinkFunctionType.Identity: result = new IdentityLinkFunction(); break; 39 | case LinkFunctionType.Inverse: result = new InverseLinkFunction(); break; 40 | case LinkFunctionType.InverseSquared: result = new InverseSquaredLinkFunction(); break; 41 | case LinkFunctionType.Logit: result = new LogitLinkFunction(); break; 42 | case LinkFunctionType.Log: result = new LogLinkFunction(); break; 43 | case LinkFunctionType.LogLog: result = new LogLogLinkFunction(); break; 44 | case LinkFunctionType.Probit: result = new ProbitLinkFunction(); break; 45 | case LinkFunctionType.Sin: result = new SinLinkFunction(); break; 46 | case LinkFunctionType.Threshold: result = new ThresholdLinkFunction(); break; 47 | } 48 | 49 | return result; 50 | } 51 | } 52 | 53 | [Cmdlet("Invoke", "GeneralizedLinearRegression")] 54 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 55 | public class InvokeGeneralizedLinearRegression : PSCmdlet 56 | { 57 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "XY")] 58 | public object X; 59 | 60 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "XY")] 61 | public object Y; 62 | 63 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 64 | public PSObject InputObject; 65 | 66 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 67 | public string OutputName; 68 | 69 | [Parameter(Mandatory = true)] 70 | public LinkFunctionType LinkFunction; 71 | 72 | [Parameter(Mandatory = false)] 73 | public object Weights; 74 | 75 | private DataFrame _data; 76 | 77 | protected override void BeginProcessing() 78 | { 79 | _data = new DataFrame(); 80 | } 81 | 82 | protected override void ProcessRecord() 83 | { 84 | if (ParameterSetName != "Pipeline") { 85 | return; 86 | } 87 | 88 | _data.AddRow(InputObject); 89 | } 90 | 91 | protected override void EndProcessing() 92 | { 93 | double[][] inputs; 94 | double[] outputs; 95 | 96 | if (ParameterSetName == "XY") { 97 | inputs = Converter.ToDoubleJaggedArray(X); 98 | outputs = Converter.ToDoubleArray(Y); 99 | } 100 | else { 101 | outputs = _data.GetColumn(OutputName).ToDoubleArray(); 102 | 103 | _data.RemoveColumn(OutputName); 104 | inputs = _data.ToDoubleJaggedArray(); 105 | } 106 | 107 | double[] w = null; 108 | if (Weights != null) { 109 | w = Converter.ToDoubleArray(Weights); 110 | } 111 | 112 | var model = new GeneralizedLinearRegression(LinkFunctionConvert.Get(LinkFunction)) { 113 | NumberOfInputs = inputs[0].Length 114 | }; 115 | 116 | var learner = new IterativeReweightedLeastSquares(model) { 117 | MaxIterations = 200, 118 | Regularization = 0 119 | }; 120 | 121 | learner.Learn(inputs, outputs, w); 122 | 123 | WriteObject(model); 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Regressions/InvokeLinearRegression.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Data; 4 | using System.Collections.Generic; 5 | using System.Management.Automation; 6 | using Accord.Statistics.Analysis; 7 | using Accord.Statistics.Filters; 8 | using Accord.Statistics.Models.Regression; 9 | using Accord.Statistics.Models.Regression.Fitting; 10 | using Accord.Math; 11 | 12 | namespace Horker.Math 13 | { 14 | [Cmdlet("Invoke", "LinearRegression")] 15 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 16 | public class InvokeLinearRegression : PSCmdlet 17 | { 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "XY")] 19 | public object X; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "XY")] 22 | public object Y; 23 | 24 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 25 | public PSObject InputObject; 26 | 27 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 28 | public string OutputName; 29 | 30 | [Parameter(Mandatory = false)] 31 | public object Weights; 32 | 33 | private DataFrame _data; 34 | 35 | protected override void BeginProcessing() 36 | { 37 | _data = new DataFrame(); 38 | } 39 | 40 | protected override void ProcessRecord() 41 | { 42 | if (ParameterSetName != "Pipeline") { 43 | return; 44 | } 45 | 46 | _data.AddRow(InputObject); 47 | } 48 | 49 | protected override void EndProcessing() 50 | { 51 | var model = new MultipleLinearRegressionAnalysis(); 52 | 53 | double[][] inputs; 54 | double[] outputs; 55 | 56 | if (ParameterSetName == "XY") { 57 | inputs = Converter.ToDoubleJaggedArray(X); 58 | outputs = Converter.ToDoubleArray(Y); 59 | } 60 | else { 61 | outputs = _data.GetColumn(OutputName).ToDoubleArray(); 62 | 63 | _data.RemoveColumn(OutputName); 64 | inputs = _data.ToDoubleJaggedArray(); 65 | 66 | model.Inputs = _data.ColumnNames.ToArray(); 67 | model.Output = OutputName; 68 | } 69 | 70 | double[] w = null; 71 | if (Weights != null) { 72 | w = Converter.ToDoubleArray(Weights); 73 | } 74 | 75 | model.Learn(inputs, outputs, w); 76 | 77 | WriteObject(model); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Regressions/InvokeLogisticRegression.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Data; 4 | using System.Collections.Generic; 5 | using System.Management.Automation; 6 | using Accord.Statistics.Analysis; 7 | using Accord.Statistics.Filters; 8 | using Accord.Statistics.Models.Regression; 9 | using Accord.Statistics.Models.Regression.Fitting; 10 | using Accord.Math; 11 | 12 | namespace Horker.Math 13 | { 14 | [Cmdlet("Invoke", "LogisticRegression")] 15 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 16 | public class InvokeLogisticRegression : PSCmdlet 17 | { 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "XY")] 19 | public object X; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "XY")] 22 | public object Y; 23 | 24 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 25 | public PSObject InputObject; 26 | 27 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 28 | public string OutputName; 29 | 30 | [Parameter(Mandatory = false)] 31 | public object Weights; 32 | 33 | private DataFrame _data; 34 | 35 | protected override void BeginProcessing() 36 | { 37 | _data = new DataFrame(); 38 | } 39 | 40 | protected override void ProcessRecord() 41 | { 42 | if (ParameterSetName != "Pipeline") { 43 | return; 44 | } 45 | 46 | _data.AddRow(InputObject); 47 | } 48 | 49 | protected override void EndProcessing() 50 | { 51 | var model = new LogisticRegressionAnalysis(); 52 | 53 | double[][] inputs; 54 | double[] outputs; 55 | 56 | if (ParameterSetName == "XY") { 57 | inputs = Converter.ToDoubleJaggedArray(X); 58 | outputs = Converter.ToDoubleArray(Y); 59 | } 60 | else { 61 | outputs = _data.GetColumn(OutputName).ToDoubleArray(); 62 | 63 | _data.RemoveColumn(OutputName); 64 | inputs = _data.ToDoubleJaggedArray(); 65 | 66 | model.Inputs = _data.ColumnNames.ToArray(); 67 | model.Output = OutputName; 68 | } 69 | 70 | double[] w = null; 71 | if (Weights != null) { 72 | w = Converter.ToDoubleArray(Weights); 73 | } 74 | 75 | model.Learn(inputs, outputs, w); 76 | 77 | WriteObject(model); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Regressions/InvokeStepwiseLogisticRegression.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Data; 3 | using System.Management.Automation; 4 | using Accord.Statistics.Analysis; 5 | using Accord.Math; 6 | 7 | namespace Horker.Math 8 | { 9 | [Cmdlet("Invoke", "StepwiseLogisticRegression")] 10 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 11 | public class InvokeStepwiseLogisticRegression : PSCmdlet 12 | { 13 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "XY")] 14 | public object X; 15 | 16 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "XY")] 17 | public object Y; 18 | 19 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 20 | public PSObject InputObject; 21 | 22 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 23 | public string OutputName; 24 | 25 | [Parameter(Mandatory = false)] 26 | public object Weights; 27 | 28 | private DataFrame _data; 29 | 30 | protected override void BeginProcessing() 31 | { 32 | _data = new DataFrame(); 33 | } 34 | 35 | protected override void ProcessRecord() 36 | { 37 | if (ParameterSetName != "Pipeline") { 38 | return; 39 | } 40 | 41 | _data.AddRow(InputObject); 42 | } 43 | 44 | protected override void EndProcessing() 45 | { 46 | double[][] inputs; 47 | double[] outputs; 48 | string[] inputNames; 49 | string outputName; 50 | 51 | if (ParameterSetName == "XY") { 52 | inputs = Converter.ToDoubleJaggedArray(X); 53 | outputs = Converter.ToDoubleArray(Y); 54 | 55 | inputNames = Accord.Math.Vector.Range(0, inputs[0].Length, 1).Select(x => "x" + x).ToArray(); 56 | outputName = "y"; 57 | } 58 | else { 59 | outputs = _data.GetColumn(OutputName).ToDoubleArray(); 60 | 61 | _data.RemoveColumn(OutputName); 62 | inputs = _data.ToDoubleJaggedArray(); 63 | 64 | inputNames = _data.ColumnNames.ToArray(); 65 | outputName = OutputName; 66 | } 67 | 68 | double[] w = null; 69 | if (Weights != null) { 70 | w = Converter.ToDoubleArray(Weights); 71 | } 72 | 73 | var model = new StepwiseLogisticRegressionAnalysis(inputs, outputs, inputNames, outputName); 74 | 75 | #pragma warning disable CS0618 76 | model.Compute(); 77 | #pragma warning restore CS0618 78 | 79 | WriteObject(model); 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeBinomialTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "BinomialTest")] 12 | public class InvokeBinomialTest : PSCmdlet 13 | { 14 | [Parameter(Position = 0, Mandatory = true)] 15 | public int SuccesCount; 16 | 17 | [Parameter(Position = 1, Mandatory = true)] 18 | public int TrialCount; 19 | 20 | [Parameter(Position = 2, Mandatory = false)] 21 | public double Probability = .5; 22 | 23 | [Parameter(Position = 3, Mandatory = false)] 24 | [ValidateSet("Different", "Greater", "Smaller")] 25 | public string Alternate = "Different"; 26 | 27 | [Parameter(Position = 4, Mandatory = false)] 28 | public double Size = .05; 29 | 30 | protected override void EndProcessing() 31 | { 32 | var hypo = TestingHelper.GetOneSampleHypothesis(Alternate); 33 | 34 | var test = new BinomialTest(SuccesCount, TrialCount, Probability, hypo) { Size = Size }; 35 | 36 | WriteObject(test); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeChiSquareTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Accord.Statistics; 7 | using System.Management.Automation; 8 | using Accord.Math; 9 | using Accord.Statistics.Analysis; 10 | using Accord.Statistics.Testing; 11 | 12 | namespace Horker.Math 13 | { 14 | [Cmdlet("Invoke", "ChiSquareTest")] 15 | [CmdletBinding(DefaultParameterSetName = "Independence")] 16 | public class InvokeChiSquareTest : PSCmdlet 17 | { 18 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Independence")] 19 | public PSObject InputObject; 20 | 21 | [Parameter(Position = 0, Mandatory = false, ParameterSetName = "Independence")] 22 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "GoodnessOfFit")] 23 | public double Size = 0.05; 24 | 25 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "GoodnessOfFit")] 26 | public double[] Observed; 27 | 28 | [Parameter(Position = 1, Mandatory = false, ParameterSetName = "GoodnessOfFit")] 29 | public double[] Expected; 30 | 31 | private DataFrame _data; 32 | 33 | protected override void BeginProcessing() 34 | { 35 | if (ParameterSetName == "Independence") { 36 | _data = new DataFrame(); 37 | } 38 | } 39 | 40 | protected override void ProcessRecord() 41 | { 42 | if (ParameterSetName == "Independence") { 43 | _data.AddRow(InputObject); 44 | } 45 | } 46 | 47 | protected override void EndProcessing() 48 | { 49 | ChiSquareTest test = null; 50 | 51 | if (ParameterSetName == "Independence") { 52 | var mat = new GeneralConfusionMatrix(_data.ToIntMatrix()); 53 | test = new ChiSquareTest(mat, false); 54 | } 55 | else { 56 | if (Expected == null) { 57 | Expected = new double[Observed.Length]; 58 | var ex = Observed.Sum() / Observed.Length; 59 | for (var i = 0; i < Expected.Length; ++i) { 60 | Expected[i] = ex; 61 | } 62 | } 63 | 64 | test = new ChiSquareTest(Expected, Observed, Observed.Length - 1); 65 | } 66 | 67 | test.Size = Size; 68 | WriteObject(test); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeFTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math.Tests 10 | { 11 | [Cmdlet("Invoke", "FTest")] 12 | public class InvokeFTest : PSCmdlet 13 | { 14 | [Parameter(Position = 0, Mandatory = true)] 15 | public double Variance1; 16 | 17 | [Parameter(Position = 1, Mandatory = true)] 18 | public double Variance2; 19 | 20 | [Parameter(Position = 3, Mandatory = true)] 21 | public int DegreesOfFreedom1; 22 | 23 | [Parameter(Position = 4, Mandatory = true)] 24 | public int DegreesOfFreedom2; 25 | 26 | [Parameter(Position = 5, Mandatory = false)] 27 | [ValidateSet("Different", "Greater", "Smaller")] 28 | public string Alternate = "Different"; 29 | 30 | [Parameter(Position = 6, Mandatory = false)] 31 | public double Size = .05; 32 | 33 | protected override void EndProcessing() 34 | { 35 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 36 | 37 | var test = new FTest(Variance1, Variance2, DegreesOfFreedom1, DegreesOfFreedom2, hypo) { Size = Size }; 38 | 39 | WriteObject(test); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeFisherExactTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Accord.Statistics; 7 | using System.Management.Automation; 8 | using Accord.Math; 9 | using Accord.Statistics.Analysis; 10 | using Accord.Statistics.Testing; 11 | 12 | namespace Horker.Math 13 | { 14 | [Cmdlet("Invoke", "FisherExactTest")] 15 | public class InvokeFisherExactTest : PSCmdlet 16 | { 17 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 18 | public PSObject InputObject; 19 | 20 | [Parameter(Position = 0, Mandatory = false)] 21 | [ValidateSet("Different", "Greater", "Smaller")] 22 | public string Alternate = "Different"; 23 | 24 | [Parameter(Position = 1, Mandatory = false)] 25 | public double Size = 0.05; 26 | 27 | private DataFrame _data; 28 | 29 | protected override void BeginProcessing() 30 | { 31 | _data = new DataFrame(); 32 | } 33 | 34 | protected override void ProcessRecord() 35 | { 36 | _data.AddRow(InputObject); 37 | } 38 | 39 | protected override void EndProcessing() 40 | { 41 | var hypo = TestingHelper.GetOneSampleHypothesis(Alternate); 42 | 43 | var mat = new ConfusionMatrix(_data.ToIntMatrix()); 44 | var test = new FisherExactTest(mat, hypo) { Size = Size }; 45 | 46 | WriteObject(test); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeKolmogorovSmirnovTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | using Accord.Statistics.Distributions; 9 | 10 | namespace Horker.Math 11 | { 12 | [Cmdlet("Invoke", "KolmogorovSmirnovTest")] 13 | public class InvokeKolmogorovSmirnovTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 16 | public double InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = true)] 19 | public IDistribution HypothesizedDistribution; 20 | 21 | [Parameter(Position = 1, Mandatory = false)] 22 | [ValidateSet("Different", "Greater", "Smaller")] 23 | public string Alternate = "Different"; 24 | 25 | [Parameter(Position = 2, Mandatory = false)] 26 | public double Size = .05; 27 | 28 | private List _data; 29 | 30 | protected override void BeginProcessing() 31 | { 32 | _data = new List(); 33 | } 34 | 35 | protected override void ProcessRecord() 36 | { 37 | _data.Add(Converter.ToDouble(InputObject)); 38 | } 39 | 40 | protected override void EndProcessing() 41 | { 42 | var hypo = TestingHelper.GetKolmogorovSmirnovTestHypothesis(Alternate); 43 | 44 | var test = new KolmogorovSmirnovTest(_data.ToArray(), HypothesizedDistribution, hypo) { Size = Size }; 45 | 46 | WriteObject(test); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeLeveneTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Math; 8 | using Accord.Statistics.Analysis; 9 | using Accord.Statistics.Testing; 10 | 11 | namespace Horker.Math 12 | { 13 | [Cmdlet("Invoke", "LeveneTest")] 14 | public class InvokeLeveneTest : PSCmdlet 15 | { 16 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 17 | public PSObject InputObject; 18 | 19 | [Parameter(Position = 0, Mandatory = true)] 20 | public string CategoryName; 21 | 22 | [Parameter(Position = 1, Mandatory = true)] 23 | public string ValueName; 24 | 25 | [Parameter(Position = 2, Mandatory = false)] 26 | public double Size = .05; 27 | 28 | [Parameter(Mandatory = false)] 29 | public SwitchParameter Median = false; 30 | 31 | [Parameter(Mandatory = false)] 32 | public double TrimPercent = double.NaN; 33 | 34 | private DataFrame _data; 35 | 36 | protected override void BeginProcessing() 37 | { 38 | _data = new DataFrame(); 39 | } 40 | 41 | protected override void ProcessRecord() 42 | { 43 | _data.AddRow(InputObject); 44 | } 45 | 46 | protected override void EndProcessing() 47 | { 48 | var g = _data.GroupBy(CategoryName).ToDoubleJaggedArrayOf(ValueName); 49 | 50 | LeveneTest test; 51 | 52 | if (double.IsNaN(TrimPercent)) { 53 | test = new LeveneTest(g, Median); 54 | } 55 | else { 56 | test = new LeveneTest(g, TrimPercent); 57 | } 58 | 59 | test.Size = Size; 60 | 61 | WriteObject(test); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeMannWhitneyWilcoxonTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Management.Automation; 3 | using Accord.Statistics.Testing; 4 | 5 | namespace Horker.Math 6 | { 7 | [Cmdlet("Invoke", "MannWhitneyWilcoxonTest")] 8 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 9 | public class InvokeMannWhitneyWilcoxonTest : PSCmdlet 10 | { 11 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 12 | public PSObject InputObject; 13 | 14 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 15 | public string CategoryName; 16 | 17 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 18 | public string ValueName; 19 | 20 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 21 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 22 | [ValidateSet("Different", "Greater", "Smaller")] 23 | public string Alternate = "Different"; 24 | 25 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 26 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 27 | public double Size = 0.05; 28 | 29 | [Parameter(Mandatory = false, ParameterSetName = "Pipeline")] 30 | [Parameter(Mandatory = false, ParameterSetName = "Samples")] 31 | public SwitchParameter Exact = false; 32 | 33 | [Parameter(Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Mandatory = false, ParameterSetName = "Samples")] 35 | public SwitchParameter NoAdjustForTies = false; 36 | 37 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 38 | public double[] Sample1; 39 | 40 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 41 | public double[] Sample2; 42 | 43 | private DataFrame _data; 44 | 45 | protected override void BeginProcessing() 46 | { 47 | if (ParameterSetName == "Pipeline") { 48 | _data = new DataFrame(); 49 | } 50 | } 51 | 52 | protected override void ProcessRecord() 53 | { 54 | if (ParameterSetName == "Pipeline") { 55 | _data.AddRow(InputObject); 56 | } 57 | } 58 | 59 | protected override void EndProcessing() 60 | { 61 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 62 | 63 | MannWhitneyWilcoxonTest test; 64 | 65 | if (ParameterSetName == "Pipeline") { 66 | var samples = _data.GroupBy(CategoryName).ToDoubleJaggedArrayOf(ValueName); 67 | if (samples.Length != 2) { 68 | WriteError(new ErrorRecord(new RuntimeException("The number of categories is not two"), "", ErrorCategory.InvalidArgument, null)); 69 | return; 70 | } 71 | test = new MannWhitneyWilcoxonTest(samples[0], samples[1], hypo, (Exact ? true : (Nullable)null), !NoAdjustForTies); 72 | } 73 | else { 74 | test = new MannWhitneyWilcoxonTest(Sample1, Sample2, hypo, (Exact ? true : (Nullable)null), !NoAdjustForTies); 75 | } 76 | 77 | test.Size = Size; 78 | 79 | WriteObject(test); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeOneWayAnova.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Math; 8 | using Accord.Statistics.Analysis; 9 | using Accord.Statistics.Testing; 10 | 11 | namespace Horker.Math 12 | { 13 | [Cmdlet("Invoke", "OneWayAnova")] 14 | public class InvokeOneWayAnova : PSCmdlet 15 | { 16 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 17 | public PSObject InputObject; 18 | 19 | [Parameter(Position = 0, Mandatory = true)] 20 | public string CategoryName; 21 | 22 | [Parameter(Position = 1, Mandatory = true)] 23 | public string ValueName; 24 | 25 | [Parameter(Position = 2, Mandatory = false)] 26 | public double Size = .05; 27 | 28 | private DataFrame _data; 29 | 30 | protected override void BeginProcessing() 31 | { 32 | _data = new DataFrame(); 33 | } 34 | 35 | protected override void ProcessRecord() 36 | { 37 | _data.AddRow(InputObject); 38 | } 39 | 40 | protected override void EndProcessing() 41 | { 42 | var groups = _data.GroupBy(CategoryName); 43 | var test = new OneWayAnova(groups.ToDoubleJaggedArrayOf(ValueName)); 44 | 45 | test.FTest.Size = Size; 46 | 47 | WriteObject(test.Table); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokePairedTTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "PairedTTest")] 12 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 13 | public class InvokePairedTTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 16 | public PSObject InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 19 | public string Sample1Name; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 22 | public string Sample2Name; 23 | 24 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 25 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 26 | public double HypothesizedDifference = 0; 27 | 28 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 29 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 30 | [ValidateSet("Different", "Greater", "Smaller")] 31 | public string Alternate = "Different"; 32 | 33 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Samples")] 35 | public double Size = 0.05; 36 | 37 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 38 | public double[] Sample1; 39 | 40 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 41 | public double[] Sample2; 42 | 43 | private DataFrame _data; 44 | 45 | protected override void BeginProcessing() 46 | { 47 | if (ParameterSetName == "Pipeline") { 48 | _data = new DataFrame(); 49 | } 50 | } 51 | 52 | protected override void ProcessRecord() 53 | { 54 | if (ParameterSetName == "Pipeline") { 55 | _data.AddRow(InputObject); 56 | } 57 | } 58 | 59 | protected override void EndProcessing() 60 | { 61 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 62 | 63 | PairedTTest test; 64 | 65 | if (ParameterSetName == "Pipeline") { 66 | test = new PairedTTest(_data[Sample1Name].ToDoubleArray(), _data[Sample2Name].ToDoubleArray(), hypo); 67 | } 68 | else { 69 | test = new PairedTTest(Sample1, Sample2, hypo); 70 | } 71 | 72 | test.Size = Size; 73 | 74 | WriteObject(test); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeShapiroWilkTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "ShapiroWilkTest")] 12 | public class InvokeShapiroWilkTest : PSCmdlet 13 | { 14 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 15 | public double InputObject; 16 | 17 | [Parameter(Position = 0, Mandatory = false)] 18 | public double Size = .05; 19 | 20 | private List _data; 21 | 22 | protected override void BeginProcessing() 23 | { 24 | _data = new List(); 25 | } 26 | 27 | protected override void ProcessRecord() 28 | { 29 | _data.Add(Converter.ToDouble(InputObject)); 30 | } 31 | 32 | protected override void EndProcessing() 33 | { 34 | var test = new ShapiroWilkTest(_data.ToArray()) { Size = Size }; 35 | 36 | WriteObject(test); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeSignTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "SignTest")] 12 | public class InvokeSignTest : PSCmdlet 13 | { 14 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 15 | public double InputObject; 16 | 17 | [Parameter(Position = 0, Mandatory = false)] 18 | public double HypothesizedMedian = 0.0; 19 | 20 | [Parameter(Position = 1, Mandatory = false)] 21 | [ValidateSet("Different", "Greater", "Smaller")] 22 | public string Alternate = "Different"; 23 | 24 | [Parameter(Position = 2, Mandatory = false)] 25 | public double Size = .05; 26 | 27 | private List _data; 28 | 29 | protected override void BeginProcessing() 30 | { 31 | _data = new List(); 32 | } 33 | 34 | protected override void ProcessRecord() 35 | { 36 | _data.Add(Converter.ToDouble(InputObject)); 37 | } 38 | 39 | protected override void EndProcessing() 40 | { 41 | var hypo = TestingHelper.GetOneSampleHypothesis(Alternate); 42 | 43 | var test = new SignTest(_data.ToArray(), HypothesizedMedian, hypo) { Size = Size }; 44 | 45 | WriteObject(test); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "TTest")] 12 | [CmdletBinding(DefaultParameterSetName = "Samples")] 13 | public class InvokeTTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Samples")] 16 | public double InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = false, ParameterSetName = "Samples")] 19 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Mean")] 20 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "SE")] 21 | public double HypothesizedMean = 0.0; 22 | 23 | [Parameter(Position = 1, Mandatory = false, ParameterSetName = "Samples")] 24 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Mean")] 25 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "SE")] 26 | [ValidateSet("Different", "Greater", "Smaller")] 27 | public string Alternate = "Different"; 28 | 29 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 30 | [Parameter(Position = 5, Mandatory = false, ParameterSetName = "Mean")] 31 | [Parameter(Position = 5, Mandatory = false, ParameterSetName = "SE")] 32 | public double Size = .05; 33 | 34 | [Parameter(Position = 0, Mandatory = false, ParameterSetName = "Mean")] 35 | public double Mean = 0.0; 36 | 37 | [Parameter(Position = 1, Mandatory = false, ParameterSetName = "Mean")] 38 | public double StdDev = 0.0; 39 | 40 | [Parameter(Position = 2, Mandatory = true, ParameterSetName = "Mean")] 41 | public int Samples; 42 | 43 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "SE")] 44 | public double Value = 0.0; 45 | 46 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "SE")] 47 | public double StandardError; 48 | 49 | [Parameter(Position = 2, Mandatory = true, ParameterSetName = "SE")] 50 | public int DegreesOfFreedom = 0; 51 | 52 | private List _data; 53 | 54 | protected override void BeginProcessing() 55 | { 56 | if (ParameterSetName == "Samples") { 57 | _data = new List(); 58 | } 59 | } 60 | 61 | protected override void ProcessRecord() 62 | { 63 | if (ParameterSetName == "Samples") { 64 | _data.Add(Converter.ToDouble(InputObject)); 65 | } 66 | } 67 | 68 | protected override void EndProcessing() 69 | { 70 | var hypo = TestingHelper.GetOneSampleHypothesis(Alternate); 71 | 72 | TTest test = null; 73 | 74 | if (ParameterSetName == "Samples") { 75 | test = new TTest(_data.ToArray(), HypothesizedMean, hypo); 76 | } 77 | else if (ParameterSetName == "Mean") { 78 | test = new TTest(Mean, StdDev, Samples, HypothesizedMean, hypo); 79 | } 80 | else if (ParameterSetName == "SE") { 81 | test = new TTest(Value, StandardError, (double)DegreesOfFreedom, HypothesizedMean, hypo); 82 | } 83 | 84 | test.Size = Size; 85 | 86 | WriteObject(test); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTwoSampleKolmogorovSmirnovTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "TwoSampleKolmogorovSmirnovTest")] 12 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 13 | public class InvokeTwoSampleKolmogorovSmirnovTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 16 | public PSObject InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 19 | public string Sample1Name; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 22 | public string Sample2Name; 23 | 24 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 25 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 26 | public double HypothesizedDifference = 0; 27 | 28 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 29 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 30 | [ValidateSet("Different", "Greater", "Smaller")] 31 | public string Alternate = "Different"; 32 | 33 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Samples")] 35 | public double Size = 0.05; 36 | 37 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 38 | public double[] Sample1; 39 | 40 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 41 | public double[] Sample2; 42 | 43 | private DataFrame _data; 44 | 45 | protected override void BeginProcessing() 46 | { 47 | if (ParameterSetName == "Pipeline") { 48 | _data = new DataFrame(); 49 | } 50 | } 51 | 52 | protected override void ProcessRecord() 53 | { 54 | if (ParameterSetName == "Pipeline") { 55 | _data.AddRow(InputObject); 56 | } 57 | } 58 | 59 | protected override void EndProcessing() 60 | { 61 | var hypo = TestingHelper.GetTwoSampleKolmogorovSmirnovTestHypothesis(Alternate); 62 | 63 | TwoSampleKolmogorovSmirnovTest test; 64 | 65 | if (ParameterSetName == "Pipeline") { 66 | test = new TwoSampleKolmogorovSmirnovTest(_data[Sample1Name].ToDoubleArray(), _data[Sample2Name].ToDoubleArray(), hypo); 67 | } 68 | else { 69 | test = new TwoSampleKolmogorovSmirnovTest(Sample1, Sample2, hypo); 70 | } 71 | 72 | test.Size = Size; 73 | 74 | WriteObject(test); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTwoSampleSignTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "TwoSampleSignTest")] 12 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 13 | public class InvokeTwoSampleSignTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 16 | public PSObject InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 19 | public string Sample1Name; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 22 | public string Sample2Name; 23 | 24 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 25 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 26 | public double HypothesizedDifference = 0; 27 | 28 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 29 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 30 | [ValidateSet("Different", "Greater", "Smaller")] 31 | public string Alternate = "Different"; 32 | 33 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Samples")] 35 | public double Size = 0.05; 36 | 37 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 38 | public double[] Sample1; 39 | 40 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 41 | public double[] Sample2; 42 | 43 | private DataFrame _data; 44 | 45 | protected override void BeginProcessing() 46 | { 47 | if (ParameterSetName == "Pipeline") { 48 | _data = new DataFrame(); 49 | } 50 | } 51 | 52 | protected override void ProcessRecord() 53 | { 54 | if (ParameterSetName == "Pipeline") { 55 | _data.AddRow(InputObject); 56 | } 57 | } 58 | 59 | protected override void EndProcessing() 60 | { 61 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 62 | 63 | TwoSampleSignTest test; 64 | 65 | if (ParameterSetName == "Pipeline") { 66 | test = new TwoSampleSignTest(_data[Sample1Name].ToDoubleArray(), _data[Sample2Name].ToDoubleArray(), hypo); 67 | } 68 | else { 69 | test = new TwoSampleSignTest(Sample1, Sample2, hypo); 70 | } 71 | 72 | test.Size = Size; 73 | 74 | WriteObject(test); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTwoSampleTTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "TwoSampleTTest")] 12 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 13 | public class InvokeTwoSampleTTest : PSCmdlet 14 | { 15 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 16 | public PSObject InputObject; 17 | 18 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 19 | public string CategoryName; 20 | 21 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 22 | public string ValueName; 23 | 24 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 25 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 26 | public double HypothesizedDifference = 0; 27 | 28 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 29 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 30 | [ValidateSet("Different", "Greater", "Smaller")] 31 | public string Alternate = "Different"; 32 | 33 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Position = 4, Mandatory = false, ParameterSetName = "Samples")] 35 | public double Size = 0.05; 36 | 37 | [Parameter(Mandatory = false, ParameterSetName = "Pipeline")] 38 | [Parameter(Mandatory = false, ParameterSetName = "Samples")] 39 | public SwitchParameter AssumeEqualVariances = false; 40 | 41 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 42 | public double[] Sample1; 43 | 44 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 45 | public double[] Sample2; 46 | 47 | private DataFrame _data; 48 | 49 | protected override void BeginProcessing() 50 | { 51 | if (ParameterSetName == "Pipeline") { 52 | _data = new DataFrame(); 53 | } 54 | } 55 | 56 | protected override void ProcessRecord() 57 | { 58 | if (ParameterSetName == "Pipeline") { 59 | _data.AddRow(InputObject); 60 | } 61 | } 62 | 63 | protected override void EndProcessing() 64 | { 65 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 66 | 67 | TwoSampleTTest test; 68 | 69 | if (ParameterSetName == "Pipeline") { 70 | var samples = _data.GroupBy(CategoryName).ToDoubleJaggedArrayOf(ValueName); 71 | if (samples.Length != 2) { 72 | WriteError(new ErrorRecord(new RuntimeException("The number of categories is not two"), "", ErrorCategory.InvalidArgument, null)); 73 | return; 74 | } 75 | test = new TwoSampleTTest(samples[0], samples[1], AssumeEqualVariances, HypothesizedDifference, hypo); 76 | } 77 | else { 78 | test = new TwoSampleTTest(Sample1, Sample2, AssumeEqualVariances, HypothesizedDifference, hypo); 79 | } 80 | 81 | test.Size = Size; 82 | 83 | WriteObject(test); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTwoSampleWilcoxonSignedRankTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Management.Automation; 3 | using Accord.Statistics.Testing; 4 | 5 | namespace Horker.Math 6 | { 7 | [Cmdlet("Invoke", "TwoSampleWilcoxonSignedRankTest")] 8 | [CmdletBinding(DefaultParameterSetName = "Pipeline")] 9 | public class InvokeTwoSampleWilcoxonSignedRankTest : PSCmdlet 10 | { 11 | [Parameter(ValueFromPipeline = true, Mandatory = true, ParameterSetName = "Pipeline")] 12 | public PSObject InputObject; 13 | 14 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Pipeline")] 15 | public string Sample1Name; 16 | 17 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Pipeline")] 18 | public string Sample2Name; 19 | 20 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Pipeline")] 21 | [Parameter(Position = 2, Mandatory = false, ParameterSetName = "Samples")] 22 | [ValidateSet("Different", "Greater", "Smaller")] 23 | public string Alternate = "Different"; 24 | 25 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Pipeline")] 26 | [Parameter(Position = 3, Mandatory = false, ParameterSetName = "Samples")] 27 | public double Size = 0.05; 28 | 29 | [Parameter(Mandatory = false, ParameterSetName = "Pipeline")] 30 | [Parameter(Mandatory = false, ParameterSetName = "Samples")] 31 | public SwitchParameter Exact = false; 32 | 33 | [Parameter(Mandatory = false, ParameterSetName = "Pipeline")] 34 | [Parameter(Mandatory = false, ParameterSetName = "Samples")] 35 | public SwitchParameter NoAdjustForTies = false; 36 | 37 | [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Samples")] 38 | public double[] Sample1; 39 | 40 | [Parameter(Position = 1, Mandatory = true, ParameterSetName = "Samples")] 41 | public double[] Sample2; 42 | 43 | private DataFrame _data; 44 | 45 | protected override void BeginProcessing() 46 | { 47 | if (ParameterSetName == "Pipeline") { 48 | _data = new DataFrame(); 49 | } 50 | } 51 | 52 | protected override void ProcessRecord() 53 | { 54 | if (ParameterSetName == "Pipeline") { 55 | _data.AddRow(InputObject); 56 | } 57 | } 58 | 59 | protected override void EndProcessing() 60 | { 61 | var hypo = TestingHelper.GetTwoSampleHypothesis(Alternate); 62 | 63 | TwoSampleWilcoxonSignedRankTest test; 64 | 65 | if (ParameterSetName == "Pipeline") { 66 | test = new TwoSampleWilcoxonSignedRankTest( 67 | _data[Sample1Name].ToDoubleArray(), 68 | _data[Sample2Name].ToDoubleArray(), 69 | hypo, 70 | (Exact ? true : (Nullable)null), 71 | !NoAdjustForTies); 72 | } 73 | else { 74 | test = new TwoSampleWilcoxonSignedRankTest( 75 | Sample1, 76 | Sample2, 77 | hypo, 78 | (Exact ? true : (Nullable)null), 79 | !NoAdjustForTies); 80 | } 81 | 82 | test.Size = Size; 83 | 84 | WriteObject(test); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeTwoWayAnova.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Math; 8 | using Accord.Statistics.Analysis; 9 | using Accord.Statistics.Testing; 10 | 11 | namespace Horker.Math 12 | { 13 | [Cmdlet("Invoke", "TwoWayAnova")] 14 | public class InvokeTwoWayAnova : PSCmdlet 15 | { 16 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 17 | public PSObject InputObject; 18 | 19 | [Parameter(Position = 0, Mandatory = true)] 20 | public string Level1Name; 21 | 22 | [Parameter(Position = 1, Mandatory = true)] 23 | public string Level2Name; 24 | 25 | [Parameter(Position = 2, Mandatory = true)] 26 | public string ValueName; 27 | 28 | [Parameter(Position = 3, Mandatory = false)] 29 | public TwoWayAnovaModel Model = TwoWayAnovaModel.Mixed; 30 | 31 | private DataFrame _data; 32 | 33 | protected override void BeginProcessing() 34 | { 35 | _data = new DataFrame(); 36 | } 37 | 38 | protected override void ProcessRecord() 39 | { 40 | _data.AddRow(InputObject); 41 | } 42 | 43 | protected override void EndProcessing() 44 | { 45 | /* 46 | var level1 = _data[Level1Name].ToDummyValues(Level1Name, CodificationType.Multilevel); 47 | var level2 = _data[Level2Name].ToDummyValues(Level2Name, CodificationType.Multilevel); 48 | var test = new TwoWayAnova( 49 | _data[ValueName].ToDoubleArray(), 50 | level1[Level1Name].ToIntArray(), 51 | level2[Level2Name].ToIntArray(), 52 | Model); 53 | 54 | WriteObject(test.Table); 55 | */ 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/InvokeWilcoxonSignedRankTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Management.Automation; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | [Cmdlet("Invoke", "WilcoxonSignedRankTest")] 12 | public class InvokeWilcoxonSignedRankTest : PSCmdlet 13 | { 14 | [Parameter(ValueFromPipeline = true, Mandatory = true)] 15 | public double InputObject; 16 | 17 | [Parameter(Position = 0, Mandatory = false)] 18 | public double HypothesizedMean = 0.0; 19 | 20 | [Parameter(Position = 1, Mandatory = false)] 21 | [ValidateSet("Different", "Greater", "Smaller")] 22 | public string Alternate = "Different"; 23 | 24 | [Parameter(Position = 2, Mandatory = false)] 25 | public double Size = .05; 26 | 27 | [Parameter(Mandatory = false)] 28 | public SwitchParameter Exact = false; 29 | 30 | [Parameter(Mandatory = false)] 31 | public SwitchParameter NoAdjustForTies = false; 32 | 33 | private List _data; 34 | 35 | protected override void BeginProcessing() 36 | { 37 | _data = new List(); 38 | } 39 | 40 | protected override void ProcessRecord() 41 | { 42 | _data.Add(Converter.ToDouble(InputObject)); 43 | } 44 | 45 | protected override void EndProcessing() 46 | { 47 | var hypo = TestingHelper.GetOneSampleHypothesis(Alternate); 48 | 49 | var test = new WilcoxonSignedRankTest( 50 | _data.ToArray(), 51 | HypothesizedMean, 52 | hypo, 53 | Exact ? true : (Nullable)null, 54 | !NoAdjustForTies) 55 | { Size = Size }; 56 | 57 | WriteObject(test); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /source/Horker.Math/Statistics/Tests/TestHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Management.Automation; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Accord.Statistics.Testing; 8 | 9 | namespace Horker.Math 10 | { 11 | public class TestingHelper 12 | { 13 | public static OneSampleHypothesis GetOneSampleHypothesis(string alternate) 14 | { 15 | OneSampleHypothesis hypo; 16 | switch (alternate) { 17 | case "Different": 18 | hypo = OneSampleHypothesis.ValueIsDifferentFromHypothesis; 19 | break; 20 | 21 | case "Greater": 22 | hypo = OneSampleHypothesis.ValueIsGreaterThanHypothesis; 23 | break; 24 | 25 | case "Smaller": 26 | hypo = OneSampleHypothesis.ValueIsSmallerThanHypothesis; 27 | break; 28 | 29 | default: 30 | throw new RuntimeException("Invalid Alternate value"); 31 | } 32 | 33 | return hypo; 34 | } 35 | 36 | public static TwoSampleHypothesis GetTwoSampleHypothesis(string alternate) 37 | { 38 | TwoSampleHypothesis hypo; 39 | switch (alternate) { 40 | case "Different": 41 | hypo = TwoSampleHypothesis.ValuesAreDifferent; 42 | break; 43 | 44 | case "Greater": 45 | hypo = TwoSampleHypothesis.FirstValueIsGreaterThanSecond; 46 | break; 47 | 48 | case "Smaller": 49 | hypo = TwoSampleHypothesis.FirstValueIsSmallerThanSecond; 50 | break; 51 | 52 | default: 53 | throw new RuntimeException("Invalid Alternate value"); 54 | } 55 | 56 | return hypo; 57 | } 58 | 59 | public static KolmogorovSmirnovTestHypothesis GetKolmogorovSmirnovTestHypothesis(string alternate) 60 | { 61 | KolmogorovSmirnovTestHypothesis hypo; 62 | switch (alternate) { 63 | case "Different": 64 | hypo = KolmogorovSmirnovTestHypothesis.SampleIsDifferent; 65 | break; 66 | 67 | case "Greater": 68 | hypo = KolmogorovSmirnovTestHypothesis.SampleIsGreater; 69 | break; 70 | 71 | case "Smaller": 72 | hypo = KolmogorovSmirnovTestHypothesis.SampleIsSmaller; 73 | break; 74 | 75 | default: 76 | throw new RuntimeException("Invalid Alternate value"); 77 | } 78 | 79 | return hypo; 80 | } 81 | 82 | public static TwoSampleKolmogorovSmirnovTestHypothesis GetTwoSampleKolmogorovSmirnovTestHypothesis(string alternate) 83 | { 84 | TwoSampleKolmogorovSmirnovTestHypothesis hypo; 85 | switch (alternate) { 86 | case "Different": 87 | hypo = TwoSampleKolmogorovSmirnovTestHypothesis.SamplesDistributionsAreUnequal; 88 | break; 89 | 90 | case "Greater": 91 | hypo = TwoSampleKolmogorovSmirnovTestHypothesis.FirstSampleIsLargerThanSecond; 92 | break; 93 | 94 | case "Smaller": 95 | hypo = TwoSampleKolmogorovSmirnovTestHypothesis.FirstSampleIsSmallerThanSecond; 96 | break; 97 | 98 | default: 99 | throw new RuntimeException("Invalid Alternate value"); 100 | } 101 | 102 | return hypo; 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /source/Horker.Math/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /source/Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("Tests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("Tests")] 10 | [assembly: AssemblyCopyright("Copyright (c) horker")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("9e4d2a29-5617-4807-bc37-5ae6938e0195")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /source/Tests/TestArrayMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace Tests 5 | { 6 | [TestClass] 7 | public class TestArrayMethods 8 | { 9 | [TestMethod] 10 | public void TestSplit() 11 | { 12 | var array = new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 13 | 14 | var s = Horker.Math.ArrayMethods.Typed.Additional.SplitInternal(array, new object[] { .6, 2 }); 15 | 16 | Assert.AreEqual(3, s.Length); 17 | 18 | Assert.AreEqual(6, s[0].Length); 19 | Assert.AreEqual(2, s[1].Length); 20 | Assert.AreEqual(2, s[2].Length); 21 | 22 | CollectionAssert.AreEqual(new object[] { 0, 1, 2, 3, 4, 5 }, s[0]); 23 | CollectionAssert.AreEqual(new object[] { 6, 7 }, s[1]); 24 | CollectionAssert.AreEqual(new object[] { 8, 9 }, s[2]); 25 | } 26 | 27 | [TestMethod] 28 | public void TestSlice1() 29 | { 30 | var array = new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 31 | 32 | var s = Horker.Math.ArrayMethods.Typed.Additional.SliceInternal(array, new object[] { 1, 5, 9 }); 33 | 34 | Assert.AreEqual(3, s.Length); 35 | 36 | CollectionAssert.AreEqual(new object[] { 1, 5, 9 }, s); 37 | } 38 | 39 | [TestMethod] 40 | public void TestSlice2() 41 | { 42 | var array = new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 43 | 44 | var s = Horker.Math.ArrayMethods.Typed.Additional.SliceInternal(array, new object[] { 1, new int []{ 5, 7 }, 9 }); 45 | 46 | Assert.AreEqual(4, s.Length); 47 | 48 | CollectionAssert.AreEqual(new object[] { 1, 5, 6, 9 }, s); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /source/Tests/TestDataFrame.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using Horker.Math; 5 | using System.Management.Automation; 6 | using System.Collections.Generic; 7 | 8 | namespace Tests 9 | { 10 | [TestClass] 11 | public class TestDataFrame 12 | { 13 | [TestMethod] 14 | public void TestAddRow() 15 | { 16 | var d = new DataFrame(); 17 | 18 | Assert.AreEqual(0, d.Count); 19 | 20 | var obj = new PSObject(); 21 | obj.Properties.Add(new PSNoteProperty("abc", 123)); 22 | obj.Properties.Add(new PSNoteProperty("xyz", "aaa")); 23 | d.AddRow(obj); 24 | 25 | var obj2 = new PSObject(); 26 | obj2.Properties.Add(new PSNoteProperty("abc", 456)); 27 | obj2.Properties.Add(new PSNoteProperty("xyz", "bbb")); 28 | d.AddRow(obj2); 29 | 30 | Assert.AreEqual(2, d.Count); 31 | 32 | Assert.AreEqual(123, d.GetRow(0).Properties["abc"].Value); 33 | Assert.AreEqual("bbb", d.GetRow(1).Properties["xyz"].Value); 34 | } 35 | 36 | [TestMethod] 37 | public void TestForeach() 38 | { 39 | var d = new DataFrame(); 40 | 41 | d.AddColumn("foo", new object[] { 1, 2, 3, 4 }); 42 | 43 | Assert.AreEqual(4, d.Count); 44 | 45 | int c = 1; 46 | foreach (PSObject e in d) { 47 | Assert.AreEqual(c, e.Properties["foo"].Value); 48 | ++c; 49 | } 50 | } 51 | 52 | [TestMethod] 53 | public void TestExpandToOneHot() 54 | { 55 | var df = new DataFrame(); 56 | var column = new DataFrameColumn(null, new int[] { 1, 2, 3 }); 57 | df.DefineNewColumn("a", column); 58 | 59 | df.ExpandToOneHot("a", 4); 60 | 61 | Assert.AreEqual(3, df.RowCount); 62 | Assert.AreEqual(4, df.ColumnCount); 63 | 64 | Assert.AreEqual(0, df["a_0"].GetObject(0)); 65 | Assert.AreEqual(1, df["a_1"].GetObject(0)); 66 | Assert.AreEqual(0, df["a_2"].GetObject(0)); 67 | Assert.AreEqual(0, df["a_3"].GetObject(0)); 68 | 69 | Assert.AreEqual(0, df["a_0"].GetObject(1)); 70 | Assert.AreEqual(0, df["a_1"].GetObject(1)); 71 | Assert.AreEqual(1, df["a_2"].GetObject(1)); 72 | Assert.AreEqual(0, df["a_3"].GetObject(1)); 73 | 74 | Assert.AreEqual(0, df["a_0"].GetObject(2)); 75 | Assert.AreEqual(0, df["a_1"].GetObject(2)); 76 | Assert.AreEqual(0, df["a_2"].GetObject(2)); 77 | Assert.AreEqual(1, df["a_3"].GetObject(2)); 78 | } 79 | 80 | [TestMethod] 81 | public void TestWiden() 82 | { 83 | var df = new DataFrame(); 84 | 85 | df.AddColumn("x", new int[] { 1, 2, 3 }); 86 | df.AddColumn("y", new string[] { "a", "b", "c" }); 87 | 88 | var result = df.Widen(4, 5, new string[] { "x", "y" }); 89 | 90 | CollectionAssert.AreEqual(new string[] { "x_0", "y_0", "x_1", "y_1", "x_2", "y_2", "x_3", "y_3" }, result.ColumnNames); 91 | 92 | Assert.AreEqual(1, result.GetColumn(0).Count); 93 | Assert.AreEqual(1, result.GetColumn(1).Count); 94 | Assert.AreEqual(1, result.GetColumn(2).Count); 95 | Assert.AreEqual(1, result.GetColumn(3).Count); 96 | Assert.AreEqual(1, result.GetColumn(4).Count); 97 | Assert.AreEqual(1, result.GetColumn(5).Count); 98 | Assert.AreEqual(1, result.GetColumn(6).Count); 99 | Assert.AreEqual(1, result.GetColumn(7).Count); 100 | 101 | Assert.AreEqual(1, result["x_0"].GetObject(0)); 102 | Assert.AreEqual("a", result["y_0"].GetObject(0)); 103 | Assert.AreEqual(2, result["x_1"].GetObject(0)); 104 | Assert.AreEqual("b", result["y_1"].GetObject(0)); 105 | Assert.AreEqual(3, result["x_2"].GetObject(0)); 106 | Assert.AreEqual("c", result["y_2"].GetObject(0)); 107 | Assert.AreEqual(0, result["x_3"].GetObject(0)); 108 | Assert.AreEqual(null, result["y_3"].GetObject(0)); 109 | } 110 | 111 | [TestMethod] 112 | public void TestConcatenate() 113 | { 114 | var df1 = new DataFrame(); 115 | df1.AddColumn("x", new int[] { 1, 2 }); 116 | df1.AddColumn("y", new string[] { "a", "b" }); 117 | 118 | var df2 = new DataFrame(); 119 | df2.AddColumn("x", new int[] { 3, 4 }); 120 | df2.AddColumn("z", new string[] { "c", "d" }); 121 | 122 | var result = DataFrame.Concatenate(df1, df2); 123 | 124 | CollectionAssert.AreEqual(new string[] { "x", "y", "z" }, result.ColumnNames); 125 | 126 | Assert.AreEqual(4, result[0].Count); 127 | Assert.AreEqual(4, result[1].Count); 128 | Assert.AreEqual(4, result[2].Count); 129 | 130 | CollectionAssert.AreEqual(new object[] { 1, 2, 3, 4 }, result[0].ToObjectArray()); 131 | CollectionAssert.AreEqual(new object[] { "a", "b", null, null }, result[1].ToObjectArray()); 132 | CollectionAssert.AreEqual(new object[] { null, null, "c", "d" }, result[2].ToObjectArray()); 133 | } 134 | 135 | [TestMethod] 136 | public void TestGroupBy() 137 | { 138 | var df = new DataFrame(); 139 | 140 | df.AddColumn("x", new string[] { "1", "2", "3", "2" }); 141 | df.AddColumn("y", new string[] { "a", "b", "c", "d" }); 142 | 143 | var g = df.GroupBy("x"); 144 | 145 | CollectionAssert.AreEqual(new object[] { "1", "2", "3" }, g.Keys); 146 | 147 | CollectionAssert.AreEqual(new string[] { "x", "y" }, g["1"].ColumnNames); 148 | CollectionAssert.AreEqual(new string[] { "x", "y" }, g["2"].ColumnNames); 149 | CollectionAssert.AreEqual(new string[] { "x", "y" }, g["3"].ColumnNames); 150 | 151 | CollectionAssert.AreEqual(new object[] { "1" }, g["1"].GetColumn("x").ToObjectArray()); 152 | CollectionAssert.AreEqual(new object[] { "a" }, g["1"].GetColumn("y").ToObjectArray()); 153 | 154 | CollectionAssert.AreEqual(new object[] { "2", "2" }, g["2"].GetColumn("x").ToObjectArray()); 155 | CollectionAssert.AreEqual(new object[] { "b", "d" }, g["2"].GetColumn("y").ToObjectArray()); 156 | 157 | CollectionAssert.AreEqual(new object[] { "3" }, g["3"].GetColumn("x").ToObjectArray()); 158 | CollectionAssert.AreEqual(new object[] { "c" }, g["3"].GetColumn("y").ToObjectArray()); 159 | } 160 | 161 | [TestMethod] 162 | public void TestPivot() 163 | { 164 | var df = new DataFrame(); 165 | 166 | df.AddColumn("x", new string[] { "a", "b", "a", "b", "c" }); 167 | df.AddColumn("y", new int[] { 10, 10, 20, 20, 20 }); 168 | df.AddColumn("v1", new double[] { 1, 2, 3, 4, 5 }); 169 | df.AddColumn("v2", new string[] { "foo", "bar", "baz", "qux", "quux" }); 170 | 171 | var p = df.Pivot("x", "y", new string[] { "v1", "v2" }); 172 | 173 | CollectionAssert.AreEqual(new string[] { "x", "10_v1", "10_v2", "20_v1", "20_v2" }, p.ColumnNames); 174 | Assert.AreEqual(3, p.RowCount); 175 | 176 | CollectionAssert.AreEqual(new object[] { "a", "b", "c" }, p["x"].ToObjectArray()); 177 | CollectionAssert.AreEqual(new object[] { 1.0, 2.0, 0.0 }, p["10_v1"].ToObjectArray()); 178 | CollectionAssert.AreEqual(new object[] { "baz", "qux", "quux" }, p["20_v2"].ToObjectArray()); 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /source/Tests/TestDataFrameColumn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using Horker.Math; 8 | using System.Management.Automation; 9 | 10 | namespace Tests 11 | { 12 | [TestClass] 13 | public class TestDataFrameColumn 14 | { 15 | [TestMethod] 16 | public void TestToDummyValues() 17 | { 18 | var v = new DataFrameColumn(null, new string[] { 19 | "a", 20 | "b", 21 | "a", 22 | "B", 23 | "C" 24 | }); 25 | 26 | DataFrame df = v.ToDummyValues("Code "); 27 | 28 | Assert.AreEqual(5, df.Count); 29 | 30 | Assert.AreEqual(0, df["Code b"].GetObject(0)); 31 | Assert.AreEqual(1, df["Code b"].GetObject(1)); 32 | Assert.AreEqual(0, df["Code b"].GetObject(2)); 33 | Assert.AreEqual(1, df["Code b"].GetObject(3)); 34 | Assert.AreEqual(0, df["Code b"].GetObject(4)); 35 | 36 | Assert.AreEqual(0, df["Code c"].GetObject(0)); 37 | Assert.AreEqual(0, df["Code c"].GetObject(1)); 38 | Assert.AreEqual(0, df["Code c"].GetObject(2)); 39 | Assert.AreEqual(0, df["Code c"].GetObject(3)); 40 | Assert.AreEqual(1, df["Code c"].GetObject(4)); 41 | } 42 | 43 | /* 44 | [TestMethod] 45 | public void TestOuter() 46 | { 47 | // |1| | (1 * 4) (1 * 5) | | 4 5 | 48 | // |2| x [ 4 5 ] = | (2 * 4) (2 * 5) | = | 8 10 | 49 | // |3| | (3 * 4) (3 * 5) | | 12 15 | 50 | 51 | var v1 = new Vector { 52 | 1, 2, 3 53 | }; 54 | var v2 = new Vector { 55 | 4, 5 56 | }; 57 | 58 | var df = v1.Outer(v2); 59 | 60 | Assert.AreEqual(df.RowCount, 3); 61 | Assert.AreEqual(df.ColumnCount, 2); 62 | 63 | Assert.AreEqual(df[0, 0], 1.0 * 4); 64 | Assert.AreEqual(df[1, 1], 2.0 * 5); 65 | Assert.AreEqual(df[2, 1], 3.0 * 5); 66 | } 67 | */ 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /source/Tests/TestDataTableMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using Horker.Math; 5 | using System.Management.Automation; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | 9 | namespace Tests 10 | { 11 | [TestClass] 12 | public class TestDataTable 13 | { 14 | [TestMethod] 15 | public void TestExpandToOneHot() 16 | { 17 | var table = new DataTable(); 18 | var column = new DataColumn("a") 19 | { 20 | DataType = typeof(Int32) 21 | }; 22 | table.Columns.Add(column); 23 | 24 | column = new DataColumn("b") 25 | { 26 | DataType = typeof(Int32), 27 | DefaultValue = 0 28 | }; 29 | table.Columns.Add(column); 30 | 31 | var row = table.NewRow(); 32 | row["a"] = 1; 33 | table.Rows.Add(row); 34 | 35 | row = table.NewRow(); 36 | row["a"] = 2; 37 | table.Rows.Add(row); 38 | 39 | row = table.NewRow(); 40 | row["a"] = 3; 41 | table.Rows.Add(row); 42 | 43 | table.ExpandToOneHot("a", 4); 44 | 45 | Assert.IsTrue(table.Columns.Contains("a_0")); 46 | Assert.IsTrue(table.Columns.Contains("a_1")); 47 | Assert.IsTrue(table.Columns.Contains("a_2")); 48 | Assert.IsTrue(table.Columns.Contains("a_3")); 49 | Assert.IsFalse(table.Columns.Contains("a_4")); 50 | 51 | Assert.AreEqual(0, table.Rows[0]["a_0"]); 52 | Assert.AreEqual(1, table.Rows[0]["a_1"]); 53 | Assert.AreEqual(0, table.Rows[0]["a_2"]); 54 | Assert.AreEqual(0, table.Rows[0]["a_3"]); 55 | 56 | Assert.AreEqual(0, table.Rows[1]["a_0"]); 57 | Assert.AreEqual(0, table.Rows[1]["a_1"]); 58 | Assert.AreEqual(1, table.Rows[1]["a_2"]); 59 | Assert.AreEqual(0, table.Rows[1]["a_3"]); 60 | 61 | Assert.AreEqual(0, table.Rows[2]["a_0"]); 62 | Assert.AreEqual(0, table.Rows[2]["a_1"]); 63 | Assert.AreEqual(0, table.Rows[2]["a_2"]); 64 | Assert.AreEqual(1, table.Rows[2]["a_3"]); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /source/Tests/TestNewMathMatrix.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using Horker.Math; 8 | using System.Management.Automation; 9 | 10 | namespace Tests 11 | { 12 | [TestClass] 13 | public class TestNewMathMatrix 14 | { 15 | [TestMethod] 16 | public void TestCreate() 17 | { 18 | using (var ps = PowerShell.Create()) { 19 | var ci = new CmdletInfo("New-Math.Matrix", typeof(NewMathMatrix)); 20 | ps.AddCommand(ci); 21 | ps.AddParameters(new object[] { new double[] { 1, 2, 3 }, 2, 3 }); 22 | var results = ps.Invoke(); 23 | 24 | Assert.AreEqual(1, results.Count); 25 | var matrix = (Matrix)results[0].BaseObject; 26 | 27 | Assert.AreEqual(2, matrix.Rows); 28 | Assert.AreEqual(3, matrix.Columns); 29 | Assert.AreEqual(2, matrix[0, 2]); 30 | } 31 | } 32 | 33 | [TestMethod] 34 | public void TestCreatePipeline() 35 | { 36 | using (var ps = PowerShell.Create()) { 37 | ps.AddScript("1,2,3"); 38 | var ci = new CmdletInfo("New-Math.Matrix", typeof(NewMathMatrix)); 39 | ps.AddCommand(ci); 40 | ps.AddParameters(new Dictionary() { 41 | { "Rows", 2 }, 42 | { "Columns", 3 } 43 | }); 44 | var results = ps.Invoke(); 45 | 46 | Assert.AreEqual(1, results.Count); 47 | var matrix = (Matrix)results[0].BaseObject; 48 | 49 | Assert.AreEqual(2, matrix.Rows); 50 | Assert.AreEqual(3, matrix.Columns); 51 | Assert.AreEqual(2, matrix[0, 2]); 52 | } 53 | } 54 | 55 | [TestMethod] 56 | public void TestAutosizing() 57 | { 58 | using (var ps = PowerShell.Create()) { 59 | var ci = new CmdletInfo("New-Math.Matrix", typeof(NewMathMatrix)); 60 | ps.AddCommand(ci); 61 | ps.AddParameters(new Dictionary() { 62 | { "Rows", 2 }, 63 | { "Values", new double[] { 1, 2, 3, 4, 5 } } 64 | }); 65 | var results = ps.Invoke(); 66 | 67 | Assert.AreEqual(1, results.Count); 68 | var matrix = (Matrix)results[0].BaseObject; 69 | 70 | Assert.AreEqual(2, matrix.Rows); 71 | Assert.AreEqual(3, matrix.Columns); 72 | Assert.AreEqual(5, matrix[0, 2]); 73 | } 74 | } 75 | 76 | [TestMethod] 77 | public void TestFromJaggedOfDouble() 78 | { 79 | using (var ps = PowerShell.Create()) { 80 | var ci = new CmdletInfo("New-Math.Matrix", typeof(NewMathMatrix)); 81 | ps.AddCommand(ci); 82 | ps.AddParameters(new Dictionary() { 83 | { "FromJagged", true }, 84 | { "Values", new double[][] { new double[] { 1, 2 }, new double[] { 3, 4, 5 } } } 85 | }); 86 | var results = ps.Invoke(); 87 | 88 | Assert.AreEqual(1, results.Count); 89 | var matrix = (Matrix)results[0].BaseObject; 90 | 91 | Assert.AreEqual(2, matrix.Rows); 92 | Assert.AreEqual(3, matrix.Columns); 93 | Assert.AreEqual(0, matrix[0, 2]); 94 | } 95 | } 96 | 97 | [TestMethod] 98 | public void TestFromJaggedOfObject() 99 | { 100 | using (var ps = PowerShell.Create()) { 101 | var ci = new CmdletInfo("New-Math.Matrix", typeof(NewMathMatrix)); 102 | ps.AddCommand(ci); 103 | ps.AddParameters(new Dictionary() { 104 | { "FromJagged", true }, 105 | { "Values", new object[][] { new object[] { 1, 2 }, new object[] { 3, 4, 5 } } } 106 | }); 107 | var results = ps.Invoke(); 108 | 109 | Assert.AreEqual(1, results.Count); 110 | var matrix = (Matrix)results[0].BaseObject; 111 | 112 | Assert.AreEqual(2, matrix.Rows); 113 | Assert.AreEqual(3, matrix.Columns); 114 | Assert.AreEqual(1, matrix[0, 0]); 115 | Assert.AreEqual(0, matrix[0, 2]); 116 | Assert.AreEqual(5, matrix[1, 2]); 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /source/Tests/TestNewMathSequence.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Collections.Generic; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using Horker.Math; 6 | using System.Management.Automation; 7 | 8 | namespace Tests 9 | { 10 | [TestClass] 11 | public class TestNewMathSequence 12 | { 13 | [TestMethod] 14 | public void TestSequence() 15 | { 16 | using (var ps = PowerShell.Create()) 17 | { 18 | var ci = new CmdletInfo("New-Math.Sequence", typeof(NewMathSequence)); 19 | ps.AddCommand(ci); 20 | ps.AddParameters(new object[] { 0, 10, 3 }); 21 | var results = ps.Invoke(); 22 | 23 | Assert.AreEqual(4, results.Count); 24 | 25 | Assert.AreEqual(0, results[0]); 26 | Assert.AreEqual(3, results[1]); 27 | Assert.AreEqual(6, results[2]); 28 | Assert.AreEqual(9, results[3]); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /source/Tests/Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9E4D2A29-5617-4807-BC37-5AE6938E0195} 8 | Library 9 | Properties 10 | Tests 11 | Tests 12 | v4.6.1 13 | 512 14 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 15.0 16 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 17 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 18 | False 19 | UnitTest 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | 42 | ..\packages\Accord.3.8.0\lib\net46\Accord.dll 43 | 44 | 45 | ..\packages\Accord.Math.3.8.0\lib\net46\Accord.Math.dll 46 | 47 | 48 | ..\packages\Accord.Math.3.8.0\lib\net46\Accord.Math.Core.dll 49 | 50 | 51 | ..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll 52 | 53 | 54 | ..\packages\MSTest.TestFramework.1.2.0\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll 55 | 56 | 57 | 58 | 59 | 60 | False 61 | ..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | {f4c2900e-adfe-4612-a40c-19393fc2ceff} 79 | Horker.Math 80 | 81 | 82 | 83 | 84 | 85 | 86 | このプロジェクトは、このコンピューター上にない NuGet パッケージを参照しています。それらのパッケージをダウンロードするには、[NuGet パッケージの復元] を使用します。詳細については、http://go.microsoft.com/fwlink/?LinkID=322105 を参照してください。見つからないファイルは {0} です。 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /source/Tests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /tools/Publish.ps1: -------------------------------------------------------------------------------- 1 | $key = cat private\NugetApiKey.txt 2 | 3 | Publish-Module -Path $PSScriptRoot\..\psmath -NugetApiKey $key -Verbose 4 | --------------------------------------------------------------------------------