v0.2.0 #206

Merged
altavir merged 210 commits from dev into master 2021-02-21 16:33:25 +03:00
22 changed files with 0 additions and 1939 deletions
Showing only changes of commit e8de7c5fb3 - Show all commits

View File

@ -1,9 +0,0 @@
plugins {
`kotlin-dsl`
}
repositories.jcenter()
dependencies {
implementation(kotlin("compiler-embeddable", "1.4.30"))
}

View File

@ -1,73 +0,0 @@
package kscience.kmath.gsl.codegen
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.com.intellij.psi.PsiFile
import org.jetbrains.kotlin.com.intellij.psi.impl.DebugUtil
import org.jetbrains.kotlin.com.intellij.psi.impl.source.PsiFileImpl
import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.psi.KtFile
import java.util.regex.Pattern
import kotlin.math.min
private val EOL_SPLIT_DONT_TRIM_PATTERN: Pattern = Pattern.compile("(\r|\n|\r\n)+")
internal fun splitByLinesDontTrim(string: String): Array<String> = EOL_SPLIT_DONT_TRIM_PATTERN.split(string)
internal object PsiTestUtil {
fun checkFileStructure(file: KtFile) {
compareFromAllRoots(file) { f -> DebugUtil.psiTreeToString(f, false) }
}
private fun compareFromAllRoots(
file: KtFile,
function: (PsiFile) -> String
) {
val dummyFile = createDummyCopy(file)
val psiTree = StringUtil.join(
file.viewProvider.allFiles,
{ param -> function(param) },
"\n"
)
val reparsedTree = StringUtil.join(
dummyFile.viewProvider.allFiles,
{ param -> function(param) },
"\n"
)
assertPsiTextTreeConsistency(psiTree, reparsedTree)
}
private fun assertPsiTextTreeConsistency(psiTree: String, reparsedTree: String) {
var psiTreeMutable = psiTree
var reparsedTreeMutable = reparsedTree
if (psiTreeMutable != reparsedTreeMutable) {
val psiLines = splitByLinesDontTrim(psiTreeMutable)
val reparsedLines = splitByLinesDontTrim(reparsedTreeMutable)
var i = 0
while (true) {
if (i >= psiLines.size || i >= reparsedLines.size || psiLines[i] != reparsedLines[i]) {
psiLines[min(i, psiLines.size - 1)] += " // in PSI structure"
reparsedLines[min(i, reparsedLines.size - 1)] += " // re-created from text"
break
}
i++
}
psiTreeMutable = StringUtil.join(*psiLines, "\n")
reparsedTreeMutable = StringUtil.join(*reparsedLines, "\n")
assert(reparsedTreeMutable == psiTreeMutable)
}
}
private fun createDummyCopy(file: KtFile): PsiFile {
val copy = LightVirtualFile(file.name, file.text)
copy.originalFile = file.viewProvider.virtualFile
val dummyCopy = requireNotNull(file.manager.findFile(copy))
if (dummyCopy is PsiFileImpl) dummyCopy.originalFile = file
return dummyCopy
}
}

View File

@ -1,70 +0,0 @@
package kscience.kmath.gsl.codegen
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.mock.MockProject
import org.jetbrains.kotlin.com.intellij.openapi.extensions.ExtensionPoint
import org.jetbrains.kotlin.com.intellij.openapi.extensions.Extensions
import org.jetbrains.kotlin.com.intellij.openapi.util.UserDataHolderBase
import org.jetbrains.kotlin.com.intellij.pom.PomModel
import org.jetbrains.kotlin.com.intellij.pom.PomModelAspect
import org.jetbrains.kotlin.com.intellij.pom.PomTransaction
import org.jetbrains.kotlin.com.intellij.pom.impl.PomTransactionBase
import org.jetbrains.kotlin.com.intellij.pom.tree.TreeAspect
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.TreeCopyHandler
import org.jetbrains.kotlin.config.CompilerConfiguration
import sun.reflect.ReflectionFactory
internal fun createProject(): MockProject {
val project = KotlinCoreEnvironment.createForProduction(
{},
CompilerConfiguration().apply { put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE) },
EnvironmentConfigFiles.JVM_CONFIG_FILES
).project as MockProject
val extensionPoint = "org.jetbrains.kotlin.com.intellij.treeCopyHandler"
arrayOf(project.extensionArea, Extensions.getRootArea())
.asSequence()
.filterNot { it.hasExtensionPoint(extensionPoint) }
.forEach {
it.registerExtensionPoint(extensionPoint, TreeCopyHandler::class.java.name, ExtensionPoint.Kind.INTERFACE)
}
project.registerService(PomModel::class.java, object : UserDataHolderBase(), PomModel {
override fun runTransaction(transaction: PomTransaction) = (transaction as PomTransactionBase).run()
@Suppress("UNCHECKED_CAST")
override fun <T : PomModelAspect> getModelAspect(aspect: Class<T>): T? {
if (aspect == TreeAspect::class.java) {
val constructor = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(
aspect,
Any::class.java.getDeclaredConstructor(*arrayOfNulls(0))
)
return constructor.newInstance() as T
}
return null
}
})
return project
}
internal operator fun PsiElement.plusAssign(e: PsiElement) {
add(e)
}
internal fun fn(pattern: String, type: String): String {
if (type == "double") return pattern.replace("R", "_")
return pattern.replace("R", "_${type}_")
}
internal fun sn(pattern: String, type: String): String {
if (type == "double") return pattern.replace("R", "")
return pattern.replace("R", "_$type")
}

View File

@ -1,106 +0,0 @@
package kscience.kmath.gsl.codegen
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.com.intellij.openapi.project.Project
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.ImportPath
import java.io.File
private fun KtPsiFactory.createMatrixClass(
f: KtFile,
cTypeName: String,
kotlinTypeName: String,
kotlinTypeAlias: String = kotlinTypeName
) {
fun fn(pattern: String) = fn(pattern, cTypeName)
val className = "Gsl${kotlinTypeAlias}Matrix"
val structName = sn("gsl_matrixR", cTypeName)
@Language("kotlin") val text = """internal class $className(
override val rawNativeHandle: CPointer<$structName>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<$kotlinTypeName, $structName>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<$kotlinTypeName>>
get() = VirtualBuffer(rowNum) { r ->
Gsl${kotlinTypeAlias}Vector(
${fn("gsl_matrixRrow")}(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<$kotlinTypeName>>
get() = VirtualBuffer(rowNum) { c ->
Gsl${kotlinTypeAlias}Vector(
${fn("gsl_matrixRcolumn")}(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): $kotlinTypeName =
${fn("gsl_matrixRget")}(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: ${kotlinTypeName}): Unit =
${fn("gsl_matrixRset")}(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): $className {
val new = checkNotNull(${fn("gsl_matrixRalloc")}(rowNum.toULong(), colNum.toULong()))
${fn("gsl_matrixRmemcpy")}(new, nativeHandle)
return $className(new, scope, true)
}
override fun close(): Unit = ${fn("gsl_matrixRfree")}(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is $className)
return ${fn("gsl_matrixRequal")}(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}"""
f += createClass(text)
f += createNewLine(2)
}
/**
* Generates matrices source code for kmath-gsl.
*/
fun matricesCodegen(outputFile: String, project: Project = createProject()) {
val f = KtPsiFactory(project, true).run {
createFile("").also { f ->
f += createPackageDirective(FqName("kscience.kmath.gsl"))
f += createNewLine(2)
f += createImportDirective(ImportPath.fromString("kotlinx.cinterop.*"))
f += createNewLine(1)
f += createImportDirective(ImportPath.fromString("kscience.kmath.structures.*"))
f += createNewLine(1)
f += createImportDirective(ImportPath.fromString("org.gnu.gsl.*"))
f += createNewLine(2)
createMatrixClass(f, "double", "Double", "Real")
createMatrixClass(f, "float", "Float")
createMatrixClass(f, "short", "Short")
createMatrixClass(f, "ushort", "UShort")
createMatrixClass(f, "long", "Long")
createMatrixClass(f, "ulong", "ULong")
createMatrixClass(f, "int", "Int")
createMatrixClass(f, "uint", "UInt")
}
}
PsiTestUtil.checkFileStructure(f)
File(outputFile).apply {
parentFile.mkdirs()
writeText(f.text)
}
}

View File

@ -1,80 +0,0 @@
package kscience.kmath.gsl.codegen
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.com.intellij.openapi.project.Project
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.ImportPath
import java.io.File
private fun KtPsiFactory.createVectorClass(
f: KtFile,
cTypeName: String,
kotlinTypeName: String,
kotlinTypeAlias: String = kotlinTypeName
) {
fun fn(pattern: String) = fn(pattern, cTypeName)
val className = "Gsl${kotlinTypeAlias}Vector"
val structName = sn("gsl_vectorR", cTypeName)
@Language("kotlin") val text =
"""internal class $className(
override val rawNativeHandle: CPointer<$structName>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<$kotlinTypeName, $structName>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): $kotlinTypeName = ${fn("gsl_vectorRget")}(nativeHandle, index.toULong())
override operator fun set(index: Int, value: $kotlinTypeName): Unit = ${fn("gsl_vectorRset")}(nativeHandle, index.toULong(), value)
override fun copy(): $className {
val new = checkNotNull(${fn("gsl_vectorRalloc")}(size.toULong()))
${fn("gsl_vectorRmemcpy")}(new, nativeHandle)
return ${className}(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is $className)
return ${fn("gsl_vectorRequal")}(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = ${fn("gsl_vectorRfree")}(nativeHandle)
}"""
f += createClass(text)
f += createNewLine(2)
}
/**
* Generates vectors source code for kmath-gsl.
*/
fun vectorsCodegen(outputFile: String, project: Project = createProject()) {
val f = KtPsiFactory(project, true).run {
createFile("").also { f ->
f += createPackageDirective(FqName("kscience.kmath.gsl"))
f += createNewLine(2)
f += createImportDirective(ImportPath.fromString("kotlinx.cinterop.*"))
f += createNewLine(1)
f += createImportDirective(ImportPath.fromString("org.gnu.gsl.*"))
f += createNewLine(2)
createVectorClass(f, "double", "Double", "Real")
createVectorClass(f, "float", "Float")
createVectorClass(f, "short", "Short")
createVectorClass(f, "ushort", "UShort")
createVectorClass(f, "long", "Long")
createVectorClass(f, "ulong", "ULong")
createVectorClass(f, "int", "Int")
createVectorClass(f, "uint", "UInt")
}
}
PsiTestUtil.checkFileStructure(f)
File(outputFile).apply {
parentFile.mkdirs()
writeText(f.text)
}
}

View File

@ -1,44 +0,0 @@
# GNU Scientific Library Integration (`kmath-core`)
This subproject implements the following features:
- [matrix-contexts](src/nativeMain/kotlin/kscience/kmath/gsl/GslMatrixContext.kt) : Matrix Contexts over Double, Float and Complex implemented with GSL
> #### Artifact:
>
> This module artifact: `kscience.kmath:kmath-gsl:0.2.0-dev-6`.
>
> Bintray release version: [ ![Download](https://api.bintray.com/packages/mipt-npm/kscience/kmath-gsl/images/download.svg) ](https://bintray.com/mipt-npm/kscience/kmath-gsl/_latestVersion)
>
> Bintray development version: [ ![Download](https://api.bintray.com/packages/mipt-npm/dev/kmath-gsl/images/download.svg) ](https://bintray.com/mipt-npm/dev/kmath-gsl/_latestVersion)
>
> **Gradle:**
>
> ```gradle
> repositories {
> maven { url "https://dl.bintray.com/kotlin/kotlin-eap" }
> maven { url 'https://dl.bintray.com/mipt-npm/kscience' }
> maven { url 'https://dl.bintray.com/mipt-npm/dev' }
> maven { url 'https://dl.bintray.com/hotkeytlt/maven' }
>
> }
>
> dependencies {
> implementation 'kscience.kmath:kmath-gsl:0.2.0-dev-6'
> }
> ```
> **Gradle Kotlin DSL:**
>
> ```kotlin
> repositories {
> maven("https://dl.bintray.com/kotlin/kotlin-eap")
> maven("https://dl.bintray.com/mipt-npm/kscience")
> maven("https://dl.bintray.com/mipt-npm/dev")
> maven("https://dl.bintray.com/hotkeytlt/maven")
> }
>
> dependencies {
> implementation("kscience.kmath:kmath-gsl:0.2.0-dev-6")
> }
> ```

View File

@ -1,73 +0,0 @@
@file:Suppress("UNUSED_VARIABLE")
import kscience.kmath.gsl.codegen.matricesCodegen
import kscience.kmath.gsl.codegen.vectorsCodegen
import ru.mipt.npm.gradle.Maturity
plugins {
id("ru.mipt.npm.mpp")
id("de.undercouch.download")
}
kotlin {
explicitApiWarning()
data class DownloadLinks(val gsl: String)
lateinit var downloadLinks: DownloadLinks
val nativeTarget = when (System.getProperty("os.name")) {
// "Mac OS X" -> macosX64()
"Linux" -> {
downloadLinks = DownloadLinks(gsl = "")
linuxX64()
}
else -> {
logger.warn("Current OS cannot build any of kmath-gsl targets.")
return@kotlin
}
}
val main by nativeTarget.compilations.getting {
cinterops {
val libgsl by creating
}
}
val test by nativeTarget.compilations.getting
sourceSets {
val nativeMain by creating {
val codegen by tasks.creating {
matricesCodegen(kotlin.srcDirs.first().absolutePath + "/kscience/kmath/gsl/_Matrices.kt")
vectorsCodegen(kotlin.srcDirs.first().absolutePath + "/kscience/kmath/gsl/_Vectors.kt")
}
kotlin.srcDirs(files().builtBy(codegen))
dependencies {
api(project(":kmath-complex"))
api(project(":kmath-core"))
}
}
val nativeTest by creating {
dependsOn(nativeMain)
}
main.defaultSourceSet.dependsOn(nativeMain)
test.defaultSourceSet.dependsOn(nativeTest)
}
}
readme {
description = "Linear Algebra classes implemented with GNU Scientific Library"
maturity = Maturity.PROTOTYPE
propertyByTemplate("artifact", rootProject.file("docs/templates/ARTIFACT-TEMPLATE.md"))
feature(
id = "matrix-contexts",
description = "Matrix Contexts over Double, Float and Complex implemented with GSL",
ref = "src/nativeMain/kotlin/kscience/kmath/gsl/GslMatrixContext.kt"
)
}

View File

@ -1,7 +0,0 @@
# GNU Scientific Library Integration (`kmath-core`)
This subproject implements the following features:
${features}
${artifact}

View File

@ -1,6 +0,0 @@
package=org.gnu.gsl
headers=gsl/gsl_blas.h gsl/gsl_linalg.h gsl/gsl_permute_matrix.h
compilerOpts.linux=-I/usr/include
compilerOpts.osx=-I/usr/local -I/usr/local/include
linkerOpts.linux=-L/usr/lib64 -L/usr/lib/x86_64-linux-gnu -lgsl
linkerOpts.osx=-L/opt/local/lib -L/usr/local/lib -lgsl

View File

@ -1,89 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.*
import kscience.kmath.complex.Complex
import kscience.kmath.structures.Buffer
import kscience.kmath.structures.VirtualBuffer
import org.gnu.gsl.*
internal fun CValue<gsl_complex>.toKMath(): Complex = useContents { Complex(dat[0], dat[1]) }
internal fun Complex.toGsl(): CValue<gsl_complex> = cValue {
dat[0] = re
dat[1] = im
}
internal class GslComplexMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_complex>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Complex, gsl_matrix_complex>(scope, owned) {
override val rowNum: Int get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Complex>>
get() = VirtualBuffer(rowNum) { r ->
GslComplexVector(
gsl_matrix_complex_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Complex>>
get() = VirtualBuffer(rowNum) { c ->
GslComplexVector(
gsl_matrix_complex_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Complex =
gsl_matrix_complex_get(nativeHandle, i.toULong(), j.toULong()).toKMath()
override operator fun set(i: Int, j: Int, value: Complex): Unit =
gsl_matrix_complex_set(nativeHandle, i.toULong(), j.toULong(), value.toGsl())
override fun copy(): GslComplexMatrix {
val new = checkNotNull(gsl_matrix_complex_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_complex_memcpy(new, nativeHandle)
return GslComplexMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_complex_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslComplexMatrix)
return gsl_matrix_complex_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslComplexVector(
override val rawNativeHandle: CPointer<gsl_vector_complex>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Complex, gsl_vector_complex>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override fun get(index: Int): Complex = gsl_vector_complex_get(nativeHandle, index.toULong()).toKMath()
override fun set(index: Int, value: Complex): Unit =
gsl_vector_complex_set(nativeHandle, index.toULong(), value.toGsl())
override fun copy(): GslComplexVector {
val new = checkNotNull(gsl_vector_complex_alloc(size.toULong()))
gsl_vector_complex_memcpy(new, nativeHandle)
return GslComplexVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslComplexVector)
return gsl_vector_complex_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_complex_free(nativeHandle)
}

View File

@ -1,73 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.staticCFunction
import kotlinx.cinterop.toKString
import org.gnu.gsl.gsl_set_error_handler
import org.gnu.gsl.gsl_set_error_handler_off
import kotlin.native.concurrent.AtomicInt
private object Container {
val isKmathHandlerRegistered = AtomicInt(0)
}
internal enum class GslErrnoValue(val code: Int, val text: String) {
GSL_SUCCESS(org.gnu.gsl.GSL_SUCCESS, ""),
GSL_FAILURE(org.gnu.gsl.GSL_FAILURE, ""),
GSL_CONTINUE(org.gnu.gsl.GSL_CONTINUE, "iteration has not converged"),
GSL_EDOM(org.gnu.gsl.GSL_EDOM, "input domain error, e.g sqrt(-1)"),
GSL_ERANGE(org.gnu.gsl.GSL_ERANGE, "output range error, e.g. exp(1e100)"),
GSL_EFAULT(org.gnu.gsl.GSL_EFAULT, "invalid pointer"),
GSL_EINVAL(org.gnu.gsl.GSL_EINVAL, "invalid argument supplied by user"),
GSL_EFAILED(org.gnu.gsl.GSL_EFAILED, "generic failure"),
GSL_EFACTOR(org.gnu.gsl.GSL_EFACTOR, "factorization failed"),
GSL_ESANITY(org.gnu.gsl.GSL_ESANITY, "sanity check failed - shouldn't happen"),
GSL_ENOMEM(org.gnu.gsl.GSL_ENOMEM, "malloc failed"),
GSL_EBADFUNC(org.gnu.gsl.GSL_EBADFUNC, "problem with user-supplied function"),
GSL_ERUNAWAY(org.gnu.gsl.GSL_ERUNAWAY, "iterative process is out of control"),
GSL_EMAXITER(org.gnu.gsl.GSL_EMAXITER, "exceeded max number of iterations"),
GSL_EZERODIV(org.gnu.gsl.GSL_EZERODIV, "tried to divide by zero"),
GSL_EBADTOL(org.gnu.gsl.GSL_EBADTOL, "user specified an invalid tolerance"),
GSL_ETOL(org.gnu.gsl.GSL_ETOL, "failed to reach the specified tolerance"),
GSL_EUNDRFLW(org.gnu.gsl.GSL_EUNDRFLW, "underflow"),
GSL_EOVRFLW(org.gnu.gsl.GSL_EOVRFLW, "overflow"),
GSL_ELOSS(org.gnu.gsl.GSL_ELOSS, "loss of accuracy"),
GSL_EROUND(org.gnu.gsl.GSL_EROUND, "failed because of roundoff error"),
GSL_EBADLEN(org.gnu.gsl.GSL_EBADLEN, "matrix, vector lengths are not conformant"),
GSL_ENOTSQR(org.gnu.gsl.GSL_ENOTSQR, "matrix not square"),
GSL_ESING(org.gnu.gsl.GSL_ESING, "apparent singularity detected"),
GSL_EDIVERGE(org.gnu.gsl.GSL_EDIVERGE, "integral or series is divergent"),
GSL_EUNSUP(org.gnu.gsl.GSL_EUNSUP, "requested feature is not supported by the hardware"),
GSL_EUNIMPL(org.gnu.gsl.GSL_EUNIMPL, "requested feature not (yet) implemented"),
GSL_ECACHE(org.gnu.gsl.GSL_ECACHE, "cache limit exceeded"),
GSL_ETABLE(org.gnu.gsl.GSL_ETABLE, "table limit exceeded"),
GSL_ENOPROG(org.gnu.gsl.GSL_ENOPROG, "iteration is not making progress towards solution"),
GSL_ENOPROGJ(org.gnu.gsl.GSL_ENOPROGJ, "jacobian evaluations are not improving the solution"),
GSL_ETOLF(org.gnu.gsl.GSL_ETOLF, "cannot reach the specified tolerance in F"),
GSL_ETOLX(org.gnu.gsl.GSL_ETOLX, "cannot reach the specified tolerance in X"),
GSL_ETOLG(org.gnu.gsl.GSL_ETOLG, "cannot reach the specified tolerance in gradient"),
GSL_EOF(org.gnu.gsl.GSL_EOF, "end of file");
override fun toString(): String = "${name}('$text')"
companion object {
fun valueOf(code: Int): GslErrnoValue? = values().find { it.code == code }
}
}
/**
* Wraps all the errors reported by GSL.
*/
public class GslException internal constructor(file: String, line: Int, reason: String, errno: Int) :
RuntimeException("$file:$line: $reason. errno - $errno, ${GslErrnoValue.valueOf(errno)}") {
}
internal fun ensureHasGslErrorHandler() {
if (Container.isKmathHandlerRegistered.value == 1) return
gsl_set_error_handler_off()
gsl_set_error_handler(staticCFunction { reason, file, line, errno ->
throw GslException(checkNotNull(file).toKString(), line, checkNotNull(reason).toKString(), errno)
})
Container.isKmathHandlerRegistered.value = 1
}

View File

@ -1,40 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.AutofreeScope
import kotlinx.cinterop.CStructVar
import kscience.kmath.linear.Matrix
import kscience.kmath.nd.NDStructure
import kscience.kmath.structures.asSequence
/**
* Wraps gsl_matrix_* objects from GSL.
*/
public abstract class GslMatrix<T : Any, H : CStructVar> internal constructor(scope: AutofreeScope, owned: Boolean) :
GslObject<H>(scope, owned), Matrix<T> {
internal abstract operator fun set(i: Int, j: Int, value: T)
internal abstract fun copy(): GslMatrix<T, H>
public override fun equals(other: Any?): Boolean {
return NDStructure.contentEquals(this, other as? NDStructure<*> ?: return false)
}
public override fun hashCode(): Int {
var ret = 7
ret = ret * 31 + rowNum
ret = ret * 31 + colNum
for (row in 0 until rowNum)
for (col in 0 until colNum)
ret = ret * 31 + (11 * (row + 1) + 17 * (col + 1)) * this[row, col].hashCode()
return ret
}
public override fun toString(): String = if (rowNum <= 5 && colNum <= 5)
"Matrix(rowsNum = $rowNum, colNum = $colNum)\n" +
rows.asSequence().joinToString(prefix = "(", postfix = ")", separator = "\n ") { buffer ->
buffer.asSequence().joinToString(separator = "\t") { it.toString() }
}
else
"Matrix(rowsNum = $rowNum, colNum = $colNum)"
}

View File

@ -1,417 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.*
import kscience.kmath.linear.*
import kscience.kmath.misc.UnstableKMathAPI
import kscience.kmath.complex.Complex
import kscience.kmath.complex.ComplexField
import kscience.kmath.complex.toComplex
import org.gnu.gsl.*
import kotlin.math.min
import kotlin.reflect.KClass
import kotlin.reflect.cast
internal inline fun <T : Any, H : CStructVar> GslMatrix<T, H>.fill(initializer: (Int, Int) -> T): GslMatrix<T, H> =
apply {
for (row in 0 until rowNum) {
for (col in 0 until colNum) this[row, col] = initializer(row, col)
}
}
internal inline fun <T : Any, H : CStructVar> GslVector<T, H>.fill(initializer: (Int) -> T): GslVector<T, H> =
apply {
for (index in 0 until size) this[index] = initializer(index)
}
/**
* Represents matrix context implementing where all the operations are delegated to GSL.
*/
public abstract class GslMatrixContext<T : Any, H1 : CStructVar, H2 : CStructVar> : MatrixContext<T, GslMatrix<T, H1>> {
init {
ensureHasGslErrorHandler()
}
/**
* Converts this matrix to GSL one.
*/
@Suppress("UNCHECKED_CAST")
public fun Matrix<T>.toGsl(): GslMatrix<T, H1> = if (this is GslMatrix<*, *>)
this as GslMatrix<T, H1>
else
produce(rowNum, colNum) { i, j -> this[i, j] }
/**
* Converts this point to GSL one.
*/
@Suppress("UNCHECKED_CAST")
public fun Point<T>.toGsl(): GslVector<T, H2> =
(if (this is GslVector<*, *>) this as GslVector<T, H2> else produceDirtyVector(size).fill { this[it] }).copy()
internal abstract fun produceDirtyMatrix(rows: Int, columns: Int): GslMatrix<T, H1>
internal abstract fun produceDirtyVector(size: Int): GslVector<T, H2>
public override fun produce(rows: Int, columns: Int, initializer: (i: Int, j: Int) -> T): GslMatrix<T, H1> =
produceDirtyMatrix(rows, columns).fill(initializer)
public override fun point(size: Int, initializer: (Int) -> T): GslVector<T, H2> =
produceDirtyVector(size).fill(initializer)
}
/**
* Represents [Double] matrix context implementing where all the operations are delegated to GSL.
*/
public class GslRealMatrixContext(internal val scope: AutofreeScope) :
GslMatrixContext<Double, gsl_matrix, gsl_vector>() {
override fun produceDirtyMatrix(rows: Int, columns: Int): GslMatrix<Double, gsl_matrix> = GslRealMatrix(
rawNativeHandle = checkNotNull(gsl_matrix_alloc(rows.toULong(), columns.toULong())),
scope = scope,
owned = true,
)
override fun produceDirtyVector(size: Int): GslVector<Double, gsl_vector> =
GslRealVector(rawNativeHandle = checkNotNull(gsl_vector_alloc(size.toULong())), scope = scope, owned = true)
public override fun Matrix<Double>.dot(other: Matrix<Double>): GslMatrix<Double, gsl_matrix> {
val x = toGsl().nativeHandle
val a = other.toGsl().nativeHandle
val result = checkNotNull(gsl_matrix_calloc(a.pointed.size1, a.pointed.size2))
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, x, a, 1.0, result)
return GslRealMatrix(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Double>.dot(vector: Point<Double>): GslVector<Double, gsl_vector> {
val x = toGsl().nativeHandle
val a = vector.toGsl().nativeHandle
val result = checkNotNull(gsl_vector_calloc(a.pointed.size))
gsl_blas_dgemv(CblasNoTrans, 1.0, x, a, 1.0, result)
return GslRealVector(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Double>.times(value: Double): GslMatrix<Double, gsl_matrix> {
val g1 = toGsl().copy()
gsl_matrix_scale(g1.nativeHandle, value)
return g1
}
public override fun add(a: Matrix<Double>, b: Matrix<Double>): GslMatrix<Double, gsl_matrix> {
val g1 = a.toGsl().copy()
gsl_matrix_add(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
public override fun multiply(a: Matrix<Double>, k: Number): GslMatrix<Double, gsl_matrix> {
val g1 = a.toGsl().copy()
gsl_matrix_scale(g1.nativeHandle, k.toDouble())
return g1
}
public override fun Matrix<Double>.minus(b: Matrix<Double>): Matrix<Double> {
val g1 = toGsl().copy()
gsl_matrix_sub(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
@Suppress("IMPLICIT_CAST_TO_ANY")
@UnstableKMathAPI
public override fun <F : Any> getFeature(m: Matrix<Double>, type: KClass<F>): F? = when (type) {
LupDecompositionFeature::class, DeterminantFeature::class -> object : LupDecompositionFeature<Double>,
DeterminantFeature<Double>, InverseMatrixFeature<Double> {
private val lups by lazy {
val lu = m.toGsl().copy()
val n = m.rowNum
val perm = GslPermutation(
rawNativeHandle = checkNotNull(gsl_permutation_alloc(n.toULong())),
scope = scope,
owned = true,
)
val signum = memScoped {
val i = alloc<IntVar>()
gsl_linalg_LU_decomp(lu.nativeHandle, perm.nativeHandle, i.ptr)
i.value
}
Triple(lu, perm, signum)
}
override val p by lazy {
val n = m.rowNum
val one = produce(n, n) { i, j -> if (i == j) 1.0 else 0.0 }
val perm = produce(n, n) { _, _ -> 0.0 }
for (j in 0 until lups.second.size)
gsl_matrix_set_col(perm.nativeHandle, j.toULong(), one.columns[lups.second[j]].toGsl().nativeHandle)
perm
}
override val l by lazy {
VirtualMatrix(lups.first.shape[0], lups.first.shape[1]) { i, j ->
when {
j < i -> lups.first[i, j]
j == i -> 1.0
else -> 0.0
}
} + LFeature
}
override val u by lazy {
VirtualMatrix(
lups.first.shape[0],
lups.first.shape[1],
) { i, j -> if (j >= i) lups.first[i, j] else 0.0 } + UFeature
}
override val determinant by lazy { gsl_linalg_LU_det(lups.first.nativeHandle, lups.third) }
override val inverse by lazy {
val inv = lups.first.copy()
gsl_linalg_LU_invx(inv.nativeHandle, lups.second.nativeHandle)
inv
}
}
CholeskyDecompositionFeature::class -> object : CholeskyDecompositionFeature<Double> {
override val l: Matrix<Double> by lazy {
val chol = m.toGsl().copy()
gsl_linalg_cholesky_decomp(chol.nativeHandle)
chol
}
}
QRDecompositionFeature::class -> object : QRDecompositionFeature<Double> {
private val qr by lazy {
val a = m.toGsl().copy()
val q = produce(m.rowNum, m.rowNum) { _, _ -> 0.0 }
val r = produce(m.rowNum, m.colNum) { _, _ -> 0.0 }
if (m.rowNum < m.colNum) {
val tau = point(min(m.rowNum, m.colNum)) { 0.0 }
gsl_linalg_QR_decomp(a.nativeHandle, tau.nativeHandle)
gsl_linalg_QR_unpack(a.nativeHandle, tau.nativeHandle, q.nativeHandle, r.nativeHandle)
} else {
val t = produce(m.colNum, m.colNum) { _, _ -> 0.0 }
gsl_linalg_QR_decomp_r(a.nativeHandle, t.nativeHandle)
gsl_linalg_QR_unpack_r(a.nativeHandle, t.nativeHandle, q.nativeHandle, r.nativeHandle)
}
q to r
}
override val q: Matrix<Double> get() = qr.first
override val r: Matrix<Double> get() = qr.second
}
else -> super.getFeature(m, type)
}?.let(type::cast)
}
/**
* Invokes [block] inside newly created [GslRealMatrixContext] which is disposed when the block is invoked.
*/
public fun <R> GslRealMatrixContext(block: GslRealMatrixContext.() -> R): R =
memScoped { GslRealMatrixContext(this).block() }
/**
* Represents [Float] matrix context implementing where all the operations are delegated to GSL.
*/
public class GslFloatMatrixContext(internal val scope: AutofreeScope) :
GslMatrixContext<Float, gsl_matrix_float, gsl_vector_float>() {
override fun produceDirtyMatrix(rows: Int, columns: Int): GslMatrix<Float, gsl_matrix_float> = GslFloatMatrix(
rawNativeHandle = checkNotNull(gsl_matrix_float_alloc(rows.toULong(), columns.toULong())),
scope = scope,
owned = true,
)
override fun produceDirtyVector(size: Int): GslVector<Float, gsl_vector_float> = GslFloatVector(
rawNativeHandle = checkNotNull(value = gsl_vector_float_alloc(size.toULong())),
scope = scope,
owned = true,
)
public override fun Matrix<Float>.dot(other: Matrix<Float>): GslMatrix<Float, gsl_matrix_float> {
val x = toGsl().nativeHandle
val a = other.toGsl().nativeHandle
val result = checkNotNull(gsl_matrix_float_calloc(a.pointed.size1, a.pointed.size2))
gsl_blas_sgemm(CblasNoTrans, CblasNoTrans, 1f, x, a, 1f, result)
return GslFloatMatrix(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Float>.dot(vector: Point<Float>): GslVector<Float, gsl_vector_float> {
val x = toGsl().nativeHandle
val a = vector.toGsl().nativeHandle
val result = checkNotNull(gsl_vector_float_calloc(a.pointed.size))
gsl_blas_sgemv(CblasNoTrans, 1f, x, a, 1f, result)
return GslFloatVector(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Float>.times(value: Float): GslMatrix<Float, gsl_matrix_float> {
val g1 = toGsl().copy()
gsl_matrix_float_scale(g1.nativeHandle, value.toDouble())
return g1
}
public override fun add(a: Matrix<Float>, b: Matrix<Float>): GslMatrix<Float, gsl_matrix_float> {
val g1 = a.toGsl().copy()
gsl_matrix_float_add(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
public override fun multiply(a: Matrix<Float>, k: Number): GslMatrix<Float, gsl_matrix_float> {
val g1 = a.toGsl().copy()
gsl_matrix_float_scale(g1.nativeHandle, k.toDouble())
return g1
}
public override fun Matrix<Float>.minus(b: Matrix<Float>): Matrix<Float> {
val g1 = toGsl().copy()
gsl_matrix_float_sub(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
}
/**
* Invokes [block] inside newly created [GslFloatMatrixContext] which is disposed when the block is invoked.
*/
public fun <R> GslFloatMatrixContext(block: GslFloatMatrixContext.() -> R): R =
memScoped { GslFloatMatrixContext(this).block() }
/**
* Represents [Complex] matrix context implementing where all the operations are delegated to GSL.
*/
public class GslComplexMatrixContext(internal val scope: AutofreeScope) :
GslMatrixContext<Complex, gsl_matrix_complex, gsl_vector_complex>() {
override fun produceDirtyMatrix(rows: Int, columns: Int): GslMatrix<Complex, gsl_matrix_complex> = GslComplexMatrix(
rawNativeHandle = checkNotNull(gsl_matrix_complex_alloc(rows.toULong(), columns.toULong())),
scope = scope,
owned = true,
)
override fun produceDirtyVector(size: Int): GslVector<Complex, gsl_vector_complex> =
GslComplexVector(
rawNativeHandle = checkNotNull(gsl_vector_complex_alloc(size.toULong())),
scope = scope,
owned = true,
)
public override fun Matrix<Complex>.dot(other: Matrix<Complex>): GslMatrix<Complex, gsl_matrix_complex> {
val x = toGsl().nativeHandle
val a = other.toGsl().nativeHandle
val result = checkNotNull(gsl_matrix_complex_calloc(a.pointed.size1, a.pointed.size2))
gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, ComplexField.one.toGsl(), x, a, ComplexField.one.toGsl(), result)
return GslComplexMatrix(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Complex>.dot(vector: Point<Complex>): GslVector<Complex, gsl_vector_complex> {
val x = toGsl().nativeHandle
val a = vector.toGsl().nativeHandle
val result = checkNotNull(gsl_vector_complex_calloc(a.pointed.size))
gsl_blas_zgemv(CblasNoTrans, ComplexField.one.toGsl(), x, a, ComplexField.one.toGsl(), result)
return GslComplexVector(rawNativeHandle = result, scope = scope, owned = true)
}
public override fun Matrix<Complex>.times(value: Complex): GslMatrix<Complex, gsl_matrix_complex> {
val g1 = toGsl().copy()
gsl_matrix_complex_scale(g1.nativeHandle, value.toGsl())
return g1
}
public override fun add(a: Matrix<Complex>, b: Matrix<Complex>): GslMatrix<Complex, gsl_matrix_complex> {
val g1 = a.toGsl().copy()
gsl_matrix_complex_add(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
public override fun multiply(a: Matrix<Complex>, k: Number): GslMatrix<Complex, gsl_matrix_complex> {
val g1 = a.toGsl().copy()
gsl_matrix_complex_scale(g1.nativeHandle, k.toComplex().toGsl())
return g1
}
public override fun Matrix<Complex>.minus(b: Matrix<Complex>): Matrix<Complex> {
val g1 = toGsl().copy()
gsl_matrix_complex_sub(g1.nativeHandle, b.toGsl().nativeHandle)
return g1
}
@Suppress("IMPLICIT_CAST_TO_ANY")
@UnstableKMathAPI
public override fun <F : Any> getFeature(m: Matrix<Complex>, type: KClass<F>): F? = when (type) {
LupDecompositionFeature::class, DeterminantFeature::class -> object : LupDecompositionFeature<Complex>,
DeterminantFeature<Complex>, InverseMatrixFeature<Complex> {
private val lups by lazy {
val lu = m.toGsl().copy()
val n = m.rowNum
val perm = GslPermutation(rawNativeHandle = checkNotNull(gsl_permutation_alloc(n.toULong())),
scope = scope,
owned = true)
val signum = memScoped {
val i = alloc<IntVar>()
gsl_linalg_complex_LU_decomp(lu.nativeHandle, perm.nativeHandle, i.ptr)
i.value
}
Triple(lu, perm, signum)
}
override val p by lazy {
val n = m.rowNum
val one = produce(n, n) { i, j -> if (i == j) 1.0.toComplex() else 0.0.toComplex() }
val perm = produce(n, n) { _, _ -> 0.0.toComplex() }
for (j in 0 until lups.second.size)
gsl_matrix_complex_set_col(perm.nativeHandle,
j.toULong(),
one.columns[lups.second[j]].toGsl().nativeHandle)
perm
}
override val l by lazy {
VirtualMatrix(lups.first.shape[0], lups.first.shape[1]) { i, j ->
when {
j < i -> lups.first[i, j]
j == i -> 1.0.toComplex()
else -> 0.0.toComplex()
}
} + LFeature
}
override val u by lazy {
VirtualMatrix(
lups.first.shape[0],
lups.first.shape[1],
) { i, j -> if (j >= i) lups.first[i, j] else 0.0.toComplex() } + UFeature
}
override val determinant by lazy {
gsl_linalg_complex_LU_det(lups.first.nativeHandle, lups.third).toKMath()
}
override val inverse by lazy {
val inv = lups.first.copy()
gsl_linalg_complex_LU_invx(inv.nativeHandle, lups.second.nativeHandle)
inv
}
}
CholeskyDecompositionFeature::class -> object : CholeskyDecompositionFeature<Complex> {
override val l by lazy {
val chol = m.toGsl().copy()
gsl_linalg_complex_cholesky_decomp(chol.nativeHandle)
chol
}
}
else -> super.getFeature(m, type)
}?.let(type::cast)
}
/**
* Invokes [block] inside newly created [GslComplexMatrixContext] which is disposed when the block is invoked.
*/
public fun <R> GslComplexMatrixContext(block: GslComplexMatrixContext.() -> R): R =
memScoped { GslComplexMatrixContext(this).block() }

View File

@ -1,36 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.AutofreeScope
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.CStructVar
import kotlinx.cinterop.DeferScope
/**
* Represents managed native GSL object. The only property this class holds is pointer to the GSL object. In order to be
* freed this class's object must be added to [DeferScope].
*
* The objects of this type shouldn't be used after being disposed by the scope.
*
* @param scope the scope where this object is declared.
*/
public abstract class GslObject<H : CStructVar> internal constructor(internal val scope: AutofreeScope, internal val owned: Boolean) {
internal abstract val rawNativeHandle: CPointer<H>
private var isClosed: Boolean = false
internal val nativeHandle: CPointer<H>
get() {
check(!isClosed) { "The use of GSL object that is closed." }
return rawNativeHandle
}
init {
ensureHasGslErrorHandler()
scope.defer {
if (owned) close()
isClosed = true
}
}
internal abstract fun close()
}

View File

@ -1,19 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.AutofreeScope
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.pointed
import org.gnu.gsl.gsl_permutation
import org.gnu.gsl.gsl_permutation_free
import org.gnu.gsl.gsl_permutation_get
internal class GslPermutation(
override val rawNativeHandle: CPointer<gsl_permutation>,
scope: AutofreeScope,
owned: Boolean,
) : GslObject<gsl_permutation>(scope, owned) {
val size get() = nativeHandle.pointed.size.toInt()
operator fun get(i: Int) = gsl_permutation_get(nativeHandle, i.toULong()).toInt()
override fun close() = gsl_permutation_free(nativeHandle)
}

View File

@ -1,25 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.AutofreeScope
import kotlinx.cinterop.CStructVar
import kscience.kmath.linear.Point
/**
* Wraps gsl_vector_* objects from GSL.
*/
public abstract class GslVector<T, H : CStructVar> internal constructor(scope: AutofreeScope, owned: Boolean) :
GslObject<H>(scope, owned), Point<T> {
internal abstract operator fun set(index: Int, value: T)
internal abstract fun copy(): GslVector<T, H>
public final override fun iterator(): Iterator<T> = object : Iterator<T> {
private var cursor = 0
override fun hasNext(): Boolean = cursor < size
override fun next(): T {
cursor++
return this@GslVector[cursor - 1]
}
}
}

View File

@ -1,414 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.*
import kscience.kmath.structures.*
import org.gnu.gsl.*
internal class GslRealMatrix(
override val rawNativeHandle: CPointer<gsl_matrix>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Double, gsl_matrix>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Double>>
get() = VirtualBuffer(rowNum) { r ->
GslRealVector(
gsl_matrix_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Double>>
get() = VirtualBuffer(rowNum) { c ->
GslRealVector(
gsl_matrix_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Double =
gsl_matrix_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: Double): Unit =
gsl_matrix_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslRealMatrix {
val new = checkNotNull(gsl_matrix_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_memcpy(new, nativeHandle)
return GslRealMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslRealMatrix)
return gsl_matrix_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslFloatMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_float>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Float, gsl_matrix_float>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Float>>
get() = VirtualBuffer(rowNum) { r ->
GslFloatVector(
gsl_matrix_float_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Float>>
get() = VirtualBuffer(rowNum) { c ->
GslFloatVector(
gsl_matrix_float_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Float =
gsl_matrix_float_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: Float): Unit =
gsl_matrix_float_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslFloatMatrix {
val new = checkNotNull(gsl_matrix_float_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_float_memcpy(new, nativeHandle)
return GslFloatMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_float_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslFloatMatrix)
return gsl_matrix_float_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslShortMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_short>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Short, gsl_matrix_short>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Short>>
get() = VirtualBuffer(rowNum) { r ->
GslShortVector(
gsl_matrix_short_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Short>>
get() = VirtualBuffer(rowNum) { c ->
GslShortVector(
gsl_matrix_short_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Short =
gsl_matrix_short_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: Short): Unit =
gsl_matrix_short_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslShortMatrix {
val new = checkNotNull(gsl_matrix_short_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_short_memcpy(new, nativeHandle)
return GslShortMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_short_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslShortMatrix)
return gsl_matrix_short_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslUShortMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_ushort>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<UShort, gsl_matrix_ushort>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<UShort>>
get() = VirtualBuffer(rowNum) { r ->
GslUShortVector(
gsl_matrix_ushort_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<UShort>>
get() = VirtualBuffer(rowNum) { c ->
GslUShortVector(
gsl_matrix_ushort_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): UShort =
gsl_matrix_ushort_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: UShort): Unit =
gsl_matrix_ushort_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslUShortMatrix {
val new = checkNotNull(gsl_matrix_ushort_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_ushort_memcpy(new, nativeHandle)
return GslUShortMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_ushort_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslUShortMatrix)
return gsl_matrix_ushort_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslLongMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_long>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Long, gsl_matrix_long>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Long>>
get() = VirtualBuffer(rowNum) { r ->
GslLongVector(
gsl_matrix_long_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Long>>
get() = VirtualBuffer(rowNum) { c ->
GslLongVector(
gsl_matrix_long_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Long =
gsl_matrix_long_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: Long): Unit =
gsl_matrix_long_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslLongMatrix {
val new = checkNotNull(gsl_matrix_long_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_long_memcpy(new, nativeHandle)
return GslLongMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_long_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslLongMatrix)
return gsl_matrix_long_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslULongMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_ulong>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<ULong, gsl_matrix_ulong>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<ULong>>
get() = VirtualBuffer(rowNum) { r ->
GslULongVector(
gsl_matrix_ulong_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<ULong>>
get() = VirtualBuffer(rowNum) { c ->
GslULongVector(
gsl_matrix_ulong_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): ULong =
gsl_matrix_ulong_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: ULong): Unit =
gsl_matrix_ulong_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslULongMatrix {
val new = checkNotNull(gsl_matrix_ulong_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_ulong_memcpy(new, nativeHandle)
return GslULongMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_ulong_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslULongMatrix)
return gsl_matrix_ulong_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslIntMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_int>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<Int, gsl_matrix_int>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<Int>>
get() = VirtualBuffer(rowNum) { r ->
GslIntVector(
gsl_matrix_int_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<Int>>
get() = VirtualBuffer(rowNum) { c ->
GslIntVector(
gsl_matrix_int_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): Int =
gsl_matrix_int_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: Int): Unit =
gsl_matrix_int_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslIntMatrix {
val new = checkNotNull(gsl_matrix_int_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_int_memcpy(new, nativeHandle)
return GslIntMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_int_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslIntMatrix)
return gsl_matrix_int_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}
internal class GslUIntMatrix(
override val rawNativeHandle: CPointer<gsl_matrix_uint>,
scope: AutofreeScope,
owned: Boolean,
) : GslMatrix<UInt, gsl_matrix_uint>(scope, owned) {
override val rowNum: Int
get() = nativeHandle.pointed.size1.toInt()
override val colNum: Int
get() = nativeHandle.pointed.size2.toInt()
override val rows: Buffer<Buffer<UInt>>
get() = VirtualBuffer(rowNum) { r ->
GslUIntVector(
gsl_matrix_uint_row(nativeHandle, r.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override val columns: Buffer<Buffer<UInt>>
get() = VirtualBuffer(rowNum) { c ->
GslUIntVector(
gsl_matrix_uint_column(nativeHandle, c.toULong()).placeTo(scope).pointed.vector.ptr,
scope,
false,
)
}
override operator fun get(i: Int, j: Int): UInt =
gsl_matrix_uint_get(nativeHandle, i.toULong(), j.toULong())
override operator fun set(i: Int, j: Int, value: UInt): Unit =
gsl_matrix_uint_set(nativeHandle, i.toULong(), j.toULong(), value)
override fun copy(): GslUIntMatrix {
val new = checkNotNull(gsl_matrix_uint_alloc(rowNum.toULong(), colNum.toULong()))
gsl_matrix_uint_memcpy(new, nativeHandle)
return GslUIntMatrix(new, scope, true)
}
override fun close(): Unit = gsl_matrix_uint_free(nativeHandle)
override fun equals(other: Any?): Boolean {
if (other is GslUIntMatrix)
return gsl_matrix_uint_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
}

View File

@ -1,205 +0,0 @@
package kscience.kmath.gsl
import kotlinx.cinterop.*
import org.gnu.gsl.*
internal class GslRealVector(
override val rawNativeHandle: CPointer<gsl_vector>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Double, gsl_vector>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): Double = gsl_vector_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: Double): Unit = gsl_vector_set(nativeHandle, index.toULong(), value)
override fun copy(): GslRealVector {
val new = checkNotNull(gsl_vector_alloc(size.toULong()))
gsl_vector_memcpy(new, nativeHandle)
return GslRealVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslRealVector)
return gsl_vector_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_free(nativeHandle)
}
internal class GslFloatVector(
override val rawNativeHandle: CPointer<gsl_vector_float>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Float, gsl_vector_float>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): Float = gsl_vector_float_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: Float): Unit = gsl_vector_float_set(nativeHandle, index.toULong(), value)
override fun copy(): GslFloatVector {
val new = checkNotNull(gsl_vector_float_alloc(size.toULong()))
gsl_vector_float_memcpy(new, nativeHandle)
return GslFloatVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslFloatVector)
return gsl_vector_float_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_float_free(nativeHandle)
}
internal class GslShortVector(
override val rawNativeHandle: CPointer<gsl_vector_short>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Short, gsl_vector_short>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): Short = gsl_vector_short_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: Short): Unit = gsl_vector_short_set(nativeHandle, index.toULong(), value)
override fun copy(): GslShortVector {
val new = checkNotNull(gsl_vector_short_alloc(size.toULong()))
gsl_vector_short_memcpy(new, nativeHandle)
return GslShortVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslShortVector)
return gsl_vector_short_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_short_free(nativeHandle)
}
internal class GslUShortVector(
override val rawNativeHandle: CPointer<gsl_vector_ushort>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<UShort, gsl_vector_ushort>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): UShort = gsl_vector_ushort_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: UShort): Unit = gsl_vector_ushort_set(nativeHandle, index.toULong(), value)
override fun copy(): GslUShortVector {
val new = checkNotNull(gsl_vector_ushort_alloc(size.toULong()))
gsl_vector_ushort_memcpy(new, nativeHandle)
return GslUShortVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslUShortVector)
return gsl_vector_ushort_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_ushort_free(nativeHandle)
}
internal class GslLongVector(
override val rawNativeHandle: CPointer<gsl_vector_long>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Long, gsl_vector_long>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): Long = gsl_vector_long_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: Long): Unit = gsl_vector_long_set(nativeHandle, index.toULong(), value)
override fun copy(): GslLongVector {
val new = checkNotNull(gsl_vector_long_alloc(size.toULong()))
gsl_vector_long_memcpy(new, nativeHandle)
return GslLongVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslLongVector)
return gsl_vector_long_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_long_free(nativeHandle)
}
internal class GslULongVector(
override val rawNativeHandle: CPointer<gsl_vector_ulong>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<ULong, gsl_vector_ulong>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): ULong = gsl_vector_ulong_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: ULong): Unit = gsl_vector_ulong_set(nativeHandle, index.toULong(), value)
override fun copy(): GslULongVector {
val new = checkNotNull(gsl_vector_ulong_alloc(size.toULong()))
gsl_vector_ulong_memcpy(new, nativeHandle)
return GslULongVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslULongVector)
return gsl_vector_ulong_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_ulong_free(nativeHandle)
}
internal class GslIntVector(
override val rawNativeHandle: CPointer<gsl_vector_int>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<Int, gsl_vector_int>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): Int = gsl_vector_int_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: Int): Unit = gsl_vector_int_set(nativeHandle, index.toULong(), value)
override fun copy(): GslIntVector {
val new = checkNotNull(gsl_vector_int_alloc(size.toULong()))
gsl_vector_int_memcpy(new, nativeHandle)
return GslIntVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslIntVector)
return gsl_vector_int_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_int_free(nativeHandle)
}
internal class GslUIntVector(
override val rawNativeHandle: CPointer<gsl_vector_uint>,
scope: AutofreeScope,
owned: Boolean,
) : GslVector<UInt, gsl_vector_uint>(scope, owned) {
override val size: Int get() = nativeHandle.pointed.size.toInt()
override operator fun get(index: Int): UInt = gsl_vector_uint_get(nativeHandle, index.toULong())
override operator fun set(index: Int, value: UInt): Unit = gsl_vector_uint_set(nativeHandle, index.toULong(), value)
override fun copy(): GslUIntVector {
val new = checkNotNull(gsl_vector_uint_alloc(size.toULong()))
gsl_vector_uint_memcpy(new, nativeHandle)
return GslUIntVector(new, scope, true)
}
override fun equals(other: Any?): Boolean {
if (other is GslUIntVector)
return gsl_vector_uint_equal(nativeHandle, other.nativeHandle) == 1
return super.equals(other)
}
override fun close(): Unit = gsl_vector_uint_free(nativeHandle)
}

View File

@ -1,32 +0,0 @@
package kscience.kmath.gsl
import org.gnu.gsl.gsl_block_calloc
import kotlin.test.Test
import kotlin.test.assertFailsWith
internal class ErrorsHandlingTest {
@Test
fun blockAllocation() {
assertFailsWith<GslException> {
ensureHasGslErrorHandler()
gsl_block_calloc(ULong.MAX_VALUE)
}
}
@Test
fun matrixAllocation() {
assertFailsWith<GslException> {
GslRealMatrixContext { produce(Int.MAX_VALUE, Int.MAX_VALUE) { _, _ -> 0.0 } }
}
}
@Test
fun useOfClosedObject() {
val mat = GslRealMatrixContext { produce(1, 1) { _, _ -> 0.0 } }
assertFailsWith<IllegalStateException> { mat.colNum }
assertFailsWith<IllegalStateException> { mat.rowNum }
assertFailsWith<IllegalStateException> { mat[0, 0] }
assertFailsWith<IllegalStateException> { mat.copy() }
assertFailsWith<IllegalStateException> { println(mat == mat) }
}
}

View File

@ -1,62 +0,0 @@
package kscience.kmath.gsl
import kscience.kmath.linear.Matrix
import kscience.kmath.linear.RealMatrixContext
import kscience.kmath.operations.invoke
import kscience.kmath.structures.asIterable
import kscience.kmath.structures.toList
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
internal class GslMatrixRealTest {
@Test
fun dimensions() = GslRealMatrixContext {
val mat = produce(42, 24) { _, _ -> 0.0 }
assertEquals(42, mat.rowNum)
assertEquals(24, mat.colNum)
}
@Test
fun get() = GslRealMatrixContext {
val mat = produce(1, 1) { _, _ -> 42.0 }
assertEquals(42.0, mat[0, 0])
}
@Test
fun copy() = GslRealMatrixContext {
val mat = produce(1, 1) { _, _ -> 42.0 }
assertEquals(mat, mat.copy())
}
@Test
fun equals() = GslRealMatrixContext {
var rng = Random(0)
val mat: Matrix<Double> = produce(2, 2) { _, _ -> rng.nextDouble() }
rng = Random(0)
val mat2: Matrix<Double> = RealMatrixContext { produce(2, 2) { _, _ -> rng.nextDouble() } }
rng = Random(0)
val mat3: Matrix<Double> = produce(2, 2) { _, _ -> rng.nextDouble() }
assertEquals(mat, mat2)
assertEquals(mat, mat3)
assertEquals(mat2, mat3)
}
@Test
fun rows() = GslRealMatrixContext {
val mat = produce(2, 2) { i, j -> i.toDouble() + j }
mat.rows.asIterable().zip(listOf(listOf(0.0, 1.0), listOf(1.0, 2.0))).forEach { (a, b) ->
assertEquals(a.toList(), b)
}
}
@Test
fun columns() = GslRealMatrixContext {
val mat = produce(2, 2) { i, j -> i.toDouble() + j }
mat.columns.asIterable().zip(listOf(listOf(0.0, 1.0), listOf(1.0, 2.0))).forEach { (a, b) ->
assertEquals(a.toList(), b)
}
}
}

View File

@ -1,58 +0,0 @@
package kscience.kmath.gsl
import kscience.kmath.linear.Matrix
import kscience.kmath.linear.RealMatrixContext
import kscience.kmath.operations.invoke
import kscience.kmath.structures.RealBuffer
import kscience.kmath.structures.asSequence
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.time.measureTime
internal class GslRealMatrixContextTest {
@Test
fun testScale() = GslRealMatrixContext {
val ma = produce(10, 10) { _, _ -> 0.1 }
val mb = ma * 20.0
assertEquals(mb[0, 1], 2.0)
}
@Test
fun testDotOfMatrixAndVector() = GslRealMatrixContext {
val ma = produce(2, 2) { _, _ -> 100.0 }
val vb = RealBuffer(2) { 0.1 }
val res1 = ma dot vb
val res2 = RealMatrixContext { ma dot vb }
println(res1.asSequence().toList())
println(res2.asSequence().toList())
assertTrue(res1.contentEquals(res2))
}
@Test
fun testDotOfMatrixAndMatrix() = GslRealMatrixContext {
val ma = produce(2, 2) { _, _ -> 100.0 }
val mb = produce(2, 2) { _, _ -> 100.0 }
val res1: Matrix<Double> = ma dot mb
val res2: Matrix<Double> = RealMatrixContext { ma dot mb }
assertEquals(res1, res2)
}
@Test
fun testManyCalls() = GslRealMatrixContext {
val expected: Matrix<Double> = RealMatrixContext {
val rng = Random(0)
var prod = produce(20, 20) { _, _ -> rng.nextDouble() }
val mult = produce(20, 20) { _, _ -> rng.nextDouble() }
measureTime { repeat(100) { prod = prod dot mult } }.also(::println)
prod
}
val rng = Random(0)
var prod: Matrix<Double> = produce(20, 20) { _, _ -> rng.nextDouble() }
val mult = produce(20, 20) { _, _ -> rng.nextDouble() }
measureTime { repeat(100) { prod = prod dot mult } }.also(::println)
assertEquals(expected, prod)
}
}

View File

@ -41,6 +41,5 @@ include(
":kmath-ast", ":kmath-ast",
":kmath-ejml", ":kmath-ejml",
":kmath-kotlingrad", ":kmath-kotlingrad",
":kmath-gsl",
":examples" ":examples"
) )